repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
JoshuaEstes/apostrophePlugin
modules/a/templates/revertSuccess.php
646
<?php // Compatible with sf_escaping_strategy: true $cancel = isset($cancel) ? $sf_data->getRaw('cancel') : null; $name = isset($name) ? $sf_data->getRaw('name') : null; $preview = isset($preview) ? $sf_data->getRaw('preview') : null; $revert = isset($revert) ? $sf_data->getRaw('revert') : null; ?> <?php use_helper('a') ?> <?php include_component('a', 'area', array('name' => $name, 'refresh' => true, 'preview' => $preview))?> <?php if ($cancel || $revert): ?> <script type="text/javascript"> $('#a-history-container-<?php echo $name?>').html(""); </script> <?php endif ?> <?php include_partial('a/globalJavascripts') ?>
mit
andreychernih/railsbox
spec/support/test_helpers/zip_contents.rb
944
module TestHelpers module ZipContents def zip_list_of_files(data) files = [] process_zip_data(data) do |zipfile| files = zipfile.entries.map(&:name) end files end # the client is reponsible for deleting dir def extract_zip(data) dir = Dir.mktmpdir process_zip_data(data) do |zipfile| zipfile.each do |f| f_path = File.join(dir, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zipfile.extract(f, f_path) unless File.exist?(f_path) end end dir end def process_zip_data(data) zip = Tempfile.new 'zip_contents' begin zip.write data zip.close # Zip::File.open_buffer is buggy, that's why we need to create # Tempfile and work with it Zip::File.open(zip.path) do |zipfile| yield zipfile end ensure zip.unlink end end end end
mit
Peter-Maximilian/settlers-remake
jsettlers.mapcreator/src/main/java/jsettlers/mapcreator/tools/landscape/FixHeightsTool.java
4022
/******************************************************************************* * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.mapcreator.tools.landscape; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.position.ShortPoint2D; import jsettlers.mapcreator.data.LandscapeConstraint; import jsettlers.mapcreator.data.MapData; import jsettlers.mapcreator.data.objects.ObjectContainer; import jsettlers.mapcreator.mapvalidator.tasks.error.ValidateLandscape; import jsettlers.mapcreator.mapvalidator.tasks.error.ValidateResources; import jsettlers.mapcreator.tools.AbstractTool; import jsettlers.mapcreator.tools.shapes.ShapeType; /** * Fix height problems * * @author Andreas Butti * */ public class FixHeightsTool extends AbstractTool { /** * Constructor */ public FixHeightsTool() { super("fixheights"); shapeTypes.addAll(LandscapeHeightTool.LANDSCAPE_SHAPES); } @Override public void apply(MapData map, ShapeType shape, ShortPoint2D start, ShortPoint2D end, double uidx) { byte[][] influences = new byte[map.getWidth()][map.getHeight()]; shape.setAffectedStatus(influences, start, end); for (int x = 0; x < map.getWidth() - 1; x++) { for (int y = 0; y < map.getWidth() - 1; y++) { if (influences[x][y] > 0) { fixResources(map, x, y); fix(map, x, y, x + 1, y); fix(map, x, y, x + 1, y + 1); fix(map, x, y, x, y + 1); } } } for (int x = map.getWidth() - 2; x >= 0; x--) { for (int y = map.getWidth() - 2; y >= 0; y--) { if (influences[x][y] > 0) { fix(map, x, y, x + 1, y); fix(map, x, y, x + 1, y + 1); fix(map, x, y, x, y + 1); } } } } private static void fixResources(MapData map, int x, int y) { if (map.getResourceAmount((short) x, (short) y) > 0) { if (!ValidateResources.mayHoldResource(map.getLandscape(x, y), map.getResourceType((short) x, (short) y))) { map.decreaseResourceTo(x, y, (byte) 0); } } } private static void fix(MapData map, int x, int y, int x2, int y2) { byte h1 = map.getLandscapeHeight(x, y); byte h2 = map.getLandscapeHeight(x2, y2); ELandscapeType l1 = map.getLandscape(x, y); ELandscapeType l2 = map.getLandscape(x2, y2); int maxHeightDiff = ValidateLandscape.getMaxHeightDiff(l1, l2); ObjectContainer container1 = map.getMapObjectContainer(x, y); if (container1 instanceof LandscapeConstraint && ((LandscapeConstraint) container1).needsFlattenedGround()) { maxHeightDiff = 0; } ObjectContainer container2 = map.getMapObjectContainer(x2, y2); if (container2 instanceof LandscapeConstraint && ((LandscapeConstraint) container2).needsFlattenedGround()) { maxHeightDiff = 0; } if (h1 - h2 > maxHeightDiff) { // h1 too big map.setHeight(x, y, h2 + maxHeightDiff); } else if (h2 - h1 > maxHeightDiff) { // h2 too big map.setHeight(x2, y2, h1 + maxHeightDiff); } } }
mit
guillochon/FriendlyFit
mosfit/model.py
40106
"""Definitions for the `Model` class.""" import importlib import inspect import json import os from collections import OrderedDict from copy import deepcopy from difflib import get_close_matches from math import isnan import inflect import numpy as np from astrocats.catalog.quantity import QUANTITY from mosfit.constants import LOCAL_LIKELIHOOD_FLOOR from mosfit.modules.module import Module from mosfit.utils import is_number, listify, pretty_num from schwimmbad import SerialPool # from scipy.optimize import differential_evolution from scipy.optimize import minimize from six import string_types # from scipy.optimize import basinhopping # from bayes_opt import BayesianOptimization class Model(object): """Define a semi-analytical model to fit transients with.""" MODEL_PRODUCTS_DIR = 'products' MIN_WAVE_FRAC_DIFF = 0.1 DRAW_LIMIT = 10 # class outClass(object): # pass def __init__(self, parameter_path='parameters.json', model='', data={}, wrap_length=100, output_path='', pool=None, test=False, printer=None, fitter=None, print_trees=False): """Initialize `Model` object.""" from mosfit.fitter import Fitter self._model_name = model self._parameter_path = parameter_path self._output_path = output_path self._pool = SerialPool() if pool is None else pool self._is_master = pool.is_master() if pool else False self._wrap_length = wrap_length self._print_trees = print_trees self._inflect = inflect.engine() self._test = test self._inflections = {} self._references = OrderedDict() self._free_parameters = [] self._user_fixed_parameters = [] self._user_released_parameters = [] self._kinds_needed = set() self._kinds_supported = set() self._draw_limit_reached = False self._fitter = Fitter() if not fitter else fitter self._printer = self._fitter._printer if not printer else printer prt = self._printer self._dir_path = os.path.dirname(os.path.realpath(__file__)) # Load suggested model associations for transient types. if os.path.isfile(os.path.join('models', 'types.json')): types_path = os.path.join('models', 'types.json') else: types_path = os.path.join(self._dir_path, 'models', 'types.json') with open(types_path, 'r') as f: model_types = json.load(f, object_pairs_hook=OrderedDict) # Create list of all available models. all_models = set() if os.path.isdir('models'): all_models |= set(next(os.walk('models'))[1]) models_path = os.path.join(self._dir_path, 'models') if os.path.isdir(models_path): all_models |= set(next(os.walk(models_path))[1]) all_models = list(sorted(list(all_models))) if not self._model_name: claimed_type = None try: claimed_type = list(data.values())[0][ 'claimedtype'][0][QUANTITY.VALUE] except Exception: prt.message('no_model_type', warning=True) all_models_txt = prt.text('all_models') suggested_models_txt = prt.text('suggested_models', [claimed_type]) another_model_txt = prt.text('another_model') type_options = model_types.get( claimed_type, []) if claimed_type else [] if not type_options: type_options = all_models model_prompt_txt = all_models_txt else: type_options.append(another_model_txt) model_prompt_txt = suggested_models_txt if not type_options: prt.message('no_model_for_type', warning=True) else: while not self._model_name: if self._test: self._model_name = type_options[0] else: sel = self._printer.prompt( model_prompt_txt, kind='option', options=type_options, message=False, default='n', none_string=prt.text('none_above_models')) if sel is not None: self._model_name = type_options[int(sel) - 1] if not self._model_name: break if self._model_name == another_model_txt: type_options = all_models model_prompt_txt = all_models_txt self._model_name = None if not self._model_name: return # Load the basic model file. if os.path.isfile(os.path.join('models', 'model.json')): basic_model_path = os.path.join('models', 'model.json') else: basic_model_path = os.path.join(self._dir_path, 'models', 'model.json') with open(basic_model_path, 'r') as f: self._model = json.load(f, object_pairs_hook=OrderedDict) # Load the model file. model = self._model_name model_dir = self._model_name if '.json' in self._model_name: model_dir = self._model_name.split('.json')[0] else: model = self._model_name + '.json' if os.path.isfile(model): model_path = model else: # Look in local hierarchy first if os.path.isfile(os.path.join('models', model_dir, model)): model_path = os.path.join('models', model_dir, model) else: model_path = os.path.join(self._dir_path, 'models', model_dir, model) with open(model_path, 'r') as f: self._model.update(json.load(f, object_pairs_hook=OrderedDict)) # Find @ tags, store them, and prune them from `_model`. for tag in list(self._model.keys()): if tag.startswith('@'): if tag == '@references': self._references.setdefault('base', []).extend( self._model[tag]) del self._model[tag] # with open(os.path.join( # self.get_products_path(), # self._model_name + '.json'), 'w') as f: # json.dump(self._model, f) # Load model parameter file. model_pp = os.path.join( self._dir_path, 'models', model_dir, 'parameters.json') pp = '' local_pp = (self._parameter_path if '/' in self._parameter_path else os.path.join('models', model_dir, self._parameter_path)) if os.path.isfile(local_pp): selected_pp = local_pp else: selected_pp = os.path.join( self._dir_path, 'models', model_dir, self._parameter_path) # First try user-specified path if self._parameter_path and os.path.isfile(self._parameter_path): pp = self._parameter_path # Then try directory we are running from elif os.path.isfile('parameters.json'): pp = 'parameters.json' # Then try the model directory, with the user-specified name elif os.path.isfile(selected_pp): pp = selected_pp # Finally try model folder elif os.path.isfile(model_pp): pp = model_pp else: raise ValueError(prt.text('no_parameter_file')) if self._is_master: prt.message('files', [basic_model_path, model_path, pp], wrapped=False) with open(pp, 'r') as f: self._parameter_json = json.load(f, object_pairs_hook=OrderedDict) self._modules = OrderedDict() self._bands = [] self._instruments = [] self._telescopes = [] # Load the call tree for the model. Work our way in reverse from the # observables, first constructing a tree for each observable and then # combining trees. root_kinds = ['output', 'objective'] self._trees = OrderedDict() self._simple_trees = OrderedDict() self.construct_trees( self._model, self._trees, self._simple_trees, kinds=root_kinds) if self._print_trees: self._printer.prt('Dependency trees:\n', wrapped=True) self._printer.tree(self._simple_trees) unsorted_call_stack = OrderedDict() self._max_depth_all = -1 for tag in self._model: model_tag = self._model[tag] roots = [] if model_tag['kind'] in root_kinds: max_depth = 0 roots = [model_tag['kind']] else: max_depth = -1 for tag2 in self._trees: if self.in_tree(tag, self._trees[tag2]): roots.extend(self._trees[tag2]['roots']) depth = self.get_max_depth(tag, self._trees[tag2], max_depth) if depth > max_depth: max_depth = depth if depth > self._max_depth_all: self._max_depth_all = depth roots = list(sorted(set(roots))) new_entry = deepcopy(model_tag) new_entry['roots'] = roots if 'children' in new_entry: del new_entry['children'] new_entry['depth'] = max_depth unsorted_call_stack[tag] = new_entry # print(unsorted_call_stack) # Currently just have one call stack for all products, can be wasteful # if only using some products. self._call_stack = OrderedDict() for depth in range(self._max_depth_all, -1, -1): for task in unsorted_call_stack: if unsorted_call_stack[task]['depth'] == depth: self._call_stack[task] = unsorted_call_stack[task] # with open(os.path.join( # self.get_products_path(), # self._model_name + '-stack.json'), 'w') as f: # json.dump(self._call_stack, f) for task in self._call_stack: cur_task = self._call_stack[task] mod_name = cur_task.get('class', task) if cur_task[ 'kind'] == 'parameter' and task in self._parameter_json: cur_task.update(self._parameter_json[task]) self._modules[task] = self._load_task_module(task) if mod_name == 'photometry': self._telescopes = self._modules[task].telescopes() self._instruments = self._modules[task].instruments() self._bands = self._modules[task].bands() self._modules[task].set_attributes(cur_task) # Look forward to see which modules want dense arrays. for task in self._call_stack: for ftask in self._call_stack: if (task != ftask and self._call_stack[ftask]['depth'] < self._call_stack[task]['depth'] and self._modules[ftask]._wants_dense): self._modules[ftask]._provide_dense = True # Count free parameters. self.determine_free_parameters() def get_products_path(self): """Get path to products.""" return os.path.join(self._output_path, self.MODEL_PRODUCTS_DIR) def _load_task_module(self, task, call_stack=None): if not call_stack: call_stack = self._call_stack cur_task = call_stack[task] kinds = self._inflect.plural(cur_task['kind']) mod_name = cur_task.get('class', task).lower() mod_path = os.path.join('modules', kinds, mod_name + '.py') if not os.path.isfile(mod_path): mod_path = os.path.join(self._dir_path, 'modules', kinds, mod_name + '.py') mod_name = 'mosfit.modules.' + kinds + mod_name try: mod = importlib.machinery.SourceFileLoader(mod_name, mod_path).load_module() except AttributeError: import imp mod = imp.load_source(mod_name, mod_path) class_name = [ x[0] for x in inspect.getmembers(mod, inspect.isclass) if issubclass(x[1], Module) and x[1].__module__ == mod.__name__][0] mod_class = getattr(mod, class_name) return mod_class( name=task, model=self, fitter=self._fitter, **cur_task) def load_data(self, data, event_name='', smooth_times=-1, extrapolate_time=0.0, limit_fitting_mjds=False, exclude_bands=[], exclude_instruments=[], exclude_systems=[], exclude_sources=[], exclude_kinds=[], time_unit=None, time_list=[], band_list=[], band_systems=[], band_instruments=[], band_bandsets=[], band_sampling_points=25, variance_for_each=[], user_fixed_parameters=[], user_released_parameters=[], pool=None): """Load the data for the specified event.""" if pool is not None: self._pool = pool self._printer._pool = pool prt = self._printer prt.message('loading_data', inline=True) # Fix user-specified parameters. fixed_parameters = [] released_parameters = [] for task in self._call_stack: for fi, param in enumerate(user_fixed_parameters): if (task == param or self._call_stack[task].get( 'class', '') == param): fixed_parameters.append(task) if fi < len(user_fixed_parameters) - 1 and is_number( user_fixed_parameters[fi + 1]): value = float(user_fixed_parameters[fi + 1]) if value not in self._call_stack: self._call_stack[task]['value'] = value if 'min_value' in self._call_stack[task]: del self._call_stack[task]['min_value'] if 'max_value' in self._call_stack[task]: del self._call_stack[task]['max_value'] self._modules[task].fix_value( self._call_stack[task]['value']) for fi, param in enumerate(user_released_parameters): if (task == param or self._call_stack[task].get( 'class', '') == param): released_parameters.append(task) self.determine_free_parameters(fixed_parameters, released_parameters) for ti, task in enumerate(self._call_stack): cur_task = self._call_stack[task] self._modules[task].set_event_name(event_name) new_per = np.round(100.0 * float(ti) / len(self._call_stack)) prt.message('loading_task', [task, new_per], inline=True) self._kinds_supported |= set(cur_task.get('supports', [])) if cur_task['kind'] == 'data': success = self._modules[task].set_data( data, req_key_values=OrderedDict(( ('band', self._bands), ('instrument', self._instruments), ('telescope', self._telescopes))), subtract_minimum_keys=['times'], smooth_times=smooth_times, extrapolate_time=extrapolate_time, limit_fitting_mjds=limit_fitting_mjds, exclude_bands=exclude_bands, exclude_instruments=exclude_instruments, exclude_systems=exclude_systems, exclude_sources=exclude_sources, exclude_kinds=exclude_kinds, time_unit=time_unit, time_list=time_list, band_list=band_list, band_systems=band_systems, band_instruments=band_instruments, band_bandsets=band_bandsets) if not success: return False fixed_parameters.extend(self._modules[task] .get_data_determined_parameters()) elif cur_task['kind'] == 'sed': self._modules[task].set_data(band_sampling_points) self._kinds_needed |= self._modules[task]._kinds_needed # Find unsupported wavebands and report to user. unsupported_kinds = self._kinds_needed - self._kinds_supported if unsupported_kinds: prt.message( 'using_unsupported_kinds' if 'none' in exclude_kinds else 'ignoring_unsupported_kinds', [', '.join( sorted(unsupported_kinds))], warning=True) # Determine free parameters again as setting data may have fixed some # more. self.determine_free_parameters(fixed_parameters, released_parameters) self.exchange_requests() prt.message('finding_bands', inline=True) # Run through once to set all inits. for root in ['output', 'objective']: outputs = self.run_stack( [0.0 for x in range(self._num_free_parameters)], root=root) # Create any data-dependent free parameters. self.adjust_fixed_parameters(variance_for_each, outputs) # Determine free parameters again as above may have changed them. self.determine_free_parameters(fixed_parameters, released_parameters) self.determine_number_of_measurements() self.exchange_requests() # Reset modules for task in self._call_stack: self._modules[task].reset_preprocessed(['photometry']) # Run through inits once more. for root in ['output', 'objective']: outputs = self.run_stack( [0.0 for x in range(self._num_free_parameters)], root=root) # Collect observed band info if self._pool.is_master() and 'photometry' in self._modules: prt.message('bands_used') bis = list( filter(lambda a: a != -1, sorted(set(outputs['all_band_indices'])))) ois = [] for bi in bis: ois.append( any([ y for x, y in zip(outputs['all_band_indices'], outputs[ 'observed']) if x == bi ])) band_len = max([ len(self._modules['photometry']._unique_bands[bi][ 'origin']) for bi in bis ]) filts = self._modules['photometry'] ubs = filts._unique_bands filterarr = [(ubs[bis[i]]['systems'], ubs[bis[i]]['bandsets'], filts._average_wavelengths[bis[i]], filts._band_offsets[bis[i]], filts._band_kinds[bis[i]], filts._band_names[bis[i]], ois[i], bis[i]) for i in range(len(bis))] filterrows = [( ' ' + (' ' if s[-2] else '*') + ubs[s[-1]]['origin'] .ljust(band_len) + ' [' + ', '.join( list( filter(None, ( 'Bandset: ' + s[1] if s[1] else '', 'System: ' + s[0] if s[0] else '', 'AB offset: ' + pretty_num( s[3]) if (s[4] == 'magnitude' and s[0] != 'AB') else '')))) + ']').replace(' []', '') for s in list(sorted(filterarr))] if not all(ois): filterrows.append(prt.text('not_observed')) prt.prt('\n'.join(filterrows)) single_freq_inst = list( sorted(set(np.array(outputs['instruments'])[ np.array(outputs['all_band_indices']) == -1]))) if len(single_freq_inst): prt.message('single_freq') for inst in single_freq_inst: prt.prt(' {}'.format(inst)) if ('unmatched_bands' in outputs and 'unmatched_instruments' in outputs): prt.message('unmatched_obs', warning=True) prt.prt(', '.join( ['{} [{}]'.format(x[0], x[1]) if x[0] and x[1] else x[0] if not x[1] else x[1] for x in list(set(zip( outputs['unmatched_bands'], outputs['unmatched_instruments'])))]), warning=True, prefix=False, wrapped=True) return True def adjust_fixed_parameters( self, variance_for_each=[], output={}): """Create free parameters that depend on loaded data.""" unique_band_indices = list( sorted(set(output.get('all_band_indices', [])))) needs_general_variance = any( np.array(output.get('all_band_indices', [])) < 0) new_call_stack = OrderedDict() for task in self._call_stack: cur_task = self._call_stack[task] vfe = listify(variance_for_each) if task == 'variance' and 'band' in vfe: vfi = vfe.index('band') + 1 mwfd = float(vfe[vfi]) if (vfi < len(vfe) and is_number( vfe[vfi])) else self.MIN_WAVE_FRAC_DIFF # Find photometry in call stack. ptask = None for ptask in self._call_stack: if ptask == 'photometry': awaves = self._modules[ptask].average_wavelengths( unique_band_indices) abands = self._modules[ptask].bands( unique_band_indices) band_pairs = list(sorted(zip(awaves, abands))) break owav = 0.0 variance_bands = [] for (awav, band) in band_pairs: wave_frac_diff = abs(awav - owav) / (awav + owav) if wave_frac_diff < mwfd: continue new_task_name = '-'.join([task, 'band', band]) if new_task_name in self._call_stack: continue new_task = deepcopy(cur_task) new_call_stack[new_task_name] = new_task if 'latex' in new_task: new_task['latex'] += '_{\\rm ' + band + '}' new_call_stack[new_task_name] = new_task self._modules[new_task_name] = self._load_task_module( new_task_name, call_stack=new_call_stack) owav = awav variance_bands.append([awav, band]) if needs_general_variance: new_call_stack[task] = deepcopy(cur_task) if self._pool.is_master(): self._printer.message( 'anchoring_variances', [', '.join([x[1] for x in variance_bands])], wrapped=True) self._modules[ptask].set_variance_bands(variance_bands) else: new_call_stack[task] = deepcopy(cur_task) # Fixed any variables to be fixed if any conditional inputs are # fixed by the data. # if any([listify(x)[-1] == 'conditional' # for x in cur_task.get('inputs', [])]): self._call_stack = new_call_stack for task in reversed(self._call_stack): cur_task = self._call_stack[task] for inp in cur_task.get('inputs', []): other = listify(inp)[0] if (cur_task['kind'] == 'parameter' and output.get(other, None) is not None): if (not self._modules[other]._fixed or self._modules[other]._fixed_by_user): self._modules[task]._fixed = True self._modules[task]._derived_keys = list(set( self._modules[task]._derived_keys + [task])) def determine_number_of_measurements(self): """Estimate the number of measurements.""" self._num_measurements = 0 for task in self._call_stack: cur_task = self._call_stack[task] if cur_task['kind'] == 'data': self._num_measurements += len( self._modules[task]._data['times']) def determine_free_parameters( self, extra_fixed_parameters=[], extra_released_parameters=[]): """Generate `_free_parameters` and `_num_free_parameters`.""" self._free_parameters = [] self._user_fixed_parameters = [] self._num_variances = 0 for task in self._call_stack: cur_task = self._call_stack[task] if (task in extra_released_parameters or ( task not in extra_fixed_parameters and cur_task['kind'] == 'parameter' and 'min_value' in cur_task and 'max_value' in cur_task and cur_task['min_value'] != cur_task['max_value'] and not self._modules[task]._fixed)): self._free_parameters.append(task) if cur_task.get('class', '') == 'variance': self._num_variances += 1 elif (cur_task['kind'] == 'parameter' and task in extra_fixed_parameters): self._user_fixed_parameters.append(task) self._num_free_parameters = len(self._free_parameters) def is_parameter_fixed_by_user(self, parameter): """Return whether a parameter is fixed by the user.""" return parameter in self._user_fixed_parameters def get_num_free_parameters(self): """Return number of free parameters.""" return self._num_free_parameters def exchange_requests(self): """Exchange requests between modules.""" for task in reversed(self._call_stack): cur_task = self._call_stack[task] if 'requests' in cur_task: requests = OrderedDict() reqs = cur_task['requests'] for req in reqs: if reqs[req] not in self._modules: raise RuntimeError( 'Request cannot be satisfied because module ' '`{}` could not be found.'.format(reqs[req])) requests[req] = self._modules[reqs[req]].send_request(req) self._modules[task].receive_requests(**requests) def frack(self, arg): """Perform fracking upon a single walker. Uses a randomly-selected global or local minimization method. """ x = np.array(arg[0]) step = 1.0 seed = arg[1] np.random.seed(seed) my_choice = np.random.choice(range(3)) # my_choice = 0 my_method = ['L-BFGS-B', 'TNC', 'SLSQP'][my_choice] opt_dict = {'disp': False, 'approx_grad': True} if my_method in ['TNC', 'SLSQP']: opt_dict['maxiter'] = 200 elif my_method == 'L-BFGS-B': opt_dict['maxfun'] = 5000 opt_dict['maxls'] = 50 # bounds = [(0.0, 1.0) for y in range(self._num_free_parameters)] bounds = list( zip(np.clip(x - step, 0.0, 1.0), np.clip(x + step, 0.0, 1.0))) bh = minimize( self.fprob, x, method=my_method, bounds=bounds, options=opt_dict) # bounds = list( # zip(np.clip(x - step, 0.0, 1.0), np.clip(x + step, 0.0, 1.0))) # # bh = differential_evolution( # self.fprob, bounds, disp=True, polish=False) # bh = basinhopping( # self.fprob, # x, # disp=True, # niter=10, # minimizer_kwargs={'method': "L-BFGS-B", # 'bounds': bounds}) # bo = BayesianOptimization(self.boprob, dict( # [('x' + str(i), # (np.clip(x[i] - step, 0.0, 1.0), # np.clip(x[i] + step, 0.0, 1.0))) # for i in range(len(x))])) # # bo.explore(dict([('x' + str(i), [x[i]]) for i in range(len(x))])) # # bo.maximize(init_points=0, n_iter=20, acq='ei') # # bh = self.outClass() # bh.x = [x[1] for x in sorted(bo.res['max']['max_params'].items())] # bh.fun = -bo.res['max']['max_val'] # m = Minuit(self.fprob) # m.migrad() return bh def construct_trees( self, d, trees, simple, kinds=[], name='', roots=[], depth=0): """Construct call trees for each root.""" leaf = kinds if len(kinds) else name if depth > 100: raise RuntimeError( 'Error: Tree depth greater than 100, suggests a recursive ' 'input loop in `{}`.'.format(leaf)) for tag in d: entry = deepcopy(d[tag]) new_roots = list(roots) if entry['kind'] in kinds or tag == name: entry['depth'] = depth if entry['kind'] in kinds: new_roots.append(entry['kind']) entry['roots'] = list(sorted(set(new_roots))) trees[tag] = entry simple[tag] = OrderedDict() inputs = listify(entry.get('inputs', [])) for inps in inputs: conditional = False if isinstance(inps, list) and not isinstance( inps, string_types) and inps[-1] == "conditional": inp = inps[0] conditional = True else: inp = inps if inp not in d: suggests = get_close_matches(inp, d, n=1, cutoff=0.8) warn_str = ( 'Module `{}` for input to `{}` ' 'not found!'.format(inp, leaf)) if len(suggests): warn_str += ( ' Did you perhaps mean `{}`?'. format(suggests[0])) raise RuntimeError(warn_str) # Conditional inputs don't propagate down the tree. if conditional: continue children = OrderedDict() simple_children = OrderedDict() self.construct_trees( d, children, simple_children, name=inp, roots=new_roots, depth=depth + 1) trees[tag].setdefault('children', OrderedDict()) trees[tag]['children'].update(children) simple[tag].update(simple_children) def draw_from_icdf(self, draw): """Draw parameters into unit interval using parameter inverse CDFs.""" return [ self._modules[self._free_parameters[i]].prior_icdf(x) for i, x in enumerate(draw) ] def draw_walker(self, test=True, walkers_pool=[], replace=False, weights=None): """Draw a walker randomly. Draw a walker randomly from the full range of all parameters, reject walkers that return invalid scores. """ p = None chosen_one = None draw_cnt = 0 while p is None: draw_cnt += 1 draw = np.random.uniform( low=0.0, high=1.0, size=self._num_free_parameters) draw = self.draw_from_icdf(draw) if walkers_pool: if not replace: chosen_one = 0 else: chosen_one = np.random.choice(range(len(walkers_pool)), p=weights) for e, elem in enumerate(walkers_pool[chosen_one]): if elem is not None: draw[e] = elem if not test: p = draw score = None break score = self.ln_likelihood(draw) if draw_cnt >= self.DRAW_LIMIT and not self._draw_limit_reached: self._printer.message('draw_limit_reached', warning=True) self._draw_limit_reached = True if ((not isnan(score) and np.isfinite(score) and (not isinstance(self._fitter._draw_above_likelihood, float) or score > self._fitter._draw_above_likelihood)) or draw_cnt >= self.DRAW_LIMIT): p = draw if not replace and chosen_one is not None: del walkers_pool[chosen_one] if weights is not None: del weights[chosen_one] if weights and None not in weights: totw = np.sum(weights) weights = [x / totw for x in weights] return (p, score) def get_max_depth(self, tag, parent, max_depth): """Return the maximum depth a given task is found in a tree.""" for child in parent.get('children', []): if child == tag: new_max = parent['children'][child]['depth'] if new_max > max_depth: max_depth = new_max else: new_max = self.get_max_depth(tag, parent['children'][child], max_depth) if new_max > max_depth: max_depth = new_max return max_depth def in_tree(self, tag, parent): """Return the maximum depth a given task is found in a tree.""" for child in parent.get('children', []): if child == tag: return True else: if self.in_tree(tag, parent['children'][child]): return True return False def pool(self): """Return processing pool.""" return self._pool def run(self, x, root='output'): """Run stack with the given root.""" outputs = self.run_stack(x, root=root) return outputs def printer(self): """Return printer.""" return self._printer def likelihood(self, x): """Return score related to maximum likelihood.""" return np.exp(self.ln_likelihood(x)) def ln_likelihood(self, x): """Return ln(likelihood).""" outputs = self.run_stack(x, root='objective') return outputs['value'] def ln_likelihood_floored(self, x): """Return ln(likelihood), floored to a finite value.""" outputs = self.run_stack(x, root='objective') return max(LOCAL_LIKELIHOOD_FLOOR, outputs['value']) def free_parameter_names(self, x): """Return list of free parameter names.""" return self._free_parameters def prior(self, x): """Return score related to paramater priors.""" return np.exp(self.ln_prior(x)) def ln_prior(self, x): """Return ln(prior).""" prior = 0.0 for pi, par in enumerate(self._free_parameters): lprior = self._modules[par].lnprior_pdf(x[pi]) prior = prior + lprior return prior def boprob(self, **kwargs): """Score for `BayesianOptimization`.""" x = [] for key in sorted(kwargs): x.append(kwargs[key]) li = self.ln_likelihood(x) + self.ln_prior(x) if not np.isfinite(li): return LOCAL_LIKELIHOOD_FLOOR return li def fprob(self, x): """Return score for fracking.""" li = -(self.ln_likelihood(x) + self.ln_prior(x)) if not np.isfinite(li): return -LOCAL_LIKELIHOOD_FLOOR return li def plural(self, x): """Pluralize and cache model-related keys.""" if x not in self._inflections: plural = self._inflect.plural(x) if plural == x: plural = x + 's' self._inflections[x] = plural else: plural = self._inflections[x] return plural def reset_unset_recommended_keys(self): """Null the list of unset recommended keys across all modules.""" for module in self._modules.values(): module.reset_unset_recommended_keys() def get_unset_recommended_keys(self): """Collect list of unset recommended keys across all modules.""" unset_keys = set() for module in self._modules.values(): unset_keys.update(module.get_unset_recommended_keys()) return unset_keys def run_stack(self, x, root='objective'): """Run module stack. Run a stack of modules as defined in the model definition file. Only run functions that match the specified root. """ inputs = OrderedDict() outputs = OrderedDict() pos = 0 cur_depth = self._max_depth_all # If this is the first time running this stack, build the ref arrays. build_refs = root not in self._references if build_refs: self._references[root] = [] for task in self._call_stack: cur_task = self._call_stack[task] if root not in cur_task['roots']: continue if cur_task['depth'] != cur_depth: inputs = outputs inputs.update(OrderedDict([('root', root)])) cur_depth = cur_task['depth'] if task in self._free_parameters: inputs.update(OrderedDict([('fraction', x[pos])])) inputs.setdefault('fractions', []).append(x[pos]) pos = pos + 1 try: new_outs = self._modules[task].process(**inputs) if not isinstance(new_outs, OrderedDict): new_outs = OrderedDict(sorted(new_outs.items())) except Exception: self._printer.prt( "Failed to execute module `{}`\'s process().".format(task), wrapped=True) raise outputs.update(new_outs) # Append module references if build_refs: self._references[root].extend(self._modules[task]._REFERENCES) if '_delete_keys' in outputs: for key in list(outputs['_delete_keys'].keys()): del outputs[key] del outputs['_delete_keys'] if build_refs: # Make sure references are unique. self._references[root] = list(map(dict, set(tuple( sorted(d.items())) for d in self._references[root]))) return outputs
mit
mekajay04/wanderlist
node_modules/sequelize/lib/dialects/abstract/connection-manager.js
9421
'use strict'; const Pooling = require('generic-pool'); const Promise = require('../../promise'); const _ = require('lodash'); const Utils = require('../../utils'); const debug = Utils.getLogger().debugContext('pool'); const semver = require('semver'); const timers = require('timers'); const defaultPoolingConfig = { max: 5, min: 0, idle: 10000, acquire: 10000, evict: 60000, handleDisconnects: true }; class ConnectionManager { constructor(dialect, sequelize) { const config = _.cloneDeep(sequelize.config); this.sequelize = sequelize; this.config = config; this.dialect = dialect; this.versionPromise = null; this.poolError = null; this.dialectName = this.sequelize.options.dialect; if (config.pool === false) { throw new Error('Support for pool:false was removed in v4.0'); } config.pool =_.defaults(config.pool || {}, defaultPoolingConfig, { validate: this._validate.bind(this), Promise }) ; // Save a reference to the bound version so we can remove it with removeListener this.onProcessExit = this.onProcessExit.bind(this); process.on('exit', this.onProcessExit); this.initPools(); } refreshTypeParser(dataTypes) { _.each(dataTypes, dataType => { if (dataType.hasOwnProperty('parse')) { if (dataType.types[this.dialectName]) { this._refreshTypeParser(dataType); } else { throw new Error('Parse function not supported for type ' + dataType.key + ' in dialect ' + this.dialectName); } } }); } onProcessExit() { if (!this.pool) { return Promise.resolve(); } return this.pool.drain().then(() => { debug('connection drain due to process exit'); return this.pool.clear(); }); } close() { // Remove the listener, so all references to this instance can be garbage collected. process.removeListener('exit', this.onProcessExit); // Mark close of pool this.getConnection = function getConnection() { return Promise.reject(new Error('ConnectionManager.getConnection was called after the connection manager was closed!')); }; return this.onProcessExit(); } initPools() { const config = this.config; if (!config.replication) { this.pool = Pooling.createPool({ create: () => new Promise(resolve => { this ._connect(config) .tap(() => { this.poolError = null; }) .then(resolve) .catch(e => { // dont throw otherwise pool will release _dispense call // which will call _connect even if error is fatal // https://github.com/coopernurse/node-pool/issues/161 this.poolError = e; }); }), destroy: connection => { return this._disconnect(connection).tap(() => { debug('connection destroy'); }); }, validate: config.pool.validate }, { Promise: config.pool.Promise, max: config.pool.max, min: config.pool.min, testOnBorrow: true, autostart: false, acquireTimeoutMillis: config.pool.acquire, idleTimeoutMillis: config.pool.idle, evictionRunIntervalMillis: config.pool.evict }); this.pool.on('factoryCreateError', error => { this.poolError = error; }); debug(`pool created max/min: ${config.pool.max}/${config.pool.min} with no replication`); return; } let reads = 0; if (!Array.isArray(config.replication.read)) { config.replication.read = [config.replication.read]; } // Map main connection config config.replication.write = _.defaults(config.replication.write, _.omit(config, 'replication')); // Apply defaults to each read config config.replication.read = _.map(config.replication.read, readConfig => _.defaults(readConfig, _.omit(this.config, 'replication')) ); // custom pooling for replication (original author @janmeier) this.pool = { release: client => { if (client.queryType === 'read') { return this.pool.read.release(client); } else { return this.pool.write.release(client); } }, acquire: (priority, queryType, useMaster) => { useMaster = _.isUndefined(useMaster) ? false : useMaster; if (queryType === 'SELECT' && !useMaster) { return this.pool.read.acquire(priority); } else { return this.pool.write.acquire(priority); } }, destroy: connection => { debug('connection destroy'); return this.pool[connection.queryType].destroy(connection); }, clear: () => { debug('all connection clear'); return Promise.join( this.pool.read.clear(), this.pool.write.clear() ); }, drain: () => { return Promise.join( this.pool.write.drain(), this.pool.read.drain() ); }, read: Pooling.createPool({ create: () => { const nextRead = reads++ % config.replication.read.length; // round robin config return new Promise(resolve => { this ._connect(config.replication.read[nextRead]) .tap(connection => { connection.queryType = 'read'; this.poolError = null; resolve(connection); }) .catch(e => { this.poolError = e; }); }); }, destroy: connection => { return this._disconnect(connection); }, validate: config.pool.validate }, { Promise: config.pool.Promise, max: config.pool.max, min: config.pool.min, testOnBorrow: true, autostart: false, acquireTimeoutMillis: config.pool.acquire, idleTimeoutMillis: config.pool.idle, evictionRunIntervalMillis: config.pool.evict }), write: Pooling.createPool({ create: () => new Promise(resolve => { this ._connect(config.replication.write) .then(connection => { connection.queryType = 'write'; this.poolError = null; return resolve(connection); }) .catch(e => { this.poolError = e; }); }), destroy: connection => { return this._disconnect(connection); }, validate: config.pool.validate }, { Promise: config.pool.Promise, max: config.pool.max, min: config.pool.min, testOnBorrow: true, autostart: false, acquireTimeoutMillis: config.pool.acquire, idleTimeoutMillis: config.pool.idle, evictionRunIntervalMillis: config.pool.evict }) }; this.pool.read.on('factoryCreateError', error => { this.poolError = error; }); this.pool.write.on('factoryCreateError', error => { this.poolError = error; }); } getConnection(options) { options = options || {}; let promise; if (this.sequelize.options.databaseVersion === 0) { if (this.versionPromise) { promise = this.versionPromise; } else { promise = this.versionPromise = this._connect(this.config.replication.write || this.config).then(connection => { const _options = {}; _options.transaction = {connection}; // Cheat .query to use our private connection _options.logging = () => {}; _options.logging.__testLoggingFn = true; return this.sequelize.databaseVersion(_options).then(version => { this.sequelize.options.databaseVersion = semver.valid(version) ? version : this.defaultVersion; this.versionPromise = null; return this._disconnect(connection); }); }).catch(err => { this.versionPromise = null; throw err; }); } } else { promise = Promise.resolve(); } return promise.then(() => { return Promise.race([ this.pool.acquire(options.priority, options.type, options.useMaster), new Promise((resolve, reject) => timers.setTimeout(() => { if (this.poolError) { reject(this.poolError); } }, 0)) ]) .tap(() => { debug('connection acquired'); }) .catch(e => { e = this.poolError || e; this.poolError = null; throw e; }); }); } releaseConnection(connection) { return this.pool.release(connection).tap(() => { debug('connection released'); }); } _connect(config) { return this.sequelize.runHooks('beforeConnect', config) .then(() => this.dialect.connectionManager.connect(config)) .then(connection => this.sequelize.runHooks('afterConnect', connection, config).return(connection)); } _disconnect(connection) { return this.dialect.connectionManager.disconnect(connection); } _validate(connection) { if (!this.dialect.connectionManager.validate) return true; return this.dialect.connectionManager.validate(connection); } } module.exports = ConnectionManager; module.exports.ConnectionManager = ConnectionManager; module.exports.default = ConnectionManager;
mit
gilsondev/login-cidadao
src/PROCERGS/LoginCidadao/NotificationBundle/Entity/PlaceholderRepository.php
1165
<?php namespace PROCERGS\LoginCidadao\NotificationBundle\Entity; use Doctrine\ORM\EntityRepository; use PROCERGS\LoginCidadao\CoreBundle\Model\PersonInterface; use PROCERGS\OAuthBundle\Model\ClientInterface; use Doctrine\ORM\QueryBuilder; class PlaceholderRepository extends EntityRepository { public function findOwnedPlaceholdersByCategoryId(PersonInterface $person, $categoryId) { return $this->getEntityManager() ->getRepository('PROCERGSLoginCidadaoNotificationBundle:Placeholder') ->createQueryBuilder('p') ->join('PROCERGSLoginCidadaoNotificationBundle:Category', 'cat', 'WITH', 'p.category = cat') ->join('PROCERGSOAuthBundle:Client', 'c', 'WITH', 'cat.client = c') ->where(':person MEMBER OF c.owners') ->andWhere('cat.id = :categoryId') ->setParameter('person', $person) ->setParameter('categoryId', $categoryId) ->orderBy('p.id', 'DESC') ->getQuery()->getResult(); } }
mit
dgreisen-cfpb/moirai
node_modules/pantheon-helpers/lib/loggers.js
915
// Generated by IcedCoffeeScript 1.8.0-c (function() { var bunyan, loggers, utils; bunyan = require('bunyan'); utils = require('./utils'); loggers = { makeLogger: function(defaultConfig, customConfig, logger) { var config; if (logger == null) { logger = bunyan; } config = utils.deepExtend(defaultConfig, customConfig); return logger.createLogger(config); }, makeLoggers: function(conf) { var loggerConf; loggerConf = conf.LOGGERS || {}; return { worker: loggers.makeLogger(loggers.getWorkerConfig(), loggerConf.WORKER), web: loggers.makeLogger(loggers.getWebConfig(), loggerConf.WEB) }; }, getWorkerConfig: function() { return { name: "worker" }; }, getWebConfig: function() { return { name: "web" }; } }; module.exports = loggers; }).call(this);
cc0-1.0
markoer/kura
kura/org.eclipse.kura.linux.net/src/main/java/org/eclipse/kura/internal/board/BoardPowerState.java
642
/******************************************************************************* * Copyright (c) 2018 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.internal.board; public enum BoardPowerState { ON, OFF, TURNING_ON, TURNING_OFF, RESETTING; }
epl-1.0
theoweiss/openhab2
bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/internal/handler/GenericMQTTThingHandler.java
7824
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.mqtt.generic.internal.handler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.type.ChannelTypeUID; import org.eclipse.smarthome.core.types.StateDescription; import org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection; import org.openhab.binding.mqtt.generic.AbstractMQTTThingHandler; import org.openhab.binding.mqtt.generic.ChannelConfig; import org.openhab.binding.mqtt.generic.ChannelState; import org.openhab.binding.mqtt.generic.ChannelStateTransformation; import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener; import org.openhab.binding.mqtt.generic.MqttChannelStateDescriptionProvider; import org.openhab.binding.mqtt.generic.TransformationServiceProvider; import org.openhab.binding.mqtt.generic.values.Value; import org.openhab.binding.mqtt.generic.values.ValueFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This handler manages manual created Things with manually added channels to link to MQTT topics. * * @author David Graeff - Initial contribution */ @NonNullByDefault public class GenericMQTTThingHandler extends AbstractMQTTThingHandler implements ChannelStateUpdateListener { private final Logger logger = LoggerFactory.getLogger(GenericMQTTThingHandler.class); final Map<ChannelUID, ChannelState> channelStateByChannelUID = new HashMap<>(); protected final MqttChannelStateDescriptionProvider stateDescProvider; protected final TransformationServiceProvider transformationServiceProvider; /** * Creates a new Thing handler for generic MQTT channels. * * @param thing The thing of this handler * @param stateDescProvider A channel state provider * @param transformationServiceProvider The transformation service provider * @param subscribeTimeout The subscribe timeout */ public GenericMQTTThingHandler(Thing thing, MqttChannelStateDescriptionProvider stateDescProvider, TransformationServiceProvider transformationServiceProvider, int subscribeTimeout) { super(thing, subscribeTimeout); this.stateDescProvider = stateDescProvider; this.transformationServiceProvider = transformationServiceProvider; } @Override public @Nullable ChannelState getChannelState(ChannelUID channelUID) { return channelStateByChannelUID.get(channelUID); } /** * Subscribe on all channel static topics on all {@link ChannelState}s. * If subscribing on all channels worked, the thing is put ONLINE, else OFFLINE. * * @param connection A started broker connection */ @Override protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) { List<CompletableFuture<@Nullable Void>> futures = channelStateByChannelUID.values().stream() .map(c -> c.start(connection, scheduler, 0)).collect(Collectors.toList()); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).thenRun(() -> { updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); }); } @Override protected void stop() { channelStateByChannelUID.values().forEach(c -> c.getCache().resetState()); } @Override public void dispose() { // Remove all state descriptions of this handler channelStateByChannelUID.forEach((uid, state) -> stateDescProvider.remove(uid)); channelStateByChannelUID.clear(); super.dispose(); } @Override public CompletableFuture<Void> unsubscribeAll() { return CompletableFuture.allOf(channelStateByChannelUID.values().stream().map(channel -> channel.stop()) .toArray(CompletableFuture[]::new)); } /** * For every Thing channel there exists a corresponding {@link ChannelState}. It consists of the MQTT state * and MQTT command topic, the ChannelUID and a value state. * * @param channelConfig The channel configuration that contains MQTT state and command topic and multiple other * configurations. * @param channelUID The channel UID * @param valueState The channel value state * @return */ protected ChannelState createChannelState(ChannelConfig channelConfig, ChannelUID channelUID, Value valueState) { ChannelState state = new ChannelState(channelConfig, channelUID, valueState, this); String[] transformations; // Incoming value transformations transformations = channelConfig.transformationPattern.split("∩"); Stream.of(transformations).filter(t -> StringUtils.isNotBlank(t)) .map(t -> new ChannelStateTransformation(t, transformationServiceProvider)) .forEach(t -> state.addTransformation(t)); // Outgoing value transformations transformations = channelConfig.transformationPatternOut.split("∩"); Stream.of(transformations).filter(t -> StringUtils.isNotBlank(t)) .map(t -> new ChannelStateTransformation(t, transformationServiceProvider)) .forEach(t -> state.addTransformationOut(t)); return state; } @Override public void initialize() { List<ChannelUID> configErrors = new ArrayList<>(); for (Channel channel : thing.getChannels()) { final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID(); if (channelTypeUID == null) { logger.warn("Channel {} has no type", channel.getLabel()); continue; } final ChannelConfig channelConfig = channel.getConfiguration().as(ChannelConfig.class); try { Value value = ValueFactory.createValueState(channelConfig, channelTypeUID.getId()); ChannelState channelState = createChannelState(channelConfig, channel.getUID(), value); channelStateByChannelUID.put(channel.getUID(), channelState); StateDescription description = value.createStateDescription(channelConfig.unit, StringUtils.isBlank(channelConfig.commandTopic)); stateDescProvider.setDescription(channel.getUID(), description); } catch (IllegalArgumentException e) { logger.warn("Channel configuration error", e); configErrors.add(channel.getUID()); } } // If some channels could not start up, put the entire thing offline and display the channels // in question to the user. if (configErrors.isEmpty()) { super.initialize(); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remove and recreate: " + configErrors.stream().map(e -> e.getAsString()).collect(Collectors.joining(","))); } } }
epl-1.0
RallySoftware/eclipselink.runtime
jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/jpa/metadata/FileBasedProjectCache.java
5155
/******************************************************************************* * Copyright (c) 2012, 2016 Oracle and/or its affiliates, IBM Corporation. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 08/01/2012-2.5 Chris Delahunt - Bug 371950 - Metadata caching * 08/29/2016 Jody Grassel * - 500441: Eclipselink core has System.getProperty() calls that are not potentially executed under doPriv() ******************************************************************************/ package org.eclipse.persistence.jpa.metadata; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.security.AccessController; import java.util.Map; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.security.PrivilegedGetSystemProperty; import org.eclipse.persistence.logging.SessionLog; import org.eclipse.persistence.sessions.Project; /** * <p><b>Purpose</b>: Support serializing/deserializing a project representing application metadata * to/from a file. * */ public class FileBasedProjectCache implements ProjectCache { @Override public Project retrieveProject(Map properties, ClassLoader loader, SessionLog log) { Project project = null; java.io.ObjectInputStream in = null; String fileName = (String)getConfigPropertyLogDebug( PersistenceUnitProperties.PROJECT_CACHE_FILE, properties, log); if (fileName != null && fileName.length() > 0) { try { java.io.File file = new java.io.File(fileName); java.io.FileInputStream fis = new java.io.FileInputStream(file); in = new java.io.ObjectInputStream(fis); project = (Project)in.readObject(); } catch (Exception e) { //need exception differentiation,logging and warnings //the project not being cached should be different than an exception from reading the stream log.logThrowable(SessionLog.WARNING, SessionLog.JPA, e); } finally { if (in != null) { try { in.close(); } catch (java.io.IOException ignore) { //ignore exceptions from close } } } } return project; } @Override public void storeProject(Project project, Map properties, SessionLog log) { String fileName = (String)getConfigPropertyLogDebug( PersistenceUnitProperties.PROJECT_CACHE_FILE, properties, log); if (fileName != null && fileName.length() > 0) { FileOutputStream fos = null; ObjectOutputStream out = null; try { File file = new File(fileName); // creates the file file.createNewFile(); fos = new FileOutputStream(file); out = new ObjectOutputStream(fos); out.writeObject(project); } catch (Exception e) { //the session is still usable, just not cachable so log a warning log.logThrowable(SessionLog.WARNING, SessionLog.JPA, e); } finally { try { if (out != null) { out.close(); fos = null; } if (fos != null) { fos.close(); } } catch (java.io.IOException ignore) {} } } } /** * Check the provided map for an object with the given name. If that object is not available, check the * System properties. Log the value returned if logging is enabled at the FINEST level * @param propertyName * @param properties * @param log * @return */ public Object getConfigPropertyLogDebug(final String propertyName, Map properties, SessionLog log) { Object value = null; if (properties != null) { value = properties.get(propertyName); } if (value == null) { if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { value = AccessController.doPrivileged(new PrivilegedGetSystemProperty(propertyName)); } else { value = System.getProperty(propertyName); } } if ((value != null) && (log != null)) { log.log(SessionLog.FINEST, SessionLog.PROPERTIES, "property_value_specified", new Object[]{propertyName, value}); } return value; } }
epl-1.0
Lsty/ygopro-scripts
c18489208.lua
1571
--カースド・フィグ function c18489208.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(18489208,0)) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_BATTLE_DESTROYED) e1:SetCondition(c18489208.con) e1:SetTarget(c18489208.tg) e1:SetOperation(c18489208.op) c:RegisterEffect(e1) end function c18489208.con(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE) end function c18489208.tg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_SZONE) and chkc:IsFacedown() end if chk==0 then return Duel.IsExistingTarget(Card.IsFacedown,tp,LOCATION_SZONE,LOCATION_SZONE,2,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEDOWN) Duel.SelectTarget(tp,Card.IsFacedown,tp,LOCATION_SZONE,LOCATION_SZONE,2,2,nil) end function c18489208.op(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsLocation(LOCATION_GRAVE) then return end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc=g:GetFirst() while tc do if c:IsRelateToEffect(e) and tc:IsFacedown() and tc:IsRelateToEffect(e) then c:SetCardTarget(tc) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_TRIGGER) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetCondition(c18489208.rcon) e1:SetValue(1) tc:RegisterEffect(e1) end tc=g:GetNext() end end function c18489208.rcon(e) return e:GetOwner():IsHasCardTarget(e:GetHandler()) end
gpl-2.0
moveable-dev1/rep1
wp-content/plugins/gravityforms/entry_list.php
58835
<?php if ( ! class_exists( 'GFForms' ) ) { die(); } class GFEntryList { public static function all_leads_page() { if ( ! GFCommon::ensure_wp_version() ) { return; } $forms = RGFormsModel::get_forms( null, 'title' ); $id = RGForms::get( 'id' ); if ( sizeof( $forms ) == 0 ) { ?> <div style="margin:50px 0 0 10px;"> <?php echo sprintf( esc_html__( "You don't have any active forms. Let's go %screate one%s", 'gravityforms' ), '<a href="?page=gf_new_form">', '</a>' ); ?> </div> <?php } else { if ( empty( $id ) ) { $id = $forms[0]->id; } self::leads_page( $id ); } } public static function leads_page( $form_id ) { global $wpdb; //quit if version of wp is not supported if ( ! GFCommon::ensure_wp_version() ) { return; } $form_id = absint( $form_id ); echo GFCommon::get_remote_message(); $action = RGForms::post( 'action' ); $filter = rgget( 'filter' ); $search = stripslashes( rgget( 's' ) ); $page_index = empty( $_GET['paged'] ) ? 0 : intval( $_GET['paged'] ) - 1; $star = $filter == 'star' ? 1 : null; $read = $filter == 'unread' ? 0 : null; $status = in_array( $filter, array( 'trash', 'spam' ) ) ? $filter : 'active'; $form = RGFormsModel::get_form_meta( $form_id ); $search_criteria['status'] = $status; if ( $star ) { $search_criteria['field_filters'][] = array( 'key' => 'is_starred', 'value' => (bool) $star ); } if ( ! is_null( $read ) ) { $search_criteria['field_filters'][] = array( 'key' => 'is_read', 'value' => (bool) $read ); } $search_field_id = rgget( 'field_id' ); $search_operator = rgget( 'operator' ); if ( isset( $_GET['field_id'] ) && $_GET['field_id'] !== '' ) { $key = $search_field_id; $val = stripslashes( rgget( 's' ) ); $strpos_row_key = strpos( $search_field_id, '|' ); if ( $strpos_row_key !== false ) { //multi-row likert $key_array = explode( '|', $search_field_id ); $key = $key_array[0]; $val = $key_array[1] . ':' . $val; } if ( 'entry_id' == $key ) { $key = 'id'; } $filter_operator = empty( $search_operator ) ? 'is' : $search_operator; $field = GFFormsModel::get_field( $form, $key ); if ( $field ) { $input_type = GFFormsModel::get_input_type( $field ); if ( $field->type == 'product' && in_array( $input_type, array( 'radio', 'select' ) ) ) { $filter_operator = 'contains'; } } $search_criteria['field_filters'][] = array( 'key' => $key, 'operator' => $filter_operator, 'value' => $val, ); } $update_message = ''; switch ( $action ) { case 'delete' : check_admin_referer( 'gforms_entry_list', 'gforms_entry_list' ); $lead_id = $_POST['action_argument']; if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { RGFormsModel::delete_lead( $lead_id ); $update_message = esc_html__( 'Entry deleted.', 'gravityforms' ); } else { $update_message = esc_html__( "You don't have adequate permission to delete entries.", 'gravityforms' ); } break; case 'bulk': check_admin_referer( 'gforms_entry_list', 'gforms_entry_list' ); $bulk_action = ! empty( $_POST['bulk_action'] ) ? $_POST['bulk_action'] : $_POST['bulk_action2']; $select_all = rgpost( 'all_entries' ); $leads = empty( $select_all ) ? $_POST['lead'] : GFFormsModel::search_lead_ids( $form_id, $search_criteria ); $entry_count = count( $leads ) > 1 ? sprintf( esc_html__( '%d entries', 'gravityforms' ), count( $leads ) ) : esc_html__( '1 entry', 'gravityforms' ); switch ( $bulk_action ) { case 'delete': if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { RGFormsModel::delete_leads( $leads ); $update_message = sprintf( esc_html__( '%s deleted.', 'gravityforms' ), $entry_count ); } else { $update_message = esc_html__( "You don't have adequate permission to delete entries.", 'gravityforms' ); } break; case 'trash': RGFormsModel::update_leads_property( $leads, 'status', 'trash' ); $update_message = sprintf( esc_html__( '%s moved to Trash.', 'gravityforms' ), $entry_count ); break; case 'restore': RGFormsModel::update_leads_property( $leads, 'status', 'active' ); $update_message = sprintf( esc_html__( '%s restored from the Trash.', 'gravityforms' ), $entry_count ); break; case 'unspam': RGFormsModel::update_leads_property( $leads, 'status', 'active' ); $update_message = sprintf( esc_html__( '%s restored from the spam.', 'gravityforms' ), $entry_count ); break; case 'spam': RGFormsModel::update_leads_property( $leads, 'status', 'spam' ); $update_message = sprintf( esc_html__( '%s marked as spam.', 'gravityforms' ), $entry_count ); break; case 'mark_read': RGFormsModel::update_leads_property( $leads, 'is_read', 1 ); $update_message = sprintf( esc_html__( '%s marked as read.', 'gravityforms' ), $entry_count ); break; case 'mark_unread': RGFormsModel::update_leads_property( $leads, 'is_read', 0 ); $update_message = sprintf( esc_html__( '%s marked as unread.', 'gravityforms' ), $entry_count ); break; case 'add_star': RGFormsModel::update_leads_property( $leads, 'is_starred', 1 ); $update_message = sprintf( esc_html__( '%s starred.', 'gravityforms' ), $entry_count ); break; case 'remove_star': RGFormsModel::update_leads_property( $leads, 'is_starred', 0 ); $update_message = sprintf( esc_html__( '%s unstarred.', 'gravityforms' ), $entry_count ); break; } break; case 'change_columns': check_admin_referer( 'gforms_entry_list', 'gforms_entry_list' ); $columns = GFCommon::json_decode( stripslashes( $_POST['grid_columns'] ), true ); RGFormsModel::update_grid_column_meta( $form_id, $columns ); break; } if ( rgpost( 'button_delete_permanently' ) ) { if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { RGFormsModel::delete_leads_by_form( $form_id, $filter ); } } $sort_field = empty( $_GET['sort'] ) ? 0 : $_GET['sort']; $sort_direction = empty( $_GET['dir'] ) ? 'DESC' : $_GET['dir']; $sort_field_meta = RGFormsModel::get_field( $form, $sort_field ); $is_numeric = $sort_field_meta['type'] == 'number'; $page_size = apply_filters( 'gform_entry_page_size', apply_filters( "gform_entry_page_size_{$form_id}", 20, $form_id ), $form_id ); $first_item_index = $page_index * $page_size; if ( ! empty( $sort_field ) ) { $sorting = array( 'key' => $_GET['sort'], 'direction' => $sort_direction, 'is_numeric' => $is_numeric ); } else { $sorting = array(); } $paging = array( 'offset' => $first_item_index, 'page_size' => $page_size ); $total_count = 0; $leads = GFAPI::get_entries( $form_id, $search_criteria, $sorting, $paging, $total_count ); $summary = RGFormsModel::get_form_counts( $form_id ); $active_lead_count = $summary['total']; $unread_count = $summary['unread']; $starred_count = $summary['starred']; $spam_count = $summary['spam']; $trash_count = $summary['trash']; $columns = RGFormsModel::get_grid_columns( $form_id, true ); $search_qs = empty( $search ) ? '' : '&s=' . esc_attr( urlencode( $search ) ); $sort_qs = empty( $sort_field ) ? '' : '&sort=' . esc_attr( $sort_field ); $dir_qs = empty( $sort_direction ) ? '' : '&dir=' . esc_attr( $sort_direction ); $star_qs = $star !== null ? '&star=' . esc_attr( $star ) : ''; $read_qs = $read !== null ? '&read=' . esc_attr( $read ) : ''; $filter_qs = '&filter=' . esc_attr( $filter ); $search_field_id_qs = ! isset( $_GET['field_id'] ) ? '' : '&field_id=' . esc_attr( $search_field_id ); $search_operator_urlencoded = urlencode( $search_operator ); $search_operator_qs = empty( $search_operator_urlencoded ) ? '' : '&operator=' . esc_attr( $search_operator_urlencoded ); $display_total = ceil( $total_count / $page_size ); $page_links = paginate_links( array( 'base' => admin_url( 'admin.php' ) . "?page=gf_entries&view=entries&id=$form_id&%_%" . $search_qs . $sort_qs . $dir_qs . $star_qs . $read_qs . $filter_qs . $search_field_id_qs . $search_operator_qs, 'format' => 'paged=%#%', 'prev_text' => esc_html__( '&laquo;', 'gravityforms' ), 'next_text' => esc_html__( '&raquo;', 'gravityforms' ), 'total' => $display_total, 'current' => $page_index + 1, 'show_all' => false, ) ); wp_print_styles( array( 'thickbox' ) ); $field_filters = GFCommon::get_field_filter_settings( $form ); $init_field_id = empty( $search_field_id ) ? 0 : $search_field_id; $init_field_operator = empty( $search_operator ) ? 'contains' : $search_operator; $init_filter_vars = array( 'mode' => 'off', 'filters' => array( array( 'field' => $init_field_id, 'operator' => $init_field_operator, 'value' => $search, ), ) ); $min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min'; ?> <script type="text/javascript"> var messageTimeout = false, gformFieldFilters = <?php echo json_encode( $field_filters ) ?>, gformInitFilter = <?php echo json_encode( $init_filter_vars ) ?> function ChangeColumns(columns) { jQuery("#action").val("change_columns"); jQuery("#grid_columns").val(jQuery.toJSON(columns)); tb_remove(); jQuery("#lead_form")[0].submit(); } function Search(sort_field_id, sort_direction, form_id, search, star, read, filter, field_id, operator) { var search_qs = search == "" ? "" : "&s=" + encodeURIComponent(search); var star_qs = star == "" ? "" : "&star=" + star; var read_qs = read == "" ? "" : "&read=" + read; var filter_qs = filter == "" ? "" : "&filter=" + filter; var field_id_qs = field_id == "" ? "" : "&field_id=" + field_id; var operator_qs = operator == "" ? "" : "&operator=" + operator; var location = "?page=gf_entries&view=entries&id=" + form_id + "&sort=" + sort_field_id + "&dir=" + sort_direction + search_qs + star_qs + read_qs + filter_qs + field_id_qs + operator_qs; document.location = location; } function ToggleStar(img, lead_id, filter) { var is_starred = img.src.indexOf("star1.png") >= 0; if (is_starred) img.src = img.src.replace("star1.png", "star0.png"); else img.src = img.src.replace("star0.png", "star1.png"); jQuery("#lead_row_" + lead_id).toggleClass("lead_starred"); //if viewing the starred entries, hide the row and adjust the paging counts if (filter == "star") { var title = jQuery("#lead_row_" + lead_id); title.css("display", 'none'); UpdatePagingCounts(1); } UpdateCount("star_count", is_starred ? -1 : 1); UpdateLeadProperty(lead_id, "is_starred", is_starred ? 0 : 1); } function ToggleRead(lead_id, filter) { var title = jQuery("#lead_row_" + lead_id); var marking_read = title.hasClass("lead_unread"); jQuery("#mark_read_" + lead_id).css("display", marking_read ? "none" : "inline"); jQuery("#mark_unread_" + lead_id).css("display", marking_read ? "inline" : "none"); jQuery("#is_unread_" + lead_id).css("display", marking_read ? "inline" : "none"); title.toggleClass("lead_unread"); //if viewing the unread entries, hide the row and adjust the paging counts if (filter == "unread") { title.css("display", "none"); UpdatePagingCounts(1); } UpdateCount("unread_count", marking_read ? -1 : 1); UpdateLeadProperty(lead_id, "is_read", marking_read ? 1 : 0); } function UpdateLeadProperty(lead_id, name, value) { var mysack = new sack("<?php echo admin_url( 'admin-ajax.php' )?>"); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar("action", "rg_update_lead_property"); mysack.setVar("rg_update_lead_property", "<?php echo wp_create_nonce( 'rg_update_lead_property' ) ?>"); mysack.setVar("lead_id", lead_id); mysack.setVar("name", name); mysack.setVar("value", value); mysack.onError = function () { alert(<?php echo json_encode( __( 'Ajax error while setting lead property', 'gravityforms' ) ); ?>) }; mysack.runAJAX(); return true; } function UpdateCount(element_id, change) { var element = jQuery("#" + element_id); var count = parseInt(element.html()) + change element.html(count + ""); } function UpdatePagingCounts(change) { //update paging header/footer Displaying # - # of #, use counts from header, no need to use footer since they are the same, just update footer paging with header info var paging_range_max_header = jQuery("#paging_range_max_header"); var paging_range_max_footer = jQuery("#paging_range_max_footer"); var range_change_max = parseInt(paging_range_max_header.html()) - change; var paging_total_header = jQuery("#paging_total_header"); var paging_total_footer = jQuery("#paging_total_footer"); var total_change = parseInt(paging_total_header.html()) - change; var paging_range_min_header = jQuery("#paging_range_min_header"); var paging_range_min_footer = jQuery("#paging_range_min_footer"); //if min and max are the same, this is the last entry item on the page, clear out the displaying # - # of # text if (parseInt(paging_range_min_header.html()) == parseInt(paging_range_max_header.html())) { var paging_header = jQuery("#paging_header"); paging_header.html(""); var paging_footer = jQuery("#paging_footer"); paging_footer.html(""); } else { paging_range_max_header.html(range_change_max + ""); paging_range_max_footer.html(range_change_max + ""); paging_total_header.html(total_change + ""); paging_total_footer.html(total_change + ""); } gformVars.countAllEntries = gformVars.countAllEntries - change; setSelectAllText(); } function DeleteLead(lead_id) { jQuery("#action").val("delete"); jQuery("#action_argument").val(lead_id); jQuery("#lead_form")[0].submit(); return true; } function handleBulkApply(actionElement) { var action = jQuery("#" + actionElement).val(); var defaultModalOptions = ''; var leadIds = getLeadIds(); if (leadIds.length == 0) { alert(<?php echo json_encode( __( 'Please select at least one entry.', 'gravityforms' ) ); ?>); return false; } switch (action) { case 'resend_notifications': resetResendNotificationsUI(); tb_show(<?php echo json_encode( esc_html__( 'Resend Notifications', 'gravityforms' ) ); ?>, '#TB_inline?width=350&amp;inlineId=notifications_modal_container', ''); return false; break; case 'print': resetPrintUI(); tb_show(<?php echo json_encode( esc_html__( 'Print Entries', 'gravityforms' ) ); ?>, '#TB_inline?width=350&amp;height=250&amp;inlineId=print_modal_container', ''); return false; break; default: jQuery('#action').val('bulk'); } } function getLeadIds() { var all = jQuery("#all_entries").val(); //compare string, the boolean isn't correct, even when casting to a boolean the 0 is set to true if (all == "1") return 0; var leads = jQuery(".check-column input[name='lead[]']:checked"); var leadIds = new Array(); jQuery(leads).each(function (i) { leadIds[i] = jQuery(leads[i]).val(); }); return leadIds; } function BulkResendNotifications() { var selectedNotifications = new Array(); jQuery(".gform_notifications:checked").each(function () { selectedNotifications.push(jQuery(this).val()); }); var leadIds = getLeadIds(); var sendTo = jQuery('#notification_override_email').val(); if (selectedNotifications.length <= 0) { displayMessage(<?php echo json_encode( esc_html__( 'You must select at least one type of notification to resend.', 'gravityforms' ) ); ?>, "error", "#notifications_container"); return; } jQuery('#please_wait_container').fadeIn(); jQuery.post(ajaxurl, { action : "gf_resend_notifications", gf_resend_notifications: '<?php echo wp_create_nonce( 'gf_resend_notifications' ); ?>', notifications : jQuery.toJSON(selectedNotifications), sendTo : sendTo, leadIds : leadIds, filter : <?php echo json_encode( rgget( 'filter' ) ) ?>, search : <?php echo json_encode( rgget( 's' ) ) ?>, operator : <?php echo json_encode( rgget( 'operator' ) ) ?>, fieldId : <?php echo json_encode( rgget( 'field_id' ) ) ?>, formId : <?php echo json_encode( $form['id'] ); ?> }, function (response) { jQuery('#please_wait_container').hide(); if (response) { displayMessage(response, 'error', '#notifications_container'); } else { var message = <?php echo json_encode( __( 'Notifications for %s were resent successfully.', 'gravityforms' ) ); ?>; var c = leadIds == 0 ? gformVars.countAllEntries : leadIds.length; displayMessage(message.replace('%s', c + ' ' + getPlural(c, <?php echo json_encode( __( 'entry', 'gravityforms' ) ); ?>, <?php echo json_encode( __( 'entries', 'gravityforms' ) ); ?>)), "updated", "#lead_form"); closeModal(true); } } ); } function resetResendNotificationsUI() { jQuery(".gform_notifications").attr('checked', false); jQuery('#notifications_container .message, #notifications_override_settings').hide(); } function BulkPrint() { var leadIds = getLeadIds(); if (leadIds != 0) leadIds = leadIds.join(','); var leadsQS = '&lid=' + leadIds; var notesQS = jQuery('#gform_print_notes').is(':checked') ? '&notes=1' : ''; var pageBreakQS = jQuery('#gform_print_page_break').is(':checked') ? '&page_break=1' : ''; var filterQS = '&filter=' + <?php echo json_encode( rgget( 'filter' ) ) ?>; var searchQS = '&s=' + <?php echo json_encode( rgget( 's' ) ) ?>; var searchFieldIdQS = '&field_id=' + <?php echo json_encode( rgget( 'field_id' ) ) ?>; var searchOperatorQS = '&operator=' + <?php echo json_encode( rgget( 'operator' ) ) ?>; var url = '<?php echo trailingslashit( site_url() ) ?>?gf_page=print-entry&fid=<?php echo absint( $form['id'] ) ?>' + leadsQS + notesQS + pageBreakQS + filterQS + searchQS + searchFieldIdQS + searchOperatorQS; window.open(url, 'printwindow'); closeModal(true); hideMessage('#lead_form', false); } function resetPrintUI() { jQuery('#print_options input[type="checkbox"]').attr('checked', false); } function displayMessage(message, messageClass, container) { hideMessage(container, true); var messageBox = jQuery('<div class="message ' + messageClass + '" style="display:none;"><p>' + message + '</p></div>'); jQuery(messageBox).prependTo(container).slideDown(); if (messageClass == 'updated') messageTimeout = setTimeout(function () { hideMessage(container, false); }, 10000); } function hideMessage(container, messageQueued) { if (messageTimeout) clearTimeout(messageTimeout); var messageBox = jQuery(container).find('.message'); if (messageQueued) jQuery(messageBox).remove(); else jQuery(messageBox).slideUp(function () { jQuery(this).remove(); }); } function closeModal(isSuccess) { if (isSuccess) jQuery('.check-column input[type="checkbox"]').attr('checked', false); tb_remove(); } function getPlural(count, singular, plural) { return count > 1 ? plural : singular; } function toggleNotificationOverride(isInit) { if (isInit) jQuery('#notification_override_email').val(''); if (jQuery(".gform_notifications:checked").length > 0) { jQuery('#notifications_override_settings').slideDown(); } else { jQuery('#notifications_override_settings').slideUp(function () { jQuery('#notification_override_email').val(''); }); } } // Select All var gformStrings = { "allEntriesOnPageAreSelected": <?php echo json_encode( sprintf( esc_html__( 'All %s{0}%s entries on this page are selected.', 'gravityforms' ), '<strong>', '</strong>' ) ); ?>, "selectAll" : <?php echo json_encode( sprintf( esc_html__( 'Select all %s{0}%s entries.', 'gravityforms' ), '<strong>', '</strong>' ) ); ?>, "allEntriesSelected" : <?php echo json_encode( sprintf( esc_html__( 'All %s{0}%s entries have been selected.', 'gravityforms' ), '<strong>', '</strong>' ) ); ?>, "clearSelection" : <?php echo json_encode( __( 'Clear selection', 'gravityforms' ) ); ?> } var gformVars = { "countAllEntries": <?php echo intval( $total_count ); ?>, "perPage" : <?php echo intval( $page_size ); ?> } function setSelectAllText() { var tr = getSelectAllText(); jQuery("#gform-select-all-message td").html(tr); } function getSelectAllText() { var count; count = jQuery("#gf_entry_list tr:visible:not('#gform-select-all-message')").length; return gformStrings.allEntriesOnPageAreSelected.format(count) + " <a href='javascript:void(0)' onclick='selectAllEntriesOnAllPages();'>" + gformStrings.selectAll.format(gformVars.countAllEntries) + "</a>"; } function getSelectAllTr() { var t = getSelectAllText(); var colspan = jQuery("#gf_entry_list").find("tr:first td").length + 1; return "<tr id='gform-select-all-message' style='display:none;background-color:lightyellow;text-align:center;'><td colspan='{0}'>{1}</td></tr>".format(colspan, t); } function toggleSelectAll(visible) { if (gformVars.countAllEntries <= gformVars.perPage) { jQuery('#gform-select-all-message').hide(); return; } if (visible) setSelectAllText(); jQuery('#gform-select-all-message').toggle(visible); } function clearSelectAllEntries() { jQuery(".check-column input[type=checkbox]").prop('checked', false); clearSelectAllMessage(); } function clearSelectAllMessage() { jQuery("#all_entries").val("0"); jQuery("#gform-select-all-message").hide(); jQuery("#gform-select-all-message td").html(''); } function selectAllEntriesOnAllPages() { var trHtmlClearSelection; trHtmlClearSelection = gformStrings.allEntriesSelected.format(gformVars.countAllEntries) + " <a href='javascript:void(0);' onclick='clearSelectAllEntries();'>" + gformStrings.clearSelection + "</a>"; jQuery("#all_entries").val("1"); jQuery("#gform-select-all-message td").html(trHtmlClearSelection); } function initSelectAllEntries() { if (gformVars.countAllEntries > gformVars.perPage) { var tr = getSelectAllTr(); jQuery("#gf_entry_list").prepend(tr); jQuery(".headercb").click(function () { toggleSelectAll(jQuery(this).prop('checked')); }); jQuery("#gf_entry_list .check-column input[type=checkbox]").click(function () { clearSelectAllMessage(); }) } } String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; // end Select All jQuery(document).ready(function () { var action = <?php echo json_encode( $action ); ?>; var message = <?php echo json_encode( $update_message ); ?>; if (action && message) displayMessage(message, 'updated', '#lead_form'); var list = jQuery("#gf_entry_list").wpList({ alt: <?php echo json_encode( esc_html__( 'Entry List', 'gravityforms' ) ) ?>}); list.bind('wpListDelEnd', function (e, s, list) { var currentStatus = <?php echo json_encode( $filter == 'trash' || $filter == 'spam' ? $filter : 'active' ); ?>; var filter = <?php echo json_encode( $filter ); ?>; var movingTo = "active"; if (s.data.status == "trash") movingTo = "trash"; else if (s.data.status == "spam") movingTo = "spam"; else if (s.data.status == "delete") movingTo = "delete"; var id = s.data.entry; var title = jQuery("#lead_row_" + id); var isUnread = title.hasClass("lead_unread"); var isStarred = title.hasClass("lead_starred"); if (movingTo != "delete") { //Updating All count var allCount = currentStatus == "active" ? -1 : 1; UpdateCount("all_count", allCount); //Updating Unread count if (isUnread) { var unreadCount = currentStatus == "active" ? -1 : 1; UpdateCount("unread_count", unreadCount); } //Updating Starred count if (isStarred) { var starCount = currentStatus == "active" ? -1 : 1; UpdateCount("star_count", starCount); } } //Updating Spam count if (currentStatus == "spam" || movingTo == "spam") { var spamCount = movingTo == "spam" ? 1 : -1; UpdateCount("spam_count", spamCount); //adjust paging counts if (filter == "spam") { UpdatePagingCounts(1); } else { UpdatePagingCounts(spamCount); } } //Updating trash count if (currentStatus == "trash" || movingTo == "trash") { var trashCount = movingTo == "trash" ? 1 : -1; UpdateCount("trash_count", trashCount); //adjust paging counts if (filter == "trash") { UpdatePagingCounts(1); } else { UpdatePagingCounts(trashCount); } } }); initSelectAllEntries(); jQuery('#entry_filters').gfFilterUI(gformFieldFilters, gformInitFilter, false); jQuery("#entry_filters").on("keypress", ".gform-filter-value", (function (event) { if (event.keyCode == 13) { Search(<?php echo json_encode( $sort_field ); ?>, <?php echo json_encode( $sort_direction ); ?>, <?php echo absint( $form_id ) ?>, jQuery('.gform-filter-value').val(), <?php echo json_encode( $star ); ?>, <?php echo json_encode( $read ); ?>, <?php echo json_encode( $filter ); ?>, jQuery('.gform-filter-field').val(), jQuery('.gform-filter-operator').val()); event.preventDefault(); } })); }); </script> <link rel="stylesheet" href="<?php echo GFCommon::get_base_url() ?>/css/admin<?php echo $min; ?>.css" type="text/css" /> <style> /*#TB_window { height: 400px !important; } #TB_ajaxContent[style] { height: 370px !important; }*/ .lead_unread a, .lead_unread td { font-weight: bold; } .lead_spam_trash a, .lead_spam_trash td { font-weight: normal; } .row-actions a { font-weight: normal; } .entry_nowrap { overflow: hidden; white-space: nowrap; } .gform-filter-operator { width: 100px } </style> <div class="wrap <?php echo GFCommon::get_browser_class() ?>"> <h2 class="gf_admin_page_title"> <span><?php esc_html_e( 'Entries', 'gravityforms' ) ?></span><span class="gf_admin_page_subtitle"><span class="gf_admin_page_formid">ID: <?php echo absint( $form['id'] ); ?></span><span class="gf_admin_page_formname"><?php esc_html_e( 'Form Name', 'gravityforms' ) ?>: <?php echo esc_html( $form['title'] ); ?></span></span> </h2> <?php RGForms::top_toolbar() ?> <form id="lead_form" method="post"> <?php wp_nonce_field( 'gforms_entry_list', 'gforms_entry_list' ) ?> <input type="hidden" value="" name="grid_columns" id="grid_columns" /> <input type="hidden" value="" name="action" id="action" /> <input type="hidden" value="" name="action_argument" id="action_argument" /> <input type="hidden" value="" name="all_entries" id="all_entries" /> <ul class="subsubsub"> <li> <a class="<?php echo empty( $filter ) ? 'current' : '' ?>" href="?page=gf_entries&view=entries&id=<?php echo absint( $form_id ) ?>"><?php _ex( 'All', 'Entry List', 'gravityforms' ); ?> <span class="count">(<span id="all_count"><?php echo $active_lead_count ?></span>)</span></a> | </li> <li> <a class="<?php echo $read !== null ? 'current' : '' ?>" href="?page=gf_entries&view=entries&id=<?php echo absint( $form_id ) ?>&filter=unread"><?php _ex( 'Unread', 'Entry List', 'gravityforms' ); ?> <span class="count">(<span id="unread_count"><?php echo $unread_count ?></span>)</span></a> | </li> <li> <a class="<?php echo $star !== null ? 'current' : '' ?>" href="?page=gf_entries&view=entries&id=<?php echo absint( $form_id ) ?>&filter=star"><?php _ex( 'Starred', 'Entry List', 'gravityforms' ); ?> <span class="count">(<span id="star_count"><?php echo $starred_count ?></span>)</span></a> | </li> <?php if ( GFCommon::spam_enabled( $form_id ) ) { ?> <li> <a class="<?php echo $filter == 'spam' ? 'current' : '' ?>" href="?page=gf_entries&view=entries&id=<?php echo absint( $form_id ) ?>&filter=spam"><?php esc_html_e( 'Spam', 'gravityforms' ); ?> <span class="count">(<span id="spam_count"><?php echo esc_html( $spam_count ); ?></span>)</span></a> | </li> <?php } ?> <li> <a class="<?php echo $filter == 'trash' ? 'current' : '' ?>" href="?page=gf_entries&view=entries&id=<?php echo absint( $form_id ) ?>&filter=trash"><?php esc_html_e( 'Trash', 'gravityforms' ); ?> <span class="count">(<span id="trash_count"><?php echo esc_html( $trash_count ); ?></span>)</span></a></li> </ul> <div style="margin-top:12px;float:right;"> <a style="float:right;" class="button" id="lead_search_button" href="javascript:Search('<?php echo esc_js( $sort_field ); ?>', '<?php echo esc_js( $sort_direction ) ?>', <?php echo absint( $form_id ); ?>, jQuery('.gform-filter-value').val(), '<?php echo esc_js( $star ); ?>', '<?php echo esc_js( $read ); ?>', '<?php echo esc_js( $filter ) ?>', jQuery('.gform-filter-field').val(), jQuery('.gform-filter-operator').val());"><?php esc_html_e( 'Search', 'gravityforms' ) ?></a> <div id="entry_filters" style="float:right"></div> </div> <div class="tablenav"> <div class="alignleft actions" style="padding:8px 0 7px 0;"> <label class="hidden" for="bulk_action"> <?php esc_html_e( 'Bulk action', 'gravityforms' ) ?></label> <select name="bulk_action" id="bulk_action"> <option value=''><?php esc_html_e( ' Bulk action ', 'gravityforms' ) ?></option> <?php switch ( $filter ) { case 'trash' : ?> <option value='restore'><?php esc_html_e( 'Restore', 'gravityforms' ) ?></option> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='delete'><?php esc_html_e( 'Delete Permanently', 'gravityforms' ) ?></option> <?php } break; case 'spam' : ?> <option value='unspam'><?php esc_html_e( 'Not Spam', 'gravityforms' ) ?></option> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='delete'><?php esc_html_e( 'Delete Permanently', 'gravityforms' ) ?></option> <?php } break; default: ?> <option value='mark_read'><?php esc_html_e( 'Mark as Read', 'gravityforms' ) ?></option> <option value='mark_unread'><?php esc_html_e( 'Mark as Unread', 'gravityforms' ) ?></option> <option value='add_star'><?php esc_html_e( 'Add Star', 'gravityforms' ) ?></option> <option value='remove_star'><?php esc_html_e( 'Remove Star', 'gravityforms' ) ?></option> <option value='resend_notifications'><?php esc_html_e( 'Resend Notifications', 'gravityforms' ) ?></option> <option value='print'><?php esc_html_e( 'Print', 'gravityforms' ) ?></option> <?php if ( GFCommon::spam_enabled( $form_id ) ) { ?> <option value='spam'><?php esc_html_e( 'Spam', 'gravityforms' ) ?></option> <?php } if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='trash'><?php esc_html_e( 'Trash', 'gravityforms' ) ?></option> <?php } }?> </select> <?php $apply_button = '<input type="submit" class="button" value="' . esc_attr__( 'Apply', 'gravityforms' ) . '" onclick="return handleBulkApply(\'bulk_action\');" />'; echo apply_filters( 'gform_entry_apply_button', $apply_button ); if ( in_array( $filter, array( 'trash', 'spam' ) ) ) { $message = $filter == 'trash' ? esc_html__( "WARNING! This operation cannot be undone. Empty trash? 'Ok' to empty trash. 'Cancel' to abort.", 'gravityforms' ) : esc_html__( "WARNING! This operation cannot be undone. Permanently delete all spam? 'Ok' to delete. 'Cancel' to abort.", 'gravityforms' ); $button_label = $filter == 'trash' ? __( 'Empty Trash', 'gravityforms' ) : __( 'Delete All Spam', 'gravityforms' ); ?> <input type="submit" class="button" name="button_delete_permanently" value="<?php echo esc_attr( $button_label ); ?>" onclick="return confirm('<?php echo esc_js( $message ) ?>');" /> <?php } ?> <div id="notifications_modal_container" style="display:none;"> <div id="notifications_container"> <div id="post_tag" class="tagsdiv"> <div id="resend_notifications_options"> <?php $notifications = GFCommon::get_notifications( 'resend_notifications', $form ); if ( ! is_array( $notifications ) || count( $form['notifications'] ) <= 0 ) { ?> <p class="description"><?php esc_html_e( 'You cannot resend notifications for these entries because this form does not currently have any notifications configured.', 'gravityforms' ); ?></p> <a href="<?php echo esc_url( admin_url( "admin.php?page=gf_edit_forms&view=settings&subview=notification&id={$form['id']}" ) ); ?>" class="button"><?php esc_html_e( 'Configure Notifications', 'gravityforms' ) ?></a> <?php } else { ?> <p class="description"><?php esc_html_e( 'Specify which notifications you would like to resend for the selected entries.', 'gravityforms' ); ?></p> <?php foreach ( $notifications as $notification ) { ?> <input type="checkbox" class="gform_notifications" value="<?php echo esc_attr( $notification['id'] ); ?>" id="notification_<?php echo esc_attr( $notification['id'] ); ?>" onclick="toggleNotificationOverride();" /> <label for="notification_<?php echo esc_attr( $notification['id'] ); ?>"><?php echo esc_html( $notification['name'] ); ?></label> <br /><br /> <?php } ?> <div id="notifications_override_settings" style="display:none;"> <p class="description" style="padding-top:0; margin-top:0;"> <?php esc_html_e( 'You may override the default notification settings by entering a comma delimited list of emails to which the selected notifications should be sent.', 'gravityforms' ); ?> </p> <label for="notification_override_email"><?php esc_html_e( 'Send To', 'gravityforms' ); ?> <?php gform_tooltip( 'notification_override_email' ) ?></label><br /> <input type="text" name="notification_override_email" id="notification_override_email" style="width:99%;" /><br /><br /> </div> <input type="button" name="notification_resend" id="notification_resend" value="<?php esc_attr_e( 'Resend Notifications', 'gravityforms' ) ?>" class="button" style="" onclick="BulkResendNotifications();" /> <span id="please_wait_container" style="display:none; margin-left: 5px;"> <i class='gficon-gravityforms-spinner-icon gficon-spin'></i> <?php esc_html_e( 'Resending...', 'gravityforms' ); ?> </span> <?php } ?> </div> <div id="resend_notifications_close" style="display:none;margin:10px 0 0;"> <input type="button" name="resend_notifications_close_button" value="<?php esc_attr_e( 'Close Window', 'gravityforms' ) ?>" class="button" style="" onclick="closeModal(true);" /> </div> </div> </div> </div> <!-- / Resend Notifications --> <div id="print_modal_container" style="display:none;"> <div id="print_container"> <div class="tagsdiv"> <div id="print_options"> <p class="description"><?php esc_html_e( 'Print all of the selected entries at once.', 'gravityforms' ); ?></p> <?php if ( GFCommon::current_user_can_any( 'gravityforms_view_entry_notes' ) ) { ?> <input type="checkbox" name="gform_print_notes" value="print_notes" checked="checked" id="gform_print_notes" /> <label for="gform_print_notes"><?php esc_html_e( 'Include notes', 'gravityforms' ); ?></label> <br /><br /> <?php } ?> <input type="checkbox" name="gform_print_page_break" value="print_notes" checked="checked" id="gform_print_page_break" /> <label for="gform_print_page_break"><?php esc_html_e( 'Add page break between entries', 'gravityforms' ); ?></label> <br /><br /> <input type="button" value="<?php esc_attr_e( 'Print', 'gravityforms' ); ?>" class="button" onclick="BulkPrint();" /> </div> </div> </div> </div> <!-- / Print --> </div> <?php echo self::display_paging_links( 'header', $page_links, $first_item_index, $page_size, $total_count ); ?> <div class="clear"></div> </div> <table class="widefat fixed" cellspacing="0"> <thead> <tr> <th scope="col" id="cb" class="manage-column column-cb check-column"> <input type="checkbox" class="headercb" /></th> <?php if ( ! in_array( $filter, array( 'spam', 'trash' ) ) ) { ?> <th scope="col" id="cb" class="manage-column column-cb check-column">&nbsp;</th> <?php } foreach ( $columns as $field_id => $field_info ) { $dir = $field_id == 0 ? 'DESC' : 'ASC'; //default every field so ascending sorting except date_created (id=0) if ( $field_id == $sort_field ) { //reverting direction if clicking on the currently sorted field $dir = $sort_direction == 'ASC' ? 'DESC' : 'ASC'; } ?> <th scope="col" class="manage-column entry_nowrap" onclick="Search('<?php echo esc_js( $field_id ); ?>', '<?php echo esc_js( $dir ); ?>', <?php echo absint( $form_id ); ?>, '<?php echo esc_js( $search ); ?>', '<?php echo esc_js( $star );?>', '<?php echo esc_js( $read ); ?>', '<?php echo esc_js( $filter ); ?>', '<?php echo esc_js( $search_field_id ); ?>', '<?php echo esc_js( $search_operator ); ?>');" style="cursor:pointer;"><?php echo esc_html( $field_info['label'] ) ?></th> <?php } ?> <th scope="col" align="right" width="50"> <a title="<?php esc_attr_e( 'click to select columns to display', 'gravityforms' ) ?>" href="<?php echo trailingslashit( site_url( null, 'admin' ) ) ?>?gf_page=select_columns&id=<?php echo absint( $form_id ); ?>&TB_iframe=true&height=365&width=600" class="thickbox entries_edit_icon"><i class="fa fa-cog"></i></a> </th> </tr> </thead> <tfoot> <tr> <th scope="col" id="cb" class="manage-column column-cb check-column" style=""><input type="checkbox" /></th> <?php if ( ! in_array( $filter, array( 'spam', 'trash' ) ) ) { ?> <th scope="col" id="cb" class="manage-column column-cb check-column">&nbsp;</th> <?php } foreach ( $columns as $field_id => $field_info ) { $dir = $field_id == 0 ? 'DESC' : 'ASC'; //default every field so ascending sorting except date_created (id=0) if ( $field_id == $sort_field ) { //reverting direction if clicking on the currently sorted field $dir = $sort_direction == 'ASC' ? 'DESC' : 'ASC'; } ?> <th scope="col" class="manage-column entry_nowrap" onclick="Search('<?php echo esc_js( $field_id ); ?>', '<?php echo esc_js( $dir ); ?>', <?php echo absint( $form_id ); ?>, '<?php echo esc_js( $search ); ?>', '<?php echo esc_js( $star ); ?>', '<?php echo esc_js( $read ); ?>', '<?php echo esc_js( $filter ); ?>');" style="cursor:pointer;"><?php echo esc_html( $field_info['label'] ) ?></th> <?php } ?> <th scope="col" style="width:15px;"> <a title="<?php esc_attr_e( 'click to select columns to display', 'gravityforms' ) ?>" href="<?php echo trailingslashit( site_url() ) ?>?gf_page=select_columns&id=<?php echo absint( $form_id ); ?>&TB_iframe=true&height=365&width=600" class="thickbox entries_edit_icon"><i class=fa-cog"></i></a> </th> </tr> </tfoot> <tbody data-wp-lists="list:gf_entry" class="user-list" id="gf_entry_list"> <?php if ( sizeof( $leads ) > 0 ) { $field_ids = array_keys( $columns ); $gf_entry_locking = new GFEntryLocking(); $alternate_row = false; foreach ( $leads as $position => $lead ) { $position = ( $page_size * $page_index ) + $position; ?> <tr id="lead_row_<?php echo esc_attr( $lead['id'] ) ?>" class='author-self status-inherit <?php echo $lead['is_read'] ? '' : 'lead_unread' ?> <?php echo $lead['is_starred'] ? 'lead_starred' : '' ?> <?php echo in_array( $filter, array( 'trash', 'spam' ) ) ? 'lead_spam_trash' : '' ?> <?php $gf_entry_locking->list_row_class( $lead['id'] ); ?> <?php echo ( $alternate_row = ! $alternate_row ) ? 'alternate' : '' ?>' valign="top" data-id="<?php echo esc_attr( $lead['id'] ) ?>"> <th scope="row" class="check-column"> <input type="checkbox" name="lead[]" value="<?php echo esc_attr( $lead['id'] ); ?>" /> <?php $gf_entry_locking->lock_indicator(); ?> </th> <?php if ( ! in_array( $filter, array( 'spam', 'trash' ) ) ) { ?> <td> <img id="star_image_<?php echo esc_attr( $lead['id'] ) ?>" src="<?php echo GFCommon::get_base_url() ?>/images/star<?php echo intval( $lead['is_starred'] ) ?>.png" onclick="ToggleStar(this, '<?php echo esc_js( $lead['id'] ); ?>','<?php echo esc_js( $filter ); ?>');" /> </td> <?php } $is_first_column = true; $nowrap_class = 'entry_nowrap'; foreach ( $field_ids as $field_id ) { $field = RGFormsModel::get_field( $form, $field_id ); $value = rgar( $lead, $field_id ); if ( ! empty( $field ) && $field->type == 'post_category' ) { $value = GFCommon::prepare_post_category_value( $value, $field, 'entry_list' ); } //filtering lead value $value = apply_filters( 'gform_get_field_value', $value, $lead, $field ); $input_type = ! empty( $columns[ $field_id ]['inputType'] ) ? $columns[ $field_id ]['inputType'] : $columns[ $field_id ]['type']; switch ( $input_type ) { case 'source_url' : $value = "<a href='" . esc_attr( $lead['source_url'] ) . "' target='_blank' alt='" . esc_attr( $lead['source_url'] ) . "' title='" . esc_attr( $lead['source_url'] ) . "'>.../" . esc_attr( GFCommon::truncate_url( $lead['source_url'] ) ) . '</a>'; break; case 'date_created' : case 'payment_date' : $value = GFCommon::format_date( $value, false ); break; case 'payment_amount' : $value = GFCommon::to_money( $value, $lead['currency'] ); break; case 'created_by' : if ( ! empty( $value ) ) { $userdata = get_userdata( $value ); if ( ! empty( $userdata ) ) { $value = $userdata->user_login; } } break; default: if ( $field !== null ) { $value = $field->get_value_entry_list( $value, $lead, $field_id, $columns, $form ); } else { $value = esc_html( $value ); } } $value = apply_filters( 'gform_entries_field_value', $value, $form_id, $field_id, $lead ); /* ^ maybe move to function */ $query_string = "gf_entries&view=entry&id={$form_id}&lid={$lead['id']}{$search_qs}{$sort_qs}{$dir_qs}{$filter_qs}&paged=" . ( $page_index + 1 ); if ( $is_first_column ) { ?> <td class="column-title"> <a href="admin.php?page=gf_entries&view=entry&id=<?php echo absint( $form_id ); ?>&lid=<?php echo esc_attr( $lead['id'] . $search_qs . $sort_qs . $dir_qs . $filter_qs ); ?>&paged=<?php echo( $page_index + 1 ) ?>&pos=<?php echo $position; ?>&field_id=<?php echo esc_attr( $search_field_id ); ?>&operator=<?php echo esc_attr( $search_operator ); ?>"><?php echo $value; ?></a> <?php $gf_entry_locking->lock_info( $lead['id'] ); ?> <div class="row-actions"> <?php switch ( $filter ) { case 'trash' : ?> <span class="edit"> <a title="<?php esc_attr_e( 'View this entry', 'gravityforms' ); ?>" href="admin.php?page=gf_entries&view=entry&id=<?php echo absint( $form_id ); ?>&lid=<?php echo esc_attr( $lead['id'] . $search_qs . $sort_qs . $dir_qs . $filter_qs ); ?>&paged=<?php echo( $page_index + 1 ) ?>&pos=<?php echo $position; ?>&field_id=<?php echo esc_attr( $search_field_id ); ?>&operator=<?php echo esc_attr( $search_operator ); ?>"><?php esc_html_e( 'View', 'gravityforms' ); ?></a> | </span> <span class="edit"> <a data-wp-lists='delete:gf_entry_list:lead_row_<?php echo esc_attr( $lead['id'] );?>::status=active&entry=<?php echo esc_attr( $lead['id'] ); ?>' title="<?php esc_attr_e( 'Restore this entry', 'gravityforms' ) ?>" href="<?php echo wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) ?>"><?php esc_html_e( 'Restore', 'gravityforms' ); ?></a> <?php echo GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ? '|' : '' ?> </span> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <span class="delete"> <?php $delete_link = '<a data-wp-lists="delete:gf_entry_list:lead_row_' . esc_attr( $lead['id'] ) . '::status=delete&entry=' . esc_attr( $lead['id'] ) . '" title="' . esc_attr__( 'Delete this entry permanently', 'gravityforms' ) . '" href="' . wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) . '">' . esc_html__( 'Delete Permanently', 'gravityforms' ) . '</a>'; echo apply_filters( 'gform_delete_entry_link', $delete_link ); ?> </span> <?php } break; case 'spam' : ?> <span class="edit"> <a title="<?php esc_attr_e( 'View this entry', 'gravityforms' ); ?>" href="admin.php?page=gf_entries&view=entry&id=<?php echo absint( $form_id ); ?>&lid=<?php echo esc_attr( $lead['id'] . $search_qs . $sort_qs . $dir_qs . $filter_qs ); ?>&paged=<?php echo( $page_index + 1 ) ?>&pos=<?php echo $position; ?>"><?php esc_html_e( 'View', 'gravityforms' ); ?></a> | </span> <span class="unspam"> <a data-wp-lists='delete:gf_entry_list:lead_row_<?php echo esc_attr( $lead['id'] ); ?>::status=unspam&entry=<?php echo esc_attr( $lead['id'] ); ?>' title="<?php esc_attr_e( 'Mark this entry as not spam', 'gravityforms' ) ?>" href="<?php echo wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) ?>"><?php esc_html_e( 'Not Spam', 'gravityforms' ); ?></a> <?php echo GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ? '|' : '' ?> </span> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <span class="delete"> <?php $delete_link = '<a data-wp-lists="delete:gf_entry_list:lead_row_' . esc_attr( $lead['id'] ) . '::status=delete&entry=' . esc_attr( $lead['id'] ) . '" title="' . esc_attr__( 'Delete this entry permanently', 'gravityforms' ) . '" href="' . wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) . '">' . esc_html__( 'Delete Permanently', 'gravityforms' ) . '</a>'; echo apply_filters( 'gform_delete_entry_link', $delete_link ); ?> </span> <?php } break; default: ?> <span class="edit"> <a title="<?php esc_attr_e( 'View this entry', 'gravityforms' ); ?>" href="admin.php?page=gf_entries&view=entry&id=<?php echo absint( $form_id ); ?>&lid=<?php echo esc_attr( $lead['id'] . $search_qs . $sort_qs . $dir_qs . $filter_qs ); ?>&paged=<?php echo( $page_index + 1 ) ?>&pos=<?php echo $position; ?>&field_id=<?php echo esc_attr( $search_field_id ); ?>&operator=<?php echo esc_attr( $search_operator ); ?>"><?php esc_html_e( 'View', 'gravityforms' ); ?></a> | </span> <span class="edit"> <a id="mark_read_<?php echo esc_attr( $lead['id'] ); ?>" title="Mark this entry as read" href="javascript:ToggleRead('<?php echo esc_js( $lead['id'] ); ?>', '<?php echo esc_js( $filter ); ?>');" style="display:<?php echo $lead['is_read'] ? 'none' : 'inline' ?>;"><?php esc_html_e( 'Mark read', 'gravityforms' ); ?></a><a id="mark_unread_<?php echo absint( $lead['id'] ); ?>" title="<?php esc_attr_e( 'Mark this entry as unread', 'gravityforms' ); ?>" href="javascript:ToggleRead('<?php echo esc_js( $lead['id'] ); ?>', '<?php echo esc_js( $filter ); ?>');" style="display:<?php echo $lead['is_read'] ? 'inline' : 'none' ?>;"><?php esc_html_e( 'Mark unread', 'gravityforms' ); ?></a> <?php echo GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) || GFCommon::akismet_enabled( $form_id ) ? '|' : '' ?> </span> <?php if ( GFCommon::spam_enabled( $form_id ) ) { ?> <span class="spam"> <a data-wp-lists='delete:gf_entry_list:lead_row_<?php echo esc_attr( $lead['id'] ) ?>::status=spam&entry=<?php echo esc_attr( $lead['id'] ); ?>' title="<?php esc_attr_e( 'Mark this entry as spam', 'gravityforms' ) ?>" href="<?php echo wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) ?>"><?php esc_html_e( 'Spam', 'gravityforms' ); ?></a> <?php echo GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ? '|' : '' ?> </span> <?php } if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <span class="trash"> <a data-wp-lists='delete:gf_entry_list:lead_row_<?php echo esc_attr( $lead['id'] ); ?>::status=trash&entry=<?php echo esc_attr( $lead['id'] ); ?>' title="<?php esc_attr_e( 'Move this entry to the trash', 'gravityforms' ) ?>" href="<?php echo wp_nonce_url( '?page=gf_entries', 'gf_delete_entry' ) ?>"><?php esc_html_e( 'Trash', 'gravityforms' ); ?></a> </span> <?php } break; } do_action( 'gform_entries_first_column_actions', $form_id, $field_id, $value, $lead, $query_string ); ?> </div> <?php do_action( 'gform_entries_first_column', $form_id, $field_id, $value, $lead, $query_string ); ?> </td> <?php } else { ?> <td class="<?php echo $nowrap_class ?>"> <?php echo apply_filters( 'gform_entries_column_filter', $value, $form_id, $field_id, $lead, $query_string ); ?>&nbsp; <?php do_action( 'gform_entries_column', $form_id, $field_id, $value, $lead, $query_string ); ?> </td> <?php } $is_first_column = false; } ?> <td>&nbsp;</td> </tr> <?php } } else { $column_count = sizeof( $columns ) + 3; switch ( $filter ) { case 'unread' : $message = isset( $_GET['field_id'] ) ? esc_html__( 'This form does not have any unread entries matching the search criteria.', 'gravityforms' ) : esc_html__( 'This form does not have any unread entries.', 'gravityforms' ); break; case 'star' : $message = isset( $_GET['field_id'] ) ? esc_html__( 'This form does not have any starred entries matching the search criteria.', 'gravityforms' ) : esc_html__( 'This form does not have any starred entries.', 'gravityforms' ); break; case 'spam' : $message = esc_html__( 'This form does not have any spam.', 'gravityforms' ); $column_count = sizeof( $columns ) + 2; break; case 'trash' : $message = isset( $_GET['field_id'] ) ? esc_html__( 'This form does not have any entries in the trash matching the search criteria.', 'gravityforms' ) : esc_html__( 'This form does not have any entries in the trash.', 'gravityforms' ); $column_count = sizeof( $columns ) + 2; break; default : $message = isset( $_GET['field_id'] ) ? esc_html__( 'This form does not have any entries matching the search criteria.', 'gravityforms' ) : esc_html__( 'This form does not have any entries yet.', 'gravityforms' ); } ?> <tr> <td colspan="<?php echo esc_attr( $column_count ) ?>" style="padding:20px;"><?php echo esc_html( $message ); ?></td> </tr> <?php } ?> </tbody> </table> <div class="clear"></div> <div class="tablenav"> <div class="alignleft actions" style="padding:8px 0 7px 0;"> <label class="hidden" for="bulk_action2"> <?php esc_html_e( 'Bulk action', 'gravityforms' ) ?></label> <select name="bulk_action2" id="bulk_action2"> <option value=''><?php esc_html_e( ' Bulk action ', 'gravityforms' ) ?></option> <?php switch ( $filter ) { case 'trash' : ?> <option value='restore'><?php esc_html_e( 'Restore', 'gravityforms' ) ?></option> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='delete'><?php esc_html_e( 'Delete Permanently', 'gravityforms' ) ?></option> <?php } break; case 'spam' : ?> <option value='unspam'><?php esc_html_e( 'Not Spam', 'gravityforms' ) ?></option> <?php if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='delete'><?php esc_html_e( 'Delete Permanently', 'gravityforms' ) ?></option> <?php } break; default: ?> <option value='mark_read'><?php esc_html_e( 'Mark as Read', 'gravityforms' ) ?></option> <option value='mark_unread'><?php esc_html_e( 'Mark as Unread', 'gravityforms' ) ?></option> <option value='add_star'><?php esc_html_e( 'Add Star', 'gravityforms' ) ?></option> <option value='remove_star'><?php esc_html_e( 'Remove Star', 'gravityforms' ) ?></option> <option value='resend_notifications'><?php esc_html_e( 'Resend Notifications', 'gravityforms' ) ?></option> <option value='print'><?php esc_html_e( 'Print Entries', 'gravityforms' ) ?></option> <?php if ( GFCommon::spam_enabled( $form_id ) ) { ?> <option value='spam'><?php esc_html_e( 'Spam', 'gravityforms' ) ?></option> <?php } if ( GFCommon::current_user_can_any( 'gravityforms_delete_entries' ) ) { ?> <option value='trash'><?php esc_html_e( 'Move to Trash', 'gravityforms' ) ?></option> <?php } }?> </select> <?php $apply_button = '<input type="submit" class="button" value="' . esc_attr__( 'Apply', 'gravityforms' ) . '" onclick="return handleBulkApply(\'bulk_action2\');" />'; echo apply_filters( 'gform_entry_apply_button', $apply_button ); ?> </div> <?php echo self::display_paging_links( 'footer', $page_links, $first_item_index, $page_size, $total_count ); ?> <div class="clear"></div> </div> </form> </div> <?php } public static function get_icon_url( $path ) { $info = pathinfo( $path ); switch ( strtolower( rgar( $info, 'extension' ) ) ) { case 'css' : $file_name = 'icon_css.gif'; break; case 'doc' : $file_name = 'icon_doc.gif'; break; case 'fla' : $file_name = 'icon_fla.gif'; break; case 'html' : case 'htm' : case 'shtml' : $file_name = 'icon_html.gif'; break; case 'js' : $file_name = 'icon_js.gif'; break; case 'log' : $file_name = 'icon_log.gif'; break; case 'mov' : $file_name = 'icon_mov.gif'; break; case 'pdf' : $file_name = 'icon_pdf.gif'; break; case 'php' : $file_name = 'icon_php.gif'; break; case 'ppt' : $file_name = 'icon_ppt.gif'; break; case 'psd' : $file_name = 'icon_psd.gif'; break; case 'sql' : $file_name = 'icon_sql.gif'; break; case 'swf' : $file_name = 'icon_swf.gif'; break; case 'txt' : $file_name = 'icon_txt.gif'; break; case 'xls' : $file_name = 'icon_xls.gif'; break; case 'xml' : $file_name = 'icon_xml.gif'; break; case 'zip' : $file_name = 'icon_zip.gif'; break; case 'gif' : case 'jpg' : case 'jpeg': case 'png' : case 'bmp' : case 'tif' : case 'eps' : $file_name = 'icon_image.gif'; break; case 'mp3' : case 'wav' : case 'wma' : $file_name = 'icon_audio.gif'; break; case 'mp4' : case 'avi' : case 'wmv' : case 'flv' : $file_name = 'icon_video.gif'; break; default: $file_name = 'icon_generic.gif'; break; } return GFCommon::get_base_url() . "/images/doctypes/$file_name"; } private static function update_message() { } private static function display_paging_links( $which, $page_links, $first_item_index, $page_size, $total_lead_count ) { //Displaying paging links if appropriate //$which - header or footer, so the items can have unique names if ( $page_links ) { $paging_html = ' <div class="tablenav-pages"> <span id="paging_' . $which . '" class="displaying-num">'; $range_max = '<span id="paging_range_max_' . $which . '">'; if ( ( $first_item_index + $page_size ) > $total_lead_count ) { $range_max .= $total_lead_count; } else { $range_max .= ( $first_item_index + $page_size ); } $range_max .= '</span>'; $range_min = '<span id="paging_range_min_' . $which . '">' . ( $first_item_index + 1 ) . '</span>'; $paging_total = '<span id="paging_total_' . $which . '">' . $total_lead_count . '</span>'; $paging_html .= sprintf( esc_html__( 'Displaying %s - %s of %s', 'gravityforms' ), $range_min, $range_max, $paging_total ); $paging_html .= '</span>' . $page_links . '</div>'; } else { $paging_html = ''; } return $paging_html; } }
gpl-2.0
mrkn/aquaskk
src/engine/editor/SKKTextBuffer.cpp
2301
/* -*- C++ -*- MacOS X implementation of the SKK input method. Copyright (C) 2008 Tomotaka SUWA <t.suwa@mac.com> 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 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 */ #include "SKKTextBuffer.h" #include "utf8util.h" SKKTextBuffer::SKKTextBuffer() : cursor_(0) {} void SKKTextBuffer::Insert(const std::string& str) { utf8::push(buf_, str, cursor_); } void SKKTextBuffer::BackSpace() { if(cursor_ != minCursorPosition()) { utf8::pop(buf_, cursor_); } } void SKKTextBuffer::Delete() { if(cursor_ != maxCursorPosition()) { CursorRight(); BackSpace(); } } void SKKTextBuffer::Clear() { buf_.clear(); cursor_ = 0; } void SKKTextBuffer::CursorLeft() { if(cursor_ != minCursorPosition()) { -- cursor_; } } void SKKTextBuffer::CursorRight() { if(cursor_ != maxCursorPosition()) { ++ cursor_; } } void SKKTextBuffer::CursorUp() { cursor_ = minCursorPosition(); } void SKKTextBuffer::CursorDown() { cursor_ = maxCursorPosition(); } int SKKTextBuffer::CursorPosition() const { return cursor_; } bool SKKTextBuffer::IsEmpty() const { return buf_.empty(); } bool SKKTextBuffer::operator==(const std::string& str) const { return buf_ == str; } std::string SKKTextBuffer::String() const { return buf_; } std::string SKKTextBuffer::LeftString() const { return utf8::left(buf_, cursor_); } std::string SKKTextBuffer::RightString() const { return utf8::right(buf_, cursor_); } int SKKTextBuffer::minCursorPosition() const { // 今のところ毎回計算する(最適化しない) return - utf8::length(buf_); } int SKKTextBuffer::maxCursorPosition() const { return 0; }
gpl-2.0
Debian/openjfx
modules/web/src/main/native/Source/JavaScriptCore/tests/es6/default_function_parameters_basic_functionality.js
147
function test() { return (function (a = 1, b = 2) { return a === 3 && b === 2; }(3)); } if (!test()) throw new Error("Test failed");
gpl-2.0
sunqueen/vlc-2.1.4.32.subproject-2013
modules/gui/qt4/util/customwidgets.hpp
4925
/***************************************************************************** * customwidgets.hpp: Custom widgets **************************************************************************** * Copyright (C) 2006 the VideoLAN team * Copyright (C) 2004 Daniel Molkentin <molkentin@kde.org> * $Id: 37fce1d4515dd95131bfb969f07e568f8aa6c79a $ * * Authors: Clément Stenac <zorglub@videolan.org> * The "ClickLineEdit" control is based on code by Daniel Molkentin * <molkentin@kde.org> for libkdepim * * 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _CUSTOMWIDGETS_H_ #define _CUSTOMWIDGETS_H_ #include <QLineEdit> #include <QPushButton> #include <QLabel> #include <QStackedWidget> #include <QSpinBox> #include <QCheckBox> #include <QList> #include <QTimer> #include <QToolButton> #include <QAbstractAnimation> class QPixmap; class QWidget; class QFramelessButton : public QPushButton { Q_OBJECT public: QFramelessButton( QWidget *parent = NULL ); virtual QSize sizeHint() const { return iconSize(); } protected: virtual void paintEvent( QPaintEvent * event ); }; class QToolButtonExt : public QToolButton { Q_OBJECT public: QToolButtonExt( QWidget *parent = 0, int ms = 0 ); private: bool shortClick; bool longClick; private slots: void releasedSlot(); void clickedSlot(); signals: void shortClicked(); void longClicked(); }; class QElidingLabel : public QLabel { public: QElidingLabel( const QString &s = QString(), Qt::TextElideMode mode = Qt::ElideRight, QWidget * parent = NULL ); void setElideMode( Qt::TextElideMode ); protected: virtual void paintEvent( QPaintEvent * event ); private: Qt::TextElideMode elideMode; }; class QVLCStackedWidget : public QStackedWidget { public: QVLCStackedWidget( QWidget *parent ) : QStackedWidget( parent ) { } QSize minimumSizeHint () const { return currentWidget() ? currentWidget()->minimumSizeHint() : QSize(); } }; class QVLCDebugLevelSpinBox : public QSpinBox { Q_OBJECT public: QVLCDebugLevelSpinBox( QWidget *parent ) : QSpinBox( parent ) { }; protected: virtual QString textFromValue( int ) const; /* QVLCDebugLevelSpinBox is read-only */ virtual int valueFromText( const QString& ) const { return -1; } }; /** An animated pixmap * Use this widget to display an animated icon based on a series of * pixmaps. The pixmaps will be stored in memory and should be kept small. * First, create the widget, add frames and then start playing. Looping * is supported. **/ class PixmapAnimator : public QAbstractAnimation { Q_OBJECT public: PixmapAnimator( QWidget *parent, QList<QString> _frames ); void setFps( int _fps ) { fps = _fps; interval = 1000.0 / fps; }; virtual int duration() const { return interval * pixmaps.count(); }; virtual ~PixmapAnimator() { qDeleteAll( pixmaps ); }; QPixmap *getPixmap() { return currentPixmap; } protected: virtual void updateCurrentTime ( int msecs ); QList<QPixmap *> pixmaps; QPixmap *currentPixmap; int fps; int interval; int lastframe_msecs; int current_frame; signals: void pixmapReady( const QPixmap & ); }; /** This spinning icon, to the colors of the VLC cone, will show * that there is some background activity running **/ class SpinningIcon : public QLabel { Q_OBJECT public: SpinningIcon( QWidget *parent ); void play( int loops = -1, int fps = 0 ) { animator->setLoopCount( loops ); if ( fps ) animator->setFps( fps ); animator->start(); } void stop() { animator->stop(); } bool isPlaying() { return animator->state() == PixmapAnimator::Running; } private: PixmapAnimator *animator; }; class YesNoCheckBox : public QCheckBox { Q_OBJECT public: YesNoCheckBox( QWidget *parent ); }; /* VLC Key/Wheel hotkeys interactions */ class QKeyEvent; class QWheelEvent; class QInputEvent; int qtKeyModifiersToVLC( QInputEvent* e ); int qtEventToVLCKey( QKeyEvent *e ); int qtWheelEventToVLCKey( QWheelEvent *e ); QString VLCKeyToString( unsigned val, bool ); #endif
gpl-2.0
impulze/newSOS
core/api/src/main/java/org/n52/sos/ogc/om/ObservationValue.java
2311
/** * Copyright (C) 2012-2015 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * 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. */ package org.n52.sos.ogc.om; import java.io.Serializable; import org.n52.sos.ogc.gml.time.Time; import org.n52.sos.ogc.om.values.Value; /** * Interface for observation values. * * @since 4.0.0 * * @param <T> * observation value type */ public interface ObservationValue<T extends Value<?>> extends Serializable { /** * Get phenomenon or sampling time of the observation * * @return Phenomenon or sampling time of the observation */ Time getPhenomenonTime(); /** * Set phenomenon or sampling time of the observation * * @param phenomenonTime * Phenomenon or sampling time of the observation */ void setPhenomenonTime(Time phenomenonTime); /** * Get observation value * * @return Observation value */ T getValue(); /** * Set observation value * * @param value * Observation value */ void setValue(T value); boolean isSetValue(); }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/runtime/cds/appcds/customLoader/ClassListFormatE.java
4957
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* * @test * @summary Tests the format checking of hotspot/src/closed/share/vm/classfile/classListParser.cpp. * * @requires vm.cds * @requires vm.cds.custom.loaders * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds * @compile ../test-classes/Hello.java test-classes/CustomLoadee.java test-classes/CustomLoadee2.java * test-classes/CustomInterface2_ia.java test-classes/CustomInterface2_ib.java * @run driver ClassListFormatE */ public class ClassListFormatE extends ClassListFormatBase { static { // Uncomment the following line to run only one of the test cases // ClassListFormatBase.RUN_ONLY_TEST = "TESTCASE E1"; } public static void main(String[] args) throws Throwable { String appJar = JarBuilder.getOrCreateHelloJar(); String customJarPath = JarBuilder.build("ClassListFormatE", "CustomLoadee", "CustomLoadee2", "CustomInterface2_ia", "CustomInterface2_ib"); //---------------------------------------------------------------------- // TESTGROUP E: super class and interfaces //---------------------------------------------------------------------- dumpShouldFail( "TESTCASE E1: missing interfaces: keyword", appJar, classlist( "Hello", "java/lang/Object id: 1", "CustomLoadee2 id: 1 super: 1 source: " + customJarPath ), "Class CustomLoadee2 implements the interface CustomInterface2_ia, but no interface has been specified in the input line"); dumpShouldFail( "TESTCASE E2: missing one interface", appJar, classlist( "Hello", "java/lang/Object id: 1", "CustomInterface2_ia id: 2 super: 1 source: " + customJarPath, "CustomInterface2_ib id: 3 super: 1 source: " + customJarPath, "CustomLoadee2 id: 4 super: 1 interfaces: 2 source: " + customJarPath ), "The interface CustomInterface2_ib implemented by class CustomLoadee2 does not match any of the specified interface IDs"); dumpShouldFail( "TESTCASE E3: specifying an interface that's not implemented by the class", appJar, classlist( "Hello", "java/lang/Object id: 1", "CustomInterface2_ia id: 2 super: 1 source: " + customJarPath, "CustomLoadee id: 2 super: 1 interfaces: 2 source: " + customJarPath ), "The number of interfaces (1) specified in class list does not match the class file (0)"); dumpShouldFail( "TESTCASE E4: repeating an ID in the interfaces: keyword", appJar, classlist( "Hello", "java/lang/Object id: 1", "CustomInterface2_ia id: 2 super: 1 source: " + customJarPath, "CustomInterface2_ib id: 3 super: 1 source: " + customJarPath, "CustomLoadee2 id: 4 super: 1 interfaces: 2 2 3 source: " + customJarPath ), "The number of interfaces (3) specified in class list does not match the class file (2)"); dumpShouldFail( "TESTCASE E5: wrong super class", appJar, classlist( "Hello", "java/lang/Object id: 1", "CustomInterface2_ia id: 2 super: 1 source: " + customJarPath, "CustomInterface2_ib id: 3 super: 1 source: " + customJarPath, "CustomLoadee id: 4 super: 1 source: " + customJarPath, "CustomLoadee2 id: 5 super: 4 interfaces: 2 3 source: " + customJarPath ), "The specified super class CustomLoadee (id 4) does not match actual super class java.lang.Object"); } }
gpl-2.0
lewurm/graal
src/os_cpu/linux_x86/vm/os_linux_x86.cpp
33720
/* * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ // no precompiled headers #include "asm/macroAssembler.hpp" #include "classfile/classLoader.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" #include "code/icBuffer.hpp" #include "code/vtableStubs.hpp" #include "interpreter/interpreter.hpp" #include "jvm_linux.h" #include "memory/allocation.inline.hpp" #include "mutex_linux.inline.hpp" #include "os_share_linux.hpp" #include "prims/jniFastGetField.hpp" #include "prims/jvm.h" #include "prims/jvm_misc.hpp" #include "runtime/arguments.hpp" #include "runtime/extendedPC.hpp" #include "runtime/frame.inline.hpp" #include "runtime/interfaceSupport.hpp" #include "runtime/java.hpp" #include "runtime/javaCalls.hpp" #include "runtime/mutexLocker.hpp" #include "runtime/osThread.hpp" #include "runtime/sharedRuntime.hpp" #include "runtime/stubRoutines.hpp" #include "runtime/thread.inline.hpp" #include "runtime/timer.hpp" #include "utilities/events.hpp" #include "utilities/vmError.hpp" // put OS-includes here # include <sys/types.h> # include <sys/mman.h> # include <pthread.h> # include <signal.h> # include <errno.h> # include <dlfcn.h> # include <stdlib.h> # include <stdio.h> # include <unistd.h> # include <sys/resource.h> # include <pthread.h> # include <sys/stat.h> # include <sys/time.h> # include <sys/utsname.h> # include <sys/socket.h> # include <sys/wait.h> # include <pwd.h> # include <poll.h> # include <ucontext.h> # include <fpu_control.h> #ifdef AMD64 #define REG_SP REG_RSP #define REG_PC REG_RIP #define REG_FP REG_RBP #define SPELL_REG_SP "rsp" #define SPELL_REG_FP "rbp" #else #define REG_SP REG_UESP #define REG_PC REG_EIP #define REG_FP REG_EBP #define SPELL_REG_SP "esp" #define SPELL_REG_FP "ebp" #endif // AMD64 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC address os::current_stack_pointer() { #ifdef SPARC_WORKS register void *esp; __asm__("mov %%"SPELL_REG_SP", %0":"=r"(esp)); return (address) ((char*)esp + sizeof(long)*2); #elif defined(__clang__) intptr_t* esp; __asm__ __volatile__ ("mov %%"SPELL_REG_SP", %0":"=r"(esp):); return (address) esp; #else register void *esp __asm__ (SPELL_REG_SP); return (address) esp; #endif } char* os::non_memory_address_word() { // Must never look like an address returned by reserve_memory, // even in its subfields (as defined by the CPU immediate fields, // if the CPU splits constants across multiple instructions). return (char*) -1; } void os::initialize_thread(Thread* thr) { // Nothing to do. } address os::Linux::ucontext_get_pc(ucontext_t * uc) { return (address)uc->uc_mcontext.gregs[REG_PC]; } intptr_t* os::Linux::ucontext_get_sp(ucontext_t * uc) { return (intptr_t*)uc->uc_mcontext.gregs[REG_SP]; } intptr_t* os::Linux::ucontext_get_fp(ucontext_t * uc) { return (intptr_t*)uc->uc_mcontext.gregs[REG_FP]; } // For Forte Analyzer AsyncGetCallTrace profiling support - thread // is currently interrupted by SIGPROF. // os::Solaris::fetch_frame_from_ucontext() tries to skip nested signal // frames. Currently we don't do that on Linux, so it's the same as // os::fetch_frame_from_context(). ExtendedPC os::Linux::fetch_frame_from_ucontext(Thread* thread, ucontext_t* uc, intptr_t** ret_sp, intptr_t** ret_fp) { assert(thread != NULL, "just checking"); assert(ret_sp != NULL, "just checking"); assert(ret_fp != NULL, "just checking"); return os::fetch_frame_from_context(uc, ret_sp, ret_fp); } ExtendedPC os::fetch_frame_from_context(void* ucVoid, intptr_t** ret_sp, intptr_t** ret_fp) { ExtendedPC epc; ucontext_t* uc = (ucontext_t*)ucVoid; if (uc != NULL) { epc = ExtendedPC(os::Linux::ucontext_get_pc(uc)); if (ret_sp) *ret_sp = os::Linux::ucontext_get_sp(uc); if (ret_fp) *ret_fp = os::Linux::ucontext_get_fp(uc); } else { // construct empty ExtendedPC for return value checking epc = ExtendedPC(NULL); if (ret_sp) *ret_sp = (intptr_t *)NULL; if (ret_fp) *ret_fp = (intptr_t *)NULL; } return epc; } frame os::fetch_frame_from_context(void* ucVoid) { intptr_t* sp; intptr_t* fp; ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp); return frame(sp, fp, epc.pc()); } // By default, gcc always save frame pointer (%ebp/%rbp) on stack. It may get // turned off by -fomit-frame-pointer, frame os::get_sender_for_C_frame(frame* fr) { return frame(fr->sender_sp(), fr->link(), fr->sender_pc()); } intptr_t* _get_previous_fp() { #ifdef SPARC_WORKS register intptr_t **ebp; __asm__("mov %%"SPELL_REG_FP", %0":"=r"(ebp)); #elif defined(__clang__) intptr_t **ebp; __asm__ __volatile__ ("mov %%"SPELL_REG_FP", %0":"=r"(ebp):); #else register intptr_t **ebp __asm__ (SPELL_REG_FP); #endif return (intptr_t*) *ebp; // we want what it points to. } frame os::current_frame() { intptr_t* fp = _get_previous_fp(); frame myframe((intptr_t*)os::current_stack_pointer(), (intptr_t*)fp, CAST_FROM_FN_PTR(address, os::current_frame)); if (os::is_first_C_frame(&myframe)) { // stack is not walkable return frame(); } else { return os::get_sender_for_C_frame(&myframe); } } // Utility functions // From IA32 System Programming Guide enum { trap_page_fault = 0xE }; extern "C" JNIEXPORT int JVM_handle_linux_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) { ucontext_t* uc = (ucontext_t*) ucVoid; Thread* t = ThreadLocalStorage::get_thread_slow(); // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away // (no destructors can be run) os::WatcherThreadCrashProtection::check_crash_protection(sig, t); SignalHandlerMark shm(t); // Note: it's not uncommon that JNI code uses signal/sigset to install // then restore certain signal handler (e.g. to temporarily block SIGPIPE, // or have a SIGILL handler when detecting CPU type). When that happens, // JVM_handle_linux_signal() might be invoked with junk info/ucVoid. To // avoid unnecessary crash when libjsig is not preloaded, try handle signals // that do not require siginfo/ucontext first. if (sig == SIGPIPE || sig == SIGXFSZ) { // allow chained handler to go first if (os::Linux::chained_handler(sig, info, ucVoid)) { return true; } else { if (PrintMiscellaneous && (WizardMode || Verbose)) { char buf[64]; warning("Ignoring %s - see bugs 4229104 or 646499219", os::exception_name(sig, buf, sizeof(buf))); } return true; } } JavaThread* thread = NULL; VMThread* vmthread = NULL; if (os::Linux::signal_handlers_are_installed) { if (t != NULL ){ if(t->is_Java_thread()) { thread = (JavaThread*)t; } else if(t->is_VM_thread()){ vmthread = (VMThread *)t; } } } /* NOTE: does not seem to work on linux. if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) { // can't decode this kind of signal info = NULL; } else { assert(sig == info->si_signo, "bad siginfo"); } */ // decide if this trap can be handled by a stub address stub = NULL; address pc = NULL; //%note os_trap_1 if (info != NULL && uc != NULL && thread != NULL) { pc = (address) os::Linux::ucontext_get_pc(uc); if (StubRoutines::is_safefetch_fault(pc)) { uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); return 1; } #ifndef AMD64 // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs // This can happen in any running code (currently more frequently in // interpreter code but has been seen in compiled code) if (sig == SIGSEGV && info->si_addr == 0 && info->si_code == SI_KERNEL) { fatal("An irrecoverable SI_KERNEL SIGSEGV has occurred due " "to unstable signal handling in this distribution."); } #endif // AMD64 // Handle ALL stack overflow variations here if (sig == SIGSEGV) { address addr = (address) info->si_addr; // check if fault address is within thread stack if (addr < thread->stack_base() && addr >= thread->stack_base() - thread->stack_size()) { // stack overflow if (thread->in_stack_yellow_zone(addr)) { thread->disable_stack_yellow_zone(); if (thread->thread_state() == _thread_in_Java) { // Throw a stack overflow exception. Guard pages will be reenabled // while unwinding the stack. stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW); } else { // Thread was in the vm or native code. Return and try to finish. return 1; } } else if (thread->in_stack_red_zone(addr)) { // Fatal red zone violation. Disable the guard pages and fall through // to handle_unexpected_exception way down below. thread->disable_stack_red_zone(); tty->print_raw_cr("An irrecoverable stack overflow has occurred."); // This is a likely cause, but hard to verify. Let's just print // it as a hint. tty->print_raw_cr("Please check if any of your loaded .so files has " "enabled executable stack (see man page execstack(8))"); } else { // Accessing stack address below sp may cause SEGV if current // thread has MAP_GROWSDOWN stack. This should only happen when // current thread was created by user code with MAP_GROWSDOWN flag // and then attached to VM. See notes in os_linux.cpp. if (thread->osthread()->expanding_stack() == 0) { thread->osthread()->set_expanding_stack(); if (os::Linux::manually_expand_stack(thread, addr)) { thread->osthread()->clear_expanding_stack(); return 1; } thread->osthread()->clear_expanding_stack(); } else { fatal("recursive segv. expanding stack."); } } } } if ((sig == SIGSEGV) && VM_Version::is_cpuinfo_segv_addr(pc)) { // Verify that OS save/restore AVX registers. stub = VM_Version::cpuinfo_cont_addr(); } if (thread->thread_state() == _thread_in_Java) { // Java thread running in Java code => find exception handler if any // a fault inside compiled code, the interpreter, or a stub if (sig == SIGSEGV && os::is_poll_address((address)info->si_addr)) { stub = SharedRuntime::get_poll_stub(pc); } else if (sig == SIGBUS /* && info->si_code == BUS_OBJERR */) { // BugId 4454115: A read from a MappedByteBuffer can fault // here if the underlying file has been truncated. // Do not crash the VM in such a case. CodeBlob* cb = CodeCache::find_blob_unsafe(pc); nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL; if (nm != NULL && nm->has_unsafe_access()) { stub = StubRoutines::handler_for_unsafe_access(); } } else #ifdef AMD64 if (sig == SIGFPE && (info->si_code == FPE_INTDIV || info->si_code == FPE_FLTDIV)) { stub = SharedRuntime:: continuation_for_implicit_exception(thread, pc, SharedRuntime:: IMPLICIT_DIVIDE_BY_ZERO); #else if (sig == SIGFPE /* && info->si_code == FPE_INTDIV */) { // HACK: si_code does not work on linux 2.2.12-20!!! int op = pc[0]; if (op == 0xDB) { // FIST // TODO: The encoding of D2I in i486.ad can cause an exception // prior to the fist instruction if there was an invalid operation // pending. We want to dismiss that exception. From the win_32 // side it also seems that if it really was the fist causing // the exception that we do the d2i by hand with different // rounding. Seems kind of weird. // NOTE: that we take the exception at the NEXT floating point instruction. assert(pc[0] == 0xDB, "not a FIST opcode"); assert(pc[1] == 0x14, "not a FIST opcode"); assert(pc[2] == 0x24, "not a FIST opcode"); return true; } else if (op == 0xF7) { // IDIV stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO); } else { // TODO: handle more cases if we are using other x86 instructions // that can generate SIGFPE signal on linux. tty->print_cr("unknown opcode 0x%X with SIGFPE.", op); fatal("please update this code."); } #endif // AMD64 } else if (sig == SIGSEGV && !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) { // Determination of interpreter/vtable stub/compiled code null exception stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL); } } else if (thread->thread_state() == _thread_in_vm && sig == SIGBUS && /* info->si_code == BUS_OBJERR && */ thread->doing_unsafe_access()) { stub = StubRoutines::handler_for_unsafe_access(); } // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in // and the heap gets shrunk before the field access. if ((sig == SIGSEGV) || (sig == SIGBUS)) { address addr = JNI_FastGetField::find_slowcase_pc(pc); if (addr != (address)-1) { stub = addr; } } // Check to see if we caught the safepoint code in the // process of write protecting the memory serialization page. // It write enables the page immediately after protecting it // so we can just return to retry the write. if ((sig == SIGSEGV) && os::is_memory_serialize_page(thread, (address) info->si_addr)) { // Block current thread until the memory serialize page permission restored. os::block_on_serialize_page_trap(); return true; } } #ifndef AMD64 // Execution protection violation // // This should be kept as the last step in the triage. We don't // have a dedicated trap number for a no-execute fault, so be // conservative and allow other handlers the first shot. // // Note: We don't test that info->si_code == SEGV_ACCERR here. // this si_code is so generic that it is almost meaningless; and // the si_code for this condition may change in the future. // Furthermore, a false-positive should be harmless. if (UnguardOnExecutionViolation > 0 && (sig == SIGSEGV || sig == SIGBUS) && uc->uc_mcontext.gregs[REG_TRAPNO] == trap_page_fault) { int page_size = os::vm_page_size(); address addr = (address) info->si_addr; address pc = os::Linux::ucontext_get_pc(uc); // Make sure the pc and the faulting address are sane. // // If an instruction spans a page boundary, and the page containing // the beginning of the instruction is executable but the following // page is not, the pc and the faulting address might be slightly // different - we still want to unguard the 2nd page in this case. // // 15 bytes seems to be a (very) safe value for max instruction size. bool pc_is_near_addr = (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15); bool instr_spans_page_boundary = (align_size_down((intptr_t) pc ^ (intptr_t) addr, (intptr_t) page_size) > 0); if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) { static volatile address last_addr = (address) os::non_memory_address_word(); // In conservative mode, don't unguard unless the address is in the VM if (addr != last_addr && (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) { // Set memory to RWX and retry address page_start = (address) align_size_down((intptr_t) addr, (intptr_t) page_size); bool res = os::protect_memory((char*) page_start, page_size, os::MEM_PROT_RWX); if (PrintMiscellaneous && Verbose) { char buf[256]; jio_snprintf(buf, sizeof(buf), "Execution protection violation " "at " INTPTR_FORMAT ", unguarding " INTPTR_FORMAT ": %s, errno=%d", addr, page_start, (res ? "success" : "failed"), errno); tty->print_raw_cr(buf); } stub = pc; // Set last_addr so if we fault again at the same address, we don't end // up in an endless loop. // // There are two potential complications here. Two threads trapping at // the same address at the same time could cause one of the threads to // think it already unguarded, and abort the VM. Likely very rare. // // The other race involves two threads alternately trapping at // different addresses and failing to unguard the page, resulting in // an endless loop. This condition is probably even more unlikely than // the first. // // Although both cases could be avoided by using locks or thread local // last_addr, these solutions are unnecessary complication: this // handler is a best-effort safety net, not a complete solution. It is // disabled by default and should only be used as a workaround in case // we missed any no-execute-unsafe VM code. last_addr = addr; } } } #endif // !AMD64 if (stub != NULL) { // save all thread context in case we need to restore it if (thread != NULL) thread->set_saved_exception_pc(pc); uc->uc_mcontext.gregs[REG_PC] = (greg_t)stub; return true; } // signal-chaining if (os::Linux::chained_handler(sig, info, ucVoid)) { return true; } if (!abort_if_unrecognized) { // caller wants another chance, so give it to him return false; } if (pc == NULL && uc != NULL) { pc = os::Linux::ucontext_get_pc(uc); } // unmask current signal sigset_t newset; sigemptyset(&newset); sigaddset(&newset, sig); sigprocmask(SIG_UNBLOCK, &newset, NULL); VMError err(t, sig, pc, info, ucVoid); err.report_and_die(); ShouldNotReachHere(); } void os::Linux::init_thread_fpu_state(void) { #ifndef AMD64 // set fpu to 53 bit precision set_fpu_control_word(0x27f); #endif // !AMD64 } int os::Linux::get_fpu_control_word(void) { #ifdef AMD64 return 0; #else int fpu_control; _FPU_GETCW(fpu_control); return fpu_control & 0xffff; #endif // AMD64 } void os::Linux::set_fpu_control_word(int fpu_control) { #ifndef AMD64 _FPU_SETCW(fpu_control); #endif // !AMD64 } // Check that the linux kernel version is 2.4 or higher since earlier // versions do not support SSE without patches. bool os::supports_sse() { #ifdef AMD64 return true; #else struct utsname uts; if( uname(&uts) != 0 ) return false; // uname fails? char *minor_string; int major = strtol(uts.release,&minor_string,10); int minor = strtol(minor_string+1,NULL,10); bool result = (major > 2 || (major==2 && minor >= 4)); #ifndef PRODUCT if (PrintMiscellaneous && Verbose) { tty->print("OS version is %d.%d, which %s support SSE/SSE2\n", major,minor, result ? "DOES" : "does NOT"); } #endif return result; #endif // AMD64 } bool os::is_allocatable(size_t bytes) { #ifdef AMD64 // unused on amd64? return true; #else if (bytes < 2 * G) { return true; } char* addr = reserve_memory(bytes, NULL); if (addr != NULL) { release_memory(addr, bytes); } return addr != NULL; #endif // AMD64 } //////////////////////////////////////////////////////////////////////////////// // thread stack #ifdef AMD64 size_t os::Linux::min_stack_allowed = 64 * K; // amd64: pthread on amd64 is always in floating stack mode bool os::Linux::supports_variable_stack_size() { return true; } #else size_t os::Linux::min_stack_allowed = (48 DEBUG_ONLY(+4))*K; #ifdef __GNUC__ #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;}) #endif // Test if pthread library can support variable thread stack size. LinuxThreads // in fixed stack mode allocates 2M fixed slot for each thread. LinuxThreads // in floating stack mode and NPTL support variable stack size. bool os::Linux::supports_variable_stack_size() { if (os::Linux::is_NPTL()) { // NPTL, yes return true; } else { // Note: We can't control default stack size when creating a thread. // If we use non-default stack size (pthread_attr_setstacksize), both // floating stack and non-floating stack LinuxThreads will return the // same value. This makes it impossible to implement this function by // detecting thread stack size directly. // // An alternative approach is to check %gs. Fixed-stack LinuxThreads // do not use %gs, so its value is 0. Floating-stack LinuxThreads use // %gs (either as LDT selector or GDT selector, depending on kernel) // to access thread specific data. // // Note that %gs is a reserved glibc register since early 2001, so // applications are not allowed to change its value (Ulrich Drepper from // Redhat confirmed that all known offenders have been modified to use // either %fs or TSD). In the worst case scenario, when VM is embedded in // a native application that plays with %gs, we might see non-zero %gs // even LinuxThreads is running in fixed stack mode. As the result, we'll // return true and skip _thread_safety_check(), so we may not be able to // detect stack-heap collisions. But otherwise it's harmless. // #ifdef __GNUC__ return (GET_GS() != 0); #else return false; #endif } } #endif // AMD64 // return default stack size for thr_type size_t os::Linux::default_stack_size(os::ThreadType thr_type) { // default stack size (compiler thread needs larger stack) #ifdef AMD64 size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M); #else size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K); #endif // AMD64 return s; } size_t os::Linux::default_guard_size(os::ThreadType thr_type) { // Creating guard page is very expensive. Java thread has HotSpot // guard page, only enable glibc guard page for non-Java threads. return (thr_type == java_thread ? 0 : page_size()); } // Java thread: // // Low memory addresses // +------------------------+ // | |\ JavaThread created by VM does not have glibc // | glibc guard page | - guard, attached Java thread usually has // | |/ 1 page glibc guard. // P1 +------------------------+ Thread::stack_base() - Thread::stack_size() // | |\ // | HotSpot Guard Pages | - red and yellow pages // | |/ // +------------------------+ JavaThread::stack_yellow_zone_base() // | |\ // | Normal Stack | - // | |/ // P2 +------------------------+ Thread::stack_base() // // Non-Java thread: // // Low memory addresses // +------------------------+ // | |\ // | glibc guard page | - usually 1 page // | |/ // P1 +------------------------+ Thread::stack_base() - Thread::stack_size() // | |\ // | Normal Stack | - // | |/ // P2 +------------------------+ Thread::stack_base() // // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from // pthread_attr_getstack() static void current_stack_region(address * bottom, size_t * size) { if (os::Linux::is_initial_thread()) { // initial thread needs special handling because pthread_getattr_np() // may return bogus value. *bottom = os::Linux::initial_thread_stack_bottom(); *size = os::Linux::initial_thread_stack_size(); } else { pthread_attr_t attr; int rslt = pthread_getattr_np(pthread_self(), &attr); // JVM needs to know exact stack location, abort if it fails if (rslt != 0) { if (rslt == ENOMEM) { vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np"); } else { fatal(err_msg("pthread_getattr_np failed with errno = %d", rslt)); } } if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) { fatal("Can not locate current stack attributes!"); } pthread_attr_destroy(&attr); } assert(os::current_stack_pointer() >= *bottom && os::current_stack_pointer() < *bottom + *size, "just checking"); } address os::current_stack_base() { address bottom; size_t size; current_stack_region(&bottom, &size); return (bottom + size); } size_t os::current_stack_size() { // stack size includes normal stack and HotSpot guard pages address bottom; size_t size; current_stack_region(&bottom, &size); return size; } ///////////////////////////////////////////////////////////////////////////// // helper functions for fatal error handler void os::print_context(outputStream *st, void *context) { if (context == NULL) return; ucontext_t *uc = (ucontext_t*)context; st->print_cr("Registers:"); #ifdef AMD64 st->print( "RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]); st->print(", RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]); st->print(", RCX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RCX]); st->print(", RDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDX]); st->cr(); st->print( "RSP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSP]); st->print(", RBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBP]); st->print(", RSI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSI]); st->print(", RDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDI]); st->cr(); st->print( "R8 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R8]); st->print(", R9 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R9]); st->print(", R10=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R10]); st->print(", R11=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R11]); st->cr(); st->print( "R12=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R12]); st->print(", R13=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R13]); st->print(", R14=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R14]); st->print(", R15=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R15]); st->cr(); st->print( "RIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RIP]); st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EFL]); st->print(", CSGSFS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_CSGSFS]); st->print(", ERR=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ERR]); st->cr(); st->print(" TRAPNO=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_TRAPNO]); #else st->print( "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EAX]); st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBX]); st->print(", ECX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ECX]); st->print(", EDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDX]); st->cr(); st->print( "ESP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_UESP]); st->print(", EBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBP]); st->print(", ESI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ESI]); st->print(", EDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDI]); st->cr(); st->print( "EIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EIP]); st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EFL]); st->print(", CR2=" INTPTR_FORMAT, uc->uc_mcontext.cr2); #endif // AMD64 st->cr(); st->cr(); intptr_t *sp = (intptr_t *)os::Linux::ucontext_get_sp(uc); st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp); print_hex_dump(st, (address)sp, (address)(sp + 8*sizeof(intptr_t)), sizeof(intptr_t)); st->cr(); // Note: it may be unsafe to inspect memory near pc. For example, pc may // point to garbage if entry point in an nmethod is corrupted. Leave // this at the end, and hope for the best. address pc = os::Linux::ucontext_get_pc(uc); st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc); print_hex_dump(st, pc - 32, pc + 32, sizeof(char)); } void os::print_register_info(outputStream *st, void *context) { if (context == NULL) return; ucontext_t *uc = (ucontext_t*)context; st->print_cr("Register to memory mapping:"); st->cr(); // this is horrendously verbose but the layout of the registers in the // context does not match how we defined our abstract Register set, so // we can't just iterate through the gregs area // this is only for the "general purpose" registers #ifdef AMD64 st->print("RAX="); print_location(st, uc->uc_mcontext.gregs[REG_RAX]); st->print("RBX="); print_location(st, uc->uc_mcontext.gregs[REG_RBX]); st->print("RCX="); print_location(st, uc->uc_mcontext.gregs[REG_RCX]); st->print("RDX="); print_location(st, uc->uc_mcontext.gregs[REG_RDX]); st->print("RSP="); print_location(st, uc->uc_mcontext.gregs[REG_RSP]); st->print("RBP="); print_location(st, uc->uc_mcontext.gregs[REG_RBP]); st->print("RSI="); print_location(st, uc->uc_mcontext.gregs[REG_RSI]); st->print("RDI="); print_location(st, uc->uc_mcontext.gregs[REG_RDI]); st->print("R8 ="); print_location(st, uc->uc_mcontext.gregs[REG_R8]); st->print("R9 ="); print_location(st, uc->uc_mcontext.gregs[REG_R9]); st->print("R10="); print_location(st, uc->uc_mcontext.gregs[REG_R10]); st->print("R11="); print_location(st, uc->uc_mcontext.gregs[REG_R11]); st->print("R12="); print_location(st, uc->uc_mcontext.gregs[REG_R12]); st->print("R13="); print_location(st, uc->uc_mcontext.gregs[REG_R13]); st->print("R14="); print_location(st, uc->uc_mcontext.gregs[REG_R14]); st->print("R15="); print_location(st, uc->uc_mcontext.gregs[REG_R15]); #else st->print("EAX="); print_location(st, uc->uc_mcontext.gregs[REG_EAX]); st->print("EBX="); print_location(st, uc->uc_mcontext.gregs[REG_EBX]); st->print("ECX="); print_location(st, uc->uc_mcontext.gregs[REG_ECX]); st->print("EDX="); print_location(st, uc->uc_mcontext.gregs[REG_EDX]); st->print("ESP="); print_location(st, uc->uc_mcontext.gregs[REG_ESP]); st->print("EBP="); print_location(st, uc->uc_mcontext.gregs[REG_EBP]); st->print("ESI="); print_location(st, uc->uc_mcontext.gregs[REG_ESI]); st->print("EDI="); print_location(st, uc->uc_mcontext.gregs[REG_EDI]); #endif // AMD64 st->cr(); } void os::setup_fpu() { #ifndef AMD64 address fpu_cntrl = StubRoutines::addr_fpu_cntrl_wrd_std(); __asm__ volatile ( "fldcw (%0)" : : "r" (fpu_cntrl) : "memory"); #endif // !AMD64 } #ifndef PRODUCT void os::verify_stack_alignment() { #ifdef AMD64 assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment"); #endif } #endif /* * IA32 only: execute code at a high address in case buggy NX emulation is present. I.e. avoid CS limit * updates (JDK-8023956). */ void os::workaround_expand_exec_shield_cs_limit() { #if defined(IA32) size_t page_size = os::vm_page_size(); /* * Take the highest VA the OS will give us and exec * * Although using -(pagesz) as mmap hint works on newer kernel as you would * think, older variants affected by this work-around don't (search forward only). * * On the affected distributions, we understand the memory layout to be: * * TASK_LIMIT= 3G, main stack base close to TASK_LIMT. * * A few pages south main stack will do it. * * If we are embedded in an app other than launcher (initial != main stack), * we don't have much control or understanding of the address space, just let it slide. */ char* hint = (char*) (Linux::initial_thread_stack_bottom() - ((StackYellowPages + StackRedPages + 1) * page_size)); char* codebuf = os::reserve_memory(page_size, hint); if ( (codebuf == NULL) || (!os::commit_memory(codebuf, page_size, true)) ) { return; // No matter, we tried, best effort. } if (PrintMiscellaneous && (Verbose || WizardMode)) { tty->print_cr("[CS limit NX emulation work-around, exec code at: %p]", codebuf); } // Some code to exec: the 'ret' instruction codebuf[0] = 0xC3; // Call the code in the codebuf __asm__ volatile("call *%0" : : "r"(codebuf)); // keep the page mapped so CS limit isn't reduced. #endif }
gpl-2.0
vnataraju/SProject
plugins/system/zend/Zend/Gdata/Photos/Extension/Client.php
1867
<?php defined( '_JEXEC') or die( 'Restricted Access' ); /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Photos * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Client.php 23775 2011-03-01 17:25:24Z ralph $ */ /** * @see Zend_Gdata_Extension */ require_once 'Zend/Gdata/Extension.php'; /** * @see Zend_Gdata_Photos */ require_once 'Zend/Gdata/Photos.php'; /** * Represents the gphoto:client element used by the API. * This is an optional field that can be used to indicate the * client which created a photo. * * @category Zend * @package Zend_Gdata * @subpackage Photos * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Photos_Extension_Client extends Zend_Gdata_Extension { protected $_rootNamespace = 'gphoto'; protected $_rootElement = 'client'; /** * Constructs a new Zend_Gdata_Photos_Extension_Client object. * * @param string $text (optional) The value to represent. */ public function __construct($text = null) { $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); parent::__construct(); $this->setText($text); } }
gpl-2.0
brunno18/AndroidAppThree
src/com/owncloud/android/ui/fragment/LocalFileListFragment.java
8646
/* ownCloud Android client application * Copyright (C) 2011 Bartek Przybylski * Copyright (C) 2012-2013 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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/>. * */ package com.owncloud.android.ui.fragment; import java.io.File; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import com.owncloud.android.R; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.ui.adapter.LocalFileListAdapter; /** * A Fragment that lists all files and folders in a given LOCAL path. * * @author David A. Velasco * */ public class LocalFileListFragment extends ExtendedListFragment { private static final String TAG = "LocalFileListFragment"; /** Reference to the Activity which this fragment is attached to. For callbacks */ private LocalFileListFragment.ContainerActivity mContainerActivity; /** Directory to show */ private File mDirectory = null; /** Adapter to connect the data from the directory with the View object */ private LocalFileListAdapter mAdapter = null; /** * {@inheritDoc} */ @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mContainerActivity = (ContainerActivity) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement " + LocalFileListFragment.ContainerActivity.class.getSimpleName()); } } /** * {@inheritDoc} */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log_OC.i(TAG, "onCreateView() start"); View v = super.onCreateView(inflater, container, savedInstanceState); setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); setSwipeEnabled(false); // Disable pull-to-refresh setMessageForEmptyList(getString(R.string.local_file_list_empty)); Log_OC.i(TAG, "onCreateView() end"); return v; } /** * {@inheritDoc} */ @Override public void onActivityCreated(Bundle savedInstanceState) { Log_OC.i(TAG, "onActivityCreated() start"); super.onActivityCreated(savedInstanceState); mAdapter = new LocalFileListAdapter(mContainerActivity.getInitialDirectory(), getActivity()); setListAdapter(mAdapter); Log_OC.i(TAG, "onActivityCreated() stop"); } /** * Checks the file clicked over. Browses inside if it is a directory. Notifies the container activity in any case. */ @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { File file = (File) mAdapter.getItem(position); if (file != null) { /// Click on a directory if (file.isDirectory()) { // just local updates listDirectory(file); // notify the click to container Activity mContainerActivity.onDirectoryClick(file); // save index and top position saveIndexAndTopPosition(position); } else { /// Click on a file ImageView checkBoxV = (ImageView) v.findViewById(R.id.custom_checkbox); if (checkBoxV != null) { if (getListView().isItemChecked(position)) { checkBoxV.setImageResource(android.R.drawable.checkbox_on_background); } else { checkBoxV.setImageResource(android.R.drawable.checkbox_off_background); } } // notify the change to the container Activity mContainerActivity.onFileClick(file); } } else { Log_OC.w(TAG, "Null object in ListAdapter!!"); } } /** * Call this, when the user presses the up button */ public void onNavigateUp() { File parentDir = null; if(mDirectory != null) { parentDir = mDirectory.getParentFile(); // can be null } listDirectory(parentDir); // restore index and top position restoreIndexAndTopPosition(); } /** * Use this to query the {@link File} object for the directory * that is currently being displayed by this fragment * * @return File The currently displayed directory */ public File getCurrentDirectory(){ return mDirectory; } /** * Calls {@link LocalFileListFragment#listDirectory(File)} with a null parameter * to refresh the current directory. */ public void listDirectory(){ listDirectory(null); } /** * Lists the given directory on the view. When the input parameter is null, * it will either refresh the last known directory. list the root * if there never was a directory. * * @param directory Directory to be listed */ public void listDirectory(File directory) { // Check input parameters for null if(directory == null) { if(mDirectory != null){ directory = mDirectory; } else { directory = Environment.getExternalStorageDirectory(); // TODO be careful with the state of the storage; could not be available if (directory == null) return; // no files to show } } // if that's not a directory -> List its parent if(!directory.isDirectory()){ Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString()); directory = directory.getParentFile(); } mCurrentListView.clearChoices(); // by now, only files in the same directory will be kept as selected mAdapter.swapDirectory(directory); if (mDirectory == null || !mDirectory.equals(directory)) { mCurrentListView.setSelection(0); } mDirectory = directory; } /** * Returns the fule paths to the files checked by the user * * @return File paths to the files checked by the user. */ public String[] getCheckedFilePaths() { ArrayList<String> result = new ArrayList<String>(); SparseBooleanArray positions = mCurrentListView.getCheckedItemPositions(); if (positions.size() > 0) { for (int i = 0; i < positions.size(); i++) { if (positions.get(positions.keyAt(i)) == true) { result.add(((File) mCurrentListView.getItemAtPosition(positions.keyAt(i))).getAbsolutePath()); } } Log_OC.d(TAG, "Returning " + result.size() + " selected files"); } return result.toArray(new String[result.size()]); } /** * Interface to implement by any Activity that includes some instance of LocalFileListFragment * * @author David A. Velasco */ public interface ContainerActivity { /** * Callback method invoked when a directory is clicked by the user on the files list * * @param directory */ public void onDirectoryClick(File directory); /** * Callback method invoked when a file (non directory) is clicked by the user on the files list * * @param file */ public void onFileClick(File file); /** * Callback method invoked when the parent activity is fully created to get the directory to list firstly. * * @return Directory to list firstly. Can be NULL. */ public File getInitialDirectory(); } }
gpl-2.0
Diegoromeropanes/glpi
front/change.php
1387
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2015-2016 Teclib'. http://glpi-project.org based on GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI 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. GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include ('../inc/includes.php'); Session::checkRightsOr('change', array(Change::READALL, Change::READMY)); Html::header(Change::getTypeName(Session::getPluralNumber()), '', "helpdesk", "change"); Search::show('Change'); Html::footer(); ?>
gpl-2.0
noamoss/littlebird
sites/all/modules/restful/src/Resource/EnabledArrayIterator.php
551
<?php /** * @file * Contains \Drupal\restful\Resource\EnabledArrayIterator. */ namespace Drupal\restful\Resource; class EnabledArrayIterator extends \FilterIterator { /** * Check whether the current element of the iterator is acceptable. * * @return bool * TRUE if the current element is acceptable, otherwise FALSE. * * @link http://php.net/manual/en/filteriterator.accept.php */ public function accept() { if (!$resource = $this->current()) { return FALSE; } return $resource->isEnabled(); } }
gpl-2.0
tunghoang/snmp-ts-stt-icingaweb2
library/vendor/Zend/Cloud/DocumentService/Exception.php
1071
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cloud * @subpackage DocumentService * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Cloud_Exception */ /** * @category Zend * @package Zend_Cloud * @subpackage DocumentService * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cloud_DocumentService_Exception extends Zend_Cloud_Exception {}
gpl-2.0
thebagmaster/WEB_COT
php/PEAR/phing/parser/NestedElementHandler.php
6919
<?php /* * $Id: NestedElementHandler.php 123 2006-09-14 20:19:08Z mrook $ * * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. */ include_once 'phing/IntrospectionHelper.php'; include_once 'phing/TaskContainer.php'; /** * The nested element handler class. * * This class handles the occurance of runtime registered tags like * datatypes (fileset, patternset, etc) and it's possible nested tags. It * introspects the implementation of the class and sets up the data structures. * * @author Andreas Aderhold <andi@binarycloud.com> * @copyright © 2001,2002 THYRELL. All rights reserved * @version $Revision: 1.10 $ $Date: 2006-09-14 20:19:08 +0000 (Thu, 14 Sep 2006) $ * @access public * @package phing.parser */ class NestedElementHandler extends AbstractHandler { /** * Reference to the parent object that represents the parent tag * of this nested element * @var object */ private $parent; /** * Reference to the child object that represents the child tag * of this nested element * @var object */ private $child; /** * Reference to the parent wrapper object * @var object */ private $parentWrapper; /** * Reference to the child wrapper object * @var object */ private $childWrapper; /** * Reference to the related target object * @var object the target instance */ private $target; /** * Constructs a new NestedElement handler and sets up everything. * * @param object the ExpatParser object * @param object the parent handler that invoked this handler * @param object the ProjectConfigurator object * @param object the parent object this element is contained in * @param object the parent wrapper object * @param object the target object this task is contained in * @access public */ function __construct($parser, $parentHandler, $configurator, $parent, $parentWrapper, $target) { parent::__construct($parser, $parentHandler); $this->configurator = $configurator; if ($parent instanceof TaskAdapter) { $this->parent = $parent->getProxy(); } else { $this->parent = $parent; } $this->parentWrapper = $parentWrapper; $this->target = $target; } /** * Executes initialization actions required to setup the data structures * related to the tag. * <p> * This includes: * <ul> * <li>creation of the nested element</li> * <li>calling the setters for attributes</li> * <li>adding the element to the container object</li> * <li>adding a reference to the element (if id attribute is given)</li> * </ul> * * @param string the tag that comes in * @param array attributes the tag carries * @throws ExpatParseException if the setup process fails * @access public */ function init($propType, $attrs) { $configurator = $this->configurator; $project = $this->configurator->project; // introspect the parent class that is custom $parentClass = get_class($this->parent); $ih = IntrospectionHelper::getHelper($parentClass); try { if ($this->parent instanceof UnknownElement) { $this->child = new UnknownElement(strtolower($propType)); $this->parent->addChild($this->child); } else { $this->child = $ih->createElement($project, $this->parent, strtolower($propType)); } $configurator->configureId($this->child, $attrs); if ($this->parentWrapper !== null) { $this->childWrapper = new RuntimeConfigurable($this->child, $propType); $this->childWrapper->setAttributes($attrs); $this->parentWrapper->addChild($this->childWrapper); } else { $configurator->configure($this->child, $attrs, $project); $ih->storeElement($project, $this->parent, $this->child, strtolower($propType)); } } catch (BuildException $exc) { throw new ExpatParseException("Error initializing nested element <$propType>", $exc, $this->parser->getLocation()); } } /** * Handles character data. * * @param string the CDATA that comes in * @throws ExpatParseException if the CDATA could not be set-up properly * @access public */ function characters($data) { $configurator = $this->configurator; $project = $this->configurator->project; if ($this->parentWrapper === null) { try { $configurator->addText($project, $this->child, $data); } catch (BuildException $exc) { throw new ExpatParseException($exc->getMessage(), $this->parser->getLocation()); } } else { $this->childWrapper->addText($data); } } /** * Checks for nested tags within the current one. Creates and calls * handlers respectively. * * @param string the tag that comes in * @param array attributes the tag carries * @access public */ function startElement($name, $attrs) { //print(get_class($this) . " name = $name, attrs = " . implode(",",$attrs) . "\n"); if ($this->child instanceof TaskContainer) { // taskcontainer nested element can contain other tasks - no other // nested elements possible $tc = new TaskHandler($this->parser, $this, $this->configurator, $this->child, $this->childWrapper, $this->target); $tc->init($name, $attrs); } else { $neh = new NestedElementHandler($this->parser, $this, $this->configurator, $this->child, $this->childWrapper, $this->target); $neh->init($name, $attrs); } } }
gpl-2.0
wp-cbos-ca/b100-sci
wp-content/plugins/wp-site-dna/post-type/post-type-block/post-type-block.php
2543
<?php defined( 'ABSPATH' ) || die(); function install_post_type_block( $user_id = 1 ){ require_once dirname( __FILE__) . '/data.php'; global $wpdb; $now = date( 'Y-m-d H:i:s' ); $now_gmt = date( 'Y-m-d H:i:s' ); //adjust $items = get_post_type_block_data(); for ( $i=1; $i <= $items['cnt']; $i++ ) { $post_title = build_post_type_block_title( $items['title_prefix'], $i ); $guid = get_option( 'home' ) . sanitize_title_with_dashes( $title ); if ( ! get_page_by_title ( $title, OBJECT, WP_POST_TYPE_ALT ) ) { $guid = get_option( 'home' ) . '/' . $post_name; $wpdb -> insert( $wpdb -> posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id pharetra velit, at dictum enim. Aliquam maximus metus sed ante cursus rutrum id eu turpis. Curabitur consequat placerat lorem quis mattis. Curabitur ut nisl nec ipsum molestie suscipit. Maecenas placerat, ex sed dignissim accumsan, ante justo tempor nunc, sed faucibus mi neque id massa. Aenean consectetur vitae mi sed semper. Praesent sed suscipit diam. Fusce semper malesuada nisi id aliquet. Curabitur vulputate arcu nec justo malesuada pulvinar. Etiam pretium enim dictum elit pellentesque imperdiet. Ut egestas ac ligula non pharetra. Cras pharetra est eget eros rhoncus vulputate. Donec et neque ac risus convallis sollicitudin. Vivamus arcu mauris, pharetra eget gravida in, ultricies a justo. Maecenas dictum mattis volutpat. Donec at ipsum orci.', 'post_excerpt' => '', 'post_title' => $post_title, 'post_name' => sanitize_title( $post_title ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $guid, 'post_type' => WP_POST_TYPE_ALT, 'comment_count' => 0, 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '' )); } } } function build_post_type_block_title( $title_prefix, $i ) { if ( $i < 10 ) { $page_num = '0' . $i; } else { $page_num = $i; } $title = sprintf( '%s %s', $title_prefix ,$page_num ); return $title; }
gpl-2.0
VitaliyProdan/bmm
wp-content/plugins/polylang/modules/wpml/wpml-compat.php
14088
<?php /** * Compatibility with WPML API. See http://wpml.org/documentation/support/wpml-coding-api/ */ if ( ! defined( 'ABSPATH' ) ) { exit; // don't access directly }; /** * defines two WPML constants once the language has been defined * the compatibility with WPML is not perfect on admin side as the constants are defined * in 'setup_theme' by Polylang ( based on user info ) and 'plugins_loaded' by WPML ( based on cookie ) * * @since 0.9.5 */ function pll_define_wpml_constants() { if ( ! empty( PLL()->curlang ) ) { if ( ! defined( 'ICL_LANGUAGE_CODE' ) ) { define( 'ICL_LANGUAGE_CODE', PLL()->curlang->slug ); } if ( ! defined( 'ICL_LANGUAGE_NAME' ) ) { define( 'ICL_LANGUAGE_NAME', PLL()->curlang->name ); } } elseif ( PLL_ADMIN ) { if ( ! defined( 'ICL_LANGUAGE_CODE' ) ) { define( 'ICL_LANGUAGE_CODE', 'all' ); } if ( ! defined( 'ICL_LANGUAGE_NAME' ) ) { define( 'ICL_LANGUAGE_NAME', '' ); } } } add_action( 'pll_language_defined', 'pll_define_wpml_constants' ); /** * link to the home page in the active language * * @since 0.9.4 * * @return string */ if ( ! function_exists( 'icl_get_home_url' ) ) { function icl_get_home_url() { return pll_home_url(); } } /** * used for building custom language selectors * available only on frontend * * list of paramaters accepted in $args * * skip_missing => wether to skip missing translation or not, 0 or 1, defaults to 0 * orderby => 'id', 'code', 'name', defaults to 'id' * order => 'ASC' or 'DESC', defaults to 'ASC' * link_empty_to => link to use when the translation is missing {$lang} is replaced by the language code * * list of parameters returned per language: * * id => the language id * active => wether this is the active language or no, 0 or 1 * native_name => the language name * missing => wether the translation is missing or not, 0 or 1 * translated_name => empty, does not exist in Polylang * language_code => the language code ( slug ) * country_flag_url => the url of the flag * url => the url of the translation * * @since 1.0 * * @param string|array $args optional * @return array array of arrays per language */ if ( ! function_exists( 'icl_get_languages' ) ) { function icl_get_languages( $args = '' ) { $args = wp_parse_args( $args, array( 'skip_missing' => 0, 'orderby' => 'id', 'order' => 'ASC' ) ); $orderby = ( isset( $args['orderby'] ) && 'code' == $args['orderby'] ) ? 'slug' : ( isset( $args['orderby'] ) && 'name' == $args['orderby'] ? 'name' : 'id' ); $order = ( ! empty( $args['order'] ) && 'desc' == $args['order'] ) ? 'DESC' : 'ASC'; $arr = array(); foreach ( PLL()->model->get_languages_list( array( 'hide_empty' => true, 'orderby' => $orderby, 'order' => $order ) ) as $lang ) { // we can find a translation only on frontend if ( method_exists( PLL()->links, 'get_translation_url' ) ) { $url = PLL()->links->get_translation_url( $lang ); } // it seems that WPML does not bother of skip_missing parameter on admin side and before the $wp_query object has been filled if ( empty( $url ) && ! empty( $args['skip_missing'] ) && ! is_admin() && did_action( 'parse_query' ) ) { continue; } $arr[ $lang->slug ] = array( 'id' => $lang->term_id, 'active' => isset( PLL()->curlang->slug ) && PLL()->curlang->slug == $lang->slug ? 1 : 0, 'native_name' => $lang->name, 'missing' => empty( $url ) ? 1 : 0, 'translated_name' => '', // does not exist in Polylang 'language_code' => $lang->slug, 'country_flag_url' => $lang->flag_url, 'url' => ! empty( $url ) ? $url : ( empty( $args['link_empty_to'] ) ? PLL()->links->get_home_url( $lang ) : str_replace( '{$lang}', $lang->slug, $args['link_empty_to'] ) ), ); } return $arr; } } /** * used for creating language dependent links in themes * * @since 1.0 * * @param int $id object id * @param string $type optional, post type or taxonomy name of the object, defaults to 'post' * @param string $text optional the link text. If not specified will produce the name of the element in the current language * @param array $args optional an array of arguments to add to the link, defaults to empty * @param string $anchor optional the anchor to add to teh link, defaults to empty * @return string a language dependent link */ if ( ! function_exists( 'icl_link_to_element' ) ) { function icl_link_to_element( $id, $type = 'post', $text = '', $args = array(), $anchor = '' ) { if ( 'tag' == $type ) { $type = 'post_tag'; } $pll_type = ( 'post' == $type || pll_is_translated_post_type( $type ) ) ? 'post' : ( 'term' == $type || pll_is_translated_taxonomy( $type ) ? 'term' : false ); if ( $pll_type && ( $lang = pll_current_language() ) && ( $tr_id = PLL()->model->$pll_type->get_translation( $id, $lang ) ) && PLL()->links->current_user_can_read( $tr_id ) ) { $id = $tr_id; } if ( post_type_exists( $type ) ) { $link = get_permalink( $id ); if ( empty( $text ) ) { $text = get_the_title( $id ); } } elseif ( taxonomy_exists( $type ) ) { $link = get_term_link( $id, $type ); if ( empty( $text ) && ( $term = get_term( $id, $type ) ) && ! empty( $term ) && ! is_wp_error( $term ) ) { $text = $term->name; } } if ( empty( $link ) || is_wp_error( $link ) ) { return ''; } if ( ! empty( $args ) ) { $link .= ( false === strpos( $link, '?' ) ? '?' : '&' ) . http_build_query( $args ); } if ( ! empty( $anchor ) ) { $link .= '#' . $anchor; } return sprintf( '<a href="%s">%s</a>', esc_url( $link ), esc_html( $text ) ); } } /** * used for calculating the IDs of objects ( usually categories ) in the current language * * @since 0.9.5 * * @param int $id object id * @param string $type, post type or taxonomy name of the object, defaults to 'post' * @param bool $return_original_if_missing optional, true if Polylang should return the original id if the translation is missing, defaults to false * @param string $lang optional language code, defaults to current language * @return int|null the object id of the translation, null if the translation is missing and $return_original_if_missing set to false */ if ( ! function_exists( 'icl_object_id' ) ) { function icl_object_id( $id, $type, $return_original_if_missing = false, $lang = false ) { $pll_type = ( 'post' === $type || pll_is_translated_post_type( $type ) ) ? 'post' : ( 'term' === $type || pll_is_translated_taxonomy( $type ) ? 'term' : false ); return $pll_type && ( $lang = $lang ? $lang : pll_current_language() ) && ( $tr_id = PLL()->model->$pll_type->get_translation( $id, $lang ) ) ? $tr_id : ( $return_original_if_missing ? $id : null ); } } /** * undocumented function used by the theme Maya * returns the post language * @see original WPML code at https://wpml.org/forums/topic/canonical-urls-for-wpml-duplicated-posts/#post-52198 * * @since 1.8 * * @param int $post_id * @return array */ if ( ! function_exists( 'wpml_get_language_information' ) ) { function wpml_get_language_information( $post_id = null ) { if ( empty( $post_id ) ) { $post_id = get_the_ID(); } // FIXME WPML may return a WP_Error object return false === $lang = PLL()->model->post->get_language( $post_id ) ? array() : array( 'locale' => $lang->locale, 'text_direction' => $lang->is_rtl, 'display_name' => $lang->name, // seems to be the post language name displayed in the current language, not a feature in Polylang 'native_name' => $lang->name, 'different_language' => $lang->slug != pll_current_language(), ); } } /** * registers a string for translation in the "strings translation" panel * * @since 0.9.3 * * @param string $context the group in which the string is registered, defaults to 'polylang' * @param string $name a unique name for the string * @param string $string the string to register */ if ( ! function_exists( 'icl_register_string' ) ) { function icl_register_string( $context, $name, $string ) { PLL_WPML_Compat::instance()->register_string( $context, $name, $string ); } } /** * removes a string from the "strings translation" panel * * @since 1.0.2 * * @param string $context the group in which the string is registered, defaults to 'polylang' * @param string $name a unique name for the string */ if ( ! function_exists( 'icl_unregister_string' ) ) { function icl_unregister_string( $context, $name ) { PLL_WPML_Compat::instance()->unregister_string( $context, $name ); } } /** * gets the translated value of a string ( previously registered with icl_register_string or pll_register_string ) * * @since 0.9.3 * * @param string $context not used by Polylang * @param string $name not used by Polylang * @param string $string the string to translated * @return string the translated string in the current language */ if ( ! function_exists( 'icl_t' ) ) { function icl_t( $context, $name, $string ) { return pll__( $string ); } } /** * undocumented function used by NextGen Gallery * seems to be used to both register and translate a string * used in PLL_Plugins_Compat for Jetpack with only 3 arguments * * @since 1.0.2 * * @param string $context the group in which the string is registered, defaults to 'polylang' * @param string $name a unique name for the string * @param string $string the string to register * @param bool $bool optional, not used by Polylang * @return string the translated string in the current language */ if ( ! function_exists( 'icl_translate' ) ) { function icl_translate( $context, $name, $string, $bool = false ) { PLL_WPML_Compat::instance()->register_string( $context, $name, $string ); return pll__( $string ); } } /** * undocumented function used by Types * FIXME: tested only with Types * probably incomplete as Types locks the custom fields for a new post, but not when edited * this is probably linked to the fact that WPML has always an original post in the default language and not Polylang :) * * @since 1.1.2 * * @return array */ if ( ! function_exists( 'wpml_get_copied_fields_for_post_edit' ) ) { function wpml_get_copied_fields_for_post_edit() { if ( empty( $_GET['from_post'] ) ) { return array(); } // don't know what WPML does but Polylang does copy all public meta keys by default foreach ( $keys = array_unique( array_keys( get_post_custom( (int) $_GET['from_post'] ) ) ) as $k => $meta_key ) { if ( is_protected_meta( $meta_key ) ) { unset( $keys[ $k ] ); } } // apply our filter and fill the expected output ( see /types/embedded/includes/fields-post.php ) /** This filter is documented in modules/sync/admin-sync.php */ $arr['fields'] = array_unique( apply_filters( 'pll_copy_post_metas', empty( $keys ) ? array() : $keys, false ) ); $arr['original_post_id'] = (int) $_GET['from_post']; return $arr; } } /** * undocumented function used by Warp 6 by Yootheme * * @since 1.0.5 * * @return string default language code */ if ( ! function_exists( 'icl_get_default_language' ) ) { function icl_get_default_language() { return pll_default_language(); } } /** * undocumented function reported to be used by Table Rate Shipping for WooCommerce * @see https://wordpress.org/support/topic/add-wpml-compatibility-function * * @since 1.8.2 * * @return string default language code */ if ( ! function_exists( 'wpml_get_default_language' ) ) { function wpml_get_default_language() { return pll_default_language(); } } /** * registers strings in a persistent way as done by WPML * * @since 1.0.2 */ class PLL_WPML_Compat { static protected $instance; // for singleton static protected $strings; // used for cache /** * constructor * * @since 1.0.2 */ protected function __construct() { self::$strings = get_option( 'polylang_wpml_strings', array() ); add_action( 'pll_get_strings', array( &$this, 'get_strings' ) ); } /** * access to the single instance of the class * * @since 1.7 * * @return object */ static public function instance() { if ( empty( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } /** * unlike pll_register_string, icl_register_string stores the string in database * so we need to do the same as some plugins or themes may expect this * we use a serialized option to do this * * @since 1.0.2 * * @param string $context the group in which the string is registered, defaults to 'polylang' * @param string $name a unique name for the string * @param string $string the string to register */ public function register_string( $context, $name, $string ) { // registers the string if it does not exist yet $to_register = array( 'context' => $context, 'name' => $name, 'string' => $string, 'multiline' => false, 'icl' => true ); if ( ! in_array( $to_register, self::$strings ) && $to_register['string'] ) { self::$strings[] = $to_register; update_option( 'polylang_wpml_strings', self::$strings ); } } /** * removes a string from the registered strings list * * @since 1.0.2 * * @param string $context the group in which the string is registered, defaults to 'polylang' * @param string $name a unique name for the string */ public function unregister_string( $context, $name ) { foreach ( self::$strings as $key => $string ) { if ( $string['context'] == $context && $string['name'] == $name ) { unset( self::$strings[ $key ] ); update_option( 'polylang_wpml_strings', self::$strings ); } } } /** * adds strings registered by icl_register_string to those registered by pll_register_string * * @since 1.0.2 * * @param array $strings existing registered strings * @return array registered strings with added strings through WPML API */ public function get_strings( $strings ) { return empty( self::$strings ) ? $strings : array_merge( $strings, self::$strings ); } }
gpl-2.0
mohapatrasiddhartha/bookmyguitar
wp-content/plugins/wp-members/admin/post.php
8903
<?php /** * WP-Members Admin Functions * * Functions to manage the post/page editor screens. * * This file is part of the WP-Members plugin by Chad Butler * You can find out more about this plugin at http://rocketgeek.com * Copyright (c) 2006-2014 Chad Butler * WP-Members(tm) is a trademark of butlerblog.com * * @package WordPress * @subpackage WP-Members * @author Chad Butler * @copyright 2006-2014 */ /** * Actions */ add_action( 'admin_footer-edit.php', 'wpmem_bulk_posts_action' ); add_action( 'load-edit.php', 'wpmem_posts_page_load' ); add_action( 'admin_notices', 'wpmem_posts_admin_notices'); /** * Function to add block/unblock to the bulk dropdown list * * @since 2.9.2 */ function wpmem_bulk_posts_action() { ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('<option>').val('block').text('<?php _e( 'Block', 'wp-members' )?>').appendTo("select[name='action']"); jQuery('<option>').val('unblock').text('<?php _e( 'Unblock', 'wp-members' )?>').appendTo("select[name='action']"); jQuery('<option>').val('block').text('<?php _e( 'Block', 'wp-members' )?>').appendTo("select[name='action2']"); jQuery('<option>').val('unblock').text('<?php _e( 'Unblock', 'wp-members' )?>').appendTo("select[name='action2']"); }); </script> <?php } /** * Function to handle bulk actions at page load * * @since 2.9.2 * * @uses WP_Users_List_Table */ function wpmem_posts_page_load() { $wp_list_table = _get_list_table( 'WP_Posts_List_Table' ); $action = $wp_list_table->current_action(); $sendback = ''; switch( $action ) { case ( 'block' ): case ( 'unblock' ): /** validate nonce **/ check_admin_referer( 'bulk-posts' ); /** get the posts **/ $posts = ( isset( $_REQUEST['post'] ) ) ? $_REQUEST['post'] : ''; /** update posts **/ $x = ''; if( $posts ) { foreach( $posts as $post_id ) { $x++; $post = get_post( $post_id ); // update accordingly if( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 0 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 0 ) ) { if( $action == 'block' ) { update_post_meta( $post_id, 'block', true); } else { delete_post_meta( $post_id, 'block' ); } } if( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 1 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 1 ) ) { if( $action == 'unblock' ) { update_post_meta( $post_id, 'unblock', true ); } else { delete_post_meta( $post_id, 'unblock' ); } } } /** set the return message */ $sendback = add_query_arg( array( 'block' => $action, 'b' => $x ), $sendback ); } else { /** set the return message */ $sendback = add_query_arg( array( 'block' => 'none' ), $sendback ); } break; default: return; } /** if we did not return already, we need to wp_redirect */ wp_redirect( $sendback ); exit(); } /** * Function to echo admin update message * * @since 2.8.2 */ function wpmem_posts_admin_notices() { global $post_type, $pagenow, $user_action_msg; if( $pagenow == 'edit.php' && $post_type == 'post' && isset( $_REQUEST['block'] ) ) { $message = sprintf( __( '%s posts %sed.', 'wp-members' ), $_REQUEST['b'], $_REQUEST['block'] ); echo "<div class=\"updated\"><p>{$message}</p></div>"; } } /** * Adds the blocking meta boxes for post and page editor screens. * * @since 2.8 */ function wpmem_block_meta_add() { /** * Filter the post meta box title * * @since 2.9.0 */ $post_title = apply_filters( 'wpmem_admin_post_meta_title', __( 'Post Restriction', 'wp-members' ) ); /** * Filter the page meta box title * * @since 2.9.0 */ $page_title = apply_filters( 'wpmem_admin_page_meta_title', __( 'Page Restriction', 'wp-members' ) ); add_meta_box( 'wpmem-block-meta-id', $post_title, 'wpmem_block_meta', 'post', 'side', 'high' ); add_meta_box( 'wpmem-block-meta-id', $page_title, 'wpmem_block_meta', 'page', 'side', 'high' ); } /** * Builds the meta boxes for post and page editor screens. * * @since 2.8 * * @uses do_action Calls 'wpmem_admin_after_block_meta' Allows actions at the end of the block meta box on pages and posts * * @global $post The WordPress post object */ function wpmem_block_meta() { global $post; wp_nonce_field( 'wpmem_block_meta_nonce', 'wpmem_block_meta_nonce' ); if( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 1 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 1 ) ) { $notice = '<p>' . ucfirst( $post->post_type ) . 's are blocked by default.&nbsp;&nbsp;<a href="' . get_admin_url() . '/options-general.php?page=wpmem-settings">Edit</a></p>'; $block = 'wpmem_unblock'; $meta = 'unblock'; $text = 'Unblock'; } elseif( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 0 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 0 ) ) { $notice = '<p>' . ucfirst( $post->post_type ) . 's are not blocked by default.&nbsp;&nbsp;<a href="' . get_admin_url() . '/options-general.php?page=wpmem-settings">Edit</a></p>'; $block = 'wpmem_block'; $meta = 'block'; $text = 'Block'; } echo $notice; ?> <p> <input type="checkbox" id="<?php echo $block; ?>" name="<?php echo $block; ?>" value="true" <?php checked( get_post_meta( $post->ID, $meta, true ), 'true' ); ?> /> <label for="<?php echo $block; ?>"><?php echo $text; ?> this <?php echo $post->post_type; ?></label> </p> <?php do_action( 'wpmem_admin_after_block_meta', $post, $block ); } /** * Saves the meta boxes data for post and page editor screens. * * @since 2.8 * * @uses do_action Calls 'wpmem_admin_block_meta_save' allows actions to be hooked to the meta save process * * @param int $post_id The post ID */ function wpmem_block_meta_save( $post_id ) { // quit if we are doing autosave if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // quit if the nonce isn't there, or is wrong if( ! isset( $_POST['wpmem_block_meta_nonce'] ) || ! wp_verify_nonce( $_POST['wpmem_block_meta_nonce'], 'wpmem_block_meta_nonce' ) ) return; // quit if the current user cannot edit posts if( ! current_user_can( 'edit_posts' ) ) return; // get values $block = isset( $_POST['wpmem_block'] ) ? $_POST['wpmem_block'] : false; $unblock = isset( $_POST['wpmem_unblock'] ) ? $_POST['wpmem_unblock'] : false; // need the post object global $post; // update accordingly if( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 0 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 0 ) ) { if( $block ) { update_post_meta( $post_id, 'block', $block ); } else { delete_post_meta( $post_id, 'block' ); } } if( ( $post->post_type == 'post' && WPMEM_BLOCK_POSTS == 1 ) || ( $post->post_type == 'page' && WPMEM_BLOCK_PAGES == 1 ) ) { if( $unblock ) { update_post_meta( $post_id, 'unblock', $unblock ); } else { delete_post_meta( $post_id, 'unblock' ); } } do_action( 'wpmem_admin_block_meta_save', $post, $block, $unblock ); } /** * Adds WP-Members blocking status to Posts Table columns * * @since 2.8.3 * * @uses wp_enqueue_style Loads the WP-Members admin stylesheet * * @param arr $columns The array of table columns */ function wpmem_post_columns( $columns ) { wp_enqueue_style ( 'wpmem-admin-css', WPMEM_DIR . '/css/admin.css', '', WPMEM_VERSION ); $columns['wpmem_block'] = ( WPMEM_BLOCK_POSTS == 1 ) ? __( 'Unblocked?', 'wp-members' ) : __( 'Blocked?', 'wp-members' ); return $columns; } /** * Adds blocking status to the Post Table column * * @since 2.8.3 * * @param $column_name * @param $post_ID */ function wpmem_post_columns_content( $column_name, $post_ID ) { if( $column_name == 'wpmem_block' ) { $block = ( WPMEM_BLOCK_POSTS == 1 ) ? 'unblock' : 'block'; echo ( get_post_custom_values( $block, $post_ID ) ) ? __( 'Yes' ) : ''; } } /** * Adds WP-Members blocking status to Page Table columns * * @since 2.8.3 * * @uses wp_enqueue_style Loads the WP-Members admin stylesheet * * @param arr $columns The array of table columns */ function wpmem_page_columns( $columns ) { wp_enqueue_style ( 'wpmem-admin-css', WPMEM_DIR . '/css/admin.css', '', WPMEM_VERSION ); $columns['wpmem_block'] = ( WPMEM_BLOCK_PAGES == 1 ) ? __( 'Unblocked?', 'wp-members' ) : __( 'Blocked?', 'wp-members' ); return $columns; } /** * Adds blocking status to the Page Table column * * @since 2.8.3 * * @param $column_name * @param $post_ID */ function wpmem_page_columns_content( $column_name, $post_ID ) { if( $column_name == 'wpmem_block' ) { $block = ( WPMEM_BLOCK_PAGES == 1 ) ? 'unblock' : 'block'; echo ( get_post_custom_values( $block, $post_ID ) ) ? __( 'Yes' ) : ''; } } /** End of File **/
gpl-2.0
pioto/paludis-pioto
paludis/args/args_dumper.hh
2369
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ /* * Copyright (c) 2006 Stephen Bennett * * This file is part of the Paludis package manager. Paludis is free software; * you can redistribute it and/or modify it under the terms of the GNU General * Public License, version 2, as published by the Free Software Foundation. * * Paludis 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 */ #ifndef PALUDIS_GUARD_PALUDIS_ARGS_ARGS_DUMPER_HH #define PALUDIS_GUARD_PALUDIS_ARGS_ARGS_DUMPER_HH 1 #include <iosfwd> #include <paludis/args/args_visitor.hh> /** \file * Declarations for the ArgsDumper class. * * \ingroup g_args * * \section Examples * * - None at this time. */ namespace paludis { namespace args { class ArgsOption; class SwitchArg; class StringArg; class IntegerArg; class AliasArg; class EnumArg; /** * Prints help text appropriate to each command line option. * * \ingroup g_args */ class PALUDIS_VISIBLE ArgsDumper { private: std::ostream & _os; void generic_visit(const ArgsOption &); public: /** * Constructor. */ ArgsDumper(std::ostream & os); /// Visit a SwitchArg. void visit(const SwitchArg &); /// Visit a StringArg. void visit(const StringArg &); /// Visit an IntegerArg. void visit(const IntegerArg &); /// Visit an AliasArg. void visit(const AliasArg &); /// Visit an EnumArg. void visit(const EnumArg &); /// Visit a StringSetArg. void visit(const StringSetArg &); /// Visit a StringSequenceArg. void visit(const StringSequenceArg &); }; } } #endif
gpl-2.0
gongleiarei/qemu
tests/qemu-iotests/iotests.py
14847
# Common utilities and Python wrappers for qemu-iotests # # Copyright (C) 2012 IBM Corp. # # 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, see <http://www.gnu.org/licenses/>. # import errno import os import re import subprocess import string import unittest import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts')) import qtest import struct import json # This will not work if arguments contain spaces but is necessary if we # want to support the override options that ./check supports. qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')] if os.environ.get('QEMU_IMG_OPTIONS'): qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ') qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')] if os.environ.get('QEMU_IO_OPTIONS'): qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ') qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')] if os.environ.get('QEMU_NBD_OPTIONS'): qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ') qemu_prog = os.environ.get('QEMU_PROG', 'qemu') qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ') imgfmt = os.environ.get('IMGFMT', 'raw') imgproto = os.environ.get('IMGPROTO', 'file') test_dir = os.environ.get('TEST_DIR') output_dir = os.environ.get('OUTPUT_DIR', '.') cachemode = os.environ.get('CACHEMODE') qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE') socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper') debug = False def qemu_img(*args): '''Run qemu-img and return the exit code''' devnull = open('/dev/null', 'r+') exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull) if exitcode < 0: sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) return exitcode def qemu_img_verbose(*args): '''Run qemu-img without suppressing its output and return the exit code''' exitcode = subprocess.call(qemu_img_args + list(args)) if exitcode < 0: sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) return exitcode def qemu_img_pipe(*args): '''Run qemu-img and return its output''' subp = subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) exitcode = subp.wait() if exitcode < 0: sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) return subp.communicate()[0] def qemu_io(*args): '''Run qemu-io and return the stdout data''' args = qemu_io_args + list(args) subp = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) exitcode = subp.wait() if exitcode < 0: sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args))) return subp.communicate()[0] def qemu_nbd(*args): '''Run qemu-nbd in daemon mode and return the parent's exit code''' return subprocess.call(qemu_nbd_args + ['--fork'] + list(args)) def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt): '''Return True if two image files are identical''' return qemu_img('compare', '-f', fmt1, '-F', fmt2, img1, img2) == 0 def create_image(name, size): '''Create a fully-allocated raw image with sector markers''' file = open(name, 'w') i = 0 while i < size: sector = struct.pack('>l504xl', i / 512, i / 512) file.write(sector) i = i + 512 file.close() def image_size(img): '''Return image's virtual size''' r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img) return json.loads(r)['virtual-size'] test_dir_re = re.compile(r"%s" % test_dir) def filter_test_dir(msg): return test_dir_re.sub("TEST_DIR", msg) win32_re = re.compile(r"\r") def filter_win32(msg): return win32_re.sub("", msg) qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)") def filter_qemu_io(msg): msg = filter_win32(msg) return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg) chown_re = re.compile(r"chown [0-9]+:[0-9]+") def filter_chown(msg): return chown_re.sub("chown UID:GID", msg) def log(msg, filters=[]): for flt in filters: msg = flt(msg) print msg class VM(qtest.QEMUQtestMachine): '''A QEMU VM''' def __init__(self, path_suffix=''): name = "qemu%s-%d" % (path_suffix, os.getpid()) super(VM, self).__init__(qemu_prog, qemu_opts, name=name, test_dir=test_dir, socket_scm_helper=socket_scm_helper) if debug: self._debug = True self._num_drives = 0 def add_device(self, opts): self._args.append('-device') self._args.append(opts) return self def add_drive_raw(self, opts): self._args.append('-drive') self._args.append(opts) return self def add_drive(self, path, opts='', interface='virtio', format=imgfmt): '''Add a virtio-blk drive to the VM''' options = ['if=%s' % interface, 'id=drive%d' % self._num_drives] if path is not None: options.append('file=%s' % path) options.append('format=%s' % format) options.append('cache=%s' % cachemode) if opts: options.append(opts) self._args.append('-drive') self._args.append(','.join(options)) self._num_drives += 1 return self def pause_drive(self, drive, event=None): '''Pause drive r/w operations''' if not event: self.pause_drive(drive, "read_aio") self.pause_drive(drive, "write_aio") return self.qmp('human-monitor-command', command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive)) def resume_drive(self, drive): self.qmp('human-monitor-command', command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive)) def hmp_qemu_io(self, drive, cmd): '''Write to a given drive using an HMP command''' return self.qmp('human-monitor-command', command_line='qemu-io %s "%s"' % (drive, cmd)) index_re = re.compile(r'([^\[]+)\[([^\]]+)\]') class QMPTestCase(unittest.TestCase): '''Abstract base class for QMP test cases''' def dictpath(self, d, path): '''Traverse a path in a nested dict''' for component in path.split('/'): m = index_re.match(component) if m: component, idx = m.groups() idx = int(idx) if not isinstance(d, dict) or component not in d: self.fail('failed path traversal for "%s" in "%s"' % (path, str(d))) d = d[component] if m: if not isinstance(d, list): self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d))) try: d = d[idx] except IndexError: self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d))) return d def flatten_qmp_object(self, obj, output=None, basestr=''): if output is None: output = dict() if isinstance(obj, list): for i in range(len(obj)): self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.') elif isinstance(obj, dict): for key in obj: self.flatten_qmp_object(obj[key], output, basestr + key + '.') else: output[basestr[:-1]] = obj # Strip trailing '.' return output def assert_qmp_absent(self, d, path): try: result = self.dictpath(d, path) except AssertionError: return self.fail('path "%s" has value "%s"' % (path, str(result))) def assert_qmp(self, d, path, value): '''Assert that the value for a specific path in a QMP dict matches''' result = self.dictpath(d, path) self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value))) def assert_no_active_block_jobs(self): result = self.vm.qmp('query-block-jobs') self.assert_qmp(result, 'return', []) def assert_has_block_node(self, node_name=None, file_name=None): """Issue a query-named-block-nodes and assert node_name and/or file_name is present in the result""" def check_equal_or_none(a, b): return a == None or b == None or a == b assert node_name or file_name result = self.vm.qmp('query-named-block-nodes') for x in result["return"]: if check_equal_or_none(x.get("node-name"), node_name) and \ check_equal_or_none(x.get("file"), file_name): return self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \ (node_name, file_name, result)) def assert_json_filename_equal(self, json_filename, reference): '''Asserts that the given filename is a json: filename and that its content is equal to the given reference object''' self.assertEqual(json_filename[:5], 'json:') self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])), self.flatten_qmp_object(reference)) def cancel_and_wait(self, drive='drive0', force=False, resume=False): '''Cancel a block job and wait for it to finish, returning the event''' result = self.vm.qmp('block-job-cancel', device=drive, force=force) self.assert_qmp(result, 'return', {}) if resume: self.vm.resume_drive(drive) cancelled = False result = None while not cancelled: for event in self.vm.get_qmp_events(wait=True): if event['event'] == 'BLOCK_JOB_COMPLETED' or \ event['event'] == 'BLOCK_JOB_CANCELLED': self.assert_qmp(event, 'data/device', drive) result = event cancelled = True self.assert_no_active_block_jobs() return result def wait_until_completed(self, drive='drive0', check_offset=True): '''Wait for a block job to finish, returning the event''' completed = False while not completed: for event in self.vm.get_qmp_events(wait=True): if event['event'] == 'BLOCK_JOB_COMPLETED': self.assert_qmp(event, 'data/device', drive) self.assert_qmp_absent(event, 'data/error') if check_offset: self.assert_qmp(event, 'data/offset', event['data']['len']) completed = True self.assert_no_active_block_jobs() return event def wait_ready(self, drive='drive0'): '''Wait until a block job BLOCK_JOB_READY event''' f = {'data': {'type': 'mirror', 'device': drive } } event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f) def wait_ready_and_cancel(self, drive='drive0'): self.wait_ready(drive=drive) event = self.cancel_and_wait(drive=drive) self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED') self.assert_qmp(event, 'data/type', 'mirror') self.assert_qmp(event, 'data/offset', event['data']['len']) def complete_and_wait(self, drive='drive0', wait_ready=True): '''Complete a block job and wait for it to finish''' if wait_ready: self.wait_ready(drive=drive) result = self.vm.qmp('block-job-complete', device=drive) self.assert_qmp(result, 'return', {}) event = self.wait_until_completed(drive=drive) self.assert_qmp(event, 'data/type', 'mirror') def notrun(reason): '''Skip this test suite''' # Each test in qemu-iotests has a number ("seq") seq = os.path.basename(sys.argv[0]) open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n') print '%s not run: %s' % (seq, reason) sys.exit(0) def verify_image_format(supported_fmts=[]): if supported_fmts and (imgfmt not in supported_fmts): notrun('not suitable for this image format: %s' % imgfmt) def verify_platform(supported_oses=['linux']): if True not in [sys.platform.startswith(x) for x in supported_oses]: notrun('not suitable for this OS: %s' % sys.platform) def supports_quorum(): return 'quorum' in qemu_img_pipe('--help') def verify_quorum(): '''Skip test suite if quorum support is not available''' if not supports_quorum(): notrun('quorum support missing') def main(supported_fmts=[], supported_oses=['linux']): '''Run tests''' global debug # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to # indicate that we're not being run via "check". There may be # other things set up by "check" that individual test cases rely # on. if test_dir is None or qemu_default_machine is None: sys.stderr.write('Please run this test via the "check" script\n') sys.exit(os.EX_USAGE) debug = '-d' in sys.argv verbosity = 1 verify_image_format(supported_fmts) verify_platform(supported_oses) # We need to filter out the time taken from the output so that qemu-iotest # can reliably diff the results against master output. import StringIO if debug: output = sys.stdout verbosity = 2 sys.argv.remove('-d') else: output = StringIO.StringIO() class MyTestRunner(unittest.TextTestRunner): def __init__(self, stream=output, descriptions=True, verbosity=verbosity): unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) # unittest.main() will use sys.exit() so expect a SystemExit exception try: unittest.main(testRunner=MyTestRunner) finally: if not debug: sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
gpl-2.0
pawelbrzycki/joomla
media/editors/tinymce/jscripts/tiny_mce/langs/pl.js
5478
// PL lang variables UTF-8 // *********************************************************************** // ** Title.........: TinyMCE RC2 polish lang // ** Version.......: 1.0 // ** Author........: Stefan Wajda, Diabl0/MAO, danieladrinka // ** Filename......: pl.js (polish language file) // ** Last changed..: 5 marca 2010 / 13 marca 2011, 22 maja 2011 // ***********************************************************************/ tinyMCE.addI18n({pl:{ common:{ edit_confirm:"Czy chcesz użyć trybu WYSIWYG dla tego pola tekstowego?", apply:"Zastosuj", insert:"Wstaw", update:"Uaktualnij", cancel:"Zrezygnuj", close:"Zamknij", browse:"Przeglądaj", class_name:"Klasa", not_set:"-- Nieustawione --", clipboard_msg:"Opcje Kopiuj/Edytuj/Wklej nie są dostępne w przeglądarkach Mozilla i Firefox.\nPotrzebujesz wiecej informacji na ten temat?", clipboard_no_support:"Aktualnie nie są obsługiwane przez twoją przeglądarkę, użyj w zamian skrótów klawiaturowych.", popup_blocked:"Masz zablokowane otwieranie dodatkowych okien. Aby w pełni korzystać z edytora, wyłącz blokujący je program lub zmień ustawienia przeglądarki.", invalid_data:"Błąd: wprowadzono nieprawidłowe wartości - zaznaczono je na czerwono.", more_colors:"Więcej kolorów" }, contextmenu:{ align:"Wyrównanie", left:"Wyrównaj do lewej", center:"Wyrównaj do środka", right:"Wyrównaj do prawej", full:"Do lewej i prawej" }, insertdatetime:{ date_fmt:"%Y-%m-%d", time_fmt:"%H:%M:%S", insertdate_desc:"Wstaw datę", inserttime_desc:"Wstaw czas", months_long:"Styczeń,Luty,Marzec,Kwiecień,Maj,Czerwiec,Lipiec,Sierpień,Wrzesień,Październik,Listopad,Grudzień", months_short:"sty,lut,mar,kwi,maj,cze,lip,sie,wrz,paź,lis,gru", day_long:"Niedziela,Poniedziałek,Wtorek,Środa,Czwartek,Piątek,Sobota,Niedziela", day_short:"N,Pn,Wt,Śr,Cz,Pt,Sb,N" }, print:{ print_desc:"Drukuj" }, preview:{ preview_desc:"Podgląd" }, directionality:{ ltr_desc:"Od lewej do prawej", rtl_desc:"Od prawej do lewej" }, layer:{ insertlayer_desc:"Wstaw nową warstwę", forward_desc:"Przesuń na wierzch", backward_desc:"Przesuń na spód", absolute_desc:"Pozycjonowanie bezwzględne", content:"Nowa warstwa..." }, save:{ save_desc:"Zapisz", cancel_desc:"Anuluj wszystkie zmiany" }, nonbreaking:{ nonbreaking_desc:"Wstaw spację nierozdzielającą" }, iespell:{ iespell_desc:"Sprawdź pisownię", download:"Nie wykryto ieSpell. Czy zainstalować teraz?" }, advhr:{ advhr_desc:"Linia pozioma" }, emotions:{ emotions_desc:"Wstaw buźkę" }, searchreplace:{ search_desc:"Znajdź", replace_desc:"Znajdź i zastąp" }, advimage:{ image_desc:"Wstaw/Dostosuj obrazek" }, advlink:{ link_desc:"Wstaw/Dostosuj odnośnik" }, xhtmlxtras:{ cite_desc:"Cytat", abbr_desc:"Skrót", acronym_desc:"Akronim", del_desc:"Usunięte", ins_desc:"Wstawione", attribs_desc:"Wstaw/Dostosuj atrybuty" }, style:{ desc:"Edytuj style CSS" }, paste:{ paste_text_desc:"Wklej czysty tekst", paste_word_desc:"Wklej z Worda", selectall_desc:"Zaznacz wszystko", plaintext_mode_sticky:"Wklejanie jest teraz w trybie tekstowym. Kliknij ponownie, aby przełączyć się do zwykłego trybu wklej. Po wklejeniu czegokolwiek nastąpi powrót do zwykłego trybu wklej.", plaintext_mode:"Wklejanie jest teraz w trybie tekstowym. Kliknij ponownie, aby przełączyć się do zwykłego trybu wklej." }, paste_dlg:{ text_title:"Aby wkleić zawartość schowka, użyj klawiszy CTRL+V.", text_linebreaks:"Zachowaj podział na linie", word_title:"Aby wkleić zawartość schowka, użyj klawiszy CTRL+V." }, table:{ desc:"Wstaw tabelę", row_before_desc:"Wstaw wiersz powyżej", row_after_desc:"Wstaw wiersz poniżej", delete_row_desc:"Usuń wiersz", col_before_desc:"Wstaw kolumnę przed", col_after_desc:"Wstaw kolumnę po", delete_col_desc:"Usuń kolumnę", split_cells_desc:"Podziel komórkę", merge_cells_desc:"Scal komórki", row_desc:"Właściwości wiersza", cell_desc:"Właściwości komórki", props_desc:"Właściwości tabeli", paste_row_before_desc:"Wklej wiersz powyżej", paste_row_after_desc:"Wklej wiersz poniżej", cut_row_desc:"Wytnij wiersz", copy_row_desc:"Kopiuj wiersz", del:"Usuń tabelę", row:"Wiersz", col:"Kolumna", cell:"Komórka" }, autosave:{ unload_msg:"Jeśli opuścisz tę stronę, wszystkie niezapisane dotychczas zmiany zostaną utracone.", restore_content:"Przywróć zawartość sprzed automatycznego zapisu.", warning_message:"Jeśli przywrócisz zawartość sprzed automatycznego zapisu, stracisz wszystkie treści, które są obecnie w edytorze. \n\nCzy na pewno chcesz przywrócić zapisane treści?" }, fullscreen:{ desc:"Pełny ekran/Powrót" }, media:{ desc:"Wstaw/Dostosuj media", edit:"Dostosuj media" }, fullpage:{ desc:"Właściwości dokumentu" }, template:{ desc:"Wstaw szablon artykułu" }, visualchars:{ desc:"Pokaż/Ukryj znaki niewidoczne" }, spellchecker:{ desc:"Sprawdzanie pisowni", menu:"Ustawienia sprawdzania pisowni", ignore_word:"Ignoruj słowo", ignore_words:"Ignoruj wszystko", langs:"Języki", wait:"Proszę czekać...", sug:"Sugestie", no_sug:"Brak sugestii", no_mpell:"Nie znaleziono błędów." }, article:{ readmore:"Wstaw Czytaj więcej", pagebreak:"Wstaw podział strony" }, pagebreak:{ desc:"Wstaw podział strony." }, advlist:{ types:"Rodzaje", def:"Domyślnie", lower_alpha:"małe litery", lower_greek:"małe litery greckie", lower_roman:"małe litery rzymskie", upper_alpha:"duże litery", upper_roman:"duże litery rzymskie", circle:"Okrąg", disc:"Dysk", square:"Kwadrat" }}});
gpl-2.0
am-immanuel/quercus
modules/resin/src/com/caucho/amp/AmpQueryCallback.java
1482
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.amp; import com.caucho.amp.actor.AmpActorRef; import com.caucho.amp.stream.AmpError; /** * callback for a query */ public interface AmpQueryCallback { public void onQueryResult(AmpActorRef to, AmpActorRef from, Object result); public void onQueryError(AmpActorRef to, AmpActorRef from, AmpError error); }
gpl-2.0
onkelhotte/test
src/Geo/Flat/FlatGeoPoint.hpp
5815
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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. } */ #ifndef FlatGeoPoint_HPP #define FlatGeoPoint_HPP #include "Math/fixed.hpp" #include "Rough/RoughAltitude.hpp" #include "Compiler.h" /** * Integer projected (flat-earth) version of Geodetic coordinates */ struct FlatGeoPoint { /** Projected x (Longitude) value [undefined units] */ int longitude; /** Projected y (Latitude) value [undefined units] */ int latitude; /** * Non-initialising constructor. */ FlatGeoPoint() = default; /** * Constructor at specified location (x,y) * * @param x x location * @param y y location * * @return Initialised object at origin */ constexpr FlatGeoPoint(const int x, const int y) :longitude(x), latitude(y) {}; /** * Find distance from one point to another * * @param sp That point * * @return Distance in projected units */ gcc_pure unsigned Distance(const FlatGeoPoint &sp) const; /** * Like Distance(), but shift the distance left by the specified * number of bits. This method can be used to avoid integer * truncation errors. Use only when you know what you're doing! */ gcc_pure unsigned ShiftedDistance(const FlatGeoPoint &sp, unsigned bits) const; /** * Find squared distance from one point to another * * @param sp That point * * @return Squared distance in projected units */ gcc_pure unsigned DistanceSquared(const FlatGeoPoint &sp) const; /** * Add one point to another * * @param p2 Point to add * * @return Added value */ constexpr FlatGeoPoint operator+(const FlatGeoPoint other) const { return FlatGeoPoint(longitude + other.longitude, latitude + other.latitude); } /** * Subtract one point from another * * @param p2 Point to subtract * * @return Subtracted value */ constexpr FlatGeoPoint operator-(const FlatGeoPoint other) const { return FlatGeoPoint(longitude - other.longitude, latitude - other.latitude); } /** * Multiply point by a constant * * @param t Value to multiply * * @return Scaled value */ gcc_pure FlatGeoPoint operator* (const fixed t) const { return FlatGeoPoint(iround(longitude * t), iround(latitude * t)); } /** * Calculate cross product of one point with another * * @param other That point * * @return Cross product */ constexpr int CrossProduct(FlatGeoPoint other) const { return longitude * other.latitude - latitude * other.longitude; } /** * Calculate dot product of one point with another * * @param other That point * * @return Dot product */ constexpr int DotProduct(FlatGeoPoint other) const { return longitude * other.longitude + latitude * other.latitude; } /** * Test whether two points are co-located * * @param other Point to compare * * @return True if coincident */ constexpr bool operator==(const FlatGeoPoint other) const { return FlatGeoPoint::Equals(other); }; constexpr bool operator!=(const FlatGeoPoint other) const { return !FlatGeoPoint::Equals(other); }; constexpr bool Equals(const FlatGeoPoint sp) const { return longitude == sp.longitude && latitude == sp.latitude; } gcc_pure bool Sort(const FlatGeoPoint& sp) const { if (longitude < sp.longitude) return false; else if (longitude == sp.longitude) return latitude > sp.latitude; else return true; } }; /** * Extension of FlatGeoPoint for altitude (3d location in flat-earth space) */ struct AFlatGeoPoint : public FlatGeoPoint { /** Nav reference altitude (m) */ RoughAltitude altitude; constexpr AFlatGeoPoint(const int x, const int y, const RoughAltitude alt): FlatGeoPoint(x,y),altitude(alt) {}; constexpr AFlatGeoPoint(const FlatGeoPoint p, const RoughAltitude alt) :FlatGeoPoint(p), altitude(alt) {}; constexpr AFlatGeoPoint():FlatGeoPoint(0,0),altitude(0) {}; /** Rounds location to reduce state space */ void RoundLocation() { // round point to correspond roughly with terrain step size longitude = (longitude >> 2) << 2; latitude = (latitude >> 2) << 2; } /** * Equality comparison operator * * @param other object to compare to * * @return true if location and altitude are equal */ constexpr bool operator==(const AFlatGeoPoint other) const { return FlatGeoPoint::Equals(other) && (altitude == other.altitude); }; /** * Ordering operator, used for set ordering. Uses lexicographic comparison. * * @param sp object to compare to * * @return true if lexicographically smaller */ gcc_pure bool Sort(const AFlatGeoPoint &sp) const { if (!FlatGeoPoint::Sort(sp)) return false; else if (FlatGeoPoint::Equals(sp)) return altitude > sp.altitude; else return true; } }; #endif
gpl-2.0
shamsbd71/digicom
components/com_digicom/helpers/category.php
717
<?php /** * @package DigiCom * @author ThemeXpert http://www.themexpert.com * @copyright Copyright (c) 2010-2015 ThemeXpert. All rights reserved. * @license GNU General Public License version 3 or later; see LICENSE.txt * @since 1.0.0 */ defined('_JEXEC') or die; /** * DigiCom Component Category Tree * * @package DigiCom * @since 1.0.0 */ class DigiComCategories extends JCategories { /** * Name of the items state field * * @var string * @since 1.0.0 */ public function __construct($options = array()) { $options['statefield'] = 'published'; $options['table'] = '#__digicom_products'; $options['extension'] = 'com_digicom'; parent::__construct($options); } }
gpl-2.0
jagnoha/website
profiles/varbase/profiles/varbase/libraries/ckeditor/plugins/toolbar/lang/ku.js
743
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'toolbar', 'ku', { toolbarCollapse: 'شاردنەوی هێڵی تووڵامراز', toolbarExpand: 'نیشاندانی هێڵی تووڵامراز', toolbarGroups: { document: 'پەڕه', clipboard: 'بڕین/پووچکردنەوە', editing: 'چاکسازی', forms: 'داڕشتە', basicstyles: 'شێوازی بنچینەیی', paragraph: 'بڕگە', links: 'بەستەر', insert: 'خستنە ناو', styles: 'شێواز', colors: 'ڕەنگەکان', tools: 'ئامرازەکان' }, toolbars: 'تووڵامرازی دەسکاریکەر' } );
gpl-2.0
ezsystems/ezpublish-api
Repository/UserService.php
17546
<?php /** * File containing the eZ\Publish\API\Repository\UserService class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\API\Repository; use eZ\Publish\API\Repository\Values\Content\Content; use eZ\Publish\API\Repository\Values\User\PasswordValidationContext; use eZ\Publish\API\Repository\Values\User\UserTokenUpdateStruct; use eZ\Publish\API\Repository\Values\User\UserCreateStruct; use eZ\Publish\API\Repository\Values\User\UserUpdateStruct; use eZ\Publish\API\Repository\Values\User\User; use eZ\Publish\API\Repository\Values\User\UserGroup; use eZ\Publish\API\Repository\Values\User\UserGroupCreateStruct; use eZ\Publish\API\Repository\Values\User\UserGroupUpdateStruct; /** * This service provides methods for managing users and user groups. * * @example Examples/user.php */ interface UserService { /** * Creates a new user group using the data provided in the ContentCreateStruct parameter. * * In 4.x in the content type parameter in the profile is ignored * - the content type is determined via configuration and can be set to null. * The returned version is published. * * @param \eZ\Publish\API\Repository\Values\User\UserGroupCreateStruct $userGroupCreateStruct a structure for setting all necessary data to create this user group * @param \eZ\Publish\API\Repository\Values\User\UserGroup $parentGroup * * @return \eZ\Publish\API\Repository\Values\User\UserGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to create a user group * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if the input structure has invalid data * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $userGroupCreateStruct is not valid * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if a required field is missing or set to an empty value */ public function createUserGroup(UserGroupCreateStruct $userGroupCreateStruct, UserGroup $parentGroup); /** * Loads a user group for the given id. * * @param mixed $id * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\UserGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to create a user group * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if the user group with the given id was not found */ public function loadUserGroup($id, array $prioritizedLanguages = []); /** * Loads the sub groups of a user group. * * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * @param int $offset the start offset for paging * @param int $limit the number of user groups returned * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\UserGroup[] * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to read the user group */ public function loadSubUserGroups(UserGroup $userGroup, $offset = 0, $limit = 25, array $prioritizedLanguages = []); /** * Removes a user group. * * the users which are not assigned to other groups will be deleted. * * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to create a user group * * @return mixed[] Affected Location Id's (List of Locations of the Content that was deleted) */ public function deleteUserGroup(UserGroup $userGroup); /** * Moves the user group to another parent. * * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * @param \eZ\Publish\API\Repository\Values\User\UserGroup $newParent * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to move the user group */ public function moveUserGroup(UserGroup $userGroup, UserGroup $newParent); /** * Updates the group profile with fields and meta data. * * 4.x: If the versionUpdateStruct is set in $userGroupUpdateStruct, this method internally creates a content draft, updates ts with the provided data * and publishes the draft. If a draft is explicitly required, the user group can be updated via the content service methods. * * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * @param \eZ\Publish\API\Repository\Values\User\UserGroupUpdateStruct $userGroupUpdateStruct * * @return \eZ\Publish\API\Repository\Values\User\UserGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to move the user group * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $userGroupUpdateStruct is not valid * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if a required field is set empty * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if a field value is not accepted by the field type */ public function updateUserGroup(UserGroup $userGroup, UserGroupUpdateStruct $userGroupUpdateStruct); /** * Create a new user. The created user is published by this method. * * @param \eZ\Publish\API\Repository\Values\User\UserCreateStruct $userCreateStruct the data used for creating the user * @param array $parentGroups the groups of type {@link \eZ\Publish\API\Repository\Values\User\UserGroup} which are assigned to the user after creation * * @return \eZ\Publish\API\Repository\Values\User\User * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to move the user group * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $userCreateStruct is not valid * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if a required field is missing or set to an empty value * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if a field value is not accepted by the field type * if a user with provided login already exists */ public function createUser(UserCreateStruct $userCreateStruct, array $parentGroups); /** * Loads a user. * * @param mixed $userId * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\User * * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if a user with the given id was not found */ public function loadUser($userId, array $prioritizedLanguages = []); /** * Loads anonymous user. * * @deprecated since 5.3, use loadUser( $anonymousUserId ) instead * * @uses ::loadUser() * * @return \eZ\Publish\API\Repository\Values\User\User */ public function loadAnonymousUser(); /** * Loads a user for the given login and password. * * Since 6.1 login is case-insensitive across all storage engines and database backends, however if login * is part of the password hash this method will essentially be case sensitive. * * @param string $login * @param string $password the plain password * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\User * * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if credentials are invalid * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if a user with the given credentials was not found */ public function loadUserByCredentials($login, $password, array $prioritizedLanguages = []); /** * Loads a user for the given login. * * Since 6.1 login is case-insensitive across all storage engines and database backends, like was the case * with mysql before in eZ Publish 3.x/4.x/5.x. * * @param string $login * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\User * * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if a user with the given credentials was not found */ public function loadUserByLogin($login, array $prioritizedLanguages = []); /** * Loads a user for the given email. * * Note: This method loads user by $email where $email might be case-insensitive on certain storage engines! * * Returns an array of Users since eZ Publish has under certain circumstances allowed * several users having same email in the past (by means of a configuration option). * * @param string $email * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\User[] */ public function loadUsersByEmail($email, array $prioritizedLanguages = []); /** * Loads a user with user hash key. * * @param string $hash * @param array $prioritizedLanguages * * @return \eZ\Publish\API\Repository\Values\User\User */ public function loadUserByToken($hash, array $prioritizedLanguages = []); /** * This method deletes a user. * * @param \eZ\Publish\API\Repository\Values\User\User $user * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to delete the user * * @return mixed[] Affected Location Id's (List of Locations of the Content that was deleted) */ public function deleteUser(User $user); /** * Updates a user. * * 4.x: If the versionUpdateStruct is set in the user update structure, this method internally creates a content draft, updates ts with the provided data * and publishes the draft. If a draft is explicitly required, the user group can be updated via the content service methods. * * @param \eZ\Publish\API\Repository\Values\User\User $user * @param \eZ\Publish\API\Repository\Values\User\UserUpdateStruct $userUpdateStruct * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to update the user * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $userUpdateStruct is not valid * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if a required field is set empty * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if a field value is not accepted by the field type * * @return \eZ\Publish\API\Repository\Values\User\User */ public function updateUser(User $user, UserUpdateStruct $userUpdateStruct); /** * Update the user token information specified by the user token struct. * * @param \eZ\Publish\API\Repository\Values\User\User $user * @param \eZ\Publish\API\Repository\Values\User\UserTokenUpdateStruct $userTokenUpdateStruct * * @return \eZ\Publish\API\Repository\Values\User\User */ public function updateUserToken(User $user, UserTokenUpdateStruct $userTokenUpdateStruct); /** * Expires user token with user hash. * * @param string $hash */ public function expireUserToken($hash); /** * Assigns a new user group to the user. * * If the user is already in the given user group this method does nothing. * * @param \eZ\Publish\API\Repository\Values\User\User $user * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to assign the user group to the user */ public function assignUserToUserGroup(User $user, UserGroup $userGroup); /** * Removes a user group from the user. * * @param \eZ\Publish\API\Repository\Values\User\User $user * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to remove the user group from the user * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if the user is not in the given user group * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException If $userGroup is the last assigned user group */ public function unAssignUserFromUserGroup(User $user, UserGroup $userGroup); /** * Loads the user groups the user belongs to. * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed read the user or user group * * @param \eZ\Publish\API\Repository\Values\User\User $user * @param int $offset the start offset for paging * @param int $limit the number of user groups returned * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\UserGroup[] */ public function loadUserGroupsOfUser(User $user, $offset = 0, $limit = 25, array $prioritizedLanguages = []); /** * Loads the users of a user group. * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the authenticated user is not allowed to read the users or user group * * @param \eZ\Publish\API\Repository\Values\User\UserGroup $userGroup * @param int $offset the start offset for paging * @param int $limit the number of users returned * @param string[] $prioritizedLanguages Used as prioritized language code on translated properties of returned object. * * @return \eZ\Publish\API\Repository\Values\User\User[] */ public function loadUsersOfUserGroup(UserGroup $userGroup, $offset = 0, $limit = 25, array $prioritizedLanguages = []); /** * Checks if Content is a user. * * @since 7.4 * * @param \eZ\Publish\API\Repository\Values\Content\Content $content * * @return bool */ public function isUser(Content $content): bool; /** * Checks if Content is a user group. * * @since 7.4 * * @param \eZ\Publish\API\Repository\Values\Content\Content $content * * @return bool */ public function isUserGroup(Content $content): bool; /** * Instantiate a user create class. * * @param string $login the login of the new user * @param string $email the email of the new user * @param string $password the plain password of the new user * @param string $mainLanguageCode the main language for the underlying content object * @param \eZ\Publish\API\Repository\Values\ContentType\ContentType $contentType 5.x the content type for the underlying content object. In 4.x it is ignored and taken from the configuration * * @return \eZ\Publish\API\Repository\Values\User\UserCreateStruct */ public function newUserCreateStruct($login, $email, $password, $mainLanguageCode, $contentType = null); /** * Instantiate a user group create class. * * @param string $mainLanguageCode The main language for the underlying content object * @param null|\eZ\Publish\API\Repository\Values\ContentType\ContentType $contentType 5.x the content type for the underlying content object. In 4.x it is ignored and taken from the configuration * * @return \eZ\Publish\API\Repository\Values\User\UserGroupCreateStruct */ public function newUserGroupCreateStruct($mainLanguageCode, $contentType = null); /** * Instantiate a new user update struct. * * @return \eZ\Publish\API\Repository\Values\User\UserUpdateStruct */ public function newUserUpdateStruct(); /** * Instantiate a new user group update struct. * * @return \eZ\Publish\API\Repository\Values\User\UserGroupUpdateStruct */ public function newUserGroupUpdateStruct(); /** * Validates given password. * * @param string $password * @param \eZ\Publish\API\Repository\Values\User\PasswordValidationContext|null $context * * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException * * @return \eZ\Publish\SPI\FieldType\ValidationError[] */ public function validatePassword(string $password, PasswordValidationContext $context = null): array; }
gpl-2.0
betauserj/DOLSharp
GameServer/packets/Server/PacketLib185.cs
1483
/* * DAWN OF LIGHT - The first free open source DAoC server emulator * * 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. * */ #define NOENCRYPTION using System; using log4net; using DOL.GS.Quests; using System.Reflection; namespace DOL.GS.PacketHandler { [PacketLib(185, GameClient.eClientVersion.Version185)] public class PacketLib185 : PacketLib184 { /// <summary> /// Defines a logger for this class. /// </summary> private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Constructs a new PacketLib for Version 1.85 clients /// </summary> /// <param name="client">the gameclient this lib is associated with</param> public PacketLib185(GameClient client):base(client) { } } }
gpl-2.0
MESH-Dev/Enclave-Capital
wp-content/plugins/wppusher/Pusher/WordPress/ThemeUpgrader.php
2110
<?php namespace Pusher\WordPress; include_once(ABSPATH . 'wp-admin/includes/theme.php'); include_once(ABSPATH . 'wp-admin/includes/file.php'); include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'); include_once(ABSPATH . 'wp-admin/includes/misc.php'); use Pusher\Dashboard; use Pusher\Log\Logger; use Theme_Upgrader; use Pusher\Theme; class ThemeUpgrader extends Theme_Upgrader { public $theme; public function __construct(ThemeUpgraderSkin $skin) { parent::__construct($skin); } public function installTheme(Theme $theme) { add_filter('upgrader_source_selection', array($this, 'upgraderSourceSelectionFilter'), 10, 3); $this->theme = $theme; parent::install($this->theme->repository->getZipUrl()); // Make sure we get out of maintenance mode $this->maintenance_mode(false); } public function upgradeTheme(Theme $theme) { add_filter("pre_site_transient_update_themes", array($this, 'preSiteTransientUpdateThemesFilter'), 10, 3); add_filter('upgrader_source_selection', array($this, 'upgraderSourceSelectionFilter'), 10, 3); $this->theme = $theme; parent::upgrade($this->theme->stylesheet); // Make sure we get out of maintenance mode $this->maintenance_mode(false); } public function upgraderSourceSelectionFilter($source, $remote_source, $upgrader) { if ($upgrader->theme->hasSubdirectory()) { $source = trailingslashit($source) . trailingslashit($upgrader->theme->getSubdirectory()); } $newSource = trailingslashit($remote_source) . trailingslashit($upgrader->theme->getSlug()); global $wp_filesystem; if ( ! $wp_filesystem->move($source, $newSource, true)) return new \WP_Error(); return $newSource; } public function preSiteTransientUpdateThemesFilter($transient) { $options = array('package' => $this->theme->repository->getZipUrl()); $transient->response[$this->theme->stylesheet] = $options; return $transient; } }
gpl-2.0
doneself/agit
wp-content/plugins/content-views-query-and-display-post-page/public/templates/_view_type_/js/main.js
212
/** * Script Name: View type * * @package PT_Content_Views * @author PT Guy <palaceofthemes@gmail.com> * @license GPL-2.0+ * @link http://www.contentviewspro.com/ * @copyright 2014 PT Guy */
gpl-2.0
wnsonsa/destin-foot
vendor/friendsofsymfony/http-cache-bundle/Tests/Unit/UserContext/RequestMatcherTest.php
1438
<?php /* * This file is part of the FOSHttpCacheBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FOS\HttpCacheBundle\Tests\Unit\UserContext; use FOS\HttpCacheBundle\UserContext\RequestMatcher; use Symfony\Component\HttpFoundation\Request; class RequestMatcherTest extends \PHPUnit_Framework_TestCase { public function testMatch() { $requestMatcher = new RequestMatcher('application/vnd.test', 'HEAD'); $request = new Request(); $request->headers->set('accept', 'application/vnd.test'); $request->setMethod('HEAD'); $this->assertTrue($requestMatcher->matches($request)); $requestMatcher = new RequestMatcher('application/vnd.test'); $this->assertTrue($requestMatcher->matches($request)); $request->setMethod('GET'); $this->assertTrue($requestMatcher->matches($request)); } public function testNoMatch() { $requestMatcher = new RequestMatcher('application/vnd.test', 'HEAD'); $request = new Request(); $request->setMethod('GET'); $this->assertFalse($requestMatcher->matches($request)); $request->headers->set('accept', 'application/vnd.test'); $this->assertFalse($requestMatcher->matches($request)); } }
gpl-2.0
saddays/jdk7u-jdk
src/share/classes/com/sun/security/ntlm/Client.java
8215
/* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.security.ntlm; import java.math.BigInteger; import java.util.Arrays; import java.util.Date; import java.util.Locale; /** * The NTLM client. Not multi-thread enabled.<p> * Example: * <pre> * Client client = new Client(null, "host", "dummy", * "REALM", "t0pSeCr3t".toCharArray()); * byte[] type1 = client.type1(); * // Send type1 to server and receive response as type2 * byte[] type3 = client.type3(type2, nonce); * // Send type3 to server * </pre> */ public final class Client extends NTLM { final private String hostname; final private String username; private String domain; // might be updated by Type 2 msg private byte[] pw1, pw2; /** * Creates an NTLM Client instance. * @param version the NTLM version to use, which can be: * <ul> * <li>LM/NTLM: Original NTLM v1 * <li>LM: Original NTLM v1, LM only * <li>NTLM: Original NTLM v1, NTLM only * <li>NTLM2: NTLM v1 with Client Challenge * <li>LMv2/NTLMv2: NTLM v2 * <li>LMv2: NTLM v2, LM only * <li>NTLMv2: NTLM v2, NTLM only * </ul> * If null, "LMv2/NTLMv2" will be used. * @param hostname hostname of the client, can be null * @param username username to be authenticated, must not be null * @param domain domain of {@code username}, can be null * @param password password for {@code username}, must not be not null. * This method does not make any modification to this parameter, it neither * needs to access the content of this parameter after this method call, * so you are free to modify or nullify this parameter after this call. * @throws NTLMException if {@code username} or {@code password} is null, * or {@code version} is illegal. * */ public Client(String version, String hostname, String username, String domain, char[] password) throws NTLMException { super(version); if ((username == null || password == null)) { throw new NTLMException(NTLMException.PROTOCOL, "username/password cannot be null"); } this.hostname = hostname; this.username = username; this.domain = domain; this.pw1 = getP1(password); this.pw2 = getP2(password); debug("NTLM Client: (h,u,t,version(v)) = (%s,%s,%s,%s(%s))\n", hostname, username, domain, version, v.toString()); } /** * Generates the Type 1 message * @return the message generated */ public byte[] type1() { Writer p = new Writer(1, 32); int flags = 0x8203; if (hostname != null) { flags |= 0x2000; } if (domain != null) { flags |= 0x1000; } if (v != Version.NTLM) { flags |= 0x80000; } p.writeInt(12, flags); p.writeSecurityBuffer(24, hostname, false); p.writeSecurityBuffer(16, domain, false); debug("NTLM Client: Type 1 created\n"); debug(p.getBytes()); return p.getBytes(); } /** * Generates the Type 3 message * @param type2 the responding Type 2 message from server, must not be null * @param nonce random 8-byte array to be used in message generation, * must not be null except for original NTLM v1 * @return the message generated * @throws NTLMException if the incoming message is invalid, or * {@code nonce} is null for NTLM v1. */ public byte[] type3(byte[] type2, byte[] nonce) throws NTLMException { if (type2 == null || (v != Version.NTLM && nonce == null)) { throw new NTLMException(NTLMException.PROTOCOL, "type2 and nonce cannot be null"); } debug("NTLM Client: Type 2 received\n"); debug(type2); Reader r = new Reader(type2); byte[] challenge = r.readBytes(24, 8); int inputFlags = r.readInt(20); boolean unicode = (inputFlags & 1) == 1; String domainFromServer = r.readSecurityBuffer(12, unicode); if (domainFromServer != null) { domain = domainFromServer; } if (domain == null) { throw new NTLMException(NTLMException.NO_DOMAIN_INFO, "No domain info"); } int flags = 0x88200 | (inputFlags & 3); Writer p = new Writer(3, 64); byte[] lm = null, ntlm = null; p.writeSecurityBuffer(28, domain, unicode); p.writeSecurityBuffer(36, username, unicode); p.writeSecurityBuffer(44, hostname, unicode); if (v == Version.NTLM) { byte[] lmhash = calcLMHash(pw1); byte[] nthash = calcNTHash(pw2); if (writeLM) lm = calcResponse (lmhash, challenge); if (writeNTLM) ntlm = calcResponse (nthash, challenge); } else if (v == Version.NTLM2) { byte[] nthash = calcNTHash(pw2); lm = ntlm2LM(nonce); ntlm = ntlm2NTLM(nthash, nonce, challenge); } else { byte[] nthash = calcNTHash(pw2); if (writeLM) lm = calcV2(nthash, username.toUpperCase(Locale.US)+domain, nonce, challenge); if (writeNTLM) { byte[] alist = type2.length > 48 ? r.readSecurityBuffer(40) : new byte[0]; byte[] blob = new byte[32+alist.length]; System.arraycopy(new byte[]{1,1,0,0,0,0,0,0}, 0, blob, 0, 8); // TS byte[] time = BigInteger.valueOf(new Date().getTime()) .add(new BigInteger("11644473600000")) .multiply(BigInteger.valueOf(10000)) .toByteArray(); for (int i=0; i<time.length; i++) { blob[8+time.length-i-1] = time[i]; } System.arraycopy(nonce, 0, blob, 16, 8); System.arraycopy(new byte[]{0,0,0,0}, 0, blob, 24, 4); System.arraycopy(alist, 0, blob, 28, alist.length); System.arraycopy(new byte[]{0,0,0,0}, 0, blob, 28+alist.length, 4); ntlm = calcV2(nthash, username.toUpperCase(Locale.US)+domain, blob, challenge); } } p.writeSecurityBuffer(12, lm); p.writeSecurityBuffer(20, ntlm); p.writeSecurityBuffer(52, new byte[0]); p.writeInt(60, flags); debug("NTLM Client: Type 3 created\n"); debug(p.getBytes()); return p.getBytes(); } /** * Returns the domain value provided by server after the authentication * is complete, or the domain value provided by the client before it. * @return the domain */ public String getDomain() { return domain; } /** * Disposes any password-derived information. */ public void dispose() { Arrays.fill(pw1, (byte)0); Arrays.fill(pw2, (byte)0); } }
gpl-2.0
leominov/artup
wp-admin/post.php
8877
<?php /** * Edit post administration panel. * * Manage Post actions: post, edit, delete, etc. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once('./admin.php'); $parent_file = 'edit.php'; $submenu_file = 'edit.php'; wp_reset_vars( array( 'action' ) ); if ( isset( $_GET['post'] ) ) $post_id = $post_ID = (int) $_GET['post']; elseif ( isset( $_POST['post_ID'] ) ) $post_id = $post_ID = (int) $_POST['post_ID']; else $post_id = $post_ID = 0; $post = $post_type = $post_type_object = null; if ( $post_id ) $post = get_post( $post_id ); if ( $post ) { $post_type = $post->post_type; $post_type_object = get_post_type_object( $post_type ); } /** * Redirect to previous page. * * @param int $post_id Optional. Post ID. */ function redirect_post($post_id = '') { if ( isset($_POST['save']) || isset($_POST['publish']) ) { $status = get_post_status( $post_id ); if ( isset( $_POST['publish'] ) ) { switch ( $status ) { case 'pending': $message = 8; break; case 'future': $message = 9; break; default: $message = 6; } } else { $message = 'draft' == $status ? 10 : 1; } $location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) ); } elseif ( isset($_POST['addmeta']) && $_POST['addmeta'] ) { $location = add_query_arg( 'message', 2, wp_get_referer() ); $location = explode('#', $location); $location = $location[0] . '#postcustom'; } elseif ( isset($_POST['deletemeta']) && $_POST['deletemeta'] ) { $location = add_query_arg( 'message', 3, wp_get_referer() ); $location = explode('#', $location); $location = $location[0] . '#postcustom'; } elseif ( 'post-quickpress-save-cont' == $_POST['action'] ) { $location = "post.php?action=edit&post=$post_id&message=7"; } else { $location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) ); } wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) ); exit; } if ( isset( $_POST['deletepost'] ) ) $action = 'delete'; elseif ( isset($_POST['wp-preview']) && 'dopreview' == $_POST['wp-preview'] ) $action = 'preview'; $sendback = wp_get_referer(); if ( ! $sendback || strpos( $sendback, 'post.php' ) !== false || strpos( $sendback, 'post-new.php' ) !== false ) { if ( 'attachment' == $post_type ) { $sendback = admin_url( 'upload.php' ); } else { $sendback = admin_url( 'edit.php' ); $sendback .= ( ! empty( $post_type ) ) ? '?post_type=' . $post_type : ''; } } else { $sendback = remove_query_arg( array('trashed', 'untrashed', 'deleted', 'ids'), $sendback ); } switch($action) { case 'postajaxpost': case 'post': case 'post-quickpress-publish': case 'post-quickpress-save': check_admin_referer('add-' . $post_type); if ( 'post-quickpress-publish' == $action ) $_POST['publish'] = 'publish'; // tell write_post() to publish if ( 'post-quickpress-publish' == $action || 'post-quickpress-save' == $action ) { $_POST['comment_status'] = get_option('default_comment_status'); $_POST['ping_status'] = get_option('default_ping_status'); $post_id = edit_post(); } else { $post_id = 'postajaxpost' == $action ? edit_post() : write_post(); } if ( 0 === strpos( $action, 'post-quickpress' ) ) { $_POST['post_ID'] = $post_id; // output the quickpress dashboard widget require_once(ABSPATH . 'wp-admin/includes/dashboard.php'); wp_dashboard_quick_press(); exit; } redirect_post($post_id); exit(); break; case 'edit': $editing = true; if ( empty( $post_id ) ) { wp_redirect( admin_url('post.php') ); exit(); } if ( ! $post ) wp_die( __( 'You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?' ) ); if ( ! $post_type_object ) wp_die( __( 'Unknown post type.' ) ); if ( ! current_user_can( 'edit_post', $post_id ) ) wp_die( __( 'You are not allowed to edit this item.' ) ); if ( 'trash' == $post->post_status ) wp_die( __( 'You can&#8217;t edit this item because it is in the Trash. Please restore it and try again.' ) ); if ( ! empty( $_GET['get-post-lock'] ) ) { wp_set_post_lock( $post_id ); wp_redirect( get_edit_post_link( $post_id, 'url' ) ); exit(); } $post_type = $post->post_type; if ( 'post' == $post_type ) { $parent_file = "edit.php"; $submenu_file = "edit.php"; $post_new_file = "post-new.php"; } elseif ( 'attachment' == $post_type ) { $parent_file = 'upload.php'; $submenu_file = 'upload.php'; $post_new_file = 'media-new.php'; } else { if ( isset( $post_type_object ) && $post_type_object->show_in_menu && $post_type_object->show_in_menu !== true ) $parent_file = $post_type_object->show_in_menu; else $parent_file = "edit.php?post_type=$post_type"; $submenu_file = "edit.php?post_type=$post_type"; $post_new_file = "post-new.php?post_type=$post_type"; } if ( ! wp_check_post_lock( $post->ID ) ) { $active_post_lock = wp_set_post_lock( $post->ID ); if ( 'attachment' !== $post_type ) wp_enqueue_script('autosave'); } if ( is_multisite() ) { add_action( 'admin_footer', '_admin_notice_post_locked' ); } else { $check_users = get_users( array( 'fields' => 'ID', 'number' => 2 ) ); if ( count( $check_users ) > 1 ) add_action( 'admin_footer', '_admin_notice_post_locked' ); unset( $check_users ); } $title = $post_type_object->labels->edit_item; $post = get_post($post_id, OBJECT, 'edit'); if ( post_type_supports($post_type, 'comments') ) { wp_enqueue_script('admin-comments'); enqueue_comment_hotkeys_js(); } include('./edit-form-advanced.php'); break; case 'editattachment': check_admin_referer('update-post_' . $post_id); // Don't let these be changed unset($_POST['guid']); $_POST['post_type'] = 'attachment'; // Update the thumbnail filename $newmeta = wp_get_attachment_metadata( $post_id, true ); $newmeta['thumb'] = $_POST['thumb']; wp_update_attachment_metadata( $post_id, $newmeta ); case 'editpost': check_admin_referer('update-post_' . $post_id); $post_id = edit_post(); // Session cookie flag that the post was saved if ( isset( $_COOKIE['wp-saving-post-' . $post_id] ) ) setcookie( 'wp-saving-post-' . $post_id, 'saved' ); redirect_post($post_id); // Send user on their way while we keep working exit(); break; case 'trash': check_admin_referer('trash-post_' . $post_id); if ( ! $post ) wp_die( __( 'The item you are trying to move to the Trash no longer exists.' ) ); if ( ! $post_type_object ) wp_die( __( 'Unknown post type.' ) ); if ( ! current_user_can( 'delete_post', $post_id ) ) wp_die( __( 'You are not allowed to move this item to the Trash.' ) ); if ( $user_id = wp_check_post_lock( $post_id ) ) { $user = get_userdata( $user_id ); wp_die( sprintf( __( 'You cannot move this item to the Trash. %s is currently editing.' ), $user->display_name ) ); } if ( ! wp_trash_post( $post_id ) ) wp_die( __( 'Error in moving to Trash.' ) ); wp_redirect( add_query_arg( array('trashed' => 1, 'ids' => $post_id), $sendback ) ); exit(); break; case 'untrash': check_admin_referer('untrash-post_' . $post_id); if ( ! $post ) wp_die( __( 'The item you are trying to restore from the Trash no longer exists.' ) ); if ( ! $post_type_object ) wp_die( __( 'Unknown post type.' ) ); if ( ! current_user_can( 'delete_post', $post_id ) ) wp_die( __( 'You are not allowed to move this item out of the Trash.' ) ); if ( ! wp_untrash_post( $post_id ) ) wp_die( __( 'Error in restoring from Trash.' ) ); wp_redirect( add_query_arg('untrashed', 1, $sendback) ); exit(); break; case 'delete': check_admin_referer('delete-post_' . $post_id); if ( ! $post ) wp_die( __( 'This item has already been deleted.' ) ); if ( ! $post_type_object ) wp_die( __( 'Unknown post type.' ) ); if ( ! current_user_can( 'delete_post', $post_id ) ) wp_die( __( 'You are not allowed to delete this item.' ) ); $force = ! EMPTY_TRASH_DAYS; if ( $post->post_type == 'attachment' ) { $force = ( $force || ! MEDIA_TRASH ); if ( ! wp_delete_attachment( $post_id, $force ) ) wp_die( __( 'Error in deleting.' ) ); } else { if ( ! wp_delete_post( $post_id, $force ) ) wp_die( __( 'Error in deleting.' ) ); } wp_redirect( add_query_arg('deleted', 1, $sendback) ); exit(); break; case 'preview': check_admin_referer( 'autosave', 'autosavenonce' ); $url = post_preview(); wp_redirect($url); exit(); break; default: wp_redirect( admin_url('edit.php') ); exit(); break; } // end switch include('./admin-footer.php');
gpl-2.0
victoralex/gameleon
includes/node_modules/pgriess-node-msgpack-4c430f7/deps/msgpack/msgpack_test.cpp
26778
#include "msgpack.hpp" #include <math.h> #include <string> #include <vector> #include <map> #include <deque> #include <set> #include <list> #include <gtest/gtest.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif using namespace std; const unsigned int kLoop = 10000; const unsigned int kElements = 100; const double kEPS = 1e-10; #define GEN_TEST(test_type) \ do { \ vector<test_type> v; \ v.push_back(0); \ v.push_back(1); \ v.push_back(2); \ v.push_back(numeric_limits<test_type>::min()); \ v.push_back(numeric_limits<test_type>::max()); \ for (unsigned int i = 0; i < kLoop; i++) \ v.push_back(rand()); \ for (unsigned int i = 0; i < v.size() ; i++) { \ msgpack::sbuffer sbuf; \ test_type val1 = v[i]; \ msgpack::pack(sbuf, val1); \ msgpack::zone z; \ msgpack::object obj; \ msgpack::unpack_return ret = \ msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); \ EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); \ test_type val2; \ obj.convert(&val2); \ EXPECT_EQ(val1, val2); \ } \ } while(0) TEST(MSGPACK, simple_buffer_short) { GEN_TEST(short); } TEST(MSGPACK, simple_buffer_int) { GEN_TEST(int); } TEST(MSGPACK, simple_buffer_long) { GEN_TEST(long); } TEST(MSGPACK, simple_buffer_long_long) { GEN_TEST(long long); } TEST(MSGPACK, simple_buffer_unsigned_short) { GEN_TEST(unsigned short); } TEST(MSGPACK, simple_buffer_unsigned_int) { GEN_TEST(unsigned int); } TEST(MSGPACK, simple_buffer_unsigned_long) { GEN_TEST(unsigned long); } TEST(MSGPACK, simple_buffer_unsigned_long_long) { GEN_TEST(unsigned long long); } TEST(MSGPACK, simple_buffer_uint8) { GEN_TEST(uint8_t); } TEST(MSGPACK, simple_buffer_uint16) { GEN_TEST(uint16_t); } TEST(MSGPACK, simple_buffer_uint32) { GEN_TEST(uint32_t); } TEST(MSGPACK, simple_buffer_uint64) { GEN_TEST(uint64_t); } TEST(MSGPACK, simple_buffer_int8) { GEN_TEST(int8_t); } TEST(MSGPACK, simple_buffer_int16) { GEN_TEST(int16_t); } TEST(MSGPACK, simple_buffer_int32) { GEN_TEST(int32_t); } TEST(MSGPACK, simple_buffer_int64) { GEN_TEST(int64_t); } TEST(MSGPACK, simple_buffer_float) { vector<float> v; v.push_back(0.0); v.push_back(-0.0); v.push_back(1.0); v.push_back(-1.0); v.push_back(numeric_limits<float>::min()); v.push_back(numeric_limits<float>::max()); v.push_back(nanf("tag")); v.push_back(1.0/0.0); // inf v.push_back(-(1.0/0.0)); // -inf for (unsigned int i = 0; i < kLoop; i++) { v.push_back(drand48()); v.push_back(-drand48()); } for (unsigned int i = 0; i < v.size() ; i++) { msgpack::sbuffer sbuf; float val1 = v[i]; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); float val2; obj.convert(&val2); if (isnan(val1)) EXPECT_TRUE(isnan(val2)); else if (isinf(val1)) EXPECT_TRUE(isinf(val2)); else EXPECT_TRUE(fabs(val2 - val1) <= kEPS); } } TEST(MSGPACK, simple_buffer_double) { vector<double> v; v.push_back(0.0); v.push_back(-0.0); v.push_back(1.0); v.push_back(-1.0); v.push_back(numeric_limits<double>::min()); v.push_back(numeric_limits<double>::max()); v.push_back(nanf("tag")); v.push_back(1.0/0.0); // inf v.push_back(-(1.0/0.0)); // -inf for (unsigned int i = 0; i < kLoop; i++) { v.push_back(drand48()); v.push_back(-drand48()); } for (unsigned int i = 0; i < v.size() ; i++) { msgpack::sbuffer sbuf; double val1 = v[i]; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); double val2; obj.convert(&val2); if (isnan(val1)) EXPECT_TRUE(isnan(val2)); else if (isinf(val1)) EXPECT_TRUE(isinf(val2)); else EXPECT_TRUE(fabs(val2 - val1) <= kEPS); } } TEST(MSGPACK, simple_buffer_true) { msgpack::sbuffer sbuf; bool val1 = true; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); bool val2; obj.convert(&val2); EXPECT_EQ(val1, val2); } TEST(MSGPACK, simple_buffer_false) { msgpack::sbuffer sbuf; bool val1 = false; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); bool val2; obj.convert(&val2); EXPECT_EQ(val1, val2); } //----------------------------------------------------------------------------- // STL TEST(MSGPACK_STL, simple_buffer_string) { for (unsigned int k = 0; k < kLoop; k++) { string val1; for (unsigned int i = 0; i < kElements; i++) val1 += 'a' + rand() % 26; msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); string val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_EQ(val1, val2); } } TEST(MSGPACK_STL, simple_buffer_vector) { for (unsigned int k = 0; k < kLoop; k++) { vector<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.push_back(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); vector<int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_TRUE(equal(val1.begin(), val1.end(), val2.begin())); } } TEST(MSGPACK_STL, simple_buffer_map) { for (unsigned int k = 0; k < kLoop; k++) { map<int, int> val1; for (unsigned int i = 0; i < kElements; i++) val1[rand()] = rand(); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); map<int, int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_TRUE(equal(val1.begin(), val1.end(), val2.begin())); } } TEST(MSGPACK_STL, simple_buffer_deque) { for (unsigned int k = 0; k < kLoop; k++) { deque<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.push_back(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); deque<int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_TRUE(equal(val1.begin(), val1.end(), val2.begin())); } } TEST(MSGPACK_STL, simple_buffer_list) { for (unsigned int k = 0; k < kLoop; k++) { list<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.push_back(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); list<int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_TRUE(equal(val1.begin(), val1.end(), val2.begin())); } } TEST(MSGPACK_STL, simple_buffer_set) { for (unsigned int k = 0; k < kLoop; k++) { set<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.insert(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); set<int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); EXPECT_TRUE(equal(val1.begin(), val1.end(), val2.begin())); } } TEST(MSGPACK_STL, simple_buffer_pair) { for (unsigned int k = 0; k < kLoop; k++) { pair<int, int> val1 = make_pair(rand(), rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); pair<int, int> val2; obj.convert(&val2); EXPECT_EQ(val1.first, val2.first); EXPECT_EQ(val1.second, val2.second); } } TEST(MSGPACK_STL, simple_buffer_multimap) { for (unsigned int k = 0; k < kLoop; k++) { multimap<int, int> val1; for (unsigned int i = 0; i < kElements; i++) { int i1 = rand(); val1.insert(make_pair(i1, rand())); val1.insert(make_pair(i1, rand())); } msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); multimap<int, int> val2; obj.convert(&val2); vector<pair<int, int> > v1, v2; multimap<int, int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) v1.push_back(make_pair(it->first, it->second)); for (it = val2.begin(); it != val2.end(); ++it) v2.push_back(make_pair(it->first, it->second)); EXPECT_EQ(val1.size(), val2.size()); EXPECT_EQ(v1.size(), v2.size()); sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); EXPECT_TRUE(v1 == v2); } } TEST(MSGPACK_STL, simple_buffer_multiset) { for (unsigned int k = 0; k < kLoop; k++) { multiset<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.insert(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); multiset<int> val2; obj.convert(&val2); vector<int> v1, v2; multiset<int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) v1.push_back(*it); for (it = val2.begin(); it != val2.end(); ++it) v2.push_back(*it); EXPECT_EQ(val1.size(), val2.size()); EXPECT_EQ(v1.size(), v2.size()); sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); EXPECT_TRUE(v1 == v2); } } // TR1 #ifdef HAVE_TR1_UNORDERED_MAP #include <tr1/unordered_map> #include "msgpack/type/tr1/unordered_map.hpp" TEST(MSGPACK_TR1, simple_buffer_unordered_map) { for (unsigned int k = 0; k < kLoop; k++) { tr1::unordered_map<int, int> val1; for (unsigned int i = 0; i < kElements; i++) val1[rand()] = rand(); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); tr1::unordered_map<int, int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); tr1::unordered_map<int, int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) { EXPECT_TRUE(val2.find(it->first) != val2.end()); EXPECT_EQ(it->second, val2.find(it->first)->second); } } } TEST(MSGPACK_TR1, simple_buffer_unordered_multimap) { for (unsigned int k = 0; k < kLoop; k++) { tr1::unordered_multimap<int, int> val1; for (unsigned int i = 0; i < kElements; i++) { int i1 = rand(); val1.insert(make_pair(i1, rand())); val1.insert(make_pair(i1, rand())); } msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); tr1::unordered_multimap<int, int> val2; obj.convert(&val2); vector<pair<int, int> > v1, v2; tr1::unordered_multimap<int, int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) v1.push_back(make_pair(it->first, it->second)); for (it = val2.begin(); it != val2.end(); ++it) v2.push_back(make_pair(it->first, it->second)); EXPECT_EQ(val1.size(), val2.size()); EXPECT_EQ(v1.size(), v2.size()); sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); EXPECT_TRUE(v1 == v2); } } #endif #ifdef HAVE_TR1_UNORDERED_SET #include <tr1/unordered_set> #include "msgpack/type/tr1/unordered_set.hpp" TEST(MSGPACK_TR1, simple_buffer_unordered_set) { for (unsigned int k = 0; k < kLoop; k++) { tr1::unordered_set<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.insert(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); tr1::unordered_set<int> val2; obj.convert(&val2); EXPECT_EQ(val1.size(), val2.size()); tr1::unordered_set<int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) EXPECT_TRUE(val2.find(*it) != val2.end()); } } TEST(MSGPACK_TR1, simple_buffer_unordered_multiset) { for (unsigned int k = 0; k < kLoop; k++) { tr1::unordered_multiset<int> val1; for (unsigned int i = 0; i < kElements; i++) val1.insert(rand()); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); tr1::unordered_multiset<int> val2; obj.convert(&val2); vector<int> v1, v2; tr1::unordered_multiset<int>::const_iterator it; for (it = val1.begin(); it != val1.end(); ++it) v1.push_back(*it); for (it = val2.begin(); it != val2.end(); ++it) v2.push_back(*it); EXPECT_EQ(val1.size(), val2.size()); EXPECT_EQ(v1.size(), v2.size()); sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); EXPECT_TRUE(v1 == v2); } } #endif // User-Defined Structures class TestClass { public: TestClass() : i(0), s("kzk") {} int i; string s; MSGPACK_DEFINE(i, s); }; TEST(MSGPACK_USER_DEFINED, simple_buffer_class) { for (unsigned int k = 0; k < kLoop; k++) { TestClass val1; msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestClass val2; val2.i = -1; val2.s = ""; obj.convert(&val2); EXPECT_EQ(val1.i, val2.i); EXPECT_EQ(val1.s, val2.s); } } class TestClass2 { public: TestClass2() : i(0), s("kzk") { for (unsigned int i = 0; i < kElements; i++) v.push_back(rand()); } int i; string s; vector<int> v; MSGPACK_DEFINE(i, s, v); }; TEST(MSGPACK_USER_DEFINED, simple_buffer_class_old_to_new) { for (unsigned int k = 0; k < kLoop; k++) { TestClass val1; msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestClass2 val2; val2.i = -1; val2.s = ""; val2.v = vector<int>(); obj.convert(&val2); EXPECT_EQ(val1.i, val2.i); EXPECT_EQ(val1.s, val2.s); EXPECT_FALSE(val2.s.empty()); } } TEST(MSGPACK_USER_DEFINED, simple_buffer_class_new_to_old) { for (unsigned int k = 0; k < kLoop; k++) { TestClass2 val1; msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestClass val2; val2.i = -1; val2.s = ""; obj.convert(&val2); EXPECT_EQ(val1.i, val2.i); EXPECT_EQ(val1.s, val2.s); EXPECT_FALSE(val2.s.empty()); } } class TestEnumMemberClass { public: TestEnumMemberClass() : t1(STATE_A), t2(STATE_B), t3(STATE_C) {} enum TestEnumType { STATE_INVALID = 0, STATE_A = 1, STATE_B = 2, STATE_C = 3 }; TestEnumType t1; TestEnumType t2; TestEnumType t3; MSGPACK_DEFINE((int&)t1, (int&)t2, (int&)t3); }; TEST(MSGPACK_USER_DEFINED, simple_buffer_enum_member) { TestEnumMemberClass val1; msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestEnumMemberClass val2; val2.t1 = TestEnumMemberClass::STATE_INVALID; val2.t2 = TestEnumMemberClass::STATE_INVALID; val2.t3 = TestEnumMemberClass::STATE_INVALID; obj.convert(&val2); EXPECT_EQ(val1.t1, val2.t1); EXPECT_EQ(val1.t2, val2.t2); EXPECT_EQ(val1.t3, val2.t3); } class TestUnionMemberClass { public: TestUnionMemberClass() {} TestUnionMemberClass(double f) { is_double = true; value.f = f; } TestUnionMemberClass(int i) { is_double = false; value.i = i; } union { double f; int i; } value; bool is_double; template <typename Packer> void msgpack_pack(Packer& pk) const { if (is_double) pk.pack(msgpack::type::tuple<bool, double>(true, value.f)); else pk.pack(msgpack::type::tuple<bool, int>(false, value.i)); } void msgpack_unpack(msgpack::object o) { msgpack::type::tuple<bool, msgpack::object> tuple; o.convert(&tuple); is_double = tuple.get<0>(); if (is_double) tuple.get<1>().convert(&value.f); else tuple.get<1>().convert(&value.i); } }; TEST(MSGPACK_USER_DEFINED, simple_buffer_union_member) { { // double TestUnionMemberClass val1(1.0); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestUnionMemberClass val2; obj.convert(&val2); EXPECT_EQ(val1.is_double, val2.is_double); EXPECT_TRUE(fabs(val1.value.f - val2.value.f) < kEPS); } { // int TestUnionMemberClass val1(1); msgpack::sbuffer sbuf; msgpack::pack(sbuf, val1); msgpack::zone z; msgpack::object obj; msgpack::unpack_return ret = msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); TestUnionMemberClass val2; obj.convert(&val2); EXPECT_EQ(val1.is_double, val2.is_double); EXPECT_EQ(val1.value.i, 1); EXPECT_EQ(val1.value.i, val2.value.i); } } //----------------------------------------------------------------------------- #define GEN_TEST_VREF(test_type) \ do { \ vector<test_type> v; \ v.push_back(0); \ for (unsigned int i = 0; i < v.size(); i++) { \ test_type val1 = v[i]; \ msgpack::vrefbuffer vbuf; \ msgpack::pack(vbuf, val1); \ msgpack::sbuffer sbuf; \ const struct iovec* cur = vbuf.vector(); \ const struct iovec* end = cur + vbuf.vector_size(); \ for(; cur != end; ++cur) \ sbuf.write((const char*)cur->iov_base, cur->iov_len); \ msgpack::zone z; \ msgpack::object obj; \ msgpack::unpack_return ret = \ msgpack::unpack(sbuf.data(), sbuf.size(), NULL, &z, &obj); \ EXPECT_EQ(msgpack::UNPACK_SUCCESS, ret); \ test_type val2; \ obj.convert(&val2); \ EXPECT_EQ(val1, val2); \ } \ } while(0); TEST(MSGPACK, vrefbuffer_short) { GEN_TEST_VREF(short); } TEST(MSGPACK, vrefbuffer_int) { GEN_TEST_VREF(int); } TEST(MSGPACK, vrefbuffer_long) { GEN_TEST_VREF(long); } TEST(MSGPACK, vrefbuffer_long_long) { GEN_TEST_VREF(long long); } TEST(MSGPACK, vrefbuffer_unsigned_short) { GEN_TEST_VREF(unsigned short); } TEST(MSGPACK, vrefbuffer_unsigned_int) { GEN_TEST_VREF(unsigned int); } TEST(MSGPACK, vrefbuffer_unsigned_long) { GEN_TEST_VREF(unsigned long); } TEST(MSGPACK, vrefbuffer_unsigned_long_long) { GEN_TEST_VREF(unsigned long long); } TEST(MSGPACK, vrefbuffer_uint8) { GEN_TEST_VREF(uint8_t); } TEST(MSGPACK, vrefbuffer_uint16) { GEN_TEST_VREF(uint16_t); } TEST(MSGPACK, vrefbuffer_uint32) { GEN_TEST_VREF(uint32_t); } TEST(MSGPACK, vrefbuffer_uint64) { GEN_TEST_VREF(uint64_t); } TEST(MSGPACK, vrefbuffer_int8) { GEN_TEST_VREF(int8_t); } TEST(MSGPACK, vrefbuffer_int16) { GEN_TEST_VREF(int16_t); } TEST(MSGPACK, vrefbuffer_int32) { GEN_TEST_VREF(int32_t); } TEST(MSGPACK, vrefbuffer_int64) { GEN_TEST_VREF(int64_t); } //----------------------------------------------------------------------------- #define GEN_TEST_STREAM(test_type) \ for (unsigned int k = 0; k < kLoop; k++) { \ msgpack::sbuffer sbuf; \ msgpack::packer<msgpack::sbuffer> pk(sbuf); \ typedef std::vector<test_type> vec_type; \ vec_type vec; \ for(unsigned int i = 0; i < rand() % kLoop; ++i) { \ vec_type::value_type r = rand(); \ vec.push_back(r); \ pk.pack(r); \ } \ msgpack::unpacker pac; \ vec_type::const_iterator it = vec.begin(); \ const char *p = sbuf.data(); \ const char * const pend = p + sbuf.size(); \ while (p < pend) { \ const size_t sz = std::min<size_t>(pend - p, rand() % 128); \ pac.reserve_buffer(sz); \ memcpy(pac.buffer(), p, sz); \ pac.buffer_consumed(sz); \ while (pac.execute()) { \ if (it == vec.end()) goto out; \ msgpack::object obj = pac.data(); \ msgpack::zone *life = pac.release_zone(); \ EXPECT_TRUE(life != NULL); \ pac.reset(); \ vec_type::value_type val; \ obj.convert(&val); \ EXPECT_EQ(*it, val); \ ++it; \ delete life; \ } \ p += sz; \ } \ out: \ ; \ } TEST(MSGPACK, stream_short) { GEN_TEST_STREAM(short); } TEST(MSGPACK, stream_int) { GEN_TEST_STREAM(int); } TEST(MSGPACK, stream_long) { GEN_TEST_STREAM(long); } TEST(MSGPACK, stream_long_long) { GEN_TEST_STREAM(long long); } TEST(MSGPACK, stream_unsigned_short) { GEN_TEST_STREAM(unsigned short); } TEST(MSGPACK, stream_unsigned_int) { GEN_TEST_STREAM(unsigned int); } TEST(MSGPACK, stream_unsigned_long) { GEN_TEST_STREAM(unsigned long); } TEST(MSGPACK, stream_unsigned_long_long) { GEN_TEST_STREAM(unsigned long long); } TEST(MSGPACK, stream_uint8) { GEN_TEST_STREAM(uint8_t); } TEST(MSGPACK, stream_uint16) { GEN_TEST_STREAM(uint16_t); } TEST(MSGPACK, stream_uint32) { GEN_TEST_STREAM(uint32_t); } TEST(MSGPACK, stream_uint64) { GEN_TEST_STREAM(uint64_t); } TEST(MSGPACK, stream_int8) { GEN_TEST_STREAM(int8_t); } TEST(MSGPACK, stream_int16) { GEN_TEST_STREAM(int16_t); } TEST(MSGPACK, stream_int32) { GEN_TEST_STREAM(int32_t); } TEST(MSGPACK, stream_int64) { GEN_TEST_STREAM(int64_t); }
gpl-2.0
vvanherk/oscar_emr
src/main/java/org/oscarehr/util/NotAuthorisedException.java
1306
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.util; /** * This is meant to be a generic exception that's thrown when ever some one * requests something they are not authorised to do. */ public class NotAuthorisedException extends Exception { public NotAuthorisedException(String s) { super(s); } }
gpl-2.0
folbo/MuseScore
zerberus/sfz.cpp
23829
//============================================================================= // Zerberos // Zample player // // Copyright (C) 2013 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include <stdio.h> #include <math.h> #include <QFile> #include <QFileInfo> #include <QStringList> #include <sndfile.h> #include "libmscore/xml.h" #include "instrument.h" #include "zone.h" #include "sample.h" #include "zerberus.h" //--------------------------------------------------------- // SfzControl //--------------------------------------------------------- struct SfzControl { QString defaultPath; int octave_offset; int note_offset; int set_cc[128]; std::map<QString, QString> defines; void init(); }; void SfzControl::init() { defaultPath.clear(); octave_offset = 0; note_offset = 0; } //--------------------------------------------------------- // SfzRegion //--------------------------------------------------------- struct SfzRegion { QString path; double amp_veltrack; // amp envelope all in seconds // but the level ones // they are in percent double ampeg_delay; double ampeg_start; // level double ampeg_attack; double ampeg_hold; double ampeg_decay; double ampeg_sustain; // level double ampeg_release; double rt_decay; double ampeg_vel2delay; double ampeg_vel2attack; double ampeg_vel2hold; double ampeg_vel2decay; double ampeg_vel2sustain; double ampeg_vel2release; QString sample; int lochan, hichan; int lokey, hikey, lovel, hivel, pitch_keycenter; double hirand, lorand; int on_locc[128]; int on_hicc[128]; int locc[128]; int hicc[128]; bool use_cc; int off_by; int group; int seq_length, seq_position; double volume; int octave_offset, note_offset; int tune, transpose; double pitch_keytrack; int loopStart, loopEnd; Trigger trigger; LoopMode loop_mode; OffMode off_mode; std::map<int, double> gain_oncc; void init(const QString&); bool isEmpty() const { return sample.isEmpty(); } int readKey(const QString&, SfzControl c) const; void readOp(const QString& token, const QString& data, SfzControl& c); void setZone(Zone*) const; }; //--------------------------------------------------------- // init //--------------------------------------------------------- void SfzRegion::init(const QString& _path) { path = _path; lochan = 1; hichan = 16; amp_veltrack = 100; ampeg_delay = 0.0; ampeg_start = 0.0; //percent ampeg_attack = 0.001; ampeg_hold = 0.0; ampeg_decay = 0.0; ampeg_sustain = 100.0; // percent ampeg_release = 0.200; // in sec ampeg_vel2delay = 0.0; ampeg_vel2attack = 0.0; ampeg_vel2hold = 0.0; ampeg_vel2decay = 0.0; ampeg_vel2sustain = 0.0; ampeg_vel2release = 0.0; rt_decay = 0.0; // dB /sec lokey = 0; hikey = 127; lovel = 0; hivel = 127; pitch_keycenter = 60; sample = ""; lorand = 0.0; hirand = 1.0; group = 0; off_by = 0; volume = 1.0; seq_length = 1; seq_position = 1; trigger = Trigger::ATTACK; loop_mode = LoopMode::CONTINUOUS; tune = 0; transpose = 0; pitch_keytrack = 100.0; loopStart = -1; loopEnd = -1; for (int i = 0; i < 128; ++i) { on_locc[i] = -1; on_hicc[i] = -1; locc[i] = 0; hicc[i] = 127; } use_cc = false; off_mode = OffMode::FAST; gain_oncc.clear(); } //--------------------------------------------------------- // setZone // set Zone from sfzRegion //--------------------------------------------------------- void SfzRegion::setZone(Zone* z) const { z->keyLo = lokey; z->keyHi = hikey; z->veloLo = lovel; z->veloHi = hivel; z->keyBase = pitch_keycenter; z->offset = 0; z->volume = pow(10.0, volume / 20.0); z->ampVeltrack = amp_veltrack; z->ampegAttack = ampeg_attack * 1000; z->ampegDelay = ampeg_delay * 1000; z->ampegStart = ampeg_start / 100.0; z->ampegHold = ampeg_hold * 1000; z->ampegDecay = ampeg_decay * 1000; z->ampegSustain = ampeg_sustain / 100.0; z->ampegRelease = ampeg_release * 1000; // all vel2* but vel2sustain are time values in seconds z->ampegVel2Delay = ampeg_vel2delay * 1000; z->ampegVel2Attack = ampeg_vel2attack * 1000; z->ampegVel2Hold = ampeg_vel2hold * 1000; z->ampegVel2Decay = ampeg_vel2decay * 1000; z->ampegVel2Sustain = ampeg_vel2sustain / 100; // level in percent z->ampegVel2Release = ampeg_vel2release * 1000; z->seqPos = seq_position - 1; z->seqLen = seq_length - 1; z->seq = 0; z->trigger = trigger; z->loopMode = loop_mode; z->tune = tune + transpose * 100; z->pitchKeytrack = pitch_keytrack / (double) 100.0; z->rtDecay = rt_decay; for (int i = 0; i < 128; ++i) { z->onLocc[i] = on_locc[i]; z->onHicc[i] = on_hicc[i]; z->locc[i] = locc[i]; z->hicc[i] = hicc[i]; } z->useCC = use_cc; z->offMode = off_mode; z->offBy = off_by; z->loRand = lorand; z->hiRand = hirand; z->group = group; z->loopEnd = loopEnd; z->loopStart = loopStart; z->gainOnCC = gain_oncc; } //--------------------------------------------------------- // readKey //--------------------------------------------------------- int SfzRegion::readKey(const QString& s, SfzControl c) const { bool ok; int i = s.toInt(&ok); if (ok) { i += c.octave_offset * 12; i += c.note_offset; return i; } switch (s[0].toLower().toLatin1()) { case 'c': i = 0; break; case 'd': i = 2; break; case 'e': i = 4; break; case 'f': i = 5; break; case 'g': i = 7; break; case 'a': i = 9; break; case 'b': i = 11; break; default: qDebug("SfzRegion: Not a note: %s", qPrintable(s)); return 0; } int idx = 1; if (s[idx].toLatin1() == '#') { i++; ++idx; } else if (s[idx].toLower().toLatin1() == 'b') { i--; ++idx; } int octave = s.mid(idx).toInt(&ok); if (!ok) { qDebug("SfzRegion: Not a note: %s", qPrintable(s)); return 0; } i += (octave + 1) * 12; i += c.octave_offset * 12; i += c.note_offset; return i; } //--------------------------------------------------------- // addRegion //--------------------------------------------------------- void ZInstrument::addRegion(SfzRegion& r) { for (int i = 0; i < 128; ++i) { if (r.on_locc[i] != -1 || r.on_hicc[i] != -1) { r.trigger = Trigger::CC; break; } } Zone* z = new Zone; z->sample = readSample(r.sample, 0); if (z->sample) { qDebug("Sample Loop - start %d, end %d, mode %d", z->sample->loopStart(), z->sample->loopEnd(), z->sample->loopMode()); // if there is no opcode defining loop ranges, use sample definitions as fallback (according to spec) if (r.loopStart == -1) r.loopStart = z->sample->loopStart(); if (r.loopEnd == -1) r.loopEnd = z->sample->loopEnd(); } r.setZone(z); if (z->sample) addZone(z); } //--------------------------------------------------------- // readDouble //--------------------------------------------------------- static void readDouble(const QString& data, double* val) { bool ok; double d = data.toDouble(&ok); if (ok) *val = d; } //--------------------------------------------------------- // readInt //--------------------------------------------------------- static void readInt(const QString& data, int* val) { bool ok; int i = data.toInt(&ok); if (ok) *val = i; } //--------------------------------------------------------- // readOp //--------------------------------------------------------- void SfzRegion::readOp(const QString& b, const QString& data, SfzControl &c) { QString opcode = QString(b); QString opcode_data_full = QString(data); for(auto define : c.defines) { opcode.replace(define.first, define.second); opcode_data_full.replace(define.first, define.second); } QStringList splitData = opcode_data_full.split(" "); // no spaces in opcode values except for sample definition QString opcode_data = splitData[0]; int i = opcode_data.toInt(); if (opcode == "amp_veltrack") readDouble(opcode_data, &amp_veltrack); else if (opcode == "ampeg_delay") readDouble(opcode_data, &ampeg_delay); else if (opcode == "ampeg_start") readDouble(opcode_data, &ampeg_start); else if (opcode == "ampeg_attack") readDouble(opcode_data, &ampeg_attack); else if (opcode == "ampeg_hold") readDouble(opcode_data, &ampeg_hold); else if (opcode == "ampeg_decay") readDouble(opcode_data, &ampeg_decay); else if (opcode == "ampeg_sustain") readDouble(opcode_data, &ampeg_sustain); else if (opcode == "ampeg_release") readDouble(opcode_data, &ampeg_release); else if (opcode == "ampeg_vel2delay") readDouble(opcode_data, &ampeg_vel2delay); else if (opcode == "ampeg_vel2attack") readDouble(opcode_data, &ampeg_vel2attack); else if (opcode == "ampeg_vel2hold") readDouble(opcode_data, &ampeg_vel2hold); else if (opcode == "ampeg_vel2decay") readDouble(opcode_data, &ampeg_vel2decay); else if (opcode == "ampeg_vel2sustain") readDouble(opcode_data, &ampeg_vel2sustain); else if (opcode == "ampeg_vel2release") readDouble(opcode_data, &ampeg_vel2release); else if (opcode == "sample") { sample = path + "/" + c.defaultPath + "/" + opcode_data_full; // spaces are allowed sample.replace("\\", "/"); } else if (opcode == "default_path") { c.defaultPath = opcode_data_full; } else if (opcode == "key") { lokey = readKey(opcode_data, c); hikey = lokey; pitch_keycenter = lokey; } else if (opcode == "pitch_keytrack") readDouble(opcode_data, &pitch_keytrack); else if (opcode == "trigger") { if (opcode_data == "attack") trigger = Trigger::ATTACK; else if (opcode_data == "release") trigger = Trigger::RELEASE; else if (opcode_data == "first") trigger = Trigger::FIRST; else if (opcode_data == "legato") trigger = Trigger::LEGATO; else qDebug("SfzRegion: bad trigger value: %s", qPrintable(opcode_data)); } else if (opcode == "loop_mode") { if (opcode_data == "no_loop") loop_mode = LoopMode::NO_LOOP; else if (opcode_data == "one_shot") loop_mode = LoopMode::ONE_SHOT; else if (opcode_data == "loop_continuous") loop_mode = LoopMode::CONTINUOUS; else if (opcode_data == "loop_sustain") loop_mode = LoopMode::SUSTAIN; if (loop_mode != LoopMode::ONE_SHOT) qDebug("SfzRegion: loop_mode <%s>", qPrintable(opcode_data)); } else if(opcode == "loop_start") readInt(opcode_data, &loopStart); else if(opcode == "loop_end") readInt(opcode_data, &loopEnd); else if (opcode.startsWith("on_locc")) { int idx = b.mid(7).toInt(); if (idx >= 0 && idx < 128) on_locc[idx] = i; } else if (opcode.startsWith("on_hicc")) { int idx = b.mid(7).toInt(); if (idx >= 0 && idx < 128) on_hicc[idx] = i; } else if (opcode.startsWith("locc")) { int idx = b.mid(4).toInt(); if (!use_cc) use_cc = i != 0; if (idx >= 0 && idx < 128) locc[idx] = i; } else if (opcode.startsWith("hicc")) { int idx = b.mid(4).toInt(); if (!use_cc) use_cc = i != 127; if (idx >= 0 && idx < 128) hicc[idx] = i; } else if (opcode.startsWith("set_cc")) { int idx = b.mid(6).toInt(); if (idx >= 0 && idx < 128) c.set_cc[idx] = i; } else if (opcode == "off_mode") { if (opcode_data == "fast") off_mode = OffMode::FAST; else if (opcode_data == "normal") off_mode = OffMode::NORMAL; } else if (opcode.startsWith("gain_cc")) { int idx = b.mid(7).toInt(); double v; if (idx >= 0 && idx < 128) { readDouble(opcode_data, &v); gain_oncc.insert(std::pair<int, double>(idx, v)); } } else if (opcode.startsWith("gain_oncc")) { int idx = b.mid(9).toInt(); double v; if (idx >= 0 && idx < 128) { readDouble(opcode_data, &v); gain_oncc.insert(std::pair<int, double>(idx, v)); } } else if (opcode == "tune") tune = i; else if (opcode == "rt_decay") readDouble(opcode_data, &rt_decay); else if (opcode == "hirand") readDouble(opcode_data, &hirand); else if (opcode == "lorand") readDouble(opcode_data, &lorand); else if (opcode == "volume") readDouble(opcode_data, &volume); else if (opcode == "pitch_keycenter") pitch_keycenter = readKey(opcode_data ,c); else if (opcode == "lokey") lokey = readKey(opcode_data, c); else if (opcode == "hikey") hikey = readKey(opcode_data, c); else if (opcode == "lovel") lovel = i; else if (opcode == "hivel") hivel = i; else if (opcode == "off_by") off_by = i; else if (opcode == "group") group = i; else if (opcode == "lochan") lochan = i; else if (opcode == "hichan") hichan = i; else if (opcode == "note_offset") c.note_offset = i; else if (opcode == "octave_offset") c.octave_offset = i; else if (opcode == "seq_length") seq_length = i; else if (opcode == "seq_position") seq_position = i; else if (opcode == "transpose") transpose = i; else qDebug("SfzRegion: unknown opcode <%s>", qPrintable(opcode)); } QStringList readFile(QString const fn) { QFile f(fn); QStringList list; if (!f.open(QIODevice::ReadOnly)) { qDebug("ZInstrument: cannot load %s", qPrintable(fn)); return list; } while (!f.atEnd()) list.append(QString(f.readLine().simplified())); return list; } //--------------------------------------------------------- // loadSfz //--------------------------------------------------------- bool ZInstrument::loadSfz(const QString& s) { _program = 0; QFileInfo fi(s); QString path = fi.absolutePath(); QStringList fileContents = readFile(s); if (fileContents.empty()) { return false; } SfzControl c; c.init(); c.defines.clear(); for (int i = 0;i < 128; i++) c.set_cc[i] = -1; int idx = 0; bool inBlockComment = false; // preprocessor while(idx < fileContents.size()) { QRegularExpression findWithSpaces("\"(.+)\""); QRegularExpression comment("//.*$"); QRegularExpression trailingSpacesOrTab("^[\\s\\t]*"); QRegularExpressionMatch foundWithSpaces; QString curLine = fileContents[idx]; QString curLineCopy = curLine; bool nextIsImportant = false; int idxBlockComment = 0; int from = 0; for (QChar chr : curLineCopy) { bool terminated = false; if (nextIsImportant) { nextIsImportant = false; if (inBlockComment && chr == '/') { // found block end inBlockComment = false; terminated = true; curLine.remove(from, idxBlockComment - from + 1); idxBlockComment = from - 1; } else if (!inBlockComment && chr == '*') { // found block start inBlockComment = true; terminated = true; from = idxBlockComment - 1; } } if (!terminated && inBlockComment && chr == '*') nextIsImportant = true; else if (!terminated && !inBlockComment && chr == '/') nextIsImportant = true; idxBlockComment++; } if (inBlockComment) curLine.remove(from, curLine.size() - from); curLine = curLine.remove(comment); curLine.remove(trailingSpacesOrTab); fileContents[idx] = curLine; if (curLine.startsWith("#define")) { QStringList define = curLine.split(" "); foundWithSpaces = findWithSpaces.match(curLine); if (define.size() == 3) c.defines.insert(std::pair<QString, QString>(define[1], define[2])); else if(foundWithSpaces.hasMatch()) c.defines.insert(std::pair<QString, QString>(define[1], foundWithSpaces.captured(1))); fileContents.removeAt(idx); } else if (curLine.startsWith("#include")) { foundWithSpaces = findWithSpaces.match(curLine); if (foundWithSpaces.hasMatch()) { QString newFilename = foundWithSpaces.captured(1); for(auto define : c.defines) { newFilename.replace(define.first, define.second); } QStringList newFileContents = readFile(path + "/" + newFilename); if (newFileContents.empty()) return false; int offset = 1; for (QString newFileLine : newFileContents) { fileContents.insert(idx+offset, newFileLine); offset++; } fileContents.removeAt(idx); } } else if (curLine.isEmpty()) fileContents.removeAt(idx); else idx++; } int total = fileContents.size(); SfzRegion r; SfzRegion g; // group SfzRegion glob; r.init(path); g.init(path); glob.init(path); bool groupMode = false; bool globMode = false; zerberus->setLoadProgress(0); for (int idx = 0; idx < fileContents.size(); idx++) { QString curLine = fileContents[idx]; zerberus->setLoadProgress(((qreal) idx * 100) / (qreal) total); if (zerberus->loadWasCanceled()) return false; if (curLine.startsWith("<global>")) { if (!globMode && !groupMode && !r.isEmpty()) addRegion(r); glob.init(path); g.init(path); // global also resets group r.init(path); globMode = true; } if (curLine.startsWith("<group>")) { if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); g.init(path); if (globMode) { glob = r; globMode = false; } else { r = glob; // initalize group with global values } groupMode = true; curLine = curLine.mid(7); } else if (curLine.startsWith("<region>")) { if (groupMode) { g = r; groupMode = false; } else if (globMode) { glob = r; g = glob; globMode = false; } else { if (!r.isEmpty()) addRegion(r); r = g; // initialize next region with group values } curLine = curLine.mid(8); } else if (curLine.startsWith("<control>")) c.init(); QRegularExpression re("\\s?([\\w\\$]+)="); // defines often use the $-sign QRegularExpressionMatchIterator i = re.globalMatch(curLine); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); int si = match.capturedEnd(); int ei; if (i.hasNext()) { QRegularExpressionMatch nextMatch = i.peekNext(); ei = nextMatch.capturedStart(); } else ei = curLine.size(); QString s = curLine.mid(si, ei-si); r.readOp(match.captured(1), s, c); } } for (int i = 0; i < 128; i++) _setcc[i] = c.set_cc[i]; zerberus->setLoadProgress(100); if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); return true; }
gpl-2.0
Laniax/Project-Extinct
src/server/game/Server/Protocol/Handlers/MovementHandler.cpp
21532
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * 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, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "Corpse.h" #include "Player.h" #include "SpellAuras.h" #include "MapManager.h" #include "Transport.h" #include "Battleground.h" #include "WaypointMovementGenerator.h" #include "InstanceSaveMgr.h" #include "ObjectMgr.h" void WorldSession::HandleMoveWorldportAckOpcode(WorldPacket & /*recv_data*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: got MSG_MOVE_WORLDPORT_ACK."); HandleMoveWorldportAckOpcode(); } void WorldSession::HandleMoveWorldportAckOpcode() { // ignore unexpected far teleports if (!GetPlayer()->IsBeingTeleportedFar()) return; GetPlayer()->SetSemaphoreTeleportFar(false); // get the teleport destination WorldLocation &loc = GetPlayer()->GetTeleportDest(); // possible errors in the coordinate validity check if (!MapManager::IsValidMapCoord(loc)) { LogoutPlayer(false); return; } // get the destination map entry, not the current one, this will fix homebind and reset greeting MapEntry const* mEntry = sMapStore.LookupEntry(loc.GetMapId()); InstanceTemplate const* mInstance = sObjectMgr->GetInstanceTemplate(loc.GetMapId()); // reset instance validity, except if going to an instance inside an instance if (GetPlayer()->m_InstanceValid == false && !mInstance) GetPlayer()->m_InstanceValid = true; Map * oldMap = GetPlayer()->GetMap(); ASSERT(oldMap); if (GetPlayer()->IsInWorld()) { sLog->outCrash("Player is still in world when teleported from map %u! to new map %u", oldMap->GetId(), loc.GetMapId()); oldMap->Remove(GetPlayer(), false); } // relocate the player to the teleport destination Map * newMap = sMapMgr->CreateMap(loc.GetMapId(), GetPlayer(), 0); // the CanEnter checks are done in TeleporTo but conditions may change // while the player is in transit, for example the map may get full if (!newMap || !newMap->CanEnter(GetPlayer())) { sLog->outError("Map %d could not be created for player %d, porting player to homebind", loc.GetMapId(), GetPlayer()->GetGUIDLow()); GetPlayer()->TeleportTo(GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation()); return; } else GetPlayer()->Relocate(&loc); GetPlayer()->ResetMap(); GetPlayer()->SetMap(newMap); GetPlayer()->SendInitialPacketsBeforeAddToMap(); if (!GetPlayer()->GetMap()->Add(GetPlayer())) { sLog->outError("WORLD: failed to teleport player %s (%d) to map %d because of unknown reason!", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), loc.GetMapId()); GetPlayer()->ResetMap(); GetPlayer()->SetMap(oldMap); GetPlayer()->TeleportTo(GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation()); return; } // battleground state prepare (in case join to BG), at relogin/tele player not invited // only add to bg group and object, if the player was invited (else he entered through command) if (_player->InBattleground()) { // cleanup setting if outdated if (!mEntry->IsBattlegroundOrArena()) { // We're not in BG _player->SetBattlegroundId(0, BATTLEGROUND_TYPE_NONE); // reset destination bg team _player->SetBGTeam(0); } // join to bg case else if (Battleground *bg = _player->GetBattleground()) { if (_player->IsInvitedForBattlegroundInstance(_player->GetBattlegroundId())) bg->AddPlayer(_player); } } GetPlayer()->SendInitialPacketsAfterAddToMap(); // flight fast teleport case if (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE) { if (!_player->InBattleground()) { // short preparations to continue flight FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top()); flight->Initialize(*GetPlayer()); return; } // battleground state prepare, stop flight GetPlayer()->GetMotionMaster()->MovementExpired(); GetPlayer()->CleanupAfterTaxiFlight(); } // resurrect character at enter into instance where his corpse exist after add to map Corpse *corpse = GetPlayer()->GetCorpse(); if (corpse && corpse->GetType() != CORPSE_BONES && corpse->GetMapId() == GetPlayer()->GetMapId()) { if (mEntry->IsDungeon()) { GetPlayer()->ResurrectPlayer(0.5f, false); GetPlayer()->SpawnCorpseBones(); } } bool allowMount = !mEntry->IsDungeon() || mEntry->IsBattlegroundOrArena(); if (mInstance) { Difficulty diff = GetPlayer()->GetDifficulty(mEntry->IsRaid()); if (MapDifficulty const* mapDiff = GetMapDifficultyData(mEntry->MapID, diff)) { if (mapDiff->resetTime) { if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(mEntry->MapID, diff)) { uint32 timeleft = uint32(timeReset - time(NULL)); GetPlayer()->SendInstanceResetWarning(mEntry->MapID, diff, timeleft); } } } allowMount = mInstance->AllowMount; } // mount allow check if (!allowMount) _player->RemoveAurasByType(SPELL_AURA_MOUNTED); // update zone immediately, otherwise leave channel will cause crash in mtmap uint32 newzone, newarea; GetPlayer()->GetZoneAndAreaId(newzone, newarea); GetPlayer()->UpdateZone(newzone, newarea); // honorless target if (GetPlayer()->pvpInfo.inHostileArea) GetPlayer()->CastSpell(GetPlayer(), 2479, true); // in friendly area else if (GetPlayer()->IsPvP() && !GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP)) GetPlayer()->UpdatePvP(false, false); // resummon pet GetPlayer()->ResummonPetTemporaryUnSummonedIfAny(); //lets process all delayed operations on successful teleport GetPlayer()->ProcessDelayedOperations(); } void WorldSession::HandleMoveTeleportAck(WorldPacket& recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_MOVE_TELEPORT_ACK"); uint64 guid; recv_data.readPackGUID(guid); uint32 flags, time; recv_data >> flags >> time; sLog->outStaticDebug("Guid " UI64FMTD, guid); sLog->outStaticDebug("Flags %u, time %u", flags, time/IN_MILLISECONDS); Unit *mover = _player->m_mover; Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL; if (!plMover || !plMover->IsBeingTeleportedNear()) return; if (guid != plMover->GetGUID()) return; plMover->SetSemaphoreTeleportNear(false); uint32 old_zone = plMover->GetZoneId(); WorldLocation const& dest = plMover->GetTeleportDest(); plMover->SetPosition(dest, true); uint32 newzone, newarea; plMover->GetZoneAndAreaId(newzone, newarea); plMover->UpdateZone(newzone, newarea); // new zone if (old_zone != newzone) { // honorless target if (plMover->pvpInfo.inHostileArea) plMover->CastSpell(plMover, 2479, true); // in friendly area else if (plMover->IsPvP() && !plMover->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP)) plMover->UpdatePvP(false, false); } // resummon pet GetPlayer()->ResummonPetTemporaryUnSummonedIfAny(); //lets process all delayed operations on successful teleport GetPlayer()->ProcessDelayedOperations(); } void WorldSession::HandleMovementOpcodes(WorldPacket & recv_data) { uint16 opcode = recv_data.GetOpcode(); recv_data.hexlike(); Unit *mover = _player->m_mover; ASSERT(mover != NULL); // there must always be a mover Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL; // ignore, waiting processing in WorldSession::HandleMoveWorldportAckOpcode and WorldSession::HandleMoveTeleportAck if (plMover && plMover->IsBeingTeleported()) { recv_data.rpos(recv_data.wpos()); // prevent warnings spam return; } /* extract packet */ uint64 guid; recv_data.readPackGUID(guid); MovementInfo movementInfo; movementInfo.guid = guid; ReadMovementInfo(recv_data, &movementInfo); recv_data.rpos(recv_data.wpos()); // prevent warnings spam // prevent tampered movement data if (guid != mover->GetGUID()) return; if (!movementInfo.pos.IsPositionValid()) { recv_data.rpos(recv_data.wpos()); // prevent warnings spam return; } /* handle special cases */ if (movementInfo.flags & MOVEMENTFLAG_ONTRANSPORT) { // transports size limited // (also received at zeppelin leave by some reason with t_* as absolute in continent coordinates, can be safely skipped) if (movementInfo.t_pos.GetPositionX() > 50 || movementInfo.t_pos.GetPositionY() > 50 || movementInfo.t_pos.GetPositionZ() > 50) { recv_data.rpos(recv_data.wpos()); // prevent warnings spam return; } if (!Trinity::IsValidMapCoord(movementInfo.pos.GetPositionX() + movementInfo.t_pos.GetPositionX(), movementInfo.pos.GetPositionY() + movementInfo.t_pos.GetPositionY(), movementInfo.pos.GetPositionZ() + movementInfo.t_pos.GetPositionZ(), movementInfo.pos.GetOrientation() + movementInfo.t_pos.GetOrientation())) { recv_data.rpos(recv_data.wpos()); // prevent warnings spam return; } // if we boarded a transport, add us to it if (plMover && !plMover->GetTransport()) { // elevators also cause the client to send MOVEMENTFLAG_ONTRANSPORT - just unmount if the guid can be found in the transport list for (MapManager::TransportSet::const_iterator iter = sMapMgr->m_Transports.begin(); iter != sMapMgr->m_Transports.end(); ++iter) { if ((*iter)->GetGUID() == movementInfo.t_guid) { plMover->m_transport = (*iter); (*iter)->AddPassenger(plMover); break; } } } if (!mover->GetTransport() && !mover->GetVehicle()) { GameObject *go = mover->GetMap()->GetGameObject(movementInfo.t_guid); if (!go || go->GetGoType() != GAMEOBJECT_TYPE_TRANSPORT) movementInfo.flags &= ~MOVEMENTFLAG_ONTRANSPORT; } } else if (plMover && plMover->GetTransport()) // if we were on a transport, leave { plMover->m_transport->RemovePassenger(plMover); plMover->m_transport = NULL; movementInfo.t_pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); movementInfo.t_time = 0; movementInfo.t_seat = -1; } // fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map). if (opcode == MSG_MOVE_FALL_LAND && plMover && !plMover->isInFlight()) plMover->HandleFall(movementInfo); if (plMover && ((movementInfo.flags & MOVEMENTFLAG_SWIMMING) != 0) != plMover->IsInWater()) { // now client not include swimming flag in case jumping under water plMover->SetInWater(!plMover->IsInWater() || plMover->GetBaseMap()->IsUnderWater(movementInfo.pos.GetPositionX(), movementInfo.pos.GetPositionY(), movementInfo.pos.GetPositionZ())); } /*----------------------*/ /* process position-change */ WorldPacket data(opcode, recv_data.size()); movementInfo.time = getMSTime(); movementInfo.guid = mover->GetGUID(); WriteMovementInfo(&data, &movementInfo); mover->SendMessageToSet(&data, _player); mover->m_movementInfo = movementInfo; // this is almost never true (not sure why it is sometimes, but it is), normally use mover->IsVehicle() if (mover->GetVehicle()) { mover->SetOrientation(movementInfo.pos.GetOrientation()); return; } mover->SetPosition(movementInfo.pos); if (plMover) // nothing is charmed, or player charmed { plMover->UpdateFallInformationIfNeed(movementInfo, opcode); if (movementInfo.pos.GetPositionZ() < -500.0f) { if (!(plMover->InBattleground() && plMover->GetBattleground() && plMover->GetBattleground()->HandlePlayerUnderMap(_player))) { // NOTE: this is actually called many times while falling // even after the player has been teleported away // TODO: discard movement packets after the player is rooted if (plMover->isAlive()) { plMover->EnvironmentalDamage(DAMAGE_FALL_TO_VOID, GetPlayer()->GetMaxHealth()); // pl can be alive if GM/etc if (!plMover->isAlive()) { // change the death state to CORPSE to prevent the death timer from // starting in the next player update plMover->KillPlayer(); plMover->BuildPlayerRepop(); } } // cancel the death timer here if started plMover->RepopAtGraveyard(); } } } } void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recv_data) { uint32 opcode = recv_data.GetOpcode(); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(opcode), opcode, opcode); /* extract packet */ uint64 guid; uint32 unk1; float newspeed; recv_data.readPackGUID(guid); // now can skip not our packet if (_player->GetGUID() != guid) { recv_data.rpos(recv_data.wpos()); // prevent warnings spam return; } // continue parse packet recv_data >> unk1; // counter or moveEvent MovementInfo movementInfo; movementInfo.guid = guid; ReadMovementInfo(recv_data, &movementInfo); recv_data >> newspeed; /*----------------*/ // client ACK send one packet for mounted/run case and need skip all except last from its // in other cases anti-cheat check can be fail in false case UnitMoveType move_type; UnitMoveType force_move_type; static char const* move_type_name[MAX_MOVE_TYPE] = { "Walk", "Run", "RunBack", "Swim", "SwimBack", "TurnRate", "Flight", "FlightBack", "PitchRate" }; switch(opcode) { case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: move_type = MOVE_WALK; force_move_type = MOVE_WALK; break; case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: move_type = MOVE_RUN; force_move_type = MOVE_RUN; break; case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: move_type = MOVE_RUN_BACK; force_move_type = MOVE_RUN_BACK; break; case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: move_type = MOVE_SWIM; force_move_type = MOVE_SWIM; break; case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: move_type = MOVE_SWIM_BACK; force_move_type = MOVE_SWIM_BACK; break; case CMSG_FORCE_TURN_RATE_CHANGE_ACK: move_type = MOVE_TURN_RATE; force_move_type = MOVE_TURN_RATE; break; case CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT; force_move_type = MOVE_FLIGHT; break; case CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT_BACK; force_move_type = MOVE_FLIGHT_BACK; break; case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: move_type = MOVE_PITCH_RATE; force_move_type = MOVE_PITCH_RATE; break; default: sLog->outError("WorldSession::HandleForceSpeedChangeAck: Unknown move type opcode: %u", opcode); return; } // skip all forced speed changes except last and unexpected // in run/mounted case used one ACK and it must be skipped.m_forced_speed_changes[MOVE_RUN} store both. if (_player->m_forced_speed_changes[force_move_type] > 0) { --_player->m_forced_speed_changes[force_move_type]; if (_player->m_forced_speed_changes[force_move_type] > 0) return; } if (!_player->GetTransport() && fabs(_player->GetSpeed(move_type) - newspeed) > 0.01f) { if (_player->GetSpeed(move_type) > newspeed) // must be greater - just correct { sLog->outError("%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value", move_type_name[move_type], _player->GetName(), _player->GetSpeed(move_type), newspeed); _player->SetSpeed(move_type, _player->GetSpeedRate(move_type), true); } else // must be lesser - cheating { sLog->outBasic("Player %s from account id %u kicked for incorrect speed (must be %f instead %f)", _player->GetName(), _player->GetSession()->GetAccountId(), _player->GetSpeed(move_type), newspeed); _player->GetSession()->KickPlayer(); } } } void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_SET_ACTIVE_MOVER"); uint64 guid; recv_data >> guid; if (GetPlayer()->IsInWorld()) { if (Unit *mover = ObjectAccessor::GetUnit(*GetPlayer(), guid)) { GetPlayer()->SetMover(mover); if (mover != GetPlayer() && mover->canFly()) { WorldPacket data(SMSG_MOVE_SET_CAN_FLY, 12); data.append(mover->GetPackGUID()); data << uint32(0); SendPacket(&data); } } else { sLog->outError("HandleSetActiveMoverOpcode: incorrect mover guid: mover is " UI64FMTD " and should be " UI64FMTD, guid, _player->m_mover->GetGUID()); GetPlayer()->SetMover(GetPlayer()); } } } void WorldSession::HandleMoveNotActiveMover(WorldPacket &recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_MOVE_NOT_ACTIVE_MOVER"); uint64 old_mover_guid; recv_data.readPackGUID(old_mover_guid); MovementInfo mi; mi.guid = old_mover_guid; ReadMovementInfo(recv_data, &mi); _player->m_movementInfo = mi; } void WorldSession::HandleMountSpecialAnimOpcode(WorldPacket& /*recv_data*/) { WorldPacket data(SMSG_MOUNTSPECIAL_ANIM, 8); data << uint64(GetPlayer()->GetGUID()); GetPlayer()->SendMessageToSet(&data, false); } void WorldSession::HandleMoveKnockBackAck(WorldPacket & recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_MOVE_KNOCK_BACK_ACK"); uint64 guid; // guid - unused recv_data.readPackGUID(guid); recv_data.read_skip<uint32>(); // unk MovementInfo movementInfo; ReadMovementInfo(recv_data, &movementInfo); } void WorldSession::HandleMoveHoverAck(WorldPacket& recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_MOVE_HOVER_ACK"); uint64 guid; // guid - unused recv_data.readPackGUID(guid); recv_data.read_skip<uint32>(); // unk MovementInfo movementInfo; ReadMovementInfo(recv_data, &movementInfo); recv_data.read_skip<uint32>(); // unk2 } void WorldSession::HandleMoveWaterWalkAck(WorldPacket& recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_MOVE_WATER_WALK_ACK"); uint64 guid; // guid - unused recv_data.readPackGUID(guid); recv_data.read_skip<uint32>(); // unk MovementInfo movementInfo; ReadMovementInfo(recv_data, &movementInfo); recv_data.read_skip<uint32>(); // unk2 } void WorldSession::HandleSummonResponseOpcode(WorldPacket& recv_data) { if (!_player->isAlive() || _player->isInCombat()) return; uint64 summoner_guid; bool agree; recv_data >> summoner_guid; recv_data >> agree; _player->SummonIfPossible(agree); }
gpl-2.0
unofficial-opensource-apple/gcc_jaguar
libjava/javax/naming/ldap/ControlFactory.java
1735
/* Copyright (C) 2001 Free Software Foundation This file is part of libgcj. This software is copyrighted work licensed under the terms of the Libgcj License. Please consult the file "LIBGCJ_LICENSE" for details. */ package javax.naming.ldap; import javax.naming.*; import java.util.StringTokenizer; import java.util.Hashtable; /** * @author Tom Tromey <tromey@redhat.com> * @date June 22, 2001 */ public abstract class ControlFactory { protected ControlFactory () { } public abstract Control getControlInstance (Control control) throws NamingException; public static Control getControlInstance (Control control, Context ctx, Hashtable env) throws NamingException { String path = (String) env.get (LdapContext.CONTROL_FACTORIES); String path2 = null; if (ctx != null) path2 = (String) ctx.getEnvironment ().get (LdapContext.CONTROL_FACTORIES); if (path == null) path = path2; else if (path2 != null) path += ":" + path2; StringTokenizer tokens = new StringTokenizer (path, ":"); while (tokens.hasMoreTokens ()) { String name = tokens.nextToken (); try { Class k = Class.forName (name); ControlFactory cf = (ControlFactory) k.newInstance (); Control ctrl = cf.getControlInstance (control); if (ctrl != null) return ctrl; } catch (ClassNotFoundException _1) { // Ignore it. } catch (ClassCastException _2) { // Ignore it. } catch (InstantiationException _3) { // If we couldn't instantiate the factory we might get // this. } catch (IllegalAccessException _4) { // Another possibility when instantiating. } } return control; } }
gpl-2.0
johnbeard/kicad-git
bitmaps_png/cpp_26/gerber_recent_files.cpp
10362
/* Do not modify this file, it was automatically generated by the * PNG2cpp CMake script, using a *.png file as input. */ #include <bitmaps.h> static const unsigned char png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x1a, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa9, 0x4a, 0x4c, 0xce, 0x00, 0x00, 0x06, 0x43, 0x49, 0x44, 0x41, 0x54, 0x48, 0xc7, 0xad, 0x96, 0x6d, 0x4c, 0x5b, 0xe7, 0x15, 0xc7, 0xff, 0xcf, 0xbd, 0xcf, 0xbd, 0xd7, 0x2f, 0xd7, 0x2f, 0xd8, 0x06, 0x07, 0x83, 0x01, 0x83, 0x21, 0x06, 0xe2, 0x17, 0x02, 0x04, 0x4a, 0x52, 0x92, 0x40, 0x12, 0x4d, 0x6d, 0xa6, 0x6e, 0x9d, 0x54, 0x69, 0x6b, 0xb7, 0x69, 0x6d, 0xd5, 0x4d, 0x8a, 0xb6, 0x69, 0x5f, 0xd6, 0xad, 0xd3, 0xb4, 0x69, 0x91, 0x26, 0x4d, 0x53, 0x17, 0x6d, 0xda, 0x87, 0x4c, 0xab, 0x34, 0x6d, 0xf9, 0x50, 0xad, 0xe9, 0xd2, 0x4a, 0x9b, 0xa6, 0x4e, 0xd1, 0x9a, 0x25, 0x30, 0xd2, 0x40, 0x42, 0x48, 0x6c, 0x12, 0x30, 0xd8, 0x80, 0xc1, 0x10, 0xb0, 0x31, 0x2f, 0x7e, 0xc1, 0xd7, 0xf7, 0x5e, 0xdf, 0x7d, 0x88, 0x54, 0x6d, 0x4a, 0x43, 0xe8, 0xb6, 0xbf, 0xf4, 0xff, 0xf6, 0x3c, 0xe7, 0xa7, 0xf3, 0x1c, 0x9d, 0xf3, 0x1c, 0xa2, 0x69, 0x1a, 0xf6, 0xaa, 0xdb, 0x5f, 0x26, 0xac, 0x58, 0xe5, 0xf8, 0x91, 0xd8, 0x14, 0x1a, 0xe0, 0x4c, 0xb6, 0x3a, 0xbd, 0xc8, 0x39, 0x39, 0x03, 0xc7, 0xcb, 0x45, 0x45, 0x29, 0xe6, 0xe5, 0xb4, 0xb2, 0xb3, 0xb3, 0x56, 0x58, 0x9c, 0x9a, 0xda, 0x8c, 0x45, 0xcf, 0x74, 0x5c, 0xd0, 0xd2, 0xff, 0x7e, 0x97, 0xec, 0x15, 0x74, 0xf7, 0x15, 0xae, 0xd9, 0xda, 0xec, 0xbf, 0xe0, 0x3c, 0xd8, 0xdd, 0xc5, 0x16, 0xe6, 0xd8, 0xf2, 0x76, 0x1a, 0xb9, 0x4c, 0xbe, 0x94, 0x2d, 0x68, 0x25, 0xa3, 0x9e, 0x70, 0xa2, 0x55, 0x10, 0xa8, 0x68, 0x85, 0x66, 0x6a, 0xc0, 0x46, 0x72, 0x33, 0x91, 0xb9, 0x7b, 0xf5, 0xac, 0xef, 0x97, 0x5b, 0x6f, 0x7d, 0x2a, 0x50, 0xf4, 0x3b, 0xb6, 0x97, 0x6d, 0x9d, 0x27, 0xcf, 0x56, 0xd8, 0xe0, 0xca, 0xcf, 0x87, 0x4b, 0x0b, 0x69, 0xbd, 0x94, 0x13, 0xbd, 0x9c, 0xe4, 0x19, 0xd4, 0xb1, 0xd5, 0x2d, 0xd0, 0x32, 0x8b, 0x60, 0x12, 0xd7, 0x15, 0xfd, 0xfa, 0x64, 0xd1, 0xc5, 0xad, 0xa0, 0xb2, 0xc9, 0x2d, 0x4a, 0xbc, 0x67, 0x67, 0xed, 0xd6, 0xd0, 0x07, 0x9e, 0x1f, 0x4f, 0x3f, 0xbf, 0x27, 0x50, 0xf8, 0x55, 0xbe, 0xd1, 0x75, 0xfc, 0x73, 0x43, 0x0c, 0x93, 0x71, 0xe5, 0xe6, 0x13, 0xd9, 0x84, 0xe9, 0x69, 0xb2, 0x52, 0xfb, 0x19, 0xb1, 0xc1, 0x5d, 0x0f, 0x8b, 0xd5, 0x8c, 0x6b, 0xc3, 0x23, 0xe8, 0xef, 0xef, 0x83, 0x56, 0x2e, 0x43, 0x2a, 0x49, 0xd8, 0x98, 0xbc, 0xa6, 0x38, 0xee, 0x9e, 0xdf, 0xf1, 0x78, 0x74, 0x22, 0xa9, 0xee, 0x52, 0x13, 0x97, 0xdf, 0xff, 0x49, 0xcb, 0x9b, 0xa9, 0xb3, 0xcc, 0x13, 0x6a, 0x42, 0xcc, 0xde, 0xf6, 0x3f, 0x58, 0x6d, 0xd4, 0x75, 0x31, 0x11, 0x50, 0xaf, 0x3a, 0x5e, 0x33, 0x2e, 0x3a, 0x07, 0xc5, 0xde, 0xee, 0x5e, 0x78, 0x9b, 0x9a, 0x41, 0x08, 0x83, 0xa1, 0xa1, 0x11, 0xe8, 0x78, 0x1d, 0x78, 0x5e, 0x07, 0x83, 0xde, 0x08, 0x67, 0xe8, 0x04, 0xcd, 0x3d, 0xf7, 0x5b, 0x53, 0x2c, 0x41, 0x72, 0x6c, 0x6e, 0x86, 0xda, 0x0f, 0x0e, 0x9c, 0x89, 0xbc, 0xa6, 0xdb, 0x4f, 0x77, 0x03, 0x19, 0xab, 0xec, 0x6f, 0x38, 0x43, 0xdd, 0x3d, 0xc5, 0xc4, 0x88, 0xda, 0xd1, 0xff, 0x0d, 0xa6, 0xd2, 0xe5, 0x26, 0xa2, 0xd1, 0x04, 0x86, 0x21, 0x18, 0xbb, 0x39, 0x86, 0xd6, 0x36, 0x1f, 0x12, 0x8b, 0x4b, 0x10, 0x04, 0x1d, 0x54, 0x55, 0x85, 0xa2, 0x32, 0x20, 0x84, 0xc0, 0x6c, 0xa9, 0xc0, 0xd6, 0x91, 0xd7, 0x8d, 0xab, 0x77, 0x7e, 0x9e, 0xab, 0xf6, 0xed, 0x73, 0xe6, 0xbd, 0xfe, 0xdf, 0xed, 0x9a, 0x91, 0xd1, 0xed, 0x3b, 0x45, 0xa5, 0x24, 0x9d, 0x48, 0x08, 0x45, 0x8b, 0xdd, 0x49, 0x2c, 0x66, 0x33, 0x04, 0x81, 0xc7, 0xa5, 0xf7, 0xfe, 0x84, 0xf6, 0x03, 0xed, 0xe0, 0x28, 0x87, 0x72, 0x59, 0x03, 0xcb, 0x50, 0xf0, 0x3c, 0x0f, 0x8e, 0xf2, 0xa0, 0x94, 0x82, 0x65, 0x59, 0x88, 0xb5, 0x3e, 0x26, 0xc9, 0xb7, 0x32, 0x4a, 0x36, 0x05, 0xb1, 0xae, 0xc5, 0xbb, 0x2b, 0x88, 0xab, 0xd8, 0x57, 0x83, 0x42, 0x0a, 0x0b, 0x6c, 0x0b, 0xb5, 0xdb, 0xed, 0xa0, 0x94, 0x82, 0x52, 0x8a, 0xa7, 0x9e, 0xea, 0xc3, 0xf2, 0xf2, 0x32, 0x36, 0x37, 0x73, 0xd0, 0xeb, 0x78, 0x64, 0x73, 0x39, 0x70, 0x94, 0x03, 0xcb, 0xb2, 0x60, 0x98, 0x87, 0x26, 0x84, 0x01, 0xeb, 0xff, 0xbc, 0x21, 0x9f, 0x55, 0x25, 0xbd, 0x48, 0xed, 0x74, 0x97, 0xfa, 0xb8, 0x3c, 0xa7, 0x5f, 0xb0, 0x4b, 0x5b, 0x79, 0xa4, 0xf8, 0x5a, 0x61, 0x76, 0x76, 0x06, 0xe9, 0x74, 0x0a, 0xeb, 0x99, 0x0c, 0x2c, 0x56, 0x0b, 0x82, 0xfe, 0x20, 0x96, 0x96, 0x57, 0x50, 0x2e, 0x2b, 0xd8, 0xd8, 0xd8, 0x84, 0xdd, 0x66, 0x03, 0x21, 0xe4, 0xa1, 0x01, 0x10, 0x42, 0x40, 0x1d, 0x75, 0xc8, 0x47, 0x04, 0xd9, 0xcc, 0x13, 0xe1, 0xb1, 0x19, 0xb1, 0x1c, 0xdd, 0xcf, 0xf3, 0x8c, 0x65, 0x27, 0xaf, 0x94, 0xba, 0xba, 0x3a, 0x40, 0x05, 0x06, 0x4d, 0x2d, 0x4d, 0x38, 0x36, 0x70, 0x14, 0x3d, 0xbd, 0x3d, 0xb0, 0x58, 0x2d, 0x78, 0xfb, 0x8f, 0xef, 0xa0, 0x5c, 0xd6, 0xf0, 0xe6, 0x2f, 0xce, 0x21, 0x1e, 0x8f, 0x43, 0x2a, 0x95, 0xa0, 0x69, 0xda, 0x7f, 0x58, 0x01, 0xa7, 0x11, 0x55, 0xc2, 0x63, 0x33, 0x52, 0x65, 0x25, 0x22, 0xe5, 0x0b, 0x19, 0x83, 0x89, 0xb3, 0xeb, 0x32, 0xf7, 0xcb, 0x9c, 0xdb, 0xc7, 0xcc, 0xce, 0x25, 0x70, 0x79, 0x3c, 0x8a, 0xaf, 0x3d, 0x7b, 0x0c, 0xae, 0x6a, 0x27, 0x16, 0x97, 0x96, 0xd0, 0xe0, 0xae, 0x41, 0x34, 0x36, 0x8f, 0xef, 0xbe, 0xf1, 0x03, 0x94, 0x4a, 0x0a, 0x78, 0x81, 0x47, 0x47, 0x28, 0x80, 0x97, 0x5e, 0x7c, 0x01, 0x65, 0x55, 0x01, 0xcf, 0xb3, 0x44, 0xd3, 0xc8, 0xee, 0x7d, 0xf4, 0xe0, 0x37, 0xa7, 0xee, 0x39, 0xac, 0xdb, 0xad, 0x6f, 0xdd, 0xb0, 0xec, 0x5c, 0x62, 0x8f, 0xeb, 0x47, 0x69, 0x13, 0xb6, 0x9c, 0x6d, 0xa8, 0x4e, 0x8e, 0xe2, 0xa4, 0x25, 0x8b, 0xee, 0x4a, 0x01, 0x23, 0xff, 0x1c, 0x86, 0xaf, 0xad, 0x15, 0xa7, 0x06, 0x07, 0x50, 0x51, 0x61, 0x01, 0xa5, 0x2c, 0x4a, 0x72, 0x09, 0x25, 0x59, 0x42, 0x69, 0x65, 0x0a, 0x2d, 0x6b, 0xef, 0x95, 0x28, 0x55, 0xe9, 0x63, 0x41, 0x84, 0x10, 0xf2, 0xc3, 0x97, 0x3a, 0xef, 0x7c, 0x64, 0x08, 0xf9, 0xaf, 0x55, 0x3e, 0x07, 0xc9, 0xd1, 0xf8, 0xc8, 0x19, 0x67, 0x72, 0x1c, 0x83, 0x62, 0x06, 0x67, 0x9e, 0xe9, 0x41, 0xb5, 0xd3, 0x01, 0x55, 0x55, 0x21, 0x2b, 0xf2, 0x43, 0xcb, 0x25, 0x30, 0xc3, 0xbf, 0xce, 0xb7, 0xd7, 0xc3, 0xb8, 0xfd, 0x60, 0x6d, 0xe5, 0x11, 0x10, 0x21, 0x44, 0x40, 0xfb, 0xe0, 0xb7, 0xe1, 0x3d, 0xf8, 0x3c, 0xe9, 0xfc, 0x6c, 0xb7, 0x66, 0xb2, 0x31, 0x4f, 0x1a, 0x51, 0x8e, 0xe4, 0x38, 0x8e, 0x0a, 0xab, 0x78, 0x65, 0xd0, 0x8f, 0x1a, 0x67, 0x25, 0x64, 0x45, 0x86, 0xb2, 0x3a, 0xa3, 0x36, 0xad, 0xfd, 0x55, 0xb2, 0x9a, 0xf3, 0x86, 0xa5, 0xf1, 0xfb, 0x1f, 0x7e, 0x0c, 0x22, 0x66, 0xb3, 0x1d, 0xfb, 0x8f, 0xbe, 0x8e, 0xc6, 0xae, 0x67, 0xd1, 0x79, 0xba, 0x0d, 0xbc, 0x0e, 0x9f, 0x56, 0xd6, 0xe4, 0x04, 0xfa, 0x98, 0x04, 0x5e, 0x3c, 0xe4, 0x46, 0x4f, 0xf2, 0xed, 0x5c, 0x43, 0x93, 0x41, 0x4c, 0x2f, 0xac, 0x24, 0x56, 0x6f, 0xde, 0xe8, 0x27, 0xa8, 0xac, 0xf5, 0xc2, 0xdb, 0xfb, 0x7d, 0xec, 0xef, 0x3b, 0x09, 0xff, 0x09, 0x37, 0x18, 0x06, 0xff, 0xab, 0xcc, 0x8b, 0x63, 0xda, 0x33, 0xc5, 0xab, 0xe4, 0x9b, 0xde, 0x85, 0x92, 0x75, 0xee, 0xd6, 0xf7, 0xda, 0x7e, 0xb5, 0x75, 0x8e, 0x41, 0x41, 0xca, 0x41, 0x96, 0x14, 0xc8, 0x45, 0x13, 0xfe, 0x4f, 0xda, 0x76, 0x77, 0x93, 0x8b, 0xce, 0xaf, 0xe0, 0x8b, 0x17, 0xb5, 0x5c, 0xfb, 0x79, 0xf5, 0x0a, 0x21, 0x84, 0xa3, 0x60, 0x78, 0x0f, 0x4a, 0x38, 0x0a, 0x83, 0xc7, 0x8a, 0xab, 0xef, 0x00, 0x15, 0x76, 0x20, 0x30, 0x00, 0x30, 0xec, 0x7f, 0x47, 0x79, 0x10, 0x03, 0x62, 0x77, 0xc0, 0xa6, 0xe6, 0xb2, 0x89, 0x0d, 0xf6, 0x5d, 0xc8, 0x4a, 0x16, 0x00, 0x61, 0x1d, 0x66, 0xa1, 0xbc, 0x4f, 0xa7, 0x05, 0xf4, 0xc5, 0xf5, 0x7a, 0xb9, 0xaa, 0x5d, 0x50, 0x4c, 0xf5, 0x40, 0xe4, 0xef, 0xc0, 0x46, 0x12, 0xa8, 0xaa, 0xc7, 0x9e, 0x9f, 0x32, 0x76, 0x1b, 0xb8, 0x77, 0x1d, 0x28, 0x12, 0xc0, 0xee, 0x05, 0x93, 0x5e, 0xd8, 0xd1, 0xb2, 0xab, 0x11, 0xac, 0xaf, 0x7e, 0xa0, 0x69, 0x52, 0x96, 0xea, 0xf5, 0xfa, 0x9a, 0x1a, 0x87, 0xc5, 0xdd, 0xd6, 0x6a, 0xd3, 0x33, 0x7c, 0x0c, 0x23, 0x8b, 0x61, 0xcc, 0x88, 0xad, 0x28, 0x98, 0x1b, 0x81, 0xe1, 0xf7, 0x01, 0x93, 0x08, 0x04, 0x07, 0x01, 0x96, 0x7b, 0x34, 0xb8, 0x56, 0x06, 0xee, 0x0d, 0x03, 0xeb, 0xa9, 0x87, 0xc1, 0x1d, 0x3e, 0xb8, 0x96, 0x87, 0xd0, 0x26, 0x8f, 0xe2, 0x40, 0xa7, 0xcd, 0x72, 0x69, 0x2e, 0xd1, 0x3b, 0x8f, 0x1c, 0x0b, 0x00, 0x54, 0x56, 0x14, 0xb6, 0xca, 0xe9, 0xd4, 0xb5, 0x1f, 0x68, 0x67, 0xa6, 0xee, 0x4f, 0xe1, 0x48, 0x8d, 0x80, 0xa7, 0xb9, 0x45, 0x0c, 0xcf, 0xdf, 0xc3, 0x8c, 0xbe, 0x05, 0x79, 0xab, 0x0f, 0x18, 0xfe, 0x33, 0x20, 0x1a, 0x80, 0xe0, 0x71, 0x80, 0x0a, 0x80, 0x2c, 0x01, 0x77, 0xff, 0x01, 0xe4, 0xf3, 0x40, 0x75, 0x00, 0xd4, 0xcc, 0xa3, 0x3e, 0x35, 0x82, 0x50, 0x45, 0x19, 0xee, 0x66, 0x23, 0xb6, 0x36, 0x0b, 0xe0, 0x28, 0x87, 0xba, 0xfa, 0x3a, 0x6d, 0x6d, 0x6d, 0xd5, 0xf0, 0xf1, 0x0f, 0x4b, 0x08, 0x21, 0x7d, 0x87, 0x8f, 0x7c, 0x35, 0x18, 0x0c, 0xbe, 0xdc, 0xda, 0xd6, 0x7a, 0x38, 0x1a, 0x9d, 0x61, 0xca, 0x6a, 0x19, 0x54, 0xa7, 0xc7, 0x70, 0x7c, 0x13, 0x51, 0xc1, 0x8b, 0x5c, 0x95, 0x1f, 0x48, 0x8e, 0x03, 0x0c, 0x00, 0x95, 0x00, 0xb5, 0x1d, 0xd0, 0xa7, 0xa6, 0xd0, 0x58, 0x98, 0xc6, 0x21, 0x97, 0x00, 0x1d, 0x53, 0x86, 0x5c, 0x92, 0xe0, 0xf3, 0xf9, 0x90, 0xcf, 0x17, 0x96, 0x27, 0x26, 0x6e, 0xff, 0x6d, 0x72, 0x32, 0xf2, 0xb3, 0xe9, 0xa9, 0xa9, 0xe9, 0x4f, 0xfc, 0xca, 0xfb, 0xfa, 0x0e, 0x7f, 0xc9, 0x1f, 0x08, 0xbc, 0xea, 0x0f, 0x04, 0xfa, 0xa7, 0xa7, 0xa3, 0xac, 0xaa, 0x2a, 0xd0, 0x19, 0x44, 0x5c, 0x9b, 0xcd, 0x20, 0xca, 0x35, 0x20, 0xeb, 0xea, 0x82, 0x79, 0xf1, 0x3a, 0xbc, 0xe5, 0x24, 0x0e, 0x7b, 0x2c, 0x28, 0xe6, 0xb6, 0xc1, 0xb2, 0x2c, 0x82, 0xc1, 0x10, 0xe2, 0xf1, 0x58, 0x34, 0x1c, 0x0e, 0xff, 0x65, 0x6c, 0xf4, 0xc6, 0x4f, 0xd3, 0xe9, 0xf4, 0xfa, 0x9e, 0xb6, 0xa0, 0x9e, 0xde, 0xde, 0x2f, 0x04, 0x02, 0xc1, 0xaf, 0x07, 0x83, 0xc1, 0x63, 0xb3, 0x33, 0xb3, 0x9c, 0x24, 0xcb, 0x30, 0x9a, 0xcc, 0x98, 0x88, 0xaf, 0xa0, 0xa3, 0x71, 0x1f, 0xd2, 0xa9, 0x35, 0x88, 0x46, 0x11, 0xc1, 0x50, 0x48, 0xbb, 0x33, 0x71, 0x7b, 0x7c, 0x32, 0x12, 0x79, 0xf7, 0xca, 0x95, 0x0f, 0xcf, 0x69, 0x9a, 0x26, 0x7d, 0xe2, 0x48, 0x7b, 0xd2, 0x72, 0xd2, 0x7d, 0xe8, 0xd0, 0xe9, 0x40, 0x20, 0x78, 0x26, 0x18, 0x0c, 0x1d, 0x9f, 0x8b, 0xc7, 0x85, 0xed, 0xec, 0x36, 0x6c, 0x36, 0x3b, 0x9a, 0x5b, 0x9a, 0x4b, 0x63, 0xa3, 0x63, 0xc3, 0x91, 0x48, 0xf8, 0xc2, 0x47, 0xd7, 0x47, 0x7e, 0xaf, 0x3d, 0x21, 0xd0, 0x9e, 0xf7, 0xba, 0xae, 0xae, 0xee, 0x13, 0xfe, 0x40, 0xe0, 0x5b, 0x0d, 0x1e, 0x4f, 0x6f, 0x3c, 0x16, 0x1b, 0x8a, 0x84, 0xc3, 0xe7, 0x6f, 0xdd, 0xba, 0x79, 0x79, 0xaf, 0xed, 0xf5, 0x2f, 0x8b, 0x1f, 0xa8, 0x3f, 0xea, 0xb6, 0xcb, 0x55, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, }; const BITMAP_OPAQUE gerber_recent_files_xpm[1] = {{ png, sizeof( png ), "gerber_recent_files_xpm" }}; //EOF
gpl-2.0
vnataraju/SProject
plugins/system/zend/Zend/Pdf/Action/GoToR.php
1212
<?php defined( '_JEXEC') or die( 'Restricted Access' ); /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @subpackage Actions * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: GoToR.php 23775 2011-03-01 17:25:24Z ralph $ */ /** Zend_Pdf_Action */ require_once 'Zend/Pdf/Action.php'; /** * PDF 'Go to a destination in another document' action * * @package Zend_Pdf * @subpackage Actions * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Action_GoToR extends Zend_Pdf_Action { }
gpl-2.0
kolab-groupware/kdelibs
nepomuk/utils/proxyfacet.cpp
5734
/* This file is part of the Nepomuk KDE project. Copyright (C) 2010 Sebastian Trueg <trueg@kde.org> 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #include "proxyfacet.h" #include "andterm.h" #include "query.h" #include "kguiitem.h" #include "kdebug.h" class Nepomuk::Utils::ProxyFacet::Private { public: Private() : m_sourceFacet(0), m_facetConditionMet(true) { } void updateConditionStatus(); Facet* m_sourceFacet; Query::Term m_facetCondition; bool m_facetConditionMet; ProxyFacet* q; }; namespace { /** * Checks if a query contains a certain term in a non-optional manner. Basically this means * that either the query's term is the term in question or the query term is an AndTerm which * contains the requested term. All other situations result in an optional usage of \p term * or are too complex to handle here. */ bool containsTerm( const Nepomuk::Query::Query& query, const Nepomuk::Query::Term& term ) { Nepomuk::Query::Term queryTerm = query.term().optimized(); if( queryTerm == term ) { return true; } else if( queryTerm.isAndTerm() ) { Q_FOREACH( const Nepomuk::Query::Term& subTerm, queryTerm.toAndTerm().subTerms() ) { if( subTerm == term ) { return true; } } } // fallback return false; } } void Nepomuk::Utils::ProxyFacet::Private::updateConditionStatus() { bool newFacetConditionMet = true; if( m_facetCondition.isValid() ) { newFacetConditionMet = containsTerm( q->clientQuery(), m_facetCondition ); kDebug() << m_facetConditionMet << newFacetConditionMet; } if( newFacetConditionMet != m_facetConditionMet ) { m_facetConditionMet = newFacetConditionMet; q->setLayoutChanged(); q->setQueryTermChanged(); } if( !m_facetConditionMet ) { q->clearSelection(); } } Nepomuk::Utils::ProxyFacet::ProxyFacet( QObject* parent ) : Facet(parent), d(new Private()) { d->q = this; } Nepomuk::Utils::ProxyFacet::~ProxyFacet() { delete d; } void Nepomuk::Utils::ProxyFacet::setSourceFacet( Facet* source ) { if( d->m_sourceFacet ) { d->m_sourceFacet->disconnect(this); } d->m_sourceFacet = source; if( d->m_sourceFacet ) { connect(d->m_sourceFacet, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term)), this, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term))); connect(d->m_sourceFacet, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*)), this, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*))); connect(d->m_sourceFacet, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*)), this, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); } setLayoutChanged(); setQueryTermChanged(); setSelectionChanged(); } Nepomuk::Utils::Facet* Nepomuk::Utils::ProxyFacet::sourceFacet() const { return d->m_sourceFacet; } Nepomuk::Utils::Facet::SelectionMode Nepomuk::Utils::ProxyFacet::selectionMode() const { return d->m_sourceFacet ? d->m_sourceFacet->selectionMode() : MatchOne; } Nepomuk::Query::Term Nepomuk::Utils::ProxyFacet::queryTerm() const { return facetConditionMet() && d->m_sourceFacet ? d->m_sourceFacet->queryTerm() : Query::Term(); } int Nepomuk::Utils::ProxyFacet::count() const { return d->m_sourceFacet && facetConditionMet() ? d->m_sourceFacet->count() : 0; } bool Nepomuk::Utils::ProxyFacet::isSelected( int index ) const { return d->m_sourceFacet ? d->m_sourceFacet->isSelected(index) : false; } KGuiItem Nepomuk::Utils::ProxyFacet::guiItem( int index ) const { return d->m_sourceFacet ? d->m_sourceFacet->guiItem(index) : KGuiItem(); } void Nepomuk::Utils::ProxyFacet::setSelected( int index, bool selected ) { if( d->m_sourceFacet && facetConditionMet() ) { d->m_sourceFacet->setSelected( index, selected ); } } void Nepomuk::Utils::ProxyFacet::clearSelection() { if( d->m_sourceFacet ) { d->m_sourceFacet->clearSelection(); } } bool Nepomuk::Utils::ProxyFacet::selectFromTerm( const Nepomuk::Query::Term& term ) { if( d->m_sourceFacet && facetConditionMet() ) { return d->m_sourceFacet->selectFromTerm( term ); } else { return false; } } void Nepomuk::Utils::ProxyFacet::handleClientQueryChange() { d->updateConditionStatus(); if( d->m_sourceFacet ) { d->m_sourceFacet->setClientQuery( clientQuery() ); } } void Nepomuk::Utils::ProxyFacet::setFacetCondition( const Nepomuk::Query::Term& term ) { d->m_facetCondition = term; d->updateConditionStatus(); } bool Nepomuk::Utils::ProxyFacet::facetConditionMet() const { return d->m_facetConditionMet; } #include "proxyfacet.moc"
gpl-2.0
albertghtoun/gcc-libitm
gcc/testsuite/g++.dg/cpp0x/enum2.C
142
// PR c++/38637 // { dg-do compile } // { dg-options "-std=c++11" } template<int> enum E : int { e }; // { dg-error "declaration|expected" }
gpl-2.0
nextgis/NextGIS_QGIS_open
python/plugins/processing/ui/ui_DlgAlgorithmBase.py
4271
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'DlgAlgorithmBase.ui' # # Created: Fri Nov 21 13:25:46 2014 # by: PyQt4 UI code generator 4.11.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(578, 406) self.verticalLayout = QtGui.QVBoxLayout(Dialog) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.tabWidget = QtGui.QTabWidget(Dialog) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.tab) self.verticalLayout_4.setSpacing(2) self.verticalLayout_4.setMargin(0) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.tab_2) self.verticalLayout_2.setSpacing(2) self.verticalLayout_2.setMargin(0) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.txtLog = QtGui.QTextEdit(self.tab_2) self.txtLog.setFrameShape(QtGui.QFrame.NoFrame) self.txtLog.setReadOnly(True) self.txtLog.setObjectName(_fromUtf8("txtLog")) self.verticalLayout_2.addWidget(self.txtLog) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.tab_3 = QtGui.QWidget() self.tab_3.setObjectName(_fromUtf8("tab_3")) self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab_3) self.verticalLayout_3.setSpacing(2) self.verticalLayout_3.setMargin(0) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.txtHelp = QtWebKit.QWebView(self.tab_3) self.txtHelp.setUrl(QtCore.QUrl(_fromUtf8("about:blank"))) self.txtHelp.setObjectName(_fromUtf8("txtHelp")) self.verticalLayout_3.addWidget(self.txtHelp) self.tabWidget.addTab(self.tab_3, _fromUtf8("")) self.verticalLayout.addWidget(self.tabWidget) self.lblProgress = QtGui.QLabel(Dialog) self.lblProgress.setText(_fromUtf8("")) self.lblProgress.setObjectName(_fromUtf8("lblProgress")) self.verticalLayout.addWidget(self.lblProgress) self.progressBar = QtGui.QProgressBar(Dialog) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName(_fromUtf8("progressBar")) self.verticalLayout.addWidget(self.progressBar) self.buttonBox = QtGui.QDialogButtonBox(Dialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Close|QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.verticalLayout.addWidget(self.buttonBox) self.retranslateUi(Dialog) self.tabWidget.setCurrentIndex(0) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(_translate("Dialog", "Dialog", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Dialog", "Parameters", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Dialog", "Log", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Dialog", "Help", None)) from PyQt4 import QtWebKit
gpl-2.0
mmplayer/MySQL
sql/rpl_info_factory.cc
30289
/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <my_global.h> #include "sql_priv.h" #include "rpl_slave.h" #include "rpl_info_factory.h" /* Defines meta information on diferent repositories. */ Rpl_info_factory::struct_table_data Rpl_info_factory::rli_table_data; Rpl_info_factory::struct_file_data Rpl_info_factory::rli_file_data; Rpl_info_factory::struct_table_data Rpl_info_factory::mi_table_data; Rpl_info_factory::struct_file_data Rpl_info_factory::mi_file_data; Rpl_info_factory::struct_file_data Rpl_info_factory::worker_file_data; Rpl_info_factory::struct_table_data Rpl_info_factory::worker_table_data; /** Creates both a Master info and a Relay log info repository whose types are defined as parameters. Nothing is done for Workers here. @todo Make the repository a pluggable component. @todo Use generic programming to make it easier and clearer to add a new repositories' types and Rpl_info objects. @param[in] mi_option Type of the Master info repository. @param[out] mi Reference to the Master_info. @param[in] rli_option Type of the Relay log info repository. @param[out] rli Reference to the Relay_log_info. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::create_coordinators(uint mi_option, Master_info **mi, uint rli_option, Relay_log_info **rli) { DBUG_ENTER("Rpl_info_factory::create_coordinators"); Rpl_info_factory::init_repository_metadata(); if (!((*mi)= Rpl_info_factory::create_mi(mi_option))) DBUG_RETURN(TRUE); if (!((*rli)= Rpl_info_factory::create_rli(rli_option, relay_log_recovery))) { delete *mi; *mi= NULL; DBUG_RETURN(TRUE); } /* Setting the cross dependency used all over the code. */ (*mi)->set_relay_log_info(*rli); (*rli)->set_master_info(*mi); DBUG_RETURN(FALSE); } /** Creates a Master info repository whose type is defined as a parameter. @param[in] mi_option Type of the repository, e.g. FILE TABLE. The execution fails if a user requests a type but a different type already exists in the system. This is done to avoid that a user accidentally accesses the wrong repository and makes the slave go out of sync. @retval Pointer to Master_info Success @retval NULL Failure */ Master_info *Rpl_info_factory::create_mi(uint mi_option) { Master_info* mi= NULL; Rpl_info_handler* handler_src= NULL; Rpl_info_handler* handler_dest= NULL; uint instances= 1; const char *msg= "Failed to allocate memory for the master info " "structure"; DBUG_ENTER("Rpl_info_factory::create_mi"); if (!(mi= new Master_info( #ifdef HAVE_PSI_INTERFACE &key_master_info_run_lock, &key_master_info_data_lock, &key_master_info_sleep_lock, &key_master_info_data_cond, &key_master_info_start_cond, &key_master_info_stop_cond, &key_master_info_sleep_cond, #endif instances ))) goto err; if(init_repositories(mi_table_data, mi_file_data, mi_option, instances, &handler_src, &handler_dest, &msg)) goto err; if (decide_repository(mi, mi_option, &handler_src, &handler_dest, &msg)) goto err; DBUG_RETURN(mi); err: delete handler_src; delete handler_dest; if (mi) { /* The handler was previously deleted so we need to remove any reference to it. */ mi->set_rpl_info_handler(NULL); delete mi; } sql_print_error("Error creating master info: %s.", msg); DBUG_RETURN(NULL); } /** Allows to change the master info repository after startup. @param[in] mi Reference to Master_info. @param[in] mi_option Type of the repository, e.g. FILE TABLE. @param[out] msg Error message if something goes wrong. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::change_mi_repository(Master_info *mi, uint mi_option, const char **msg) { Rpl_info_handler* handler_src= mi->get_rpl_info_handler(); Rpl_info_handler* handler_dest= NULL; uint instances= 1; DBUG_ENTER("Rpl_info_factory::change_mi_repository"); DBUG_ASSERT(handler_src); if (handler_src->get_rpl_info_type() == mi_option) DBUG_RETURN(false); if (init_repositories(mi_table_data, mi_file_data, mi_option, instances, NULL, &handler_dest, msg)) goto err; if (decide_repository(mi, mi_option, &handler_src, &handler_dest, msg)) goto err; DBUG_RETURN(FALSE); err: delete handler_dest; handler_dest= NULL; sql_print_error("Error changing the type of master info's repository: %s.", *msg); DBUG_RETURN(TRUE); } /** Creates a Relay log info repository whose type is defined as a parameter. @param[in] rli_option Type of the Relay log info repository @param[in] is_slave_recovery If the slave should try to start a recovery process to get consistent relay log files The execution fails if a user requests a type but a different type already exists in the system. This is done to avoid that a user accidentally accesses the wrong repository and make the slave go out of sync. @retval Pointer to Relay_log_info Success @retval NULL Failure */ Relay_log_info *Rpl_info_factory::create_rli(uint rli_option, bool is_slave_recovery) { Relay_log_info *rli= NULL; Rpl_info_handler* handler_src= NULL; Rpl_info_handler* handler_dest= NULL; uint instances= 1; uint worker_repository= INVALID_INFO_REPOSITORY; uint worker_instances= 1; const char *msg= NULL; const char *msg_alloc= "Failed to allocate memory for the relay log info " "structure"; DBUG_ENTER("Rpl_info_factory::create_rli"); /* Returns how many occurrences of rli's repositories exist. For example, if the repository is a table, this retrieves the number of rows in it. Besides, it also returns the type of the repository where entries were found. */ if (rli_option != INFO_REPOSITORY_DUMMY && scan_repositories(&worker_instances, &worker_repository, worker_table_data, worker_file_data, &msg)) goto err; if (!(rli= new Relay_log_info(is_slave_recovery #ifdef HAVE_PSI_INTERFACE ,&key_relay_log_info_run_lock, &key_relay_log_info_data_lock, &key_relay_log_info_sleep_lock, &key_relay_log_info_data_cond, &key_relay_log_info_start_cond, &key_relay_log_info_stop_cond, &key_relay_log_info_sleep_cond #endif , instances ))) { msg= msg_alloc; goto err; } if(init_repositories(rli_table_data, rli_file_data, rli_option, instances, &handler_src, &handler_dest, &msg)) goto err; if (rli_option != INFO_REPOSITORY_DUMMY && worker_repository != INVALID_INFO_REPOSITORY && worker_repository != rli_option) { opt_rli_repository_id= rli_option= worker_repository; sql_print_warning("It is not possible to change the type of the relay log " "repository because there are workers repositories with " "possible execution gaps. " "The value of --relay_log_info_repository is altered to " "one of the found Worker repositories. " "The gaps have to be sorted out before resuming with " "the type change."); std::swap(handler_src, handler_dest); } if (decide_repository(rli, rli_option, &handler_src, &handler_dest, &msg)) goto err; DBUG_RETURN(rli); err: delete handler_src; delete handler_dest; if (rli) { /* The handler was previously deleted so we need to remove any reference to it. */ rli->set_rpl_info_handler(NULL); delete rli; } sql_print_error("Error creating relay log info: %s.", msg); DBUG_RETURN(NULL); } /** Allows to change the relay log info repository after startup. @param[in] mi Pointer to Relay_log_info. @param[in] mi_option Type of the repository, e.g. FILE TABLE. @param[out] msg Error message if something goes wrong. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::change_rli_repository(Relay_log_info *rli, uint rli_option, const char **msg) { Rpl_info_handler* handler_src= rli->get_rpl_info_handler(); Rpl_info_handler* handler_dest= NULL; uint instances= 1; DBUG_ENTER("Rpl_info_factory::change_rli_repository"); DBUG_ASSERT(handler_src != NULL); if (handler_src->get_rpl_info_type() == rli_option) DBUG_RETURN(false); if (init_repositories(rli_table_data, rli_file_data, rli_option, instances, NULL, &handler_dest, msg)) goto err; if (decide_repository(rli, rli_option, &handler_src, &handler_dest, msg)) goto err; DBUG_RETURN(FALSE); err: delete handler_dest; handler_dest= NULL; sql_print_error("Error changing the type of relay log info's repository: %s.", *msg); DBUG_RETURN(TRUE); } /** Delete all info from Worker info tables to render them useless in future MTS recovery, and indicate that in Coordinator info table. @return false on success, true when a failure in deletion or writing to Coordinator table fails. */ bool Rpl_info_factory::reset_workers(Relay_log_info *rli) { bool error= true; DBUG_ENTER("Rpl_info_factory::reset_workers"); if (rli->recovery_parallel_workers == 0) DBUG_RETURN(0); if (Rpl_info_file::do_reset_info(Slave_worker::get_number_worker_fields(), worker_file_data.pattern, worker_file_data.name_indexed)) goto err; if (Rpl_info_table::do_reset_info(Slave_worker::get_number_worker_fields(), MYSQL_SCHEMA_NAME.str, WORKER_INFO_NAME.str)) goto err; error= false; DBUG_EXECUTE_IF("mts_debug_reset_workers_fails", error= true;); err: if (error) sql_print_error("Could not delete from Slave Workers info repository."); rli->recovery_parallel_workers= 0; if (rli->flush_info(true)) { error= true; sql_print_error("Could not store the reset Slave Worker state into " "the slave info repository."); } DBUG_RETURN(error); } /** Creates a Slave worker repository whose type is defined as a parameter. @param[in] rli_option Type of the repository, e.g. FILE TABLE. @param[in] rli Pointer to Relay_log_info. The execution fails if a user requests a type but a different type already exists in the system. This is done to avoid that a user accidentally accesses the wrong repository and make the slave go out of sync. @retval Pointer to Slave_worker Success @retval NULL Failure */ Slave_worker *Rpl_info_factory::create_worker(uint rli_option, uint worker_id, Relay_log_info *rli, bool is_gaps_collecting_phase) { Rpl_info_handler* handler_src= NULL; Rpl_info_handler* handler_dest= NULL; Slave_worker* worker= NULL; const char *msg= "Failed to allocate memory for the worker info " "structure"; DBUG_ENTER("Rpl_info_factory::create_worker"); /* Define the name of the worker and its repository. */ char *pos= strmov(worker_file_data.name, worker_file_data.pattern); sprintf(pos, "%u", worker_id + 1); if (!(worker= new Slave_worker(rli #ifdef HAVE_PSI_INTERFACE ,&key_relay_log_info_run_lock, &key_relay_log_info_data_lock, &key_relay_log_info_sleep_lock, &key_relay_log_info_data_cond, &key_relay_log_info_start_cond, &key_relay_log_info_stop_cond, &key_relay_log_info_sleep_cond #endif , worker_id ))) goto err; if(init_repositories(worker_table_data, worker_file_data, rli_option, worker_id + 1, &handler_src, &handler_dest, &msg)) goto err; if (decide_repository(worker, rli_option, &handler_src, &handler_dest, &msg)) goto err; if (worker->rli_init_info(is_gaps_collecting_phase)) { msg= "Failed to initialize the worker info structure"; goto err; } if (rli->info_thd && rli->info_thd->is_error()) { msg= "Failed to initialize worker info table"; goto err; } DBUG_RETURN(worker); err: delete handler_src; delete handler_dest; if (worker) { /* The handler was previously deleted so we need to remove any reference to it. */ worker->set_rpl_info_handler(NULL); delete worker; } sql_print_error("Error creating relay log info: %s.", msg); DBUG_RETURN(NULL); } /** Initializes startup information on diferent repositories. */ void Rpl_info_factory::init_repository_metadata() { char* pos= NULL; rli_table_data.n_fields= Relay_log_info::get_number_info_rli_fields(); rli_table_data.schema= MYSQL_SCHEMA_NAME.str; rli_table_data.name= RLI_INFO_NAME.str; rli_file_data.n_fields= Relay_log_info::get_number_info_rli_fields(); strmov(rli_file_data.name, relay_log_info_file); strmov(rli_file_data.pattern, relay_log_info_file); rli_file_data.name_indexed= false; mi_table_data.n_fields= Master_info::get_number_info_mi_fields(); mi_table_data.schema= MYSQL_SCHEMA_NAME.str; mi_table_data.name= MI_INFO_NAME.str; mi_file_data.n_fields= Master_info::get_number_info_mi_fields(); strmov(mi_file_data.name, master_info_file); strmov(mi_file_data.pattern, master_info_file); rli_file_data.name_indexed= false; worker_table_data.n_fields= Slave_worker::get_number_worker_fields(); worker_table_data.schema= MYSQL_SCHEMA_NAME.str; worker_table_data.name= WORKER_INFO_NAME.str; worker_file_data.n_fields= Slave_worker::get_number_worker_fields(); pos= strmov(worker_file_data.name, "worker-"); pos= strmov(pos, relay_log_info_file); strmov(pos, "."); pos= strmov(worker_file_data.pattern, "worker-"); pos= strmov(pos, relay_log_info_file); strmov(pos, "."); worker_file_data.name_indexed= true; } /** Decides during startup what repository will be used based on the following decision table: \code |--------------+-----------------------+-----------------------| | Exists \ Opt | SOURCE | DESTINATION | |--------------+-----------------------+-----------------------| | ~is_s, ~is_d | - | Create/Update D | | ~is_s, is_d | - | Continue with D | | is_s, ~is_d | Copy S into D | Create/Update D | | is_s, is_d | Error | Error | |--------------+-----------------------+-----------------------| \endcode @param[in] info Either master info or relay log info. @param[in] option Identifies the type of the repository that will be used, i.e., destination repository. @param[out] handler_src Source repository from where information is copied into the destination repository. @param[out] handler_dest Destination repository to where informaiton is copied. @param[out] msg Error message if something goes wrong. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::decide_repository(Rpl_info *info, uint option, Rpl_info_handler **handler_src, Rpl_info_handler **handler_dest, const char **msg) { bool error= true; enum_return_check return_check_src= ERROR_CHECKING_REPOSITORY; enum_return_check return_check_dst= ERROR_CHECKING_REPOSITORY; DBUG_ENTER("Rpl_info_factory::decide_repository"); if (option == INFO_REPOSITORY_DUMMY) { delete (*handler_src); *handler_src= NULL; info->set_rpl_info_handler(*handler_dest); error = false; goto err; } DBUG_ASSERT((*handler_src) != NULL && (*handler_dest) != NULL && (*handler_src) != (*handler_dest)); return_check_src= check_src_repository(info, option, handler_src); return_check_dst= (*handler_dest)->do_check_info(info->get_internal_id()); if (return_check_src == ERROR_CHECKING_REPOSITORY || return_check_dst == ERROR_CHECKING_REPOSITORY) { /* If there is a problem with one of the repositories we print out more information and exit. */ DBUG_RETURN(check_error_repository(info, *handler_src, *handler_dest, return_check_src, return_check_dst, msg)); } else { if ((return_check_src == REPOSITORY_EXISTS && return_check_dst == REPOSITORY_DOES_NOT_EXIST) || (return_check_src == REPOSITORY_EXISTS && return_check_dst == REPOSITORY_EXISTS)) { /* If there is no error, we can proceed with the normal operation. However, if both repositories are set an error will be printed out. */ if (return_check_src == REPOSITORY_EXISTS && return_check_dst == REPOSITORY_EXISTS) { *msg= "Multiple replication metadata repository instances " "found with data in them. Unable to decide which is " "the correct one to choose"; goto err; } /* Do a low-level initialization to be able to do a state transfer. */ if (init_repositories(info, handler_src, handler_dest, msg)) goto err; /* Transfer information from source to destination and delete the source. Note this is not fault-tolerant and a crash before removing source may cause the next restart to fail as is_src and is_dest may be true. Moreover, any failure in removing the source may lead to the same. /Alfranio */ if (info->copy_info(*handler_src, *handler_dest) || (*handler_dest)->flush_info(true)) { *msg= "Error transfering information"; goto err; } (*handler_src)->end_info(); if ((*handler_src)->remove_info()) { *msg= "Error removing old repository"; goto err; } } else if (return_check_src == REPOSITORY_DOES_NOT_EXIST && return_check_dst == REPOSITORY_EXISTS) { DBUG_ASSERT(info->get_rpl_info_handler() == NULL); if ((*handler_dest)->do_init_info(info->get_internal_id())) { *msg= "Error reading repository"; goto err; } } else { DBUG_ASSERT(return_check_src == REPOSITORY_DOES_NOT_EXIST && return_check_dst == REPOSITORY_DOES_NOT_EXIST); } delete (*handler_src); *handler_src= NULL; info->set_rpl_info_handler(*handler_dest); error= false; } err: DBUG_RETURN(error); } /** This method is called by the decide_repository() and is used to check if the source repository exits. @param[in] info Either master info or relay log info. @param[in] option Identifies the type of the repository that will be used, i.e., destination repository. @param[out] handler_src Source repository from where information is @return enum_return_check The repository's status. */ enum_return_check Rpl_info_factory::check_src_repository(Rpl_info *info, uint option, Rpl_info_handler **handler_src) { enum_return_check return_check_src= ERROR_CHECKING_REPOSITORY; bool live_migration = info->get_rpl_info_handler() != NULL; if (!live_migration) { /* This is not a live migration and we don't know whether the repository exists or not. */ return_check_src= (*handler_src)->do_check_info(info->get_internal_id()); /* Since this is not a live migration, if we are using file repository and there is some error on table repository (for instance, engine disabled) we can ignore it instead of stopping replication. A warning saying that table is not ready to be used was logged. */ if (ERROR_CHECKING_REPOSITORY == return_check_src && INFO_REPOSITORY_FILE == option && INFO_REPOSITORY_TABLE == (*handler_src)->do_get_rpl_info_type()) { return_check_src= REPOSITORY_DOES_NOT_EXIST; /* If a already existent thread was used to access info tables, current_thd will point to it and we must clear access error on it. If a temporary thread was used, then there is nothing to clean because the thread was already deleted. See Rpl_info_table_access::create_thd(). */ if (current_thd) current_thd->clear_error(); } } else { /* This is a live migration as the repository is already associated to. However, we cannot assume that it really exists, for instance, if a file was really created. This situation may happen when we start a slave for the first time but skips its initialization and tries to migrate it. */ return_check_src= (*handler_src)->do_check_info(); } return return_check_src; } /** This method is called by the decide_repository() and is used print out information on errors. @param info Either master info or relay log info. @param handler_src Source repository from where information is copied into the destination repository. @param handler_dest Destination repository to where informaiton is copied. @param err_src Possible error status of the source repo check @param err_dst Possible error status of the destination repo check @param[out] msg Error message if something goes wrong. @retval TRUE Failure */ bool Rpl_info_factory::check_error_repository(Rpl_info *info, Rpl_info_handler *handler_src, Rpl_info_handler *handler_dest, enum_return_check err_src, enum_return_check err_dst, const char **msg) { bool error = true; /* If there is an error in any of the source or destination repository checks, the normal operation can't be proceeded. The runtime repository won't be initialized. */ if (err_src == ERROR_CHECKING_REPOSITORY) sql_print_error("Error in checking %s repository info type of %s.", handler_src->get_description_info(), handler_src->get_rpl_info_type_str()); if (err_dst == ERROR_CHECKING_REPOSITORY) sql_print_error("Error in checking %s repository info type of %s.", handler_dest->get_description_info(), handler_dest->get_rpl_info_type_str()); *msg= "Error checking repositories"; return error; } /** This method is called by the decide_repository() and is used to initialize the repositories through a low-level interfacei, which means that if they do not exist nothing will be created. @param[in] info Either master info or relay log info. @param[out] handler_src Source repository from where information is copied into the destination repository. @param[out] handler_dest Destination repository to where informaiton is copied. @param[out] msg Error message if something goes wrong. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::init_repositories(Rpl_info *info, Rpl_info_handler **handler_src, Rpl_info_handler **handler_dest, const char **msg) { bool live_migration = info->get_rpl_info_handler() != NULL; if (!live_migration) { if ((*handler_src)->do_init_info(info->get_internal_id()) || (*handler_dest)->do_init_info(info->get_internal_id())) { *msg= "Error transfering information"; return true; } } else { if ((*handler_dest)->do_init_info(info->get_internal_id())) { *msg= "Error transfering information"; return true; } } return false; } /** Creates repositories that will be associated to either the Master_info or Relay_log_info. @param[in] table_data Defines information to create a table repository. @param[in] file_data Defines information to create a file repository. @param[in] rep_option Identifies the type of the repository that will be used, i.e., destination repository. @param[in] instance Identifies the instance of the repository that will be used. @param[out] handler_src Source repository from where information is copied into the destination repository. @param[out] handler_dest Destination repository to where informaiton is copied. @param[out] msg Error message if something goes wrong. @retval FALSE No error @retval TRUE Failure */ bool Rpl_info_factory::init_repositories(const struct_table_data table_data, const struct_file_data file_data, uint rep_option, uint instance, Rpl_info_handler **handler_src, Rpl_info_handler **handler_dest, const char **msg) { bool error= TRUE; *msg= "Failed to allocate memory for master info repositories"; DBUG_ENTER("Rpl_info_factory::init_mi_repositories"); DBUG_ASSERT(handler_dest != NULL); switch (rep_option) { case INFO_REPOSITORY_FILE: if (!(*handler_dest= new Rpl_info_file(file_data.n_fields, file_data.pattern, file_data.name, file_data.name_indexed))) goto err; if (handler_src && !(*handler_src= new Rpl_info_table(table_data.n_fields, table_data.schema, table_data.name))) goto err; break; case INFO_REPOSITORY_TABLE: if (!(*handler_dest= new Rpl_info_table(table_data.n_fields, table_data.schema, table_data.name))) goto err; if (handler_src && !(*handler_src= new Rpl_info_file(file_data.n_fields, file_data.pattern, file_data.name, file_data.name_indexed))) goto err; break; case INFO_REPOSITORY_DUMMY: if (!(*handler_dest= new Rpl_info_dummy(Master_info::get_number_info_mi_fields()))) goto err; break; default: DBUG_ASSERT(0); } error= FALSE; err: DBUG_RETURN(error); } bool Rpl_info_factory::scan_repositories(uint* found_instances, uint* found_rep_option, const struct_table_data table_data, const struct_file_data file_data, const char **msg) { bool error= false; uint file_instances= 0; uint table_instances= 0; DBUG_ASSERT(found_rep_option != NULL); DBUG_ENTER("Rpl_info_factory::scan_repositories"); if (Rpl_info_table::do_count_info(table_data.n_fields, table_data.schema, table_data.name, &table_instances)) { error= true; goto err; } if (Rpl_info_file::do_count_info(file_data.n_fields, file_data.pattern, file_data.name_indexed, &file_instances)) { error= true; goto err; } if (file_instances != 0 && table_instances != 0) { error= true; *msg= "Multiple repository instances found with data in " "them. Unable to decide which is the correct one to " "choose"; goto err; } if (table_instances != 0) { *found_instances= table_instances; *found_rep_option= INFO_REPOSITORY_TABLE; } else if (file_instances != 0) { *found_instances= file_instances; *found_rep_option= INFO_REPOSITORY_FILE; } else { *found_instances= 0; *found_rep_option= INVALID_INFO_REPOSITORY; } err: DBUG_RETURN(error); }
gpl-2.0
Jacob-Kroeze/mdl4biz
lib/classes/event/content_viewed.php
3878
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Abstract event for content viewing. * * @package core * @copyright 2013 Ankit Agarwal * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace core\event; defined('MOODLE_INTERNAL') || die(); /** * Class content_viewed. * * Base class for a content view event. Each plugin must extend this to create their own content view event. * * An example usage:- * $event = \report_participation\event\content_viewed::create(array('courseid' => $course->id, * 'other' => array('content' => 'participants')); * $event->set_page_detail(); * $event->set_legacy_logdata(array($course->id, "course", "report participation", * "report/participation/index.php?id=$course->id", $course->id)); * $event->trigger(); * where \report_participation\event\content_viewed extends \core\event\content_viewed * * @package core * @copyright 2013 Ankit Agarwal * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class content_viewed extends base { /** @var null|array $legacylogdata Legacy log data */ protected $legacylogdata = null; /** * Set basic properties of the event. */ protected function init() { global $PAGE; $this->data['crud'] = 'r'; $this->data['level'] = self::LEVEL_OTHER; $this->context = $PAGE->context; } /** * Set basic page properties. */ public function set_page_detail() { global $PAGE; if (!isset($this->data['other'])) { $this->data['other'] = array(); } $this->data['other'] = array_merge(array('url' => $PAGE->url->out_as_local_url(false), 'heading' => $PAGE->heading, 'title' => $PAGE->title), $this->data['other']); } /** * Returns localised general event name. * * @return string */ public static function get_name() { return get_string('eventcontentviewed', 'moodle'); } /** * Returns non-localised description of what happened. * * @return string */ public function get_description() { return 'User with id ' . $this->userid . ' viewed content ' . $this->get_url(); } /** * Set legacy logdata. * * @param array $legacydata legacy logdata. */ public function set_legacy_logdata(array $legacydata) { $this->legacylogdata = $legacydata; } /** * Get legacy logdata. * * @return null|array legacy log data. */ protected function get_legacy_logdata() { return $this->legacylogdata; } /** * Custom validation. * * @throws \coding_exception when validation does not pass. * @return void */ protected function validate_data() { if (debugging('', DEBUG_DEVELOPER)) { // Make sure this class is never used without a content identifier. if (empty($this->other['content'])) { throw new \coding_exception('content_viewed event must define content identifier.'); } } } }
gpl-3.0
mateusop/LogEvolut
src/com/cburch/logisim/prefs/PrefMonitorString.java
2608
/******************************************************************************* * This file is part of logisim-evolution. * * logisim-evolution 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. * * logisim-evolution 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 logisim-evolution. If not, see <http://www.gnu.org/licenses/>. * * Original code by Carl Burch (http://www.cburch.com), 2011. * Subsequent modifications by : * + Haute École Spécialisée Bernoise * http://www.bfh.ch * + Haute École du paysage, d'ingénierie et d'architecture de Genève * http://hepia.hesge.ch/ * + Haute École d'Ingénierie et de Gestion du Canton de Vaud * http://www.heig-vd.ch/ * The project is currently maintained by : * + REDS Institute - HEIG-VD * Yverdon-les-Bains, Switzerland * http://reds.heig-vd.ch *******************************************************************************/ package com.cburch.logisim.prefs; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.Preferences; class PrefMonitorString extends AbstractPrefMonitor<String> { private static boolean isSame(String a, String b) { return a == null ? b == null : a.equals(b); } private String dflt; private String value; PrefMonitorString(String name, String dflt) { super(name); this.dflt = dflt; Preferences prefs = AppPreferences.getPrefs(); this.value = prefs.get(name, dflt); prefs.addPreferenceChangeListener(this); } public String get() { return value; } public void preferenceChange(PreferenceChangeEvent event) { Preferences prefs = event.getNode(); String prop = event.getKey(); String name = getIdentifier(); if (prop.equals(name)) { String oldValue = value; String newValue = prefs.get(name, dflt); if (!isSame(oldValue, newValue)) { value = newValue; AppPreferences.firePropertyChange(name, oldValue, newValue); } } } public void set(String newValue) { String oldValue = value; if (!isSame(oldValue, newValue)) { value = newValue; AppPreferences.getPrefs().put(getIdentifier(), newValue); } } }
gpl-3.0
slombard54/graylog2-server
graylog2-shared/src/main/java/org/graylog2/shared/rest/resources/RestResource.java
6191
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.shared.rest.resources; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.jaxrs.cfg.EndpointConfigBase; import com.fasterxml.jackson.jaxrs.cfg.ObjectWriterInjector; import com.fasterxml.jackson.jaxrs.cfg.ObjectWriterModifier; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import org.apache.shiro.subject.Subject; import org.graylog2.plugin.BaseConfiguration; import org.graylog2.plugin.database.users.User; import org.graylog2.shared.security.ShiroSecurityContext; import org.graylog2.shared.users.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.ForbiddenException; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.security.Principal; import java.util.Arrays; public abstract class RestResource { private static final Logger LOG = LoggerFactory.getLogger(RestResource.class); @Inject protected ObjectMapper objectMapper; @Inject protected UserService userService; @Inject private BaseConfiguration configuration; @Context SecurityContext securityContext; @Context UriInfo uriInfo; @QueryParam("pretty") public void setPrettyPrint(boolean prettyPrint) { if (prettyPrint) { /* sigh jersey, hooray @cowtowncoder : https://twitter.com/cowtowncoder/status/402226988603035648 */ ObjectWriterInjector.set(new ObjectWriterModifier() { @Override public ObjectWriter modify(EndpointConfigBase<?> endpoint, MultivaluedMap<String, Object> responseHeaders, Object valueToWrite, ObjectWriter w, JsonGenerator g) { return w.withDefaultPrettyPrinter(); } }); } } protected Subject getSubject() { if (securityContext == null) { LOG.error("Cannot retrieve current subject, SecurityContext isn't set."); return null; } final Principal p = securityContext.getUserPrincipal(); if (!(p instanceof ShiroSecurityContext.ShiroPrincipal)) { LOG.error("Unknown SecurityContext class {}, cannot continue.", securityContext); throw new IllegalStateException(); } final ShiroSecurityContext.ShiroPrincipal principal = (ShiroSecurityContext.ShiroPrincipal) p; return principal.getSubject(); } protected boolean isPermitted(String permission, String instanceId) { return getSubject().isPermitted(permission + ":" + instanceId); } protected void checkPermission(String permission) { if (!isPermitted(permission)) { throw new ForbiddenException("Not authorized"); } } protected boolean isPermitted(String permission) { return getSubject().isPermitted(permission); } protected void checkPermission(String permission, String instanceId) { if (!isPermitted(permission, instanceId)) { throw new ForbiddenException("Not authorized to access resource id " + instanceId); } } protected boolean isAnyPermitted(String[] permissions, final String instanceId) { final Iterable<String> instancePermissions = Iterables.transform(Arrays.asList(permissions), new Function<String, String>() { @Nullable @Override public String apply(String permission) { return permission + ":" + instanceId; } }); return isAnyPermitted(FluentIterable.from(instancePermissions).toArray(String.class)); } protected boolean isAnyPermitted(String... permissions) { final boolean[] permitted = getSubject().isPermitted(permissions); for (boolean p : permitted) { if (p) { return true; } } return false; } protected void checkAnyPermission(String permissions[], String instanceId) { if (!isAnyPermitted(permissions, instanceId)) { throw new ForbiddenException("Not authorized to access resource id " + instanceId); } } protected User getCurrentUser() { final Object principal = getSubject().getPrincipal(); final User user = userService.load(principal.toString()); if (user == null) { LOG.error("Loading the current user failed, this should not happen. Did you call this method in an unauthenticated REST resource?"); } return user; } protected UriBuilder getUriBuilderToSelf() { if (configuration.getRestTransportUri() != null) { return UriBuilder.fromUri(configuration.getRestTransportUri()); } else return uriInfo.getBaseUriBuilder(); } }
gpl-3.0
Ninjistix/darkstar
scripts/zones/Everbloom_Hollow/Zone.lua
717
----------------------------------- -- -- Zone: Everbloom_Hollow -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Everbloom_Hollow/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Everbloom_Hollow/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
wisdom-garden/dotcms
src/com/dotmarketing/portlets/structure/factories/RelationshipFactory.java
24994
package com.dotmarketing.portlets.structure.factories; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import com.dotcms.content.elasticsearch.business.ESContentFactoryImpl; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Tree; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotCacheException; import com.dotmarketing.business.DotStateException; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.factories.TreeFactory; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.structure.model.Relationship; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; public class RelationshipFactory { private static RelationshipCache cache = CacheLocator.getRelationshipCache(); // ### READ ### public static Relationship getRelationshipByInode(String inode) { Relationship rel = null; try { rel = cache.getRelationshipByInode(inode); if(rel != null) return rel; } catch (DotCacheException e) { Logger.error(RelationshipFactory.class, "Unable to access the cache to obtaion the relationship", e); } rel = (Relationship) InodeFactory.getInode(inode, Relationship.class); if(rel!= null && InodeUtils.isSet(rel.getInode())) cache.putRelationshipByInode(rel); return rel; } @SuppressWarnings("unchecked") public static List<Relationship> getRelationshipsByParent (Structure parent) { List<Relationship> list =new ArrayList<Relationship>(); String query = "select {relationship.*} from relationship, inode relationship_1_ " + "where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and " + "relationship.parent_structure_inode = ?"; try { HibernateUtil dh = new HibernateUtil(Relationship.class); dh.setSQLQuery(query); dh.setParam(parent.getInode()); list = dh.list(); } catch (DotHibernateException e) { Logger.error(RelationshipFactory.class, e.getMessage(), e); } return list; } @SuppressWarnings("unchecked") public static List<Relationship> getRelationshipsByChild (Structure child) { List<Relationship> list = new ArrayList<Relationship>(); String query = "select {relationship.*} from relationship, inode relationship_1_ " + "where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and " + "relationship.child_structure_inode = ?"; try { HibernateUtil dh = new HibernateUtil(Relationship.class); dh.setSQLQuery(query); dh.setParam(child.getInode()); list = dh.list(); } catch (DotHibernateException e) { Logger.error(RelationshipFactory.class, e.getMessage(), e); } return list; } public static List<Relationship> getAllRelationships() { String orderBy = "inode"; return getRelationships(orderBy,null); } @SuppressWarnings("unchecked") public static List<Relationship> getRelationships(String orderBy, String structureId) { List<Relationship> list = new ArrayList<Relationship>(); String query; if(structureId.equals("all")){ query = "select {relationship.*} from relationship, inode relationship_1_, structure parentstruct, " + "structure childstruct where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and " + "relationship.parent_structure_inode = parentstruct.inode and " + "relationship.child_structure_inode = childstruct.inode order by " + orderBy; }else{ query = "select {relationship.*} from relationship, inode relationship_1_, structure parentstruct, " + "structure childstruct where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and " + "relationship.parent_structure_inode = parentstruct.inode and " + "relationship.child_structure_inode = childstruct.inode and (relationship.parent_structure_inode = '" +structureId + "' or relationship.child_structure_inode = '"+structureId +"') order by " + orderBy; } try { HibernateUtil dh = new HibernateUtil(Relationship.class); dh.setSQLQuery(query); list = dh.list(); } catch (DotHibernateException e) { Logger.error(RelationshipFactory.class, e.getMessage(), e); } return list; } public static Relationship getRelationshipByRelationTypeValue(String typeValue) { Relationship rel = null; try { rel = cache.getRelationshipByName(typeValue); if(rel != null) return rel; } catch (DotCacheException e) { Logger.error(RelationshipFactory.class, "Unable to access the cache to obtaion the relationship", e); } rel = (Relationship) InodeFactory.getInodeOfClassByCondition(Relationship.class, "relation_type_value = '" + typeValue + "'"); if(rel!= null && InodeUtils.isSet(rel.getInode())) cache.putRelationshipByInode(rel); return rel; } @SuppressWarnings("unchecked") public static List<Relationship> getAllRelationshipsByStructure(Structure st) { List<Relationship> list = null; try { list = cache.getRelationshipsByStruct(st); } catch (DotCacheException e1) { //Logger.debug(RelationshipFactory.class,e1.getMessage(),e1); } if(list ==null){ String query = "select {relationship.*} from relationship, inode relationship_1_ " + "where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and " + "(relationship.parent_structure_inode = ? or relationship.child_structure_inode = ?)"; try { HibernateUtil dh = new HibernateUtil(Relationship.class); dh.setSQLQuery(query); dh.setParam(st.getInode()); dh.setParam(st.getInode()); list = dh.list(); cache.putRelationshipsByStruct(st, list); } catch (DotHibernateException e) { Logger.error(RelationshipFactory.class, e.getMessage(), e); }catch (DotCacheException e) { Logger.error(RelationshipFactory.class,e.getMessage(),e); } } return list; } @SuppressWarnings("unchecked") public static List<Relationship> getAllRelationshipsByStructure(Structure st, boolean hasParent) { List<Relationship> list = new ArrayList<Relationship>(); String query = "select {relationship.*} from relationship, inode relationship_1_ " + "where relationship_1_.type='relationship' and relationship.inode = relationship_1_.inode and "; if (hasParent) query += "(relationship.parent_structure_inode = ?)"; else query += "(relationship.child_structure_inode = ?)"; try { HibernateUtil dh = new HibernateUtil(Relationship.class); dh.setSQLQuery(query); dh.setParam(st.getInode()); list = dh.list(); } catch (DotHibernateException e) { Logger.error(RelationshipFactory.class, e.getMessage(), e); } return list; } public static List<Contentlet> getAllRelationshipRecords(Relationship relationship, Contentlet contentlet) throws DotStateException, DotDataException { String stInode = contentlet.getStructure().getInode(); List<Contentlet> matches = new ArrayList<Contentlet>(); if (relationship.getParentStructureInode().equalsIgnoreCase(stInode)) { matches = getAllRelationshipRecords(relationship, contentlet, true); } else if (relationship.getChildStructureInode().equalsIgnoreCase(stInode)) { matches = getAllRelationshipRecords(relationship, contentlet, false); } return matches; } public static List<Contentlet> getAllRelationshipRecords(Relationship relationship, Contentlet contentlet, boolean hasParent) throws DotStateException, DotDataException { return getAllRelationshipRecords (relationship, contentlet, hasParent, false, "tree_order"); } public static List<Tree> getAllRelationshipTrees(Relationship relationship, Contentlet contentlet) throws DotStateException, DotDataException { String stInode = contentlet.getStructure().getInode(); List<Tree> matches = new ArrayList<Tree>(); if (relationship.getParentStructureInode().equalsIgnoreCase(stInode)) { matches = getAllRelationshipTrees(relationship, contentlet, true); } else if (relationship.getChildStructureInode().equalsIgnoreCase(stInode)) { matches = getAllRelationshipTrees(relationship, contentlet, false); } return matches; } @SuppressWarnings("deprecation") public static List<Tree> getAllRelationshipTrees(Relationship relationship, Contentlet contentlet, boolean hasParent) throws DotStateException, DotDataException { List<Tree> matches = new ArrayList<Tree>(); List<Tree> trees = new ArrayList<Tree>(); Identifier iden = APILocator.getIdentifierAPI().find(contentlet); if (hasParent) { trees = TreeFactory.getTreesByParentAndRelationType(iden, relationship.getRelationTypeValue()); for (Tree tree : trees) { matches.add(tree); } } else { trees = TreeFactory.getTreesByChildAndRelationType(iden, relationship.getRelationTypeValue()); for (Tree tree : trees) { matches.add(tree); } } return matches; } @SuppressWarnings("deprecation") public static List<Contentlet> getAllRelationshipRecords(Relationship relationship, Contentlet contentlet, boolean hasParent, boolean live, String orderBy) throws DotStateException, DotDataException { List<Contentlet> matches = new ArrayList<Contentlet>(); if(contentlet == null || !InodeUtils.isSet(contentlet.getInode())) return matches; String iden = ""; try{ iden = APILocator.getIdentifierAPI().find(contentlet).getInode(); }catch(DotHibernateException dhe){ Logger.error(RelationshipFactory.class, "Unable to retrive Identifier", dhe); } if(!InodeUtils.isSet(iden)) return matches; if (hasParent) { if (live) matches = getRelatedContentByParent(iden, relationship.getRelationTypeValue(),true, orderBy); else matches = getRelatedContentByParent(iden, relationship.getRelationTypeValue(),false, orderBy); } else { if (live) matches = getRelatedContentByChild(iden, relationship.getRelationTypeValue(),true, orderBy); else matches = getRelatedContentByChild(iden, relationship.getRelationTypeValue(),false, orderBy); } return matches; } public static boolean isParentOfTheRelationship(Relationship rel, Structure st) { if (rel.getParentStructureInode().equalsIgnoreCase(st.getInode()) && !(rel.getParentRelationName().equals(rel.getChildRelationName()) && rel.getChildStructureInode().equalsIgnoreCase(rel.getParentStructureInode()))) return true; return false; } public static boolean isChildOfTheRelationship(Relationship rel, Structure st) { if (rel.getChildStructureInode().equalsIgnoreCase(st.getInode()) && !(rel.getParentRelationName().equals(rel.getChildRelationName()) && rel.getChildStructureInode().equalsIgnoreCase(rel.getParentStructureInode()))) return true; return false; } public static boolean isSameStructureRelationship(Relationship rel, Structure st) { if (rel.getChildStructureInode().equalsIgnoreCase(rel.getParentStructureInode()) ) return true; return false; } public static boolean isSameStructureRelationship(Relationship rel) { if (rel.getChildStructureInode().equalsIgnoreCase(rel.getParentStructureInode()) ) return true; return false; } // ### CREATE AND UPDATE public static void saveRelationship(Relationship relationship) throws DotHibernateException { HibernateUtil.saveOrUpdate(relationship); CacheLocator.getRelationshipCache().removeRelationshipByInode(relationship); try{ CacheLocator.getRelationshipCache().removeRelationshipsByStruct(relationship.getParentStructure()); CacheLocator.getRelationshipCache().removeRelationshipsByStruct(relationship.getChildStructure()); } catch(Exception e){ Logger.error(RelationshipFactory.class, e.getMessage(),e); } } /** * ISSUE 2222: https://github.com/dotCMS/dotCMS/issues/2222 * * @author Graziano Aliberti * Mar 4, 2013 - 4:54:16 PM */ public static void saveRelationship(Relationship relationship, String inode) throws DotHibernateException { Date now = new Date(); relationship.setiDate(now); HibernateUtil.saveWithPrimaryKey(relationship, inode); } // ### DELETE ### public static void deleteRelationship(String inode) throws DotHibernateException { Relationship relationship = getRelationshipByInode(inode); deleteRelationship(relationship); } public static void deleteRelationship(Relationship relationship) throws DotHibernateException { InodeFactory.deleteInode(relationship); CacheLocator.getRelationshipCache().removeRelationshipByInode(relationship); try { CacheLocator.getRelationshipCache().removeRelationshipsByStruct(relationship.getParentStructure()); CacheLocator.getRelationshipCache().removeRelationshipsByStruct(relationship.getChildStructure()); } catch (DotCacheException e) { Logger.error(RelationshipFactory.class, e.getMessage(),e); } } @SuppressWarnings("unchecked") public static List<Contentlet> getRelatedContentByParent(String parentInode, String relationType, boolean live, String orderBy) { try { HibernateUtil dh = new HibernateUtil(com.dotmarketing.portlets.contentlet.business.Contentlet.class); String sql = "SELECT {contentlet.*} from contentlet contentlet, inode contentlet_1_, contentlet_version_info vi, tree tree1 " + "where tree1.parent = ? and tree1.relation_type = ? " + "and tree1.child = contentlet.identifier " + "and contentlet.inode = contentlet_1_.inode and vi.identifier=contentlet.identifier " + "and " + ((live)?"vi.live_inode":"vi.working_inode") + " = contentlet.inode "; if (UtilMethods.isSet(orderBy) && !(orderBy.trim().equals("sort_order") || orderBy.trim().equals("tree_order"))) { sql = sql + " order by contentlet." + orderBy; } else { sql = sql + " order by tree1.tree_order"; } Logger.debug(RelationshipFactory.class, "sql: " + sql + "\n"); Logger.debug(RelationshipFactory.class, "parentInode: " + parentInode + "\n"); Logger.debug(RelationshipFactory.class, "relationType: " + relationType + "\n"); dh.setSQLQuery(sql); dh.setParam(parentInode); dh.setParam(relationType); List<com.dotmarketing.portlets.contentlet.business.Contentlet> l = dh.list(); List<Contentlet> conResult = new ArrayList<Contentlet>(); ESContentFactoryImpl conFac = new ESContentFactoryImpl(); for (com.dotmarketing.portlets.contentlet.business.Contentlet fatty : l) { conResult.add(conFac.convertFatContentletToContentlet(fatty)); } return conResult; } catch (Exception e) { Logger.error(RelationshipFactory.class, "getChildrenClass failed:" + e, e); throw new DotRuntimeException(e.toString()); } } /** * This method can be used to find the next in a sort order * @param parentInode The parent Relationship * @param relationType * @return the max in the sort order */ public static int getMaxInSortOrder(String parentInode, String relationType) { try { DotConnect db = new DotConnect(); String sql = "SELECT max(tree_order) as tree_order from tree tree1 " + "where tree1.parent = ? and tree1.relation_type = ? "; db.setSQL(sql); db.addParam(parentInode); db.addParam(relationType); int x= db.getInt("tree_order"); return x; } catch (Exception e) { Logger.debug(InodeFactory.class, "getMaxInSortOrder failed:" + e, e); } return 0; } @SuppressWarnings("unchecked") public static List<Contentlet> getRelatedContentByChild(String childInode, String relationType, boolean live, String orderBy) { try { HibernateUtil dh = new HibernateUtil(com.dotmarketing.portlets.contentlet.business.Contentlet.class); String sql = "SELECT {contentlet.*} "+ "from contentlet "+ "join inode contentlet_1_ "+ "on (contentlet.inode = contentlet_1_.inode) "+ "join contentlet_version_info vi "+ "on (vi."+(live?"live":"working")+"_inode = contentlet.inode) "+ "join tree "+ "on (tree.parent=contentlet.identifier) "+ "where "+ " tree.child = ? "+ " and tree.relation_type = ?"; if (UtilMethods.isSet(orderBy) && !(orderBy.trim().equals("sort_order") || orderBy.trim().equals("tree_order"))) { sql = sql + " order by contentlet." + orderBy; } else { sql = sql + " order by tree.tree_order"; } Logger.debug(RelationshipFactory.class, "sql: " + sql + "\n"); Logger.debug(RelationshipFactory.class, "childInode: " + childInode + "\n"); Logger.debug(RelationshipFactory.class, "relationType: " + relationType + "\n"); dh.setSQLQuery(sql); dh.setParam(childInode); dh.setParam(relationType); List<com.dotmarketing.portlets.contentlet.business.Contentlet> l = dh.list(); List<Contentlet> conResult = new ArrayList<Contentlet>(); ESContentFactoryImpl conFac = new ESContentFactoryImpl(); for (com.dotmarketing.portlets.contentlet.business.Contentlet fatty : l) { conResult.add(conFac.convertFatContentletToContentlet(fatty)); } return conResult; } catch (Exception e) { Logger.error(RelationshipFactory.class, "getChildrenClass failed:" + e, e); throw new DotRuntimeException(e.toString()); } } public static List<Contentlet> getAllRelationshipRecords(Relationship relationship, Contentlet contentlet, boolean hasParent, boolean live) throws DotStateException, DotDataException { return getAllRelationshipRecords(relationship, contentlet, hasParent, live,""); } /** * This method retrieves all the related contenlets and regardless if it has to retrieve parents, children or siblings * @param relationship * @param contentlet * @param orderBy * @return */ public static List<Contentlet> getRelatedContentlets(Relationship relationship, Contentlet contentlet, String orderBy, String sqlCondition, boolean liveContent) { return getRelatedContentlets(relationship, contentlet, orderBy, sqlCondition, liveContent, 0); } /** * Removes the relationships from the list of related contentlets to the passed in contentlet * @param contentlet * @param relationship * @param relatedContentlets * @throws DotDataException */ public static void deleteRelationships(Contentlet contentlet, Relationship relationship, List<Contentlet> relatedContentlets) throws DotDataException{ Tree t = new Tree(); for (Contentlet con : relatedContentlets) { t= TreeFactory.getTree(contentlet.getIdentifier(), con.getIdentifier(), relationship.getRelationTypeValue()); if(InodeUtils.isSet(t.getChild()) & InodeUtils.isSet(t.getParent())){ TreeFactory.deleteTree(t); }else{ t= TreeFactory.getTree(con.getIdentifier(),contentlet.getIdentifier(), relationship.getRelationTypeValue()); if(InodeUtils.isSet(t.getChild()) & InodeUtils.isSet(t.getParent())){ TreeFactory.deleteTree(t); } } } } /** * This method retrieves all the related contenlets and regardless if it has to retrieve parents, children or siblings * @param relationship * @param contentlet * @param orderBy * @param sqlCondition * @param liveContent * @param limit * @return */ @SuppressWarnings("unchecked") public static List<Contentlet> getRelatedContentlets(Relationship relationship, Contentlet contentlet, String orderBy, String sqlCondition, boolean liveContent, int limit) { List<Contentlet> matches = new ArrayList<Contentlet>(); if(contentlet == null || !InodeUtils.isSet(contentlet.getInode())) { return matches; } try { Identifier iden = APILocator.getIdentifierAPI().find(contentlet); if(iden == null || !InodeUtils.isSet(iden.getInode())) return matches; HibernateUtil dh = new HibernateUtil(com.dotmarketing.portlets.contentlet.business.Contentlet.class); String sql = "SELECT {contentlet.*} from contentlet contentlet, inode contentlet_1_, tree relationshipTree, identifier iden, tree identifierTree " + "where (relationshipTree.child = ? or relationshipTree.parent = ?) and relationshipTree.relation_type = ? " + "and (iden.inode = relationshipTree.parent or iden.inode = relationshipTree.child) " + "and (iden.inode = identifierTree.parent and identifierTree.child = contentlet_1_.inode) " + "and contentlet.inode = contentlet_1_.inode and contentlet.inode <> ? "; if(liveContent) sql += "and contentlet.live = " + DbConnectionFactory.getDBTrue(); else sql += "and contentlet.working = " + DbConnectionFactory.getDBTrue(); if(UtilMethods.isSet(sqlCondition)) sql += "and " + sqlCondition; if (UtilMethods.isSet(orderBy) && !(orderBy.trim().equals("sort_order") || orderBy.trim().equals("tree_order"))) { sql = sql + " order by contentlet." + orderBy; } else { sql = sql + " order by relationshipTree.tree_order"; } Logger.debug(RelationshipFactory.class, "sql: " + sql + "\n"); dh.setSQLQuery(sql); dh.setParam(iden.getInode()); dh.setParam(iden.getInode()); dh.setParam(relationship.getRelationTypeValue()); dh.setParam(contentlet.getInode()); if(limit > 0) { dh.setMaxResults(limit); } List<com.dotmarketing.portlets.contentlet.business.Contentlet> l = dh.list(); List<Contentlet> conResult = new ArrayList<Contentlet>(); ESContentFactoryImpl conFac = new ESContentFactoryImpl(); for (com.dotmarketing.portlets.contentlet.business.Contentlet fatty : l) { conResult.add(conFac.convertFatContentletToContentlet(fatty)); } return new ArrayList<Contentlet> (new LinkedHashSet<Contentlet>(conResult)); } catch (Exception e) { Logger.error(RelationshipFactory.class, "getChildrenClass failed:" + e, e); throw new DotRuntimeException(e.toString()); } } }
gpl-3.0
siteserverekun/cms
BaiRong.Core/ThirdParty/Alipay/openapi/Response/AlipayOpenPublicLifeMsgRecallResponse.cs
243
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipayOpenPublicLifeMsgRecallResponse. /// </summary> public class AlipayOpenPublicLifeMsgRecallResponse : AopResponse { } }
gpl-3.0
chirag52999/thinkAgain
node_modules/grunt-bower-installer/node_modules/bower/node_modules/bower-registry-client/test/core/util/Cache.js
1724
var Cache = require('../../../lib/util/Cache'); var expect = require('expect.js'); describe('Cache', function () { beforeEach(function () { this.cache = new Cache(); }); describe('Constructor', function () { describe('instantiating cache', function () { it('should provide an instance of RegistryClient', function () { expect(this.cache instanceof Cache).to.be.ok; }); it('should inherit LRU cache methods', function () { var self = this, lruMethods = [ 'max', 'lengthCalculator', 'length', 'itemCount', 'forEach', 'keys', 'values', 'reset', 'dump', 'dumpLru', 'set', 'has', 'get', 'peek', 'del' ]; lruMethods.forEach(function (method) { expect(self.cache._cache).to.have.property(method); }); }); }); it('should have a get prototype method', function () { expect(Cache.prototype).to.have.property('get'); }); it('should have a set prototype method', function () { expect(Cache.prototype).to.have.property('set'); }); it('should have a del prototype method', function () { expect(Cache.prototype).to.have.property('del'); }); it('should have a clear prototype method', function () { expect(Cache.prototype).to.have.property('clear'); }); it('should have a reset prototype method', function () { expect(Cache.prototype).to.have.property('reset'); }); }); });
gpl-3.0
SoftwareEngineeringToolDemos/ICSE-2012-TraceLab
Main/TraceLab/TraceLab.UI.GTK/DrawingLibrary/Locators/AbsoluteLocator.cs
2364
// MonoHotDraw. Diagramming Framework // // Authors: // Manuel Cerón <ceronman@gmail.com> // // Copyright (C) 2006, 2007, 2008, 2009 MonoUML Team (http://www.monouml.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Cairo; using MonoHotDraw.Figures; namespace MonoHotDraw.Locators { public class AbsoluteLocator: ILocator { private AbsoluteTo m_absoluteTo; public AbsoluteLocator(): this(0.0, 0.0, AbsoluteTo.TopLeft) { } public AbsoluteLocator(double x, double y, AbsoluteTo absoluteTo) { this.x = x; this.y = y; m_absoluteTo = absoluteTo; } public PointD Locate(IFigure owner) { if (m_absoluteTo == AbsoluteTo.TopRight) { PointD topRight = owner.DisplayBox.TopRight; return new PointD { X = topRight.X - x, Y = topRight.Y + y, }; } else { PointD topLeft = owner.DisplayBox.TopLeft; return new PointD { X = topLeft.X + x, Y = topLeft.Y + y, }; } } double x; double y; public enum AbsoluteTo { TopLeft, TopRight } } }
gpl-3.0
deependhulla/archive-plus-ediscovery
files/groupoffice/modules/calendar/language/el.php
7215
<?php $l["addressbook"]='Ευρετήριο Διευθύνσεων'; $l["appointments"]= 'Συναντήσεις'; $l["recurrence"]= 'Επανάληψη'; $l["options"]= 'επιλογές'; $l["repeatForever"]= 'Επανάληψη για πάντα'; $l["repeatEvery"]= 'Επανάληψη κάθε'; $l["repeatUntil"]= 'Επανάληψη μέχρι'; $l["busy"]= 'Εμφάνιση σαν απασχολημένος'; $l["allDay"]= 'Ο χρόνος δεν είναι εφαρμόσιμος'; $l["navigation"]= 'Περιήγηση'; $l["oneDay"]= '1 ημέρα'; $l["fiveDays"]= '5 ημέρες'; $l["sevenDays"]= '7 ημέρες'; $l["month"]= 'Μήνας'; $l["recurringEvent"]= 'Επαναλαμβανόμενο γεγονός'; $l["deleteRecurringEvent"]= 'Επιθυμείτε να σβήσετε ένα ή όλα τα στιγμιότυπα αυτού του επαναλαμβανόμενου γεγονότος;'; $l["singleOccurence"]= 'Μια εμφάνιση'; $l["entireSeries"]= 'Όλη τη σειρά'; $l["calendar"]= 'Ημερολόγιο'; $l["calendars"]= 'Ημερολόγια'; $l["views"]= 'Όψεις'; $l["administration"]= 'Διαχείριση'; $l["needsAction"]= 'Χρήζει ενέργειας'; $l["accepted"]= 'Έχει γίνει αποδεκτό'; $l["declined"]= 'Έχει απορριφθεί'; $l["tentative"]= 'Υπό δοκιμή'; $l["delegated"]= 'Δια εκπροσώπου'; $l["noRecurrence"]= 'Καμία επανάληψη'; $l["notRespondedYet"]= 'Δεν έχει απαντήσει ακόμα'; $l["days"]= 'ημέρες'; $l["weeks"]= 'Εβδομάδες'; $l["monthsByDate"]= 'Μήνες ανά ημερομηνία'; $l["monthsByDay"]= 'Μήνες ανά ημέρα'; $l["years"]= 'έτη'; $l["atDays"]= 'Στις ημέρες'; $l["noReminder"]= 'Χωρίς υπενθύμιση'; $l["reminder"]='Υπενθύμιση'; $l["participants"]= 'Συμμετέχοντες'; $l["checkAvailability"]= 'Έλεγχος διαθεσιμότητας'; $l["sendInvitation"]= 'Αποστολή πρόσκλησης'; $l["emailSendingNotConfigured"]= 'Η αποστολή ηλεκτρονικού ταχυδρομείου δεν έχει ρυθμιστεί.'; $l["privateEvent"]= 'Ιδιωτικό'; $l["noInformationAvailable"]= 'Δεν υπάρχουν διαθέσιμες πληροφορίες'; $l["noParticipantsToDisplay"]= 'Δεν υπάρχουν συμμετέχοντες προς εμφάνιση'; $l["previousDay"]= 'Προηγούμενη ημέρα'; $l["nextDay"]= 'Επόμενη ημέρα'; $l["noAppointmentsToDisplay"]= 'Δεν υπάρχουν συναντήσεις προς εμφάνιση'; $l["selectCalendar"]= 'Επιλογή ημερολογίου'; $l["selectCalendarForAppointment"]= 'Επιλέξτε το ημερολόγιο στο οποίο επιθυμείτε να τοποθετήσετε αυτή τη συνάντηση'; $l["closeWindow"]= 'Η συνάντηση έχει γίνει αποδεκτή και δομολογήθηκε. Μπορείτε να κλείσετε αυτό το παράθυρο.'; $l["list"]='Λίστα'; $l["editRecurringEvent"]='Θέλετε να τροποποιήσετε αυτή την εμφάνιση ή όλη τη σειρά;'; $l["selectIcalendarFile"]='Επιλέξτε ένα αρχείο icalendar (*.ics)'; $l["eventDefaults"]='Προεπιλεγμένες ρυθμίσεις συναντήσεων'; $l['name'] = 'Ημερολόγιο'; $l['description'] = 'Άρθρωμα Ημερολογίου. Κάθε χρήστης μπορεί να προσθέσει, να τροποποιήσει ή να διαγράψει συναντήσεις.Επιπλέον, υπάρχουν διαθέσιμες οι συναντήσεις από άλλους χρήστες και μπορούν να τροποποιηθούν εάν υπάρξει ανάγκη.'; $lang['link_type'][1]='Συνάντηση'; $l['groupView'] = 'Όψη ομάδας'; $l['event']='Γεγονός'; $l['startsAt']='Ξεκινάει στις'; $l['endsAt']='Τελειώνει στις'; $l['exceptionNoCalendarID'] = 'Τερματικό σφάλμα: Δεν υπάρχει αριθμός ταυτότητας (ID) του ημερολογίου!'; $l['appointment'] = 'Συνάντηση: '; $l['allTogether'] = 'Όλα μαζί'; $l['invited']='Έχετε προσκληθεί στο παρακάτω γεγονός'; $l['acccept_question']='Αποδέχεστε αυτό το γεγονός;'; $l['accept']='Αποδοχή'; $l['decline']='Απόρριψη'; $l['bad_event']='Αυτό το γεγονός δεν υφίσταται πλεόν'; $l['subject']='Θέμα'; $l['status']='Κατάσταση'; $l['statuses']['NEEDS-ACTION'] = 'Χρήζει ενέργειας'; $l['statuses']['ACCEPTED'] = 'Έχει γίνει αποδοχή'; $l['statuses']['DECLINED'] = 'Έχει απορριφθεί'; $l['statuses']['TENTATIVE'] = 'Υπό δοκιμή'; $l['statuses']['DELEGATED'] = 'Δια εκπροσώπου'; $l['statuses']['COMPLETED'] = 'Ολοκληρωμένο'; $l['statuses']['IN-PROCESS'] = 'Σε εξέλιξη'; $l['accept_mail_subject'] = 'Η πρόσκληση για το \'%s\' έχει γίνει αποδεκτή'; $l['accept_mail_body'] = 'Ο/Η %s δέχτηκε την πρόσκληση σας για:'; $l['decline_mail_subject'] = 'Η πρόσκληση για το \'%s\' απορρίφθηκε'; $l['decline_mail_body'] = 'Ο/Η %s απόρριψε την πρόσκληση σας για:'; $l['location']='Τοποθεσία'; $l['and']='και'; $l['repeats'] = 'Επανάλαμβάνεται κάθε %s'; $l['repeats_at'] = 'Επανάλαμβάνεται κάθε %s στις %s';//eg. Repeats every month at the first monday; $l['repeats_at_not_every'] = 'Επανάλαμβάνεται κάθε %s %s στις %s';//eg. Repeats every 2 weeks at monday; $l['until']='μέχρι'; ; $l['not_invited']='Δεν προσκληθήκατε σε αυτό το γεγονός. Πιθανώς πρέπει να κάνετε είσοδο σαν διαφορετικός χρήστης.'; $l['accept_title']='Αποδοχή'; $l['accept_confirm']='Ο δημιουργός θα ειδοποιηθεί για την αποδοχή σας σε αυτό το γεγονός'; $l['decline_title']='Απόρριψη'; $l['decline_confirm']='Ο δημιουργός θα ειδοποιηθεί για την απόρριψη σας σε αυτό το γεγονός'; $l['cumulative']='Μη έγκυρος κανόνας επανάληψης. Η επόμενη επανάληψη δεν μπορεί να ξεκινά πριν τελειώση η προηγούμενη.'; $l['already_accepted']='Έχετε ήδη αποδεχτεί αυτό το γεγονός.'; $l['private']='Ιδιωτικό'; $l['import_success']='Εισήχθησαν %s γεγονότα'; $l['printTimeFormat']='Από %s έως %s'; $l['printLocationFormat']=' στην τοποθεσία "%s"'; $l['printPage']='Σελίδα %s από %s'; $l['printList']='Λίστα συναντήσεων'; $l['printAllDaySingle']='Όλη την ημέρα'; $l['printAllDayMultiple']='Όλη την ημέρα από %s έως %s';
gpl-3.0
rmackay9/rmackay9-ardupilot
libraries/AP_GPS/AP_GPS_NMEA.cpp
20920
/* 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/>. */ // // NMEA parser, adapted by Michael Smith from TinyGPS v9: // // TinyGPS - a small GPS library for Arduino providing basic NMEA parsing // Copyright (C) 2008-9 Mikal Hart // All rights reserved. // /// @file AP_GPS_NMEA.cpp /// @brief NMEA protocol parser /// /// This is a lightweight NMEA parser, derived originally from the /// TinyGPS parser by Mikal Hart. /// #include <AP_Common/AP_Common.h> #include <AP_Common/NMEA.h> #include <ctype.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include "AP_GPS_NMEA.h" #if AP_GPS_NMEA_ENABLED extern const AP_HAL::HAL& hal; // Convenience macros ////////////////////////////////////////////////////////// // #define DIGIT_TO_VAL(_x) (_x - '0') #define hexdigit(x) ((x)>9?'A'+((x)-10):'0'+(x)) bool AP_GPS_NMEA::read(void) { int16_t numc; bool parsed = false; numc = port->available(); while (numc--) { char c = port->read(); if (_decode(c)) { parsed = true; } #if AP_GPS_DEBUG_LOGGING_ENABLED log_data((const uint8_t *)&c, 1); #endif } return parsed; } bool AP_GPS_NMEA::_decode(char c) { bool valid_sentence = false; _sentence_length++; switch (c) { case ',': // term terminators _parity ^= c; FALLTHROUGH; case '\r': case '\n': case '*': if (_sentence_done) { return false; } if (_term_offset < sizeof(_term)) { _term[_term_offset] = 0; valid_sentence = _term_complete(); } ++_term_number; _term_offset = 0; _is_checksum_term = c == '*'; return valid_sentence; case '$': // sentence begin _term_number = _term_offset = 0; _parity = 0; _sentence_type = _GPS_SENTENCE_OTHER; _is_checksum_term = false; _gps_data_good = false; _sentence_length = 1; _sentence_done = false; return valid_sentence; } // ordinary characters if (_term_offset < sizeof(_term) - 1) _term[_term_offset++] = c; if (!_is_checksum_term) _parity ^= c; return valid_sentence; } int32_t AP_GPS_NMEA::_parse_decimal_100(const char *p) { char *endptr = nullptr; long ret = 100 * strtol(p, &endptr, 10); int sign = ret < 0 ? -1 : 1; if (ret >= (long)INT32_MAX) { return INT32_MAX; } if (ret <= (long)INT32_MIN) { return INT32_MIN; } if (endptr == nullptr || *endptr != '.') { return ret; } if (isdigit(endptr[1])) { ret += sign * 10 * DIGIT_TO_VAL(endptr[1]); if (isdigit(endptr[2])) { ret += sign * DIGIT_TO_VAL(endptr[2]); if (isdigit(endptr[3])) { ret += sign * (DIGIT_TO_VAL(endptr[3]) >= 5); } } } return ret; } /* parse a NMEA latitude/longitude degree value. The result is in degrees*1e7 */ uint32_t AP_GPS_NMEA::_parse_degrees() { char *p, *q; uint8_t deg = 0, min = 0; float frac_min = 0; int32_t ret = 0; // scan for decimal point or end of field for (p = _term; *p && isdigit(*p); p++) ; q = _term; // convert degrees while ((p - q) > 2 && *q) { if (deg) deg *= 10; deg += DIGIT_TO_VAL(*q++); } // convert minutes while (p > q && *q) { if (min) min *= 10; min += DIGIT_TO_VAL(*q++); } // convert fractional minutes if (*p == '.') { q = p + 1; float frac_scale = 0.1f; while (*q && isdigit(*q)) { frac_min += DIGIT_TO_VAL(*q) * frac_scale; q++; frac_scale *= 0.1f; } } ret = (deg * (int32_t)10000000UL); ret += (min * (int32_t)10000000UL / 60); ret += (int32_t) (frac_min * (1.0e7f / 60.0f)); return ret; } /* see if we have a new set of NMEA messages */ bool AP_GPS_NMEA::_have_new_message() { if (_last_RMC_ms == 0 || _last_GGA_ms == 0) { return false; } uint32_t now = AP_HAL::millis(); if (now - _last_RMC_ms > 150 || now - _last_GGA_ms > 150) { return false; } if (_last_VTG_ms != 0 && now - _last_VTG_ms > 150) { return false; } /* if we have seen a message with 3D velocity data messages then wait for them again. This is important as the have_vertical_velocity field will be overwritten by fill_3d_velocity() */ if (_last_vvelocity_ms != 0 && now - _last_vvelocity_ms > 150 && now - _last_vvelocity_ms < 1000) { // waiting on a message with velocity return false; } if (_last_vaccuracy_ms != 0 && now - _last_vaccuracy_ms > 150 && now - _last_vaccuracy_ms < 1000) { // waiting on a message with velocity accuracy return false; } // prevent these messages being used again if (_last_VTG_ms != 0) { _last_VTG_ms = 1; } if (now - _last_yaw_ms > 300) { // we have lost GPS yaw state.have_gps_yaw = false; } if (now - _last_KSXT_pos_ms > 500) { // we have lost KSXT _last_KSXT_pos_ms = 0; } // special case for fixing low output rate of ALLYSTAR GPS modules const int32_t dt_ms = now - _last_fix_ms; if (labs(dt_ms - gps._rate_ms[state.instance]) > 50 && get_type() == AP_GPS::GPS_TYPE_ALLYSTAR) { nmea_printf(port, "$PHD,06,42,UUUUTTTT,BB,0,%u,55,0,%u,0,0,0", unsigned(1000U/gps._rate_ms[state.instance]), unsigned(gps._rate_ms[state.instance])); } _last_fix_ms = now; _last_GGA_ms = 1; _last_RMC_ms = 1; return true; } // Processes a just-completed term // Returns true if new sentence has just passed checksum test and is validated bool AP_GPS_NMEA::_term_complete() { // handle the last term in a message if (_is_checksum_term) { _sentence_done = true; uint8_t nibble_high = 0; uint8_t nibble_low = 0; if (!hex_to_uint8(_term[0], nibble_high) || !hex_to_uint8(_term[1], nibble_low)) { return false; } const uint8_t checksum = (nibble_high << 4u) | nibble_low; if (checksum == _parity) { if (_gps_data_good) { uint32_t now = AP_HAL::millis(); switch (_sentence_type) { case _GPS_SENTENCE_RMC: _last_RMC_ms = now; //time = _new_time; //date = _new_date; if (_last_KSXT_pos_ms == 0) { state.location.lat = _new_latitude; state.location.lng = _new_longitude; } if (_last_3D_velocity_ms == 0 || now - _last_3D_velocity_ms > 1000) { state.ground_speed = _new_speed*0.01f; state.ground_course = wrap_360(_new_course*0.01f); } make_gps_time(_new_date, _new_time * 10); set_uart_timestamp(_sentence_length); state.last_gps_time_ms = now; if (_last_vvelocity_ms == 0 || now - _last_vvelocity_ms > 1000) { fill_3d_velocity(); } break; case _GPS_SENTENCE_GGA: _last_GGA_ms = now; if (_last_KSXT_pos_ms == 0) { state.location.alt = _new_altitude; state.location.lat = _new_latitude; state.location.lng = _new_longitude; } state.num_sats = _new_satellite_count; state.hdop = _new_hdop; switch(_new_quality_indicator) { case 0: // Fix not available or invalid state.status = AP_GPS::NO_FIX; break; case 1: // GPS SPS Mode, fix valid state.status = AP_GPS::GPS_OK_FIX_3D; break; case 2: // Differential GPS, SPS Mode, fix valid state.status = AP_GPS::GPS_OK_FIX_3D_DGPS; break; case 3: // GPS PPS Mode, fix valid state.status = AP_GPS::GPS_OK_FIX_3D; break; case 4: // Real Time Kinematic. System used in RTK mode with fixed integers state.status = AP_GPS::GPS_OK_FIX_3D_RTK_FIXED; break; case 5: // Float RTK. Satellite system used in RTK mode, floating integers state.status = AP_GPS::GPS_OK_FIX_3D_RTK_FLOAT; break; case 6: // Estimated (dead reckoning) Mode state.status = AP_GPS::NO_FIX; break; default://to maintain compatibility with MAV_GPS_INPUT and others state.status = AP_GPS::GPS_OK_FIX_3D; break; } break; case _GPS_SENTENCE_VTG: _last_VTG_ms = now; if (_last_3D_velocity_ms == 0 || now - _last_3D_velocity_ms > 1000) { state.ground_speed = _new_speed*0.01f; state.ground_course = wrap_360(_new_course*0.01f); if (_last_vvelocity_ms == 0 || now - _last_vvelocity_ms > 1000) { fill_3d_velocity(); } } // VTG has no fix indicator, can't change fix status break; case _GPS_SENTENCE_HDT: case _GPS_SENTENCE_THS: _last_yaw_ms = now; state.gps_yaw = wrap_360(_new_gps_yaw*0.01f); state.have_gps_yaw = true; state.gps_yaw_time_ms = AP_HAL::millis(); // remember that we are setup to provide yaw. With // a NMEA GPS we can only tell if the GPS is // configured to provide yaw when it first sends a // HDT sentence. state.gps_yaw_configured = true; break; case _GPS_SENTENCE_PHD: if (_phd.msg_id == 12) { state.velocity.x = _phd.fields[0] * 0.01; state.velocity.y = _phd.fields[1] * 0.01; state.velocity.z = _phd.fields[2] * 0.01; state.have_vertical_velocity = true; _last_vvelocity_ms = now; // we prefer a true 3D velocity when available state.ground_course = wrap_360(degrees(atan2f(state.velocity.y, state.velocity.x))); state.ground_speed = state.velocity.xy().length(); _last_3D_velocity_ms = now; } else if (_phd.msg_id == 26) { state.horizontal_accuracy = MAX(_phd.fields[0],_phd.fields[1]) * 0.001; state.have_horizontal_accuracy = true; state.vertical_accuracy = _phd.fields[2] * 0.001; state.have_vertical_accuracy = true; state.speed_accuracy = MAX(_phd.fields[3],_phd.fields[4]) * 0.001; state.have_speed_accuracy = true; _last_vaccuracy_ms = now; } break; case _GPS_SENTENCE_KSXT: state.location.lat = _ksxt.fields[2]*1.0e7; state.location.lng = _ksxt.fields[1]*1.0e7; state.location.alt = _ksxt.fields[3]*1.0e2; _last_KSXT_pos_ms = now; if (_ksxt.fields[9] >= 1) { // we have 3D fix constexpr float kmh_to_mps = 1.0 / 3.6; state.velocity.y = _ksxt.fields[16] * kmh_to_mps; state.velocity.x = _ksxt.fields[17] * kmh_to_mps; state.velocity.z = _ksxt.fields[18] * -kmh_to_mps; state.have_vertical_velocity = true; _last_vvelocity_ms = now; // we prefer a true 3D velocity when available state.ground_course = wrap_360(degrees(atan2f(state.velocity.y, state.velocity.x))); state.ground_speed = state.velocity.xy().length(); _last_3D_velocity_ms = now; } if (is_equal(3.0f, _ksxt.fields[10])) { // have good yaw (from RTK fixed moving baseline solution) _last_yaw_ms = now; state.gps_yaw = _ksxt.fields[4]; state.have_gps_yaw = true; state.gps_yaw_time_ms = AP_HAL::millis(); state.gps_yaw_configured = true; } break; } } else { switch (_sentence_type) { case _GPS_SENTENCE_RMC: case _GPS_SENTENCE_GGA: // Only these sentences give us information about // fix status. state.status = AP_GPS::NO_FIX; break; case _GPS_SENTENCE_THS: state.have_gps_yaw = false; break; } } // see if we got a good message return _have_new_message(); } // we got a bad message, ignore it return false; } // the first term determines the sentence type if (_term_number == 0) { /* special case for $PHD message */ if (strcmp(_term, "PHD") == 0) { _sentence_type = _GPS_SENTENCE_PHD; return false; } if (strcmp(_term, "KSXT") == 0) { _sentence_type = _GPS_SENTENCE_KSXT; _gps_data_good = true; return false; } /* The first two letters of the NMEA term are the talker ID. The most common is 'GP' but there are a bunch of others that are valid. We accept any two characters here. */ if (_term[0] < 'A' || _term[0] > 'Z' || _term[1] < 'A' || _term[1] > 'Z') { _sentence_type = _GPS_SENTENCE_OTHER; return false; } const char *term_type = &_term[2]; if (strcmp(term_type, "RMC") == 0) { _sentence_type = _GPS_SENTENCE_RMC; } else if (strcmp(term_type, "GGA") == 0) { _sentence_type = _GPS_SENTENCE_GGA; } else if (strcmp(term_type, "HDT") == 0) { _sentence_type = _GPS_SENTENCE_HDT; // HDT doesn't have a data qualifier _gps_data_good = true; } else if (strcmp(term_type, "THS") == 0) { _sentence_type = _GPS_SENTENCE_THS; } else if (strcmp(term_type, "VTG") == 0) { _sentence_type = _GPS_SENTENCE_VTG; // VTG may not contain a data qualifier, presume the solution is good // unless it tells us otherwise. _gps_data_good = true; } else { _sentence_type = _GPS_SENTENCE_OTHER; } return false; } // 32 = RMC, 64 = GGA, 96 = VTG, 128 = HDT, 160 = THS if (_sentence_type != _GPS_SENTENCE_OTHER && _term[0]) { switch (_sentence_type + _term_number) { // operational status // case _GPS_SENTENCE_RMC + 2: // validity (RMC) _gps_data_good = _term[0] == 'A'; break; case _GPS_SENTENCE_GGA + 6: // Fix data (GGA) _gps_data_good = _term[0] > '0'; _new_quality_indicator = _term[0] - '0'; break; case _GPS_SENTENCE_THS + 2: // validity (THS) _gps_data_good = _term[0] == 'A'; break; case _GPS_SENTENCE_VTG + 9: // validity (VTG) (we may not see this field) _gps_data_good = _term[0] != 'N'; break; case _GPS_SENTENCE_GGA + 7: // satellite count (GGA) _new_satellite_count = atol(_term); break; case _GPS_SENTENCE_GGA + 8: // HDOP (GGA) _new_hdop = (uint16_t)_parse_decimal_100(_term); break; // time and date // case _GPS_SENTENCE_RMC + 1: // Time (RMC) case _GPS_SENTENCE_GGA + 1: // Time (GGA) _new_time = _parse_decimal_100(_term); break; case _GPS_SENTENCE_RMC + 9: // Date (GPRMC) _new_date = atol(_term); break; // location // case _GPS_SENTENCE_RMC + 3: // Latitude case _GPS_SENTENCE_GGA + 2: _new_latitude = _parse_degrees(); break; case _GPS_SENTENCE_RMC + 4: // N/S case _GPS_SENTENCE_GGA + 3: if (_term[0] == 'S') _new_latitude = -_new_latitude; break; case _GPS_SENTENCE_RMC + 5: // Longitude case _GPS_SENTENCE_GGA + 4: _new_longitude = _parse_degrees(); break; case _GPS_SENTENCE_RMC + 6: // E/W case _GPS_SENTENCE_GGA + 5: if (_term[0] == 'W') _new_longitude = -_new_longitude; break; case _GPS_SENTENCE_GGA + 9: // Altitude (GPGGA) _new_altitude = _parse_decimal_100(_term); break; // course and speed // case _GPS_SENTENCE_RMC + 7: // Speed (GPRMC) case _GPS_SENTENCE_VTG + 5: // Speed (VTG) _new_speed = (_parse_decimal_100(_term) * 514) / 1000; // knots-> m/sec, approximiates * 0.514 break; case _GPS_SENTENCE_HDT + 1: // Course (HDT) _new_gps_yaw = _parse_decimal_100(_term); break; case _GPS_SENTENCE_THS + 1: // Course (THS) _new_gps_yaw = _parse_decimal_100(_term); break; case _GPS_SENTENCE_RMC + 8: // Course (GPRMC) case _GPS_SENTENCE_VTG + 1: // Course (VTG) _new_course = _parse_decimal_100(_term); break; case _GPS_SENTENCE_PHD + 1: // PHD class _phd.msg_class = atol(_term); break; case _GPS_SENTENCE_PHD + 2: // PHD message _phd.msg_id = atol(_term); if (_phd.msg_class == 1 && (_phd.msg_id == 12 || _phd.msg_id == 26)) { // we only support $PHD messages 1/12 and 1/26 _gps_data_good = true; } break; case _GPS_SENTENCE_PHD + 5: // PHD message, itow _phd.itow = strtoul(_term, nullptr, 10); break; case _GPS_SENTENCE_PHD + 6 ... _GPS_SENTENCE_PHD + 11: // PHD message, fields _phd.fields[_term_number-6] = atol(_term); break; case _GPS_SENTENCE_KSXT + 1 ... _GPS_SENTENCE_KSXT + 22: // PHD message, fields _ksxt.fields[_term_number-1] = atof(_term); break; } } return false; } /* detect a NMEA GPS. Adds one byte, and returns true if the stream matches a NMEA string */ bool AP_GPS_NMEA::_detect(struct NMEA_detect_state &state, uint8_t data) { switch (state.step) { case 0: state.ck = 0; if ('$' == data) { state.step++; } break; case 1: if ('*' == data) { state.step++; } else { state.ck ^= data; } break; case 2: if (hexdigit(state.ck>>4) == data) { state.step++; } else { state.step = 0; } break; case 3: if (hexdigit(state.ck&0xF) == data) { state.step = 0; return true; } state.step = 0; break; } return false; } #endif
gpl-3.0
bernte/monstra-cms
plugins/box/filesmanager/languages/ja.lang.php
673
<?php return array( 'filesmanager' => array( 'Files' => 'ファイル', 'Files manager' => 'ファイルの管理', 'Name' => '名前', 'Actions' => '操作', 'Delete' => '削除', 'Upload' => 'アップロード', 'directory' => 'ディレクトリ', 'Delete directory: :dir' => 'ディレクトリの削除: :dir', 'Delete file: :file' => 'ファイルの削除 :file', 'Extension' => '拡張子', 'Size' => 'サイズ', 'Select file' => 'ファイルの選択', 'Change' => '変更', ) );
gpl-3.0
Walt280/cosmos
code/mathematical-algorithms/reverse_number/reverse_number.cpp
276
#include<iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation int reverse_number(int n){ int ans = 0; while(n != 0){ ans *= 10; ans += n % 10; n /= 10; } return ans; } int main(){ int n; cin >> n; cout << reverse_number(n); return 0; }
gpl-3.0
materemias/sentrifugo
application/modules/default/controllers/PrefixController.php
12125
<?php /********************************************************************************* * This file is part of Sentrifugo. * Copyright (C) 2015 Sapplica * * Sentrifugo 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. * * Sentrifugo 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 Sentrifugo. If not, see <http://www.gnu.org/licenses/>. * * Sentrifugo Support <support@sentrifugo.com> ********************************************************************************/ class Default_PrefixController extends Zend_Controller_Action { private $options; public function preDispatch() { } public function init() { $this->_options= $this->getInvokeArg('bootstrap')->getOptions(); } public function indexAction() { $prefixmodel = new Default_Model_Prefix(); $call = $this->_getParam('call'); if($call == 'ajaxcall') $this->_helper->layout->disableLayout(); $view = Zend_Layout::getMvcInstance()->getView(); $objname = $this->_getParam('objname'); $refresh = $this->_getParam('refresh'); $dashboardcall = $this->_getParam('dashboardcall'); $data = array(); $searchQuery = ''; $searchArray = array(); $tablecontent=''; if($refresh == 'refresh') { if($dashboardcall == 'Yes') $perPage = DASHBOARD_PERPAGE; else $perPage = PERPAGE; $sort = 'DESC';$by = 'modifieddate';$pageNo = 1;$searchData = '';$searchQuery = '';$searchArray=''; } else { $sort = ($this->_getParam('sort') !='')? $this->_getParam('sort'):'DESC'; $by = ($this->_getParam('by')!='')? $this->_getParam('by'):'modifieddate'; if($dashboardcall == 'Yes') $perPage = $this->_getParam('per_page',DASHBOARD_PERPAGE); else $perPage = $this->_getParam('per_page',PERPAGE); $pageNo = $this->_getParam('page', 1); /** search from grid - START **/ $searchData = $this->_getParam('searchData'); $searchData = rtrim($searchData,','); /** search from grid - END **/ } $dataTmp = $prefixmodel->getGrid($sort, $by, $perPage, $pageNo, $searchData,$call,$dashboardcall); array_push($data,$dataTmp); $this->view->dataArray = $data; $this->view->call = $call ; $this->view->messages = $this->_helper->flashMessenger->getMessages(); } public function viewAction() { $id = $this->getRequest()->getParam('id'); $callval = $this->getRequest()->getParam('call'); if($callval == 'ajaxcall') $this->_helper->layout->disableLayout(); $objName = 'prefix'; $prefixform = new Default_Form_prefix(); $prefixform->removeElement("submit"); $elements = $prefixform->getElements(); if(count($elements)>0) { foreach($elements as $key=>$element) { if(($key!="Cancel")&&($key!="Edit")&&($key!="Delete")&&($key!="Attachments")){ $element->setAttrib("disabled", "disabled"); } } } $prefixmodel = new Default_Model_Prefix(); try { if($id) { if(is_numeric($id) && $id>0) { $data = $prefixmodel->getsinglePrefixData($id); if(!empty($data) && $data != "norows") { $prefixform->populate($data[0]); $this->view->form = $prefixform; $this->view->controllername = $objName; $this->view->data = $data; $this->view->id = $id; $this->view->ermsg = ''; } else { $this->view->ermsg = 'nodata'; } }else { $this->view->ermsg = 'nodata'; } }else { $this->view->ermsg = 'nodata'; } } catch(Exception $e) { $this->view->ermsg = 'nodata'; } } public function editAction() { $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()){ $loginUserId = $auth->getStorage()->read()->id; } $id = $this->getRequest()->getParam('id'); $callval = $this->getRequest()->getParam('call'); if($callval == 'ajaxcall') $this->_helper->layout->disableLayout(); $prefixform = new Default_Form_prefix(); $prefixmodel = new Default_Model_Prefix(); try { if($id) { if(is_numeric($id) && $id>0) { $data = $prefixmodel->getsinglePrefixData($id); if(!empty($data) && $data != "norows") { $prefixform->populate($data[0]); $prefixform->submit->setLabel('Update'); $this->view->data = $data; $this->view->id = $id; $this->view->ermsg = ''; } else { $this->view->ermsg = 'nodata'; } }else { $this->view->ermsg = 'nodata'; } }else { $this->view->ermsg = ''; } } catch(Exception $e) { $this->view->ermsg = 'nodata'; } $this->view->form = $prefixform; if($this->getRequest()->getPost()){ if($prefixform->isValid($this->_request->getPost())){ $prefix = $this->_request->getParam('prefix'); $description = $this->_request->getParam('description'); $date = new Zend_Date(); $actionflag = ''; $tableid = ''; $data = array('prefix'=>trim($prefix), 'description'=>trim($description), 'modifiedby'=>$loginUserId, 'modifieddate'=>gmdate("Y-m-d H:i:s") ); if($id!=''){ $where = array('id=?'=>$id); $actionflag = 2; } else { $data['createdby'] = $loginUserId; $data['createddate'] = gmdate("Y-m-d H:i:s"); $data['isactive'] = 1; $where = ''; $actionflag = 1; } $Id = $prefixmodel->SaveorUpdatePrefixData($data, $where); if($Id == 'update') { $tableid = $id; $this->_helper->getHelper("FlashMessenger")->addMessage(array("success"=>"Prefix updated successfully.")); } else { $tableid = $Id; $this->_helper->getHelper("FlashMessenger")->addMessage(array("success"=>"Prefix added successfully.")); } $menuID = PREFIX; $result = sapp_Global::logManager($menuID,$actionflag,$loginUserId,$tableid); $this->_redirect('prefix'); }else { $messages = $prefixform->getMessages(); foreach ($messages as $key => $val) { foreach($val as $key2 => $val2) { $msgarray[$key] = $val2; break; } } $this->view->msgarray = $msgarray; } } } public function saveupdateAction() { $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()){ $loginUserId = $auth->getStorage()->read()->id; } $id = $this->_request->getParam('id'); $gendercode = $this->_request->getParam('gendercode'); $gendername = $this->_request->getParam('gendername'); $description = $this->_request->getParam('description'); $genderform = new Default_Form_gender(); $gendermodel = new Default_Model_Gender(); $messages = $genderform->getMessages(); $actionflag = ''; $tableid = ''; if($this->getRequest()->getPost()){ if($genderform->isValid($this->_request->getPost())){ $data = array('gendercode'=>trim($gendercode), 'gendername'=>trim($gendername), 'description'=>trim($description), 'modifiedby'=>$loginUserId, 'modifieddate'=>Zend_Registry::get('currentdate') ); if($id!=''){ $where = array('id=?'=>$id); $messages['message']='Gender updated successfully.'; $actionflag = 2; } else { $data['createdby'] = $loginUserId; $data['createddate'] = Zend_Registry::get('currentdate'); $data['isactive'] = 1; $where = ''; $messages['message']='Gender added successfully.'; $actionflag = 1; } $Id = $gendermodel->SaveorUpdateGenderData($data, $where); if($Id == 'update') $tableid = $id; else $tableid = $Id; $menuID = GENDER; $result = sapp_Global::logManager($menuID,$actionflag,$loginUserId,$tableid); $messages['result']='saved'; $this->_helper->json($messages); }else { $messages = $genderform->getMessages(); $messages['result']='error'; $this->_helper->json($messages); } } } public function deleteAction() { $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()){ $loginUserId = $auth->getStorage()->read()->id; } $id = $this->_request->getParam('objid'); $deleteflag= $this->_request->getParam('deleteflag'); $messages['message'] = ''; $messages['msgtype'] = ''; $actionflag = 3; if($id) { $prefixmodel = new Default_Model_Prefix(); $prefixdata = $prefixmodel->getsinglePrefixData($id); $data = array('isactive'=>0,'modifieddate'=>gmdate("Y-m-d H:i:s")); $where = array('id=?'=>$id); $Id = $prefixmodel->SaveorUpdatePrefixData($data, $where); if($Id == 'update') { $menuID = PREFIX; $result = sapp_Global::logManager($menuID,$actionflag,$loginUserId,$id); $configmail = sapp_Global::send_configuration_mail('Prefix',$prefixdata[0]['prefix']); $messages['message'] = 'Prefix deleted successfully.'; $messages['msgtype'] = 'success'; } else { $messages['message'] = 'Prefix cannot be deleted.'; $messages['msgtype'] = 'error'; } } else { $messages['message'] = 'Prefix cannot be deleted.'; $messages['msgtype'] = 'error'; } if($deleteflag==1) { if( $messages['msgtype'] == 'error') { $this->_helper->getHelper("FlashMessenger")->addMessage(array("error"=>$messages['message'],"msgtype"=>$messages['msgtype'] ,'deleteflag'=>$deleteflag)); } if( $messages['msgtype'] == 'success') { $this->_helper->getHelper("FlashMessenger")->addMessage(array("success"=>$messages['message'],"msgtype"=>$messages['msgtype'],'deleteflag'=>$deleteflag)); } } $this->_helper->json($messages); } public function addpopupAction() { Zend_Layout::getMvcInstance()->setLayoutPath(APPLICATION_PATH."/layouts/scripts/popup/"); $auth = Zend_Auth::getInstance(); if($auth->hasIdentity()){ $loginUserId = $auth->getStorage()->read()->id; } $id = $this->getRequest()->getParam('id'); $msgarray = array(); $controllername = 'prefix'; $prefixform = new Default_Form_prefix(); $prefixmodel = new Default_Model_Prefix(); $prefixform->setAction(BASE_URL.'prefix/addpopup'); if($this->getRequest()->getPost()){ if($prefixform->isValid($this->_request->getPost())){ $id = $this->_request->getParam('id'); $prefix = $this->_request->getParam('prefix'); $description = $this->_request->getParam('description'); $date = new Zend_Date(); $actionflag = ''; $tableid = ''; $data = array('prefix'=>trim($prefix), 'description'=>trim($description), 'modifiedby'=>$loginUserId, 'modifieddate'=>gmdate("Y-m-d H:i:s") ); if($id!=''){ $where = array('id=?'=>$id); $actionflag = 2; } else { $data['createdby'] = $loginUserId; $data['createddate'] = gmdate("Y-m-d H:i:s"); $data['isactive'] = 1; $where = ''; $actionflag = 1; } $Id = $prefixmodel->SaveorUpdatePrefixData($data, $where); $tableid = $Id; $menuID = PREFIX; $result = sapp_Global::logManager($menuID,$actionflag,$loginUserId,$tableid); $prefixData = $prefixmodel->fetchAll('isactive = 1','prefix')->toArray(); $opt =''; foreach($prefixData as $record){ $opt .= sapp_Global::selectOptionBuilder($record['id'], $record['prefix']); } $this->view->prefixData = $opt; $this->view->eventact = 'added'; $close = 'close'; $this->view->popup=$close; }else { $messages = $prefixform->getMessages(); foreach ($messages as $key => $val) { foreach($val as $key2 => $val2) { $msgarray[$key] = $val2; break; } } $this->view->msgarray = $msgarray; } } $this->view->controllername = $controllername; $this->view->form = $prefixform; $this->view->ermsg = ''; } }
gpl-3.0
deependhulla/archive-plus-ediscovery
files/groupoffice/go/vendor/swift/lib/classes/Swift/Mime/ContentEncoder.php
1020
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Interface for all Transfer Encoding schemes. * * @package Swift * @subpackage Mime * @author Chris Corbyn */ interface Swift_Mime_ContentEncoder extends Swift_Encoder { /** * Encode $in to $out. * * @param Swift_OutputByteStream $os to read from * @param Swift_InputByteStream $is to write to * @param integer $firstLineOffset * @param integer $maxLineLength - 0 indicates the default length for this encoding */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0); /** * Get the MIME name of this content encoding scheme. * * @return StringHelper */ public function getName(); }
gpl-3.0
kgao/MediaDrop
PasteScript-1.7.5-py2.7.egg/paste/script/templates.py
10040
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import sys import os import inspect import copydir import command from paste.util.template import paste_script_template_renderer class Template(object): # Subclasses must define: # _template_dir (or template_dir()) # summary # Variables this template uses (mostly for documentation now) # a list of instances of var() vars = [] # Eggs that should be added as plugins: egg_plugins = [] # Templates that must be applied first: required_templates = [] # Use Cheetah for substituting templates: use_cheetah = False # If true, then read all the templates to find the variables: read_vars_from_templates = False # You can also give this function/method to use something other # than Cheetah or string.Template. The function should be of the # signature template_renderer(content, vars, filename=filename). # Careful you don't turn this into a method by putting a function # here (without staticmethod)! template_renderer = None def __init__(self, name): self.name = name self._read_vars = None def module_dir(self): """Returns the module directory of this template.""" mod = sys.modules[self.__class__.__module__] return os.path.dirname(mod.__file__) def template_dir(self): assert self._template_dir is not None, ( "Template %r didn't set _template_dir" % self) if isinstance( self._template_dir, tuple): return self._template_dir else: return os.path.join(self.module_dir(), self._template_dir) def run(self, command, output_dir, vars): self.pre(command, output_dir, vars) self.write_files(command, output_dir, vars) self.post(command, output_dir, vars) def check_vars(self, vars, cmd): expect_vars = self.read_vars(cmd) if not expect_vars: # Assume that variables aren't defined return vars converted_vars = {} unused_vars = vars.copy() errors = [] for var in expect_vars: if var.name not in unused_vars: if cmd.interactive: prompt = 'Enter %s' % var.full_description() response = cmd.challenge(prompt, var.default, var.should_echo) converted_vars[var.name] = response elif var.default is command.NoDefault: errors.append('Required variable missing: %s' % var.full_description()) else: converted_vars[var.name] = var.default else: converted_vars[var.name] = unused_vars.pop(var.name) if errors: raise command.BadCommand( 'Errors in variables:\n%s' % '\n'.join(errors)) converted_vars.update(unused_vars) vars.update(converted_vars) return converted_vars def read_vars(self, command=None): if self._read_vars is not None: return self._read_vars assert (not self.read_vars_from_templates or self.use_cheetah), ( "You can only read variables from templates if using Cheetah") if not self.read_vars_from_templates: self._read_vars = self.vars return self.vars vars = self.vars[:] var_names = [var.name for var in self.vars] read_vars = find_args_in_dir( self.template_dir(), verbose=command and command.verbose > 1).items() read_vars.sort() for var_name, var in read_vars: if var_name not in var_names: vars.append(var) self._read_vars = vars return vars def write_files(self, command, output_dir, vars): template_dir = self.template_dir() if not os.path.exists(output_dir): print "Creating directory %s" % output_dir if not command.simulate: # Don't let copydir create this top-level directory, # since copydir will svn add it sometimes: os.makedirs(output_dir) copydir.copy_dir(template_dir, output_dir, vars, verbosity=command.verbose, simulate=command.options.simulate, interactive=command.interactive, overwrite=command.options.overwrite, indent=1, use_cheetah=self.use_cheetah, template_renderer=self.template_renderer) def print_vars(self, indent=0): vars = self.read_vars() var.print_vars(vars) def pre(self, command, output_dir, vars): """ Called before template is applied. """ pass def post(self, command, output_dir, vars): """ Called after template is applied. """ pass NoDefault = command.NoDefault class var(object): def __init__(self, name, description, default='', should_echo=True): self.name = name self.description = description self.default = default self.should_echo = should_echo def __repr__(self): return '<%s %s default=%r should_echo=%s>' % ( self.__class__.__name__, self.name, self.default, self.should_echo) def full_description(self): if self.description: return '%s (%s)' % (self.name, self.description) else: return self.name def print_vars(cls, vars, indent=0): max_name = max([len(v.name) for v in vars]) for var in vars: if var.description: print '%s%s%s %s' % ( ' '*indent, var.name, ' '*(max_name-len(var.name)), var.description) else: print ' %s' % var.name if var.default is not command.NoDefault: print ' default: %r' % var.default if var.should_echo is True: print ' should_echo: %s' % var.should_echo print print_vars = classmethod(print_vars) class BasicPackage(Template): _template_dir = 'paster-templates/basic_package' summary = "A basic setuptools-enabled package" vars = [ var('version', 'Version (like 0.1)'), var('description', 'One-line description of the package'), var('long_description', 'Multi-line description (in reST)'), var('keywords', 'Space-separated keywords/tags'), var('author', 'Author name'), var('author_email', 'Author email'), var('url', 'URL of homepage'), var('license_name', 'License name'), var('zip_safe', 'True/False: if the package can be distributed as a .zip file', default=False), ] template_renderer = staticmethod(paste_script_template_renderer) _skip_variables = ['VFN', 'currentTime', 'self', 'VFFSL', 'dummyTrans', 'getmtime', 'trans'] def find_args_in_template(template): if isinstance(template, (str, unicode)): # Treat as filename: import Cheetah.Template template = Cheetah.Template.Template(file=template) if not hasattr(template, 'body'): # Don't know... return None method = template.body args, varargs, varkw, defaults = inspect.getargspec(method) defaults=list(defaults or []) vars = [] while args: if len(args) == len(defaults): default = defaults.pop(0) else: default = command.NoDefault arg = args.pop(0) if arg in _skip_variables: continue # @@: No way to get description yet vars.append( var(arg, description=None, default=default)) return vars def find_args_in_dir(dir, verbose=False): all_vars = {} for fn in os.listdir(dir): if fn.startswith('.') or fn == 'CVS' or fn == '_darcs': continue full = os.path.join(dir, fn) if os.path.isdir(full): inner_vars = find_args_in_dir(full) elif full.endswith('_tmpl'): inner_vars = {} found = find_args_in_template(full) if found is None: # Couldn't read variables if verbose: print 'Template %s has no parseable variables' % full continue for var in found: inner_vars[var.name] = var else: # Not a template, don't read it continue if verbose: print 'Found variable(s) %s in Template %s' % ( ', '.join(inner_vars.keys()), full) for var_name, var in inner_vars.items(): # Easy case: if var_name not in all_vars: all_vars[var_name] = var continue # Emit warnings if the variables don't match well: cur_var = all_vars[var_name] if not cur_var.description: cur_var.description = var.description elif (cur_var.description and var.description and var.description != cur_var.description): print >> sys.stderr, ( "Variable descriptions do not match: %s: %s and %s" % (var_name, cur_var.description, var.description)) if (cur_var.default is not command.NoDefault and var.default is not command.NoDefault and cur_var.default != var.default): print >> sys.stderr, ( "Variable defaults do not match: %s: %r and %r" % (var_name, cur_var.default, var.default)) return all_vars
gpl-3.0
Rinnegatamante/easyrpg-player-3ds
src/plane.cpp
1800
/* * This file is part of EasyRPG Player. * * EasyRPG Player 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. * * EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ // Headers #include "plane.h" #include "graphics.h" #include "player.h" #include "bitmap.h" Plane::Plane() : type(TypePlane), visible(true), z(0), ox(0), oy(0) { Graphics::RegisterDrawable(this); } Plane::~Plane() { Graphics::RemoveDrawable(this); } void Plane::Draw() { if (!visible || !bitmap) return; BitmapRef dst = DisplayUi->GetDisplaySurface(); Rect dst_rect(0, 0, DisplayUi->GetWidth(), DisplayUi->GetHeight()); dst->TiledBlit(-ox, -oy, bitmap->GetRect(), *bitmap, dst_rect, 255); } BitmapRef const& Plane::GetBitmap() const { return bitmap; } void Plane::SetBitmap(BitmapRef const& nbitmap) { bitmap = nbitmap; } bool Plane::GetVisible() const { return visible; } void Plane::SetVisible(bool nvisible) { visible = nvisible; } int Plane::GetZ() const { return z; } void Plane::SetZ(int nz) { if (z != nz) Graphics::UpdateZCallback(); z = nz; } int Plane::GetOx() const { return ox; } void Plane::SetOx(int nox) { ox = nox; } int Plane::GetOy() const { return oy; } void Plane::SetOy(int noy) { oy = noy; } DrawableType Plane::GetType() const { return type; }
gpl-3.0
Waikato/moa
moa/src/main/java/moa/tasks/TaskCompletionListener.java
1385
/* * TaskCompletionListener.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * 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/>. * */ package moa.tasks; /** * Interface representing a listener for the task in TaskThread to be completed. * TaskThread fires that the task is completed * to all its listeners when it finishes to run its task. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public interface TaskCompletionListener { /** * The method to perform when the task finishes. * * @param task the TaskThead that this listener is listening */ public void taskCompleted(TaskThread task); }
gpl-3.0
mcseemka/frostwire-desktop
lib/jars-src/jaudiotagger/srctest/org/jaudiotagger/tag/id3/NewInterfaceTest.java
60368
package org.jaudiotagger.tag.id3; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.TagOptionSingleton; import org.jaudiotagger.tag.TagTextField; import org.jaudiotagger.tag.datatype.DataTypes; import org.jaudiotagger.tag.id3.framebody.*; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Testing retrofitting of entagged interfaces */ public class NewInterfaceTest extends TestCase { private static final String V1_ARTIST = "V1ARTIST"; public static final String ALBUM_TEST_STRING = "mellow gold"; public static final String ALBUM_TEST_STRING2 = "odelay"; /** * */ protected void setUp() { TagOptionSingleton.getInstance().setToDefault(); } /** * */ protected void tearDown() { } /** * Constructor * * @param arg0 */ public NewInterfaceTest(String arg0) { super(arg0); } /** * Command line entrance. * * @param args */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Builds the Test Suite. * * @return the Test Suite. */ public static Test suite() { return new TestSuite(NewInterfaceTest.class); } public void testBasicWrite() { Exception ex = null; try { File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testBasicWrite.mp3")); org.jaudiotagger.audio.AudioFile audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); org.jaudiotagger.tag.Tag newTag = audioFile.getTag(); if (audioFile.getTag() == null) { audioFile.setTag(new ID3v23Tag()); newTag = audioFile.getTag(); } newTag.setField(FieldKey.ALBUM,"album"); newTag.setField(FieldKey.ARTIST,"artist"); newTag.setField(FieldKey.COMMENT,"comment"); newTag.setField(FieldKey.GENRE,"Rock"); newTag.setField(FieldKey.TITLE,"title"); newTag.setField(FieldKey.YEAR,"year"); newTag.setField(FieldKey.TRACK,Integer.toString(1)); assertEquals("album", newTag.getFirst(FieldKey.ALBUM)); assertEquals("artist", newTag.getFirst(FieldKey.ARTIST)); assertEquals("comment", newTag.getFirst(FieldKey.COMMENT)); assertEquals("Rock", newTag.getFirst(FieldKey.GENRE)); assertEquals("title", newTag.getFirst(FieldKey.TITLE)); assertEquals("year", newTag.getFirst(FieldKey.YEAR)); assertEquals("1", newTag.getFirst(FieldKey.TRACK)); audioFile.commit(); audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); newTag = audioFile.getTag(); assertEquals("album", newTag.getFirst(FieldKey.ALBUM)); assertEquals("artist", newTag.getFirst(FieldKey.ARTIST)); assertEquals("comment", newTag.getFirst(FieldKey.COMMENT)); assertEquals("Rock", newTag.getFirst(FieldKey.GENRE)); assertEquals("title", newTag.getFirst(FieldKey.TITLE)); assertEquals("year", newTag.getFirst(FieldKey.YEAR)); assertEquals("1", newTag.getFirst(FieldKey.TRACK)); AbstractTagFrameBody body = (((ID3v23Frame) newTag.getFirstField(ID3v23FieldKey.ALBUM.getFrameId())).getBody()); assertEquals(TextEncoding.ISO_8859_1, body.getTextEncoding()); TagOptionSingleton.getInstance().setId3v23DefaultTextEncoding(TextEncoding.UTF_16); TagOptionSingleton.getInstance().setResetTextEncodingForExistingFrames(true); audioFile.commit(); audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); newTag = audioFile.getTag(); assertEquals("album", newTag.getFirst(FieldKey.ALBUM)); assertEquals("artist", newTag.getFirst(FieldKey.ARTIST)); assertEquals("comment", newTag.getFirst(FieldKey.COMMENT)); assertEquals("Rock", newTag.getFirst(FieldKey.GENRE)); assertEquals("title", newTag.getFirst(FieldKey.TITLE)); assertEquals("year", newTag.getFirst(FieldKey.YEAR)); assertEquals("1", newTag.getFirst(FieldKey.TRACK)); body = (((ID3v23Frame) newTag.getFirstField(ID3v23FieldKey.ALBUM.getFrameId())).getBody()); assertEquals(TextEncoding.UTF_16, body.getTextEncoding()); TagOptionSingleton.getInstance().setId3v23DefaultTextEncoding(TextEncoding.ISO_8859_1); TagOptionSingleton.getInstance().setResetTextEncodingForExistingFrames(true); audioFile.commit(); audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); newTag = audioFile.getTag(); body = (((ID3v23Frame) newTag.getFirstField(ID3v23FieldKey.ALBUM.getFrameId())).getBody()); assertEquals(TextEncoding.ISO_8859_1, body.getTextEncoding()); TagOptionSingleton.getInstance().setResetTextEncodingForExistingFrames(false); } catch (Exception e) { ex = e; ex.printStackTrace(); } assertNull(ex); } public void testNewInterfaceBasicReadandWriteID3v1() throws Exception { Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testnewIntId3v1.mp3")); MP3File mp3File = new MP3File(testFile); //Has no tag at this point assertFalse(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Create v1 tag (old method) ID3v11Tag v1tag = new ID3v11Tag(); v1tag.setField(FieldKey.ARTIST,V1_ARTIST); v1tag.setField(FieldKey.ALBUM,"V1ALBUM" + "\u01ff"); //Note always convert to single byte so will be written as FF v1tag.setField(v1tag.createField(FieldKey.TITLE, "title")); v1tag.setField(FieldKey.GENRE,"Rock"); v1tag.setField(v1tag.createField(FieldKey.TRACK, "12")); mp3File.setID3v1Tag(v1tag); mp3File.save(); //Has only v1 tag assertTrue(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Read fields AudioFile af = AudioFileIO.read(testFile); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals("V1ALBUM" + "\u00ff", af.getTag().getFirst(FieldKey.ALBUM)); //Lost the 00, is that what we want assertEquals("title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Rock", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("12", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("12", af.getTag().getFirst(FieldKey.TRACK)); //Delete some fields (just sets string to empty String) af.getTag().deleteField(FieldKey.TITLE); assertEquals("", af.getTag().getFirst(FieldKey.TITLE)); //Modify a value af.getTag().setField(FieldKey.TITLE,"newtitle"); assertEquals("newtitle", af.getTag().getFirst(FieldKey.TITLE)); //Adding just replaces current value af.getTag().addField(FieldKey.TITLE,"newtitle2"); assertEquals("newtitle2", af.getTag().getFirst(FieldKey.TITLE)); } public void testNewInterfaceBasicReadandWriteID3v24() throws Exception { Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testnewIntId3v24.mp3")); MP3File mp3File = new MP3File(testFile); //Has no tag at this point assertFalse(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Create v1 tag (old method) ID3v11Tag v1tag = new ID3v11Tag(); v1tag.setField(FieldKey.ARTIST,V1_ARTIST); v1tag.setField(FieldKey.ALBUM,"V1ALBUM"); mp3File.setID3v1Tag(v1tag); mp3File.save(); //Has only v1 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1) AudioFile af = AudioFileIO.read(testFile); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); //Add artist frame (old method) ID3v24Tag tag = new ID3v24Tag(); ID3v24Frame frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_ARTIST); ((FrameBodyTPE1) frame.getBody()).setText(FrameBodyTPE1Test.TPE1_TEST_STRING); tag.setFrame(frame); mp3File.setID3v2TagOnly(tag); mp3File.save(); //Has v1 and v2 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertTrue(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1 value overridden by v2 method) af = AudioFileIO.read(testFile); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING,((TagTextField)af.getTag().getFirstField(FieldKey.ARTIST)).getContent()); //.... but v1 value is still there assertEquals(V1_ARTIST, ((MP3File) af).getID3v1Tag().getFirst(FieldKey.ARTIST)); //Write album ( new method) af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING); af.commit(); //Read back album (new method) af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING,((TagTextField)af.getTag().getFirstField(FieldKey.ALBUM)).getContent()); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //Read back album (old method) AbstractID3v2Frame checkframe = (AbstractID3v2Frame) ((MP3File) af).getID3v2Tag().getFrame(ID3v24Frames.FRAME_ID_ALBUM); assertEquals(ALBUM_TEST_STRING, ((FrameBodyTALB) checkframe.getBody()).getText()); //If addField again, the value gets appended using the null char sperator system af.getTag().addField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2,af.getTag().getValue(FieldKey.ALBUM,1)); assertEquals(ALBUM_TEST_STRING, ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.ALBUM)); assertEquals("mellow gold\0odelay",((TagTextField)af.getTag().getFirstField(FieldKey.ALBUM)).getContent()); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //And can replace existing value af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //and deleteField it af.getTag().deleteField(FieldKey.ALBUM); af.commit(); af = AudioFileIO.read(testFile); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.ALBUM)); assertEquals(0, af.getTag().getFields(FieldKey.ALBUM).size()); //Test out the other basic fields //Year af.getTag().setField(FieldKey.YEAR,"1991"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.YEAR)); assertEquals("1991",((TagTextField)af.getTag().getFirstField(FieldKey.YEAR)).getContent()); assertEquals(1, af.getTag().getFields(FieldKey.YEAR).size()); assertEquals(2, af.getTag().getFieldCount()); //Title af.getTag().setField(FieldKey.TITLE,"Title"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.TITLE)); assertEquals("Title",((TagTextField)af.getTag().getFirstField(FieldKey.TITLE)).getContent()); assertEquals(1, af.getTag().getFields(FieldKey.TITLE).size()); assertEquals(3, af.getTag().getFieldCount()); //Comment, trickier because uses different framebody subclass to the ones above af.getTag().setField(FieldKey.COMMENT,"Comment"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Comment", af.getTag().getFirst(FieldKey.COMMENT)); assertEquals("Comment", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.COMMENT)); //By default comments are created with empty description because this is what expected //by plyers such as iTunes. ID3v24Frame commentFrame = (ID3v24Frame) ((ID3v24Tag) af.getTag()).getFrame("COMM"); FrameBodyCOMM fb = (FrameBodyCOMM) commentFrame.getBody(); assertEquals("", fb.getDescription()); assertEquals("Comment", fb.getText()); //Change description, cant do this with common interface fb.setDescription("test"); //Because has different description the following setField will addField another comment rather than overwriting the first one af.getTag().setField(FieldKey.COMMENT,"Comment2"); assertEquals(2, af.getTag().getFields(FieldKey.COMMENT).size()); //Add third Comment List<TagField> comments = af.getTag().getFields(FieldKey.COMMENT); ((FrameBodyCOMM) ((ID3v24Frame) comments.get(1)).getBody()).setDescription("test2"); af.getTag().setField(FieldKey.COMMENT,"Comment3"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, af.getTag().getFields(FieldKey.COMMENT).size()); //Add fourth Comment (but duplicate key - so overwrites 3rd comment) af.getTag().setField(FieldKey.COMMENT,"Comment4"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, af.getTag().getFields(FieldKey.COMMENT).size()); //Remove all Comment tags af.getTag().deleteField(FieldKey.COMMENT); assertEquals(0, af.getTag().getFields(FieldKey.COMMENT).size()); //Add first one back in af.getTag().setField(FieldKey.COMMENT,"Comment"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(1, af.getTag().getFields(FieldKey.COMMENT).size()); assertEquals(4, af.getTag().getFieldCount()); //Genre //TODO only one genre frame allowed, but that can contain multiple GENRE values, currently //must parse as one genre e.g 34 67 af.getTag().setField(FieldKey.GENRE,"CustomGenre"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("CustomGenre", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("CustomGenre", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("CustomGenre", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.GENRE)); assertEquals(1, af.getTag().getFields(FieldKey.GENRE).size()); assertEquals(5, af.getTag().getFieldCount()); //Track af.getTag().setField(FieldKey.TRACK,"7"); af.getTag().setField(af.getTag().createField(FieldKey.TRACK_TOTAL, "11")); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); af.commit(); af = AudioFileIO.read(testFile); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.TRACK)); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); assertEquals(1, af.getTag().getFields(FieldKey.TRACK).size()); assertEquals(6, af.getTag().getFieldCount()); //AmazonId //This is one of many fields that uses the TXXX frame, the logic is more complicated af.getTag().setField(af.getTag().createField(FieldKey.AMAZON_ID, "asin123456" + "\u01ff")); af.commit(); af = AudioFileIO.read(testFile); //Mood af.getTag().setField(af.getTag().createField(FieldKey.MOOD, "mood")); af.commit(); af = AudioFileIO.read(testFile); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals("asin123456" + "\u01ff", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(8, af.getTag().getFieldCount()); //Now addField another different field that also uses a TXXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICIP_ID, "musicip_id")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v24Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("musicip_id", ((ID3v24Tag) af.getTag()).getFirst(ID3v24FieldKey.MUSICIP_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals(9, af.getTag().getFieldCount()); //Now addField yet another different field that also uses a TXXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_RELEASEID, "releaseid")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, ((List) ((ID3v24Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("releaseid", af.getTag().getFirst(FieldKey.MUSICBRAINZ_RELEASEID)); assertEquals("releaseid",((TagTextField)af.getTag().getFirstField(FieldKey.MUSICBRAINZ_RELEASEID)).getContent()); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICBRAINZ_RELEASEID).size()); assertEquals(10, af.getTag().getFieldCount()); //Now deleteField field af.getTag().deleteField(FieldKey.MUSICBRAINZ_RELEASEID); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v24Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(9, af.getTag().getFieldCount()); //Cover Art:invalid way to do it try { af.getTag().setField(af.getTag().createField(FieldKey.COVER_ART, "coverart")); } catch (java.lang.UnsupportedOperationException uoe) { e = uoe; } assertTrue(e instanceof UnsupportedOperationException); //Add new image correctly RandomAccessFile imageFile = new RandomAccessFile(new File("testdata", "coverart.png"), "r"); byte[] imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(1, ((ID3v24Tag) af.getTag()).getFields(FieldKey.COVER_ART).size()); assertEquals(1, ((ID3v24Tag) af.getTag()).getFields(ID3v24FieldKey.COVER_ART.getFieldName()).size()); //TODO This isnt very user friendly TagField tagField = af.getTag().getFirstField(ID3v24FieldKey.COVER_ART.getFieldName()); assertEquals("image/png::18545",((TagTextField)af.getTag().getFirstField(FieldKey.COVER_ART)).getContent()); assertTrue(tagField instanceof ID3v24Frame); ID3v24Frame apicFrame = (ID3v24Frame) tagField; assertTrue(apicFrame.getBody() instanceof FrameBodyAPIC); FrameBodyAPIC apicframebody = (FrameBodyAPIC) apicFrame.getBody(); assertFalse(apicframebody.isImageUrl()); assertEquals(10, af.getTag().getFieldCount()); //Add another image correctly imageFile = new RandomAccessFile(new File("testdata", "coverart_small.png"), "r"); imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(11, af.getTag().getFieldCount()); //Actually createField the image from the read data BufferedImage bi = null; TagField imageField = af.getTag().getFields(FieldKey.COVER_ART).get(0); if (imageField instanceof AbstractID3v2Frame) { FrameBodyAPIC imageFrameBody = (FrameBodyAPIC) ((AbstractID3v2Frame) imageField).getBody(); if (!imageFrameBody.isImageUrl()) { byte[] imageRawData = (byte[]) imageFrameBody.getObjectValue(DataTypes.OBJ_PICTURE_DATA); bi = ImageIO.read(new ByteArrayInputStream(imageRawData)); } } assertNotNull(bi); //Add a linked Image af.getTag().addField(tag.createLinkedArtworkField("../testdata/coverart.jpg")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(12, af.getTag().getFieldCount()); List<TagField> imageFields = af.getTag().getFields(FieldKey.COVER_ART); tagField = imageFields.get(2); apicFrame = (ID3v24Frame) tagField; assertTrue(apicFrame.getBody() instanceof FrameBodyAPIC); apicframebody = (FrameBodyAPIC) apicFrame.getBody(); assertTrue(apicframebody.isImageUrl()); assertEquals("../testdata/coverart.jpg", apicframebody.getImageUrl()); } /* public void testReadUrlImage() throws Exception { Exception ex = null; try { File testFile = AbstractTestCase.copyAudioToTmp("testV1withurlimage.mp3"); org.jaudiotagger.audio.AudioFile audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); ID3v23Tag newTag = (ID3v23Tag)audioFile.getTag(); assertEquals(1, newTag.getFields(FieldKey.COVER_ART).size()); TagField tagField = newTag.getFirstField(ID3v23FieldKey.COVER_ART.getFieldName()); assertTrue(tagField instanceof ID3v23Frame); ID3v23Frame apicFrame = (ID3v23Frame)tagField; assertTrue(apicFrame.getBody() instanceof FrameBodyAPIC); FrameBodyAPIC apicframebody = (FrameBodyAPIC)apicFrame.getBody(); assertFalse(apicframebody.isImageUrl()); } catch(Exception e) { ex=e; ex.printStackTrace(); } assertNull(ex); } */ public void testNewInterfaceBasicReadandWriteID3v23() throws Exception { Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testnewIntId3v23.mp3")); MP3File mp3File = new MP3File(testFile); //Has no tag at this point assertFalse(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Create v1 tag (old method) ID3v11Tag v1tag = new ID3v11Tag(); v1tag.setField(FieldKey.ARTIST,V1_ARTIST); v1tag.setField(FieldKey.ALBUM,"V1ALBUM"); mp3File.setID3v1Tag(v1tag); mp3File.save(); //Has only v1 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1) AudioFile af = AudioFileIO.read(testFile); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); //Add artist frame (old method) ID3v23Tag tag = new ID3v23Tag(); ID3v23Frame frame = new ID3v23Frame(ID3v23Frames.FRAME_ID_V3_ARTIST); ((FrameBodyTPE1) frame.getBody()).setText(FrameBodyTPE1Test.TPE1_TEST_STRING); tag.setFrame(frame); mp3File.setID3v2TagOnly(tag); mp3File.save(); //Has v1 and v2 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertTrue(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1 value overrriden by v2 method) af = AudioFileIO.read(testFile); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.ARTIST)); //.... but v1 value is still there assertEquals(V1_ARTIST, ((MP3File) af).getID3v1Tag().getFirst(FieldKey.ARTIST)); //Write album ( new method) af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING); af.commit(); //Read back album (new method) af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //Read back album (old method) AbstractID3v2Frame checkframe = (AbstractID3v2Frame) ((MP3File) af).getID3v2Tag().getFrame(ID3v23Frames.FRAME_ID_V3_ALBUM); assertEquals(ALBUM_TEST_STRING, ((FrameBodyTALB) checkframe.getBody()).getText()); //If add smae field again appended to existiong frame af.getTag().addField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //But can replace existing value af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //and deleteField it af.getTag().deleteField(FieldKey.ALBUM); af.commit(); af = AudioFileIO.read(testFile); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.ALBUM)); assertEquals(0, af.getTag().getFields(FieldKey.ALBUM).size()); //Test out the other basic fields //Year af.getTag().setField(FieldKey.YEAR,"1991"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.YEAR)); assertEquals(1, af.getTag().getFields(FieldKey.YEAR).size()); assertEquals(2, af.getTag().getFieldCount()); //Title af.getTag().setField(FieldKey.TITLE,"Title"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.TITLE)); assertEquals(1, af.getTag().getFields(FieldKey.TITLE).size()); assertEquals(3, af.getTag().getFieldCount()); //Comment, trickier because uses different framebody subclass to the ones above af.getTag().setField(FieldKey.COMMENT,"Comment"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Comment", af.getTag().getFirst(FieldKey.COMMENT)); assertEquals("Comment", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.COMMENT)); assertEquals(1, af.getTag().getFields(FieldKey.COMMENT).size()); assertEquals(4, af.getTag().getFieldCount()); //Genre //TODO only one genre frame allowed, but that can contain multiple GENRE values, currently //must parse as one genre e.g 34 67 af.getTag().setField(FieldKey.GENRE,"CustomGenre"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("CustomGenre", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("CustomGenre", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.GENRE)); assertEquals(1, af.getTag().getFields(FieldKey.GENRE).size()); assertEquals(5, af.getTag().getFieldCount()); //Track af.getTag().setField(FieldKey.TRACK,"7"); af.getTag().setField(af.getTag().createField(FieldKey.TRACK_TOTAL, "11")); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); af.commit(); af = AudioFileIO.read(testFile); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.TRACK)); assertEquals(1, af.getTag().getFields(FieldKey.TRACK).size()); assertEquals(6, af.getTag().getFieldCount()); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); //AmazonId also testing utf encoding here //This is one of many fields that uses the TXXX frame, the logic is more complicated af.getTag().setField(af.getTag().createField(FieldKey.AMAZON_ID, "asin123456" + "\u01ff")); af.commit(); af = AudioFileIO.read(testFile); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals("asin123456" + "\u01ff", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(7, af.getTag().getFieldCount()); //Mood af.getTag().setField(af.getTag().createField(FieldKey.MOOD, "mood")); af.commit(); af = AudioFileIO.read(testFile); assertEquals("mood", af.getTag().getFirst(FieldKey.MOOD)); //Now deleteField field af.getTag().deleteField(FieldKey.MOOD); af.commit(); af = AudioFileIO.read(testFile); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); //Track Total af.getTag().setField(af.getTag().createField(FieldKey.TRACK_TOTAL, "11")); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); //Now addField another different field that also uses a TXXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICIP_ID, "musicip_id")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v23Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("musicip_id", ((ID3v23Tag) af.getTag()).getFirst(ID3v23FieldKey.MUSICIP_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); assertEquals(8, af.getTag().getFieldCount()); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); assertEquals("7",((ID3v23Tag)af.getTag()).getFirst(ID3v23FieldKey.TRACK)); assertEquals("11",((ID3v23Tag)af.getTag()).getFirst(ID3v23FieldKey.TRACK_TOTAL)); //Now addField yet another different field that also uses a TXXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_RELEASEID, "releaseid")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, ((List) ((ID3v23Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("releaseid", af.getTag().getFirst(FieldKey.MUSICBRAINZ_RELEASEID)); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICBRAINZ_RELEASEID).size()); assertEquals(9, af.getTag().getFieldCount()); //Now deleteField field af.getTag().deleteField(FieldKey.MUSICBRAINZ_RELEASEID); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v23Tag) af.getTag()).getFrame("TXXX")).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(8, af.getTag().getFieldCount()); //Cover Art:invalid way to do it try { af.getTag().setField(af.getTag().createField(FieldKey.COVER_ART, "coverart")); } catch (java.lang.UnsupportedOperationException uoe) { e = uoe; } assertTrue(e instanceof UnsupportedOperationException); //Add new image correctly RandomAccessFile imageFile = new RandomAccessFile(new File("testdata", "coverart.png"), "r"); byte[] imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(1, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(9, af.getTag().getFieldCount()); //Add another image correctly imageFile = new RandomAccessFile(new File("testdata", "coverart_small.png"), "r"); imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(10, af.getTag().getFieldCount()); } public void testNewInterfaceBasicReadandWriteID3v22() throws Exception { Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testnewIntId3v22.mp3")); MP3File mp3File = new MP3File(testFile); //Has no tag at this point assertFalse(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Create v1 tag (old method) ID3v11Tag v1tag = new ID3v11Tag(); v1tag.setField(FieldKey.ARTIST,V1_ARTIST); v1tag.setField(FieldKey.ALBUM,"V1ALBUM"); mp3File.setID3v1Tag(v1tag); mp3File.save(); //Has only v1 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertFalse(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1) AudioFile af = AudioFileIO.read(testFile); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(V1_ARTIST, af.getTag().getFirst(FieldKey.ARTIST)); //Add artist frame (old method) ID3v22Tag tag = new ID3v22Tag(); ID3v22Frame frame = new ID3v22Frame(ID3v22Frames.FRAME_ID_V2_ARTIST); ((FrameBodyTPE1) frame.getBody()).setText(FrameBodyTPE1Test.TPE1_TEST_STRING); tag.setFrame(frame); mp3File.setID3v2TagOnly(tag); mp3File.save(); //Has v1 and v2 tag at this point assertTrue(mp3File.hasID3v1Tag()); assertTrue(mp3File.hasID3v2Tag()); //Read back artist (new method ,v1 value overrriden by v2 method) af = AudioFileIO.read(testFile); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, af.getTag().getFirst(FieldKey.ARTIST)); assertEquals(FrameBodyTPE1Test.TPE1_TEST_STRING, ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.ARTIST)); //.... but v1 value is still there assertEquals(V1_ARTIST, ((MP3File) af).getID3v1Tag().getFirst(FieldKey.ARTIST)); //Write album ( new method) af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); af.commit(); //Read back album (new method) af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //Read back album (old method) AbstractID3v2Frame checkframe = (AbstractID3v2Frame) ((MP3File) af).getID3v2Tag().getFrame(ID3v22Frames.FRAME_ID_V2_ALBUM); assertEquals(ALBUM_TEST_STRING, ((FrameBodyTALB) checkframe.getBody()).getText()); //If add extra text field its appended to existing frame af.getTag().addField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING, af.getTag().getValue(FieldKey.ALBUM,0)); assertEquals(ALBUM_TEST_STRING2, af.getTag().getValue(FieldKey.ALBUM,1)); assertEquals(ALBUM_TEST_STRING, ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.ALBUM)); assertEquals(1, af.getTag().getFields(FieldKey.ALBUM).size()); //But can replace existing value af.getTag().setField(FieldKey.ALBUM,ALBUM_TEST_STRING2); af.commit(); af = AudioFileIO.read(testFile); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, af.getTag().getFirst(FieldKey.ALBUM)); assertEquals(ALBUM_TEST_STRING2, ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.ALBUM)); assertEquals(1,af.getTag().getFields(FieldKey.ALBUM).size()); //and deleteField it af.getTag().deleteField(FieldKey.ALBUM); af.commit(); af = AudioFileIO.read(testFile); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", af.getTag().getFirst(FieldKey.ALBUM)); assertEquals("", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.ALBUM)); assertEquals(0, af.getTag().getFields(FieldKey.ALBUM).size()); //Test out the other basic fields //Year af.getTag().setField(FieldKey.YEAR,"1991"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", af.getTag().getFirst(FieldKey.YEAR)); assertEquals("1991", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.YEAR)); assertEquals(1, af.getTag().getFields(FieldKey.YEAR).size()); assertEquals(2, af.getTag().getFieldCount()); //Title af.getTag().setField(FieldKey.TITLE,"Title"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", af.getTag().getFirst(FieldKey.TITLE)); assertEquals("Title", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.TITLE)); assertEquals(1, af.getTag().getFields(FieldKey.TITLE).size()); assertEquals(3, af.getTag().getFieldCount()); //Comment, trickier because uses different framebody subclass to the ones above af.getTag().setField(FieldKey.COMMENT,"Comment"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("Comment", af.getTag().getFirst(FieldKey.COMMENT)); assertEquals("Comment", af.getTag().getFirst(FieldKey.COMMENT)); assertEquals("Comment", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.COMMENT)); assertEquals(1, af.getTag().getFields(FieldKey.COMMENT).size()); assertEquals(4, af.getTag().getFieldCount()); //Genre //TODO only one genre frame allowed, but that can contain multiple GENRE values, currently //must parse as one genre e.g 34 67 af.getTag().setField(FieldKey.GENRE,"CustomGenre"); af.commit(); af = AudioFileIO.read(testFile); assertEquals("CustomGenre", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("CustomGenre", af.getTag().getFirst(FieldKey.GENRE)); assertEquals("CustomGenre", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.GENRE)); assertEquals(1, af.getTag().getFields(FieldKey.GENRE).size()); assertEquals(5, af.getTag().getFieldCount()); //Track af.getTag().setField(FieldKey.TRACK,"7"); af.getTag().setField(af.getTag().createField(FieldKey.TRACK_TOTAL, "11")); assertEquals("7",af.getTag().getFirst(FieldKey.TRACK)); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); af.commit(); af = AudioFileIO.read(testFile); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", af.getTag().getFirst(FieldKey.TRACK)); assertEquals("7", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.TRACK)); assertEquals("11",af.getTag().getFirst(FieldKey.TRACK_TOTAL)); assertEquals(1, af.getTag().getFields(FieldKey.TRACK).size()); assertEquals(1, af.getTag().getFields(FieldKey.TRACK).size()); assertEquals(6, af.getTag().getFieldCount()); //AmazonId //This is one of many fields that uses the TXXX frame, the logic is more complicated af.getTag().setField(af.getTag().createField(FieldKey.AMAZON_ID, "asin123456" + "\u01ff")); af.commit(); af = AudioFileIO.read(testFile); //Mood af.getTag().setField(af.getTag().createField(FieldKey.MOOD, "mood")); af.commit(); af = AudioFileIO.read(testFile); assertEquals("mood", af.getTag().getFirst(FieldKey.MOOD)); //Now deleteField field af.getTag().deleteField(FieldKey.MOOD); af.commit(); af = AudioFileIO.read(testFile); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals("asin123456" + "\u01ff", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(7, af.getTag().getFieldCount()); //Now addField another different field that also uses a TXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICIP_ID, "musicip_id")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v22Tag) af.getTag()).getFrame("TXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("musicip_id", ((ID3v22Tag) af.getTag()).getFirst(ID3v22FieldKey.MUSICIP_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals(8, af.getTag().getFieldCount()); //Now addField yet another different field that also uses a TXX frame af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_RELEASEID, "releaseid")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, ((List) ((ID3v22Tag) af.getTag()).getFrame("TXX")).size()); assertEquals("musicip_id", af.getTag().getFirst(FieldKey.MUSICIP_ID)); assertEquals("releaseid", af.getTag().getFirst(FieldKey.MUSICBRAINZ_RELEASEID)); assertEquals("asin123456" + "\u01ff", af.getTag().getFirst(FieldKey.AMAZON_ID)); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICBRAINZ_RELEASEID).size()); assertEquals(9, af.getTag().getFieldCount()); //Now deleteField field af.getTag().deleteField(FieldKey.MUSICBRAINZ_RELEASEID); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, ((List) ((ID3v22Tag) af.getTag()).getFrame("TXX")).size()); assertEquals(1, af.getTag().getFields(FieldKey.MUSICIP_ID).size()); assertEquals(1, af.getTag().getFields(FieldKey.AMAZON_ID).size()); assertEquals(8, af.getTag().getFieldCount()); //Cover Art:invalid way to do it try { af.getTag().setField(af.getTag().createField(FieldKey.COVER_ART, "coverart")); } catch (java.lang.UnsupportedOperationException uoe) { e = uoe; } assertTrue(e instanceof UnsupportedOperationException); //Add new image correctly RandomAccessFile imageFile = new RandomAccessFile(new File("testdata", "coverart.png"), "r"); byte[] imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(1, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(9, af.getTag().getFieldCount()); //Add another image correctly imageFile = new RandomAccessFile(new File("testdata", "coverart_small.png"), "r"); imagedata = new byte[(int) imageFile.length()]; imageFile.read(imagedata); af.getTag().addField(tag.createArtworkField(imagedata, "image/png")); af.commit(); af = AudioFileIO.read(testFile); assertEquals(2, af.getTag().getFields(FieldKey.COVER_ART).size()); assertEquals(10, af.getTag().getFieldCount()); } /** * Test how adding multiple frameswith new interface of same type is is handled * * @throws Exception */ public void testSettingMultipleFramesofSameType() throws Exception { Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testSetMultiple.mp3")); AudioFile af = AudioFileIO.read(testFile); MP3File mp3File = (MP3File) af; ID3v24Tag tag = new ID3v24Tag(); ID3v24Frame frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_COMMENT); ((FrameBodyCOMM) frame.getBody()).setText("Comment"); tag.setFrame(frame); mp3File.setID3v2TagOnly(tag); mp3File.save(); af = AudioFileIO.read(testFile); mp3File = (MP3File) af; //COMM { ID3v24Frame commentFrame = (ID3v24Frame) ((ID3v24Tag) af.getTag()).getFrame("COMM"); FrameBodyCOMM fb = (FrameBodyCOMM) commentFrame.getBody(); assertEquals("", fb.getDescription()); assertEquals("Comment", fb.getText()); //Change description, cant do this with common interface fb.setDescription("test"); //Because has different description the following setField will addField another comment rather than overwriting the first one af.getTag().setField(FieldKey.COMMENT,"Comment2"); assertEquals(2, af.getTag().getFields(FieldKey.COMMENT).size()); //Add third Comment List<TagField> comments = af.getTag().getFields(FieldKey.COMMENT); ((FrameBodyCOMM) ((ID3v24Frame) comments.get(1)).getBody()).setDescription("test2"); af.getTag().setField(FieldKey.COMMENT,"Comment3"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, af.getTag().getFields(FieldKey.COMMENT).size()); //Add fourth Comment (but duplicate key - so overwrites 3rd comment) af.getTag().setField(FieldKey.COMMENT,"Comment4"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(3, af.getTag().getFields(FieldKey.COMMENT).size()); //Add comment using generic call af.getTag().setField(af.getTag().createField(FieldKey.COMMENT, "abcdef-ghijklmn")); //Remove all Comment tags af.getTag().deleteField(FieldKey.COMMENT); assertEquals(0, af.getTag().getFields(FieldKey.COMMENT).size()); //Add first one back in af.getTag().setField(FieldKey.COMMENT,"Comment"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(1, af.getTag().getFields(FieldKey.COMMENT).size()); assertEquals(1, af.getTag().getFieldCount()); } //TXXX { tag = (ID3v24Tag) af.getTag(); frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_USER_DEFINED_INFO); ((FrameBodyTXXX) frame.getBody()).setText("UserDefined"); tag.setFrame(frame); ID3v24Frame txxxFrame = (ID3v24Frame) tag.getFrame("TXXX"); FrameBodyTXXX fb = (FrameBodyTXXX) txxxFrame.getBody(); assertEquals("", fb.getDescription()); assertEquals("UserDefined", fb.getText()); //Change description, cant do this with common interface fb.setDescription("test"); //Because has different description the following setField will addField another txxx rather than overwriting the first one af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_ARTISTID, "abcdef-ghijklmn")); assertEquals(2, ((List) tag.getFrame("TXXX")).size()); //Now adding TXXX with same id so gets overwritten af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_ARTISTID, "abcfffff")); assertEquals(2, ((List) tag.getFrame("TXXX")).size()); //Try deleting some of these tag.removeFrameOfType("TXXX"); assertNull(tag.getFrame("TXXX")); af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_ARTISTID, "abcdef-ghijklmn")); ((ID3v24Tag) af.getTag()).deleteField(FieldKey.MUSICBRAINZ_ARTISTID); assertNull(tag.getFrame("TXXX")); } //UFID { tag = (ID3v24Tag) af.getTag(); frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_UNIQUE_FILE_ID); ((FrameBodyUFID) frame.getBody()).setOwner("owner"); tag.setFrame(frame); ID3v24Frame ufidFrame = (ID3v24Frame) tag.getFrame("UFID"); FrameBodyUFID fb = (FrameBodyUFID) ufidFrame.getBody(); assertEquals("owner", fb.getOwner()); //Because has different owner the following setField will addField another ufid rather than overwriting the first one af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_TRACK_ID, "abcdef-ghijklmn")); assertEquals(2, ((List) tag.getFrame("UFID")).size()); //Now adding UFID with same owner so gets overwritten af.getTag().setField(af.getTag().createField(FieldKey.MUSICBRAINZ_TRACK_ID, "abcfffff")); assertEquals(2, ((List) tag.getFrame("UFID")).size()); //Try deleting some of these tag.removeFrame("UFID"); assertNull(tag.getFrame("UFID")); } //ULST { tag = (ID3v24Tag) af.getTag(); frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_UNSYNC_LYRICS); ((FrameBodyUSLT) frame.getBody()).setDescription("lyrics1"); tag.setFrame(frame); ID3v24Frame usltFrame = (ID3v24Frame) tag.getFrame("USLT"); FrameBodyUSLT fb = (FrameBodyUSLT) usltFrame.getBody(); assertEquals("lyrics1", fb.getDescription()); //Because has different desc the following setField will addField another uslt rather than overwriting the first one af.getTag().setField(af.getTag().createField(FieldKey.LYRICS, "abcdef-ghijklmn")); assertEquals(2, ((List) tag.getFrame("USLT")).size()); assertEquals(2, af.getTag().getFields(FieldKey.LYRICS).size()); frame = (ID3v24Frame) ((List) tag.getFrame("USLT")).get(1); assertEquals("", ((FrameBodyUSLT) frame.getBody()).getDescription()); //Now adding USLT with same description so gets overwritten af.getTag().setField(af.getTag().createField(FieldKey.LYRICS, "abcfffff")); assertEquals(2, ((List) tag.getFrame("USLT")).size()); assertEquals(2, af.getTag().getFields(FieldKey.LYRICS).size()); } //POPM TODO not a supported FieldKey yet { tag = (ID3v24Tag) af.getTag(); frame = new ID3v24Frame(ID3v24Frames.FRAME_ID_POPULARIMETER); ((FrameBodyPOPM) frame.getBody()).setEmailToUser("paultaylor@jthink.net"); tag.setFrame(frame); ID3v24Frame popmFrame = (ID3v24Frame) tag.getFrame("POPM"); FrameBodyPOPM fb = (FrameBodyPOPM) popmFrame.getBody(); assertEquals("paultaylor@jthink.net", fb.getEmailToUser()); } } public void testIterator() throws Exception { File orig = new File("testdata", "test26.mp3"); if (!orig.isFile()) { return; } Exception e = null; File testFile = AbstractTestCase.copyAudioToTmp("test26.mp3"); MP3File mp3File = new MP3File(testFile); assertEquals(0, mp3File.getID3v2Tag().getFieldCount()); Iterator<TagField> i = mp3File.getID3v2Tag().getFields(); assertFalse(i.hasNext()); try { i.next(); } catch(Exception ex) { e=ex; } assertTrue(e instanceof NoSuchElementException); mp3File.getID3v2Tag().addField(FieldKey.ALBUM,"album"); assertEquals(1, mp3File.getID3v2Tag().getFieldCount()); i = mp3File.getID3v2Tag().getFields(); //Should be able to iterate without actually having to call isNext() first i.next(); //Should be able to call hasNext() without it having any effect i = mp3File.getID3v2Tag().getFields(); assertTrue(i.hasNext()); Object o = i.next(); assertTrue( o instanceof ID3v23Frame); assertEquals("album",((AbstractFrameBodyTextInfo)(((ID3v23Frame)o).getBody())).getFirstTextValue()); try { i.next(); } catch(Exception ex) { e=ex; } assertTrue(e instanceof NoSuchElementException); assertFalse(i.hasNext()); //Empty frame map and force adding of empty list mp3File.getID3v2Tag().frameMap.clear(); mp3File.getID3v2Tag().frameMap.put("TXXX",new ArrayList()); assertEquals(0,mp3File.getID3v2Tag().getFieldCount()); //Issue #236 //i = mp3File.getID3v2Tag().getFields(); //assertFalse(i.hasNext()); } /** * Currently genres are written to and from v2 tag as is, the decoding from genre number to string has to be done manually */ public void testGenres() { Exception ex = null; try { File testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3", new File("testBasicWrite.mp3")); org.jaudiotagger.audio.AudioFile audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); org.jaudiotagger.tag.Tag newTag = audioFile.getTag(); assertTrue(newTag == null); if (audioFile.getTag() == null) { audioFile.setTag(new ID3v23Tag()); newTag = audioFile.getTag(); } //Write literal String newTag.setField(FieldKey.GENRE,"Rock"); audioFile.commit(); audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); newTag = audioFile.getTag(); //..and read back assertEquals("Rock", newTag.getFirst(FieldKey.GENRE)); //Write Code newTag.setField(FieldKey.GENRE,"(17)"); audioFile.commit(); audioFile = org.jaudiotagger.audio.AudioFileIO.read(testFile); newTag = audioFile.getTag(); //..and read back assertEquals("(17)", newTag.getFirst(FieldKey.GENRE)); } catch (Exception e) { ex = e; ex.printStackTrace(); } assertNull(ex); } public void testRemoveFrameOfType() { File orig = new File("testdata", "test30.mp3"); if (!orig.isFile()) { return; } Exception exceptionCaught = null; File testFile = AbstractTestCase.copyAudioToTmp("test30.mp3"); MP3File mp3file = null; try { mp3file = new MP3File(testFile); //deleteField multiple frames starting make change to file ((ID3v24Tag) mp3file.getID3v2Tag()).removeFrameOfType("PRIV"); } catch (Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); } }
gpl-3.0
XG-Project/XG-Project-v2
styles/views/fleet/fleet2_mission_row.php
190
<tr height="20"> <th> <input{id}type="radio" name="mission" value="{value}"{checked}/> <label for="inpuT_{input}">{mission}</label> <br /> {expedition_message} </th> </tr>
gpl-3.0
rkapka/Rubberduck
RubberduckTests/QuickFixes/MakeSingleLineParamegerQuickFixTests.cs
1032
using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] public class MakeSingleLineParamegerQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] public void MultilineParameter_QuickFixWorks() { const string inputCode = @"Public Sub Foo( _ ByVal _ Var1 _ As _ Integer) End Sub"; const string expectedCode = @"Public Sub Foo( _ ByVal Var1 As Integer) End Sub"; var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new MultilineParameterInspection(state)); Assert.AreEqual(expectedCode, actualCode); } protected override IQuickFix QuickFix(RubberduckParserState state) { return new MakeSingleLineParameterQuickFix(); } } }
gpl-3.0
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Converter/src/test0210/Test.java
97
package test0210; import java.util.*; public class Test { /** JavaDoc Comment*/ int i;/**/ }
gpl-3.0
OpenFOAM/OpenFOAM-5.x
src/meshTools/coordinateSystems/coordinateRotation/cylindrical.C
7323
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "cylindrical.H" #include "axesRotation.H" #include "addToRunTimeSelectionTable.H" #include "polyMesh.H" #include "tensorIOField.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { defineTypeNameAndDebug(cylindrical, 0); addToRunTimeSelectionTable ( coordinateRotation, cylindrical, dictionary ); addToRunTimeSelectionTable ( coordinateRotation, cylindrical, objectRegistry ); } // * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * * // void Foam::cylindrical::init ( const objectRegistry& obr, const List<label>& cells ) { const polyMesh& mesh = refCast<const polyMesh>(obr); const vectorField& cc = mesh.cellCentres(); if (cells.size()) { Rptr_.reset(new tensorField(cells.size())); tensorField& R = Rptr_(); forAll(cells, i) { label celli = cells[i]; vector dir = cc[celli] - origin_; dir /= mag(dir) + VSMALL; R[i] = axesRotation(e3_, dir).R(); } } else { Rptr_.reset(new tensorField(mesh.nCells())); tensorField& R = Rptr_(); forAll(cc, celli) { vector dir = cc[celli] - origin_; dir /= mag(dir) + VSMALL; R[celli] = axesRotation(e3_, dir).R(); } } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::cylindrical::cylindrical ( const dictionary& dict, const objectRegistry& obr ) : Rptr_(), origin_(point::zero), e3_(Zero) { // If origin is specified in the coordinateSystem if (dict.parent().found("origin")) { dict.parent().lookup("origin") >> origin_; } // rotation axis dict.lookup("e3") >> e3_; init(obr); } Foam::cylindrical::cylindrical ( const objectRegistry& obr, const vector& axis, const point& origin ) : Rptr_(), origin_(origin), e3_(axis) { init(obr); } Foam::cylindrical::cylindrical ( const objectRegistry& obr, const vector& axis, const point& origin, const List<label>& cells ) : Rptr_(), origin_(origin), e3_(axis) { init(obr, cells); } Foam::cylindrical::cylindrical(const dictionary& dict) : Rptr_(), origin_(), e3_() { FatalErrorInFunction << " cylindrical can not be constructed from dictionary " << " use the construtctor : " "(" " const dictionary&, const objectRegistry&" ")" << exit(FatalIOError); } Foam::cylindrical::cylindrical(const tensorField& R) : Rptr_(), origin_(Zero), e3_(Zero) { Rptr_() = R; } // * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * // void Foam::cylindrical::clear() { if (!Rptr_.empty()) { Rptr_.clear(); } } void Foam::cylindrical::updateCells ( const polyMesh& mesh, const labelList& cells ) { const vectorField& cc = mesh.cellCentres(); tensorField& R = Rptr_(); forAll(cells, i) { label celli = cells[i]; vector dir = cc[celli] - origin_; dir /= mag(dir) + VSMALL; R[celli] = axesRotation(e3_, dir).R(); } } Foam::tmp<Foam::vectorField> Foam::cylindrical::transform ( const vectorField& vf ) const { if (Rptr_->size() != vf.size()) { FatalErrorInFunction << "vectorField st has different size to tensorField " << abort(FatalError); } return (Rptr_() & vf); } Foam::vector Foam::cylindrical::transform(const vector& v) const { NotImplemented; return Zero; } Foam::vector Foam::cylindrical::transform ( const vector& v, const label cmptI ) const { return (Rptr_()[cmptI] & v); } Foam::tmp<Foam::vectorField> Foam::cylindrical::invTransform ( const vectorField& vf ) const { return (Rptr_().T() & vf); } Foam::vector Foam::cylindrical::invTransform(const vector& v) const { NotImplemented; return Zero; } Foam::vector Foam::cylindrical::invTransform ( const vector& v, const label cmptI ) const { return (Rptr_()[cmptI].T() & v); } Foam::tmp<Foam::tensorField> Foam::cylindrical::transformTensor ( const tensorField& tf ) const { if (Rptr_->size() != tf.size()) { FatalErrorInFunction << "tensorField st has different size to tensorField Tr" << abort(FatalError); } return (Rptr_() & tf & Rptr_().T()); } Foam::tensor Foam::cylindrical::transformTensor ( const tensor& t ) const { NotImplemented; return Zero; } Foam::tmp<Foam::tensorField> Foam::cylindrical::transformTensor ( const tensorField& tf, const labelList& cellMap ) const { if (cellMap.size() != tf.size()) { FatalErrorInFunction << "tensorField tf has different size to tensorField Tr" << abort(FatalError); } const tensorField& R = Rptr_(); const tensorField Rtr(R.T()); tmp<tensorField> tt(new tensorField(cellMap.size())); tensorField& t = tt.ref(); forAll(cellMap, i) { const label celli = cellMap[i]; t[i] = R[celli] & tf[i] & Rtr[celli]; } return tt; } Foam::tmp<Foam::symmTensorField> Foam::cylindrical::transformVector ( const vectorField& vf ) const { if (Rptr_->size() != vf.size()) { FatalErrorInFunction << "tensorField vf has different size to tensorField Tr" << abort(FatalError); } tmp<symmTensorField> tfld(new symmTensorField(Rptr_->size())); symmTensorField& fld = tfld.ref(); const tensorField& R = Rptr_(); forAll(fld, i) { fld[i] = transformPrincipal(R[i], vf[i]); } return tfld; } Foam::symmTensor Foam::cylindrical::transformVector ( const vector& v ) const { NotImplemented; return Zero; } void Foam::cylindrical::write(Ostream& os) const { os.writeKeyword("e3") << e3() << token::END_STATEMENT << nl; } // ************************************************************************* //
gpl-3.0
deependhulla/archive-plus-ediscovery
files/groupoffice/modules/tasks/language/pl.php
3143
<?php $l["noTask"]= 'Brak zadań do wyświetlenia'; $l["tasks"]= 'Zadania'; $l["addTask"]= 'Dodaj zadanie ...'; $l["tasklist"]= 'Lista zadań'; $l["tasklists"]= 'Listy zadań'; $l["showCompletedTasks"]= 'Pokaż zakończone zadania'; $l["filter"]= 'Filtr'; $l["dueDate"]= 'Termin zakończenia'; $l["dueAt"]= 'Zakończenie'; $l["needsAction"]= 'Wymaga akcji'; $l["accepted"]= 'Zaakceptowane'; $l["declined"]= 'Odrzucone'; $l["tentative"]= 'Tentative'; $l["delegated"]= 'Delegowane'; $l["completed"]= 'Zakończone'; $l["inProcess"]= 'W trakcie realizacji'; $l["repeatEvery"]= 'Powtarzaj co'; $l["atDays"]= 'W dniach'; $l["repeatUntil"]= 'Powtarzaj dopóki'; $l["repeatForever"]= 'powtarzaj zawsze'; $l["recurrence"]= 'Powtarzanie'; $l["remindMe"]= 'Przypomnij mi'; $l["options"]= 'Opcje'; $l["createLink"]= 'Uwtórz link'; $l["startsAt"]='Rozpoczecie'; $l["showInactiveTasks"]='Pokaż nieaktywne zadania'; $l["scheduleCall"]='Planowe wywołanie'; $l["completedAt"]='Zakończone o'; $l["taskDefaults"]='Domślne ustawienia dla zadań'; $l["daysBeforeStart"]='Dni przed startem'; $l["defaultTasklist"]='Domyślna lista zadań'; $l["visibleTasklists"]='Widoczne listy zadań'; $l["visible"]='Widoczna'; $l["selectIcalendarFile"]='Wybierz plik icalendar (*.ics)'; $l["continueTask"]='Kontynuuj zadanie'; $l["categories"]='Kategorie'; $l["category"]='Kategoria'; $l["selectCategory"]='Wybierz kategorię'; $l["noTasklistSelected"]='Proszę wybrać przynajmniej jedną listę zadań.'; $l["selectAllTasklists"]='Wybierz wszystkie listy zadań'; $l["globalCategory"]='Globala kategoria'; $l["showFutureTasks"]='Pokaż przyszłe zadania'; $l["incompleteTasks"]='Niedokończone zadania'; $l["dueInSevenDays"]='Następne 7 dni'; $l["overDue"]='Zaległe'; $l["futureTasks"]='Przyszłe'; $l["all"]='Wszystkie'; $l["active"]='Aktywne'; $l['name']='Zadania'; $l['description']='Moduł do zarządzania zadaniami'; $l['task']='Zadanie'; $l['status']='Status'; $l['scheduled_call']='Zaplanowane wywołania o %s'; $l['statuses']['NEEDS-ACTION'] = 'Wymaga akcji'; $l['statuses']['ACCEPTED'] = 'Zaakceptowane'; $l['statuses']['DECLINED'] = 'Odrzucone'; $l['statuses']['TENTATIVE'] = 'Niepewne'; $l['statuses']['DELEGATED'] = 'Delegowane'; $l['statuses']['COMPLETED'] = 'Zakończone'; $l['statuses']['IN-PROCESS'] = 'W trakcie realizacji'; $l['import_success']='%s zadań zostało zaimportowanych'; $l['call']='Wywołanie'; $l['list']='Lista zadań'; $l['tasklistChanged']="* Lista zadań zmieniona z '%s' na '%s'"; $l['statusChanged']="* Status zmieniony z '%s' na '%s'"; $l['multipleSelected']='Wybrano wiele list zadań'; $l['incomplete_delete']='Nie masz uprawnień do usunięcia wszystkich zaznaczonych zadań'; $l['completedTasks']='Zakończone zadania'; $l['globalsettings_templatelabel']='Szablon zadania'; $l['globalsettings_allchangelabel']='Zamienić istniejący?'; $l['globalsettings_renameall']= 'Rename all?'; $l['taskName']='Nazwa'; $l['taskCtime']='Utworzono'; $l['taskMtime']='Zmodyfikowano'; $l['taskStatus']='Status'; $l['taskCompletion_time']='Ukończono'; $l['taskProject_name']='Projekt'; $l['taskPercentage_complete']='Procent ukończenia';
gpl-3.0
jeremiahyan/odoo
addons/point_of_sale/static/src/js/Screens/ProductScreen/ProductsWidget.js
3742
odoo.define('point_of_sale.ProductsWidget', function(require) { 'use strict'; const { useState } = owl.hooks; const PosComponent = require('point_of_sale.PosComponent'); const { useListener } = require('web.custom_hooks'); const Registries = require('point_of_sale.Registries'); class ProductsWidget extends PosComponent { /** * @param {Object} props * @param {number?} props.startCategoryId */ constructor() { super(...arguments); useListener('switch-category', this._switchCategory); useListener('update-search', this._updateSearch); useListener('try-add-product', this._tryAddProduct); useListener('clear-search', this._clearSearch); useListener('update-product-list', this._updateProductList); this.state = useState({ searchWord: '' }); } mounted() { this.env.pos.on('change:selectedCategoryId', this.render, this); } willUnmount() { this.env.pos.off('change:selectedCategoryId', null, this); this.trigger('toggle-mobile-searchbar', false); } get selectedCategoryId() { return this.env.pos.get('selectedCategoryId'); } get searchWord() { return this.state.searchWord.trim(); } get productsToDisplay() { let list = []; if (this.searchWord !== '') { list = this.env.pos.db.search_product_in_category( this.selectedCategoryId, this.searchWord ); } else { list = this.env.pos.db.get_product_by_category(this.selectedCategoryId); } return list.sort(function (a, b) { return a.display_name.localeCompare(b.display_name) }); } get subcategories() { return this.env.pos.db .get_category_childs_ids(this.selectedCategoryId) .map(id => this.env.pos.db.get_category_by_id(id)); } get breadcrumbs() { if (this.selectedCategoryId === this.env.pos.db.root_category_id) return []; return [ ...this.env.pos.db .get_category_ancestors_ids(this.selectedCategoryId) .slice(1), this.selectedCategoryId, ].map(id => this.env.pos.db.get_category_by_id(id)); } get hasNoCategories() { return this.env.pos.db.get_category_childs_ids(0).length === 0; } _switchCategory(event) { this.env.pos.set('selectedCategoryId', event.detail); } _updateSearch(event) { this.state.searchWord = event.detail; } _tryAddProduct(event) { const searchResults = this.productsToDisplay; // If the search result contains one item, add the product and clear the search. if (searchResults.length === 1) { const { searchWordInput } = event.detail; this.trigger('click-product', searchResults[0]); // the value of the input element is not linked to the searchWord state, // so we clear both the state and the element's value. searchWordInput.el.value = ''; this._clearSearch(); } } _clearSearch() { this.state.searchWord = ''; } _updateProductList(event) { this.render(); this.trigger('switch-category', 0); } } ProductsWidget.template = 'ProductsWidget'; Registries.Component.add(ProductsWidget); return ProductsWidget; });
gpl-3.0
yesbox/ansible
test/units/plugins/test_plugins.py
3459
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.compat.tests import unittest from ansible.compat.tests import BUILTINS from ansible.compat.tests.mock import mock_open, patch, MagicMock from ansible.plugins import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader class TestErrors(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @patch.object(PluginLoader, '_get_paths') def test_print_paths(self, mock_method): mock_method.return_value = ['/path/one', '/path/two', '/path/three'] pl = PluginLoader('foo', 'foo', '', 'test_plugins') paths = pl.print_paths() expected_paths = os.pathsep.join(['/path/one', '/path/two', '/path/three']) self.assertEqual(paths, expected_paths) def test_plugins__get_package_paths_no_package(self): pl = PluginLoader('test', '', 'test', 'test_plugin') self.assertEqual(pl._get_package_paths(), []) def test_plugins__get_package_paths_with_package(self): # the _get_package_paths() call uses __import__ to load a # python library, and then uses the __file__ attribute of # the result for that to get the library path, so we mock # that here and patch the builtin to use our mocked result m = MagicMock() m.return_value.__file__ = '/path/to/my/test.py' pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin') with patch('{0}.__import__'.format(BUILTINS), m): self.assertEqual(pl._get_package_paths(), ['/path/to/my/bar/bam']) def test_plugins__get_paths(self): pl = PluginLoader('test', '', 'test', 'test_plugin') pl._paths = ['/path/one', '/path/two'] self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) # NOT YET WORKING #def fake_glob(path): # if path == 'test/*': # return ['test/foo', 'test/bar', 'test/bam'] # elif path == 'test/*/*' #m._paths = None #mock_glob = MagicMock() #mock_glob.return_value = [] #with patch('glob.glob', mock_glob): # pass def assertPluginLoaderConfigBecomes(self, arg, expected): pl = PluginLoader('test', '', arg, 'test_plugin') self.assertEqual(pl.config, expected) def test_plugin__init_config_list(self): config = ['/one', '/two'] self.assertPluginLoaderConfigBecomes(config, config) def test_plugin__init_config_str(self): self.assertPluginLoaderConfigBecomes('test', ['test']) def test_plugin__init_config_none(self): self.assertPluginLoaderConfigBecomes(None, [])
gpl-3.0
FilippoLeon/ProjectPorcupine
Assets/Scripts/Models/CharacterAnimation.cs
3812
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using System; using System.Collections.Generic; using UnityEngine; /// <summary> /// CharacterAnimation gets reference to character, and should be able to /// figure out which animation to play, by looking at character Facing and IsMoving. /// </summary> public class CharacterAnimation { private Character character; private SpriteRenderer renderer; // currentframe is incremented each update... fix to run on time instead private int currentFrame = 0; // frames before loop. halfway through the next frame is triggered private int animationLength = 40; // TODO: should be more flexible .... private Sprite[] sprites = new Sprite[9]; public CharacterAnimation(Character c, SpriteRenderer r) { character = c; renderer = r; } public void Update(float deltaTime) { if (currentFrame >= animationLength) { currentFrame = 0; } currentFrame++; CallAnimation(); } public void SetSprites(Sprite[] s) { sprites = s; // make sure that every sprite has correct filtermode foreach (Sprite sprite in sprites) { sprite.texture.filterMode = FilterMode.Point; } } private void CallAnimation() { if (character.IsWalking) { // character walking switch (character.CharFacing) { case Facing.NORTH: // walk north ToggleAnimation(5, 6); renderer.flipX = false; break; case Facing.EAST: // walk east ToggleAnimation(3, 4); renderer.flipX = false; break; case Facing.SOUTH: // walk south ToggleAnimation(7, 8); renderer.flipX = false; break; case Facing.WEST: // walk west ToggleAnimation(3, 4); // FLIP east sprite renderer.flipX = true; break; default: break; } } else { // character idle switch (character.CharFacing) { case Facing.NORTH: // walk north ShowSprite(2); renderer.flipX = false; break; case Facing.EAST: // walk east ShowSprite(1); renderer.flipX = false; break; case Facing.SOUTH: // walk south ShowSprite(0); renderer.flipX = false; break; case Facing.WEST: // walk west ShowSprite(1); // FLIP east sprite renderer.flipX = true; break; default: break; } } } private void ToggleAnimation(int s1, int s2) { if (currentFrame == 1) { renderer.sprite = sprites[s1]; } else if (currentFrame == animationLength / 2) { renderer.sprite = sprites[s2]; } } private void ShowSprite(int s) { renderer.sprite = sprites[s]; } }
gpl-3.0
Rydra/OpenRA
OpenRA.Mods.RA/Air/AttackHeli.cs
801
#region Copyright & License Information /* * Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using OpenRA.Traits; namespace OpenRA.Mods.RA.Air { class AttackHeliInfo : AttackFrontalInfo { public override object Create(ActorInitializer init) { return new AttackHeli(init.self, this); } } class AttackHeli : AttackFrontal { public AttackHeli(Actor self, AttackHeliInfo info) : base(self, info) { } public override Activity GetAttackActivity(Actor self, Target newTarget, bool allowMove) { return new HeliAttack(newTarget); } } }
gpl-3.0
rodolfochicone/djangoecommerce
checkout/admin.py
149
# coding=utf-8 from django.contrib import admin from .models import CartItem, Order, OrderItem admin.site.register([CartItem, Order, OrderItem])
gpl-3.0
s1yf0x/java-for-testing
saop-sample/src/main/java/net/webservicex/GetGeoIP.java
1571
package net.webservicex; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; 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&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="IPAddress" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ipAddress" }) @XmlRootElement(name = "GetGeoIP") public class GetGeoIP { @XmlElement(name = "IPAddress") protected String ipAddress; /** * Gets the value of the ipAddress property. * * @return * possible object is * {@link String } * */ public String getIPAddress() { return ipAddress; } /** * Sets the value of the ipAddress property. * * @param value * allowed object is * {@link String } * */ public void setIPAddress(String value) { this.ipAddress = value; } }
gpl-3.0
jmcPereira/overture
ide/plugins/combinatorialtesting/src/main/java/org/overture/ide/plugins/combinatorialtesting/views/internal/TraceNodeSorter.java
1459
/* * #%~ * Combinatorial Testing * %% * Copyright (C) 2008 - 2014 Overture * %% * 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>. * #~% */ package org.overture.ide.plugins.combinatorialtesting.views.internal; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.overture.ide.plugins.combinatorialtesting.views.treeView.TraceTestTreeNode; /** * Trace node sorter that sorts based on the number and not the label string * * @author kel */ public class TraceNodeSorter extends ViewerSorter { @Override public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof TraceTestTreeNode && e2 instanceof TraceTestTreeNode) { return ((TraceTestTreeNode) e1).getNumber().compareTo(((TraceTestTreeNode) e2).getNumber()); } return super.compare(viewer, e1, e2); } }
gpl-3.0
SoftwareEngineeringToolDemos/ICSE-2012-TraceLab
Main/external/ikvm/src/openjdk/sun/jdbc/odbc/JdbcOdbcStatement.java
9067
/* Copyright (C) 2009, 2011 Volker Berlin (i-net software) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ package sun.jdbc.odbc; import java.sql.*; import cli.System.Data.*; import cli.System.Data.Common.*; import cli.System.Data.Odbc.*; /** * This JDBC Driver is a wrapper to the ODBC.NET Data Provider. */ public class JdbcOdbcStatement implements Statement{ private final JdbcOdbcConnection jdbcConn; protected final OdbcCommand command; private final int resultSetType; private final int resultSetConcurrency; private DbDataReader reader; private ResultSet rs; private int updateCount; private boolean isClosed; private ResultSet moreResults; public JdbcOdbcStatement(JdbcOdbcConnection jdbcConn, OdbcCommand command, int resultSetType, int resultSetConcurrency){ this.jdbcConn = jdbcConn; this.command = command; this.resultSetType = resultSetType; this.resultSetConcurrency = resultSetConcurrency; } public void addBatch(String sql) throws SQLException{ // TODO Auto-generated method stub } public void cancel() throws SQLException{ try{ command.Cancel(); }catch(Throwable ex){ throw JdbcOdbcUtils.createSQLException(ex); } } public void clearBatch() throws SQLException{ // TODO Auto-generated method stub } public void clearWarnings() throws SQLException{ // TODO Auto-generated method stub } public void close() throws SQLException{ isClosed = true; if(rs != null){ rs.close(); } if(reader != null){ reader.Close(); } command.Dispose(); } public boolean execute(String sql) throws SQLException{ try{ if(sql != null){ command.set_CommandText(sql); } command.ExecuteNonQuery(); return false; }catch(Throwable ex){ throw JdbcOdbcUtils.createSQLException(ex); } } public boolean execute(String sql, int autoGeneratedKeys){ throw new UnsupportedOperationException(); } public boolean execute(String sql, int[] columnIndexes){ throw new UnsupportedOperationException(); } public boolean execute(String sql, String[] columnNames){ throw new UnsupportedOperationException(); } public int[] executeBatch() throws SQLException{ // TODO Auto-generated method stub return null; } public ResultSet executeQuery(String sql) throws SQLException{ try{ if(sql != null){ command.set_CommandText(sql); } if(resultSetConcurrency == ResultSet.CONCUR_UPDATABLE){ rs = new JdbcOdbcUpdateableResultSet(command); }else{ if(resultSetType == ResultSet.TYPE_FORWARD_ONLY){ reader = command.ExecuteReader(); rs = new JdbcOdbcResultSet(this, reader); }else{ OdbcDataAdapter da = new OdbcDataAdapter(command); DataTable dt = new DataTable(); da.Fill(dt); rs = new JdbcOdbcDTResultSet(dt); } } return rs; }catch(Throwable ex){ throw JdbcOdbcUtils.createSQLException(ex); } } public int executeUpdate(String sql) throws SQLException{ try{ if(sql != null){ command.set_CommandText(sql); } updateCount = command.ExecuteNonQuery(); return updateCount; }catch(Throwable ex){ throw JdbcOdbcUtils.createSQLException(ex); } } public int executeUpdate(String sql, int autoGeneratedKeys){ throw new UnsupportedOperationException(); } public int executeUpdate(String sql, int[] columnIndexes){ throw new UnsupportedOperationException(); } public int executeUpdate(String sql, String[] columnNames){ throw new UnsupportedOperationException(); } public Connection getConnection(){ return jdbcConn; } public int getFetchDirection(){ return ResultSet.FETCH_UNKNOWN; } public int getFetchSize(){ return 0; } public ResultSet getGeneratedKeys(){ throw new UnsupportedOperationException(); } public int getMaxFieldSize() throws SQLException{ // TODO Auto-generated method stub return 0; } public int getMaxRows() throws SQLException{ // TODO Auto-generated method stub return 0; } public boolean getMoreResults() throws SQLException{ try{ if(moreResults != null){ rs = moreResults; moreResults = null; return true; } boolean isNext = reader.NextResult(); if(isNext){ rs = new JdbcOdbcResultSet(this, reader); return true; } rs = null; return false; }catch(Throwable th){ throw JdbcOdbcUtils.createSQLException(th); } } public boolean getMoreResults(int current) throws SQLException{ // TODO Auto-generated method stub return false; } public int getQueryTimeout(){ return command.get_CommandTimeout(); } public ResultSet getResultSet(){ return rs; } public int getResultSetConcurrency(){ return resultSetConcurrency; } public int getResultSetHoldability() throws SQLException{ // TODO Auto-generated method stub return 0; } public int getResultSetType(){ return resultSetType; } public int getUpdateCount(){ return updateCount; } public SQLWarning getWarnings() throws SQLException{ // TODO Auto-generated method stub return null; } public boolean isClosed(){ return isClosed; } public void setCursorName(String name) throws SQLException{ // TODO Auto-generated method stub } public void setEscapeProcessing(boolean enable) throws SQLException{ // TODO Auto-generated method stub } public void setFetchDirection(int direction){ // ignore it } public void setFetchSize(int rows){ // ignore it } public void setMaxFieldSize(int max) throws SQLException{ // TODO Auto-generated method stub } public void setMaxRows(int max) throws SQLException{ // TODO Auto-generated method stub } public boolean isPoolable(){ return false; } public void setPoolable(boolean poolable) throws SQLException{ // ignore it } public void setQueryTimeout(int seconds){ command.set_CommandTimeout(seconds); } public boolean isWrapperFor(Class<?> iface){ return iface.isAssignableFrom(this.getClass()); } public <T>T unwrap(Class<T> iface) throws SQLException{ if(isWrapperFor(iface)){ return (T)this; } throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); } /** * Close the DbDataReader if there are no more results. * This give some blocking free without calling close() explicit. * If there are more results then we need to save it. */ void closeReaderIfPossible(){ ResultSet currentRs = rs; boolean isMoreResults; try{ isMoreResults = getMoreResults(); }catch(SQLException ex){ isMoreResults = false; } if(!isMoreResults){ reader.Close(); //this give the ODBC cursor free }else{ moreResults = rs; } rs = currentRs; } /** * {@inheritDoc} */ public void closeOnCompletion() throws SQLException { } /** * {@inheritDoc} */ public boolean isCloseOnCompletion() throws SQLException { return false; } }
gpl-3.0
axmetishe/serna-free
serna/i18n/ts/qscintilla_fr.ts
68017
<!DOCTYPE TS><TS> <context> <name>QextScintillaCommand</name> <message> <source>Move down one line</source> <translation>Déplacement d&apos;une ligne vers le bas</translation> </message> <message> <source>Extend selection down one line</source> <translation>Extension de la sélection d&apos;une ligne vers le bas</translation> </message> <message> <source>Scroll view down one line</source> <translation>Decendre la vue d&apos;une ligne</translation> </message> <message> <source>Extend rectangular selection down one line</source> <translation>Extension de la sélection rectangulaire d&apos;une ligne vers le bas</translation> </message> <message> <source>Move up one line</source> <translation>Déplacement d&apos;une ligne vers le haut</translation> </message> <message> <source>Extend selection up one line</source> <translation>Extension de la sélection d&apos;une ligne vers le haut</translation> </message> <message> <source>Scroll view up one line</source> <translation>Remonter la vue d&apos;une ligne</translation> </message> <message> <source>Extend rectangular selection up one line</source> <translation>Extension de la sélection rectangulaire d&apos;une ligne vers le haut</translation> </message> <message> <source>Move up one paragraph</source> <translation>Déplacement d&apos;un paragraphe vers le haut</translation> </message> <message> <source>Extend selection up one paragraph</source> <translation>Extension de la sélection d&apos;un paragraphe vers le haut</translation> </message> <message> <source>Move down one paragraph</source> <translation>Déplacement d&apos;un paragraphe vers le bas</translation> </message> <message> <source>Extend selection down one paragraph</source> <translation>Extension de la sélection d&apos;un paragraphe vers le bas</translation> </message> <message> <source>Move left one character</source> <translation>Déplacement d&apos;un caractère vers la gauche</translation> </message> <message> <source>Extend selection left one character</source> <translation>Extension de la sélection d&apos;un caractère vers la gauche</translation> </message> <message> <source>Move left one word</source> <translation>Déplacement d&apos;un mot vers la gauche</translation> </message> <message> <source>Extend selection left one word</source> <translation>Extension de la sélection d&apos;un mot vers la gauche</translation> </message> <message> <source>Extend rectangular selection left one character</source> <translation>Extension de la sélection rectangulaire d&apos;un caractère vers la gauche</translation> </message> <message> <source>Move right one character</source> <translation>Déplacement d&apos;un caractère vers la droite</translation> </message> <message> <source>Extend selection right one character</source> <translation>Extension de la sélection d&apos;un caractère vers la droite</translation> </message> <message> <source>Move right one word</source> <translation>Déplacement d&apos;un mot vers la droite</translation> </message> <message> <source>Extend selection right one word</source> <translation>Extension de la sélection d&apos;un mot vers la droite</translation> </message> <message> <source>Extend rectangular selection right one character</source> <translation>Extension de la sélection rectangulaire d&apos;un caractère vers la droite</translation> </message> <message> <source>Move left one word part</source> <translation>Déplacement d&apos;une part de mot vers la gauche</translation> </message> <message> <source>Extend selection left one word part</source> <translation>Extension de la sélection d&apos;une part de mot vers la gauche</translation> </message> <message> <source>Move right one word part</source> <translation>Déplacement d&apos;une part de mot vers la droite</translation> </message> <message> <source>Extend selection right one word part</source> <translation>Extension de la sélection d&apos;une part de mot vers la droite</translation> </message> <message> <source>Move to first visible character in line</source> <translation>Déplacement vers le premier caractère visible de la ligne</translation> </message> <message> <source>Extend selection to first visible character in line</source> <translation>Extension de la sélection jusqu&apos;au premier caractère visible de la ligne</translation> </message> <message> <source>Move to start of text</source> <translation>Déplacement au début du texte</translation> </message> <message> <source>Extend selection to start of text</source> <translation>Extension de la sélection jusqu&apos;au début du texte</translation> </message> <message> <source>Move to start of displayed line</source> <translation>Déplacement au le début de la ligne affichée</translation> </message> <message> <source>Extend selection to start of line</source> <translation>Extension de la sélection jusqu&apos;au début de la ligne</translation> </message> <message> <source>Extend rectangular selection to first visible character in line</source> <translation>Extension de la sélection rectangulaire jusqu&apos;au premier caractère visible de la ligne</translation> </message> <message> <source>Move to end of line</source> <translation>Déplacement à la fin de la ligne</translation> </message> <message> <source>Extend selection to end of line</source> <translation>Extension de la sélection jusqu&apos;à la fin de la ligne</translation> </message> <message> <source>Move to end of text</source> <translation>Déplacement à la fin du du texte</translation> </message> <message> <source>Extend selection to end of text</source> <translation>Extension de la sélection jusqu&apos;à la fin du texte</translation> </message> <message> <source>Move to end of displayed line</source> <translation>Déplacement à la fin de la ligne affichée</translation> </message> <message> <source>Extend selection to end of displayed line</source> <translation>Extension de la sélection à la fin de la ligne affichée</translation> </message> <message> <source>Extend rectangular selection to end of line</source> <translation>Extension de la sélection rectangulaire à la fin de la ligne</translation> </message> <message> <source>Move up one page</source> <translation>Déplacement d&apos;une page vers le haut</translation> </message> <message> <source>Extend selection up one page</source> <translation>Extension de la sélection d&apos;une page vers le haut</translation> </message> <message> <source>Extend rectangular selection up one page</source> <translation>Extension de la sélection rectangulaire d&apos;une page vers le haut</translation> </message> <message> <source>Move down one page</source> <translation>Déplacement d&apos;une page vers le bas</translation> </message> <message> <source>Extend selection down one page</source> <translation>Extension de la sélection d&apos;une page vers le bas</translation> </message> <message> <source>Extend rectangular selection down one page</source> <translation>Extension de la sélection rectangulaire d&apos;une page vers le bas</translation> </message> <message> <source>Delete current character</source> <translation>Effacement du caractère courant</translation> </message> <message> <source>Cut selection</source> <translation>Couper la sélection</translation> </message> <message> <source>Delete word to right</source> <translation>Suppression du mot de droite</translation> </message> <message> <source>Delete line to right</source> <translation>Suppression de la partie droite de la ligne</translation> </message> <message> <source>Toggle insert/overtype</source> <translation>Basculement Insertion /Ecrasement</translation> </message> <message> <source>Paste</source> <translation>Coller</translation> </message> <message> <source>Copy selection</source> <translation>Copier la sélection</translation> </message> <message> <source>Cancel</source> <translation>Annuler</translation> </message> <message> <source>Delete previous character</source> <translation>Suppression du dernier caractère</translation> </message> <message> <source>Delete word to left</source> <translation>Suppression du mot de gauche</translation> </message> <message> <source>Undo the last command</source> <translation>Annuler la dernière commande</translation> </message> <message> <source>Delete line to left</source> <translation>Effacer la partie gauche de la ligne</translation> </message> <message> <source>Redo last command</source> <translation>Refaire la dernière commande</translation> </message> <message> <source>Select all text</source> <translation>Sélectionner tout le texte</translation> </message> <message> <source>Indent one level</source> <translation>Indentation d&apos;un niveau</translation> </message> <message> <source>Move back one indentation level</source> <translation>Désindentation d&apos;un niveau</translation> </message> <message> <source>Insert new line</source> <translation>Insertion d&apos;une nouvelle ligne</translation> </message> <message> <source>Zoom in</source> <translation>Zoom avant</translation> </message> <message> <source>Zoom out</source> <translation>Zoom arrière</translation> </message> <message> <source>Set zoom</source> <translation>Définition du zoom</translation> </message> <message> <source>Formfeed</source> <translation>Chargement de la page</translation> </message> <message> <source>Cut current line</source> <translation>Couper la ligne courante</translation> </message> <message> <source>Delete current line</source> <translation>Suppression de la ligne courante</translation> </message> <message> <source>Copy current line</source> <translation>Copier la ligne courante</translation> </message> <message> <source>Swap current and previous lines</source> <translation>Permuter la ligne précédente avec la ligne courante</translation> </message> <message> <source>Duplicate current line</source> <translation>Duppliquer la ligne courante</translation> </message> <message> <source>Convert selection to lower case</source> <translation>Conversion de la ligne courante en minuscules</translation> </message> <message> <source>Convert selection to upper case</source> <translation>Conversion de la ligne courante en majuscules</translation> </message> <message> <source>Delete previous character if not at line start</source> <translation>Suppression du caractère précédent sauf en début de ligne</translation> </message> </context> <context> <name>QextScintillaContextMenu</name> <message> <source>Undo</source> <translation>Annuler l&apos;action</translation> </message> <message> <source>Redo</source> <translation>Rétablir l&apos;action</translation> </message> <message> <source>Cut</source> <translation>Couper</translation> </message> <message> <source>Copy</source> <translation>Copier</translation> </message> <message> <source>Paste</source> <translation>Coller</translation> </message> <message> <source>Delete</source> <translation>Effacer</translation> </message> <message> <source>Select All</source> <translation>Tout sélectionner</translation> </message> </context> <context> <name>QextScintillaLexerBash</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Scalar</source> <translation>Scalaire</translation> </message> <message> <source>Parameter expansion</source> <translation>Extension de paramètre</translation> </message> <message> <source>Backticks</source> <translation>Quotes inverses</translation> </message> <message> <source>Here document delimiter</source> <translation>Délimiteur de texte intégré (cat &lt;&lt;EOF....EOF)</translation> </message> <message> <source>Single-quoted here document</source> <translation>Document intégré guillemets simples</translation> </message> </context> <context> <name>QextScintillaLexerBatch</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Label</source> <translation>Titre</translation> </message> <message> <source>Hide command character</source> <translation>Cacher le caratère de commande</translation> </message> <message> <source>External command</source> <translation>Commande externe</translation> </message> <message> <source>Variable</source> <translation>Variable</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> </context> <context> <name>QextScintillaLexerCPP</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>C comment</source> <translation>Commentaire C</translation> </message> <message> <source>C++ comment</source> <translation>Commentaire C++</translation> </message> <message> <source>JavaDoc style C comment</source> <translation>Commentaire C de style JavaDoc</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Pre-processor block</source> <translation>Instructions de pré-processing</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Unclosed string</source> <translation>Chaîne de caractères non refermée</translation> </message> <message> <source>JavaDoc style C++ comment</source> <translation>Commentaire C++ de style JavaDoc</translation> </message> <message> <source>Secondary keywords and identifiers</source> <translation>Seconds mots-clés et identificateurs</translation> </message> <message> <source>JavaDoc keyword</source> <translation>Mot-clé JavaDoc</translation> </message> <message> <source>JavaDoc keyword error</source> <translation>Erreur de mot-clé JavaDoc</translation> </message> <message> <source>Global classes and typedefs</source> <translation>Classes globales et définitions de types</translation> </message> </context> <context> <name>QextScintillaLexerCSS</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Tag</source> <translation>Balise</translation> </message> <message> <source>Class selector</source> <translation>Classe</translation> </message> <message> <source>Pseudo-class</source> <translation>Pseudo-classe</translation> </message> <message> <source>Unknown pseudo-class</source> <translation>Peudo-classe inconnue</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>CSS1 property</source> <translation>Propriété CSS1</translation> </message> <message> <source>Unknown property</source> <translation>Propriété inconnue</translation> </message> <message> <source>Value</source> <translation>Valeur</translation> </message> <message> <source>ID selector</source> <translation>ID</translation> </message> <message> <source>Important</source> <translation>Important</translation> </message> <message> <source>@-rule</source> <translation>règle-@</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>CSS2 property</source> <translation>Propriété CSS2</translation> </message> <message> <source>Attribute</source> <translation>Attribut</translation> </message> </context> <context> <name>QextScintillaLexerCSharp</name> <message> <source>Verbatim string</source> <translation>Chaine verbatim</translation> </message> </context> <context> <name>QextScintillaLexerDiff</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Command</source> <translation>Commande</translation> </message> <message> <source>Header</source> <translation>En-tête</translation> </message> <message> <source>Position</source> <translation>Position</translation> </message> <message> <source>Removed line</source> <translation>Ligne supprimée</translation> </message> <message> <source>Added line</source> <translation>Ligne ajoutée</translation> </message> </context> <context> <name>QextScintillaLexerHTML</name> <message> <source>HTML default</source> <translation>HTML par défaut</translation> </message> <message> <source>Tag</source> <translation>Balise</translation> </message> <message> <source>Unknown tag</source> <translation>Balise inconnue</translation> </message> <message> <source>Attribute</source> <translation>Attribut</translation> </message> <message> <source>Unknown attribute</source> <translation>Attribut inconnu</translation> </message> <message> <source>HTML number</source> <translation>Nombre HTML</translation> </message> <message> <source>HTML double-quoted string</source> <translation>Chaîne de caractères HTML (guillemets doubles)</translation> </message> <message> <source>HTML single-quoted string</source> <translation>Chaîne de caractères HTML (guillemets simples)</translation> </message> <message> <source>Other text in a tag</source> <translation>Autre texte dans les balises</translation> </message> <message> <source>HTML comment</source> <translation>Commentaire HTML</translation> </message> <message> <source>Entity</source> <translation>Entité</translation> </message> <message> <source>End of a tag</source> <translation>Balise fermante</translation> </message> <message> <source>Start of an XML fragment</source> <translation>Début de block XML</translation> </message> <message> <source>End of an XML fragment</source> <translation>Fin de block XML</translation> </message> <message> <source>Script tag</source> <translation>Balise de script</translation> </message> <message> <source>Start of an ASP fragment with @</source> <translation>Début de block ASP avec @</translation> </message> <message> <source>Start of an ASP fragment</source> <translation>Début de block ASP</translation> </message> <message> <source>CDATA</source> <translation>CDATA</translation> </message> <message> <source>Start of a PHP fragment</source> <translation>Début de block PHP</translation> </message> <message> <source>Unquoted HTML value</source> <translation>Valeur HTML sans guillemets</translation> </message> <message> <source>ASP X-Code comment</source> <translation>Commentaire X-Code ASP</translation> </message> <message> <source>SGML default</source> <translation>SGML par défaut</translation> </message> <message> <source>SGML command</source> <translation>Commande SGML</translation> </message> <message> <source>First parameter of an SGML command</source> <translation>Premier paramètre de commande SGML</translation> </message> <message> <source>SGML double-quoted string</source> <translation>Chaîne de caractères SGML (guillemets doubles)</translation> </message> <message> <source>SGML single-quoted string</source> <translation>Chaîne de caractères SGML (guillemets simples)</translation> </message> <message> <source>SGML error</source> <translation>Erreur SGML</translation> </message> <message> <source>SGML special entity</source> <translation>Entité SGML spéciale</translation> </message> <message> <source>SGML comment</source> <translation>Commentaire SGML</translation> </message> <message> <source>First parameter comment of an SGML command</source> <translation>Premier paramètre de commentaire de commande SGML</translation> </message> <message> <source>SGML block default</source> <translation>Block SGML par défaut</translation> </message> <message> <source>Start of a JavaScript fragment</source> <translation>Début de block JavaScript</translation> </message> <message> <source>JavaScript default</source> <translation>JavaScript par défaut</translation> </message> <message> <source>JavaScript comment</source> <translation>Commentaire JavaScript</translation> </message> <message> <source>JavaScript line comment</source> <translation>Commentaire de ligne JavaScript</translation> </message> <message> <source>JavaDoc style JavaScript comment</source> <translation>Commentaire JavaScript de style JavaDoc</translation> </message> <message> <source>JavaScript number</source> <translation>Nombre JavaScript</translation> </message> <message> <source>JavaScript word</source> <translation>Mot JavaScript</translation> </message> <message> <source>JavaScript keyword</source> <translation>Mot-clé JavaScript</translation> </message> <message> <source>JavaScript double-quoted string</source> <translation>Chaîne de caractères JavaScript (guillemets doubles)</translation> </message> <message> <source>JavaScript single-quoted string</source> <translation>Chaîne de caractères JavaScript (guillemets simples)</translation> </message> <message> <source>JavaScript symbol</source> <translation>Symbole JavaScript</translation> </message> <message> <source>JavaScript unclosed string</source> <translation>Chaîne de caractères JavaScript non refermée</translation> </message> <message> <source>JavaScript regular expression</source> <translation>Expression régulière JavaScript</translation> </message> <message> <source>Start of an ASP JavaScript fragment</source> <translation>Début de block JavaScript ASP</translation> </message> <message> <source>ASP JavaScript default</source> <translation>JavaScript ASP par défaut</translation> </message> <message> <source>ASP JavaScript comment</source> <translation>Commentaire JavaScript ASP</translation> </message> <message> <source>ASP JavaScript line comment</source> <translation>Commentaire de ligne JavaScript ASP</translation> </message> <message> <source>JavaDoc style ASP JavaScript comment</source> <translation>Commentaire JavaScript ASP de style JavaDoc</translation> </message> <message> <source>ASP JavaScript number</source> <translation>Nombre JavaScript ASP</translation> </message> <message> <source>ASP JavaScript word</source> <translation>Mot JavaScript ASP</translation> </message> <message> <source>ASP JavaScript keyword</source> <translation>Mot-clé JavaScript ASP </translation> </message> <message> <source>ASP JavaScript double-quoted string</source> <translation>Chaîne de caractères JavaScript ASP (guillemets doubles)</translation> </message> <message> <source>ASP JavaScript single-quoted string</source> <translation>Chaîne de caractères JavaScript ASP (guillemets simples)</translation> </message> <message> <source>ASP JavaScript symbol</source> <translation>Symbole JavaScript ASP</translation> </message> <message> <source>ASP JavaScript unclosed string</source> <translation>Chaîne de caractères JavaScript ASP non refermée</translation> </message> <message> <source>ASP JavaScript regular expression</source> <translation>Expression régulière JavaScript ASP</translation> </message> <message> <source>Start of a VBScript fragment</source> <translation>Début de block VBScript</translation> </message> <message> <source>VBScript default</source> <translation>VBScript par défaut</translation> </message> <message> <source>VBScript comment</source> <translation>Commentaire VBScript</translation> </message> <message> <source>VBScript number</source> <translation>Nombre VBScript</translation> </message> <message> <source>VBScript keyword</source> <translation>Mot-clé VBScript</translation> </message> <message> <source>VBScript string</source> <translation>Chaîne de caractères VBScript</translation> </message> <message> <source>VBScript identifier</source> <translation>Identificateur VBScript</translation> </message> <message> <source>VBScript unclosed string</source> <translation>Chaîne de caractères VBScript non refermée</translation> </message> <message> <source>Start of an ASP VBScript fragment</source> <translation>Début de block VBScript ASP</translation> </message> <message> <source>ASP VBScript default</source> <translation>VBScript ASP par défaut</translation> </message> <message> <source>ASP VBScript comment</source> <translation>Commentaire VBScript ASP</translation> </message> <message> <source>ASP VBScript number</source> <translation>Nombre VBScript ASP</translation> </message> <message> <source>ASP VBScript keyword</source> <translation>Mot-clé VBScript ASP </translation> </message> <message> <source>ASP VBScript string</source> <translation>Chaîne de caractères VBScript ASP</translation> </message> <message> <source>ASP VBScript identifier</source> <translation>Identificateur VBScript ASP</translation> </message> <message> <source>ASP VBScript unclosed string</source> <translation>Chaîne de caractères VBScript ASP non refermée</translation> </message> <message> <source>Start of a Python fragment</source> <translation>Début de block Python</translation> </message> <message> <source>Python default</source> <translation>Python par défaut</translation> </message> <message> <source>Python comment</source> <translation>Commentaire Python</translation> </message> <message> <source>Python number</source> <translation>Nombre Python</translation> </message> <message> <source>Python double-quoted string</source> <translation>Chaîne de caractères Python (guillemets doubles)</translation> </message> <message> <source>Python single-quoted string</source> <translation>Chaîne de caractères Python (guillemets simples)</translation> </message> <message> <source>Python keyword</source> <translation>Mot-clé Python</translation> </message> <message> <source>Python triple double-quoted string</source> <translation>Chaîne de caractères Python (triples guillemets doubles)</translation> </message> <message> <source>Python triple single-quoted string</source> <translation>Chaîne de caractères Python (triples guillemets simples)</translation> </message> <message> <source>Python class name</source> <translation>Nom de classe Python</translation> </message> <message> <source>Python function or method name</source> <translation>Méthode ou fonction Python</translation> </message> <message> <source>Python operator</source> <translation>Opérateur Python</translation> </message> <message> <source>Python identifier</source> <translation>Identificateur Python</translation> </message> <message> <source>Start of an ASP Python fragment</source> <translation>Début de block Python ASP</translation> </message> <message> <source>ASP Python default</source> <translation>Python ASP par défaut</translation> </message> <message> <source>ASP Python comment</source> <translation>Commentaire Python ASP</translation> </message> <message> <source>ASP Python number</source> <translation>Nombre Python ASP</translation> </message> <message> <source>ASP Python double-quoted string</source> <translation>Chaîne de caractères Python ASP (guillemets doubles)</translation> </message> <message> <source>ASP Python single-quoted string</source> <translation>Chaîne de caractères Python ASP (guillemets simples)</translation> </message> <message> <source>ASP Python keyword</source> <translation>Mot-clé Python ASP</translation> </message> <message> <source>ASP Python triple double-quoted string</source> <translation>Chaîne de caractères Python ASP (triples guillemets doubles)</translation> </message> <message> <source>ASP Python triple single-quoted string</source> <translation>Chaîne de caractères Python ASP (triples guillemets simples)</translation> </message> <message> <source>ASP Python class name</source> <translation>Nom de classe Python ASP</translation> </message> <message> <source>ASP Python function or method name</source> <translation>Méthode ou fonction Python ASP</translation> </message> <message> <source>ASP Python operator</source> <translation>Opérateur Python ASP</translation> </message> <message> <source>ASP Python identifier</source> <translation>Identificateur Python ASP</translation> </message> <message> <source>PHP default</source> <translation>PHP par défaut</translation> </message> <message> <source>PHP double-quoted string</source> <translation>Chaîne de caractères PHP (guillemets doubles)</translation> </message> <message> <source>PHP single-quoted string</source> <translation>Chaîne de caractères PHP (guillemets simples)</translation> </message> <message> <source>PHP keyword</source> <translation>Mot-clé PHP</translation> </message> <message> <source>PHP number</source> <translation>Nombre PHP</translation> </message> <message> <source>PHP variable</source> <translation>Variable PHP</translation> </message> <message> <source>PHP comment</source> <translation>Commentaire PHP</translation> </message> <message> <source>PHP line comment</source> <translation>Commentaire de ligne PHP</translation> </message> <message> <source>PHP double-quoted variable</source> <translation>Variable PHP (guillemets doubles)</translation> </message> <message> <source>PHP operator</source> <translation>Opérateur PHP</translation> </message> </context> <context> <name>QextScintillaLexerIDL</name> <message> <source>UUID</source> <translation>UUID</translation> </message> </context> <context> <name>QextScintillaLexerJavaScript</name> <message> <source>Regular expression</source> <translation>Expression régulière</translation> </message> </context> <context> <name>QextScintillaLexerLua</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Line comment</source> <translation>Commentaire de ligne</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>String</source> <translation>Chaîne de caractères</translation> </message> <message> <source>Character</source> <translation>Caractère</translation> </message> <message> <source>Literal string</source> <translation>Chaîne littérale</translation> </message> <message> <source>Preprocessor</source> <translation>Préprocessing</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Unclosed string</source> <translation>Chaîne de caractères non refermée</translation> </message> <message> <source>Basic functions</source> <translation>Fonctions de base</translation> </message> <message> <source>String, table and maths functions</source> <translation>Fonctions sur les chaînes, tables et fonctions mathématiques</translation> </message> <message> <source>Coroutines, i/o and system facilities</source> <translation>Coroutines, i/o et fonctions système</translation> </message> </context> <context> <name>QextScintillaLexerMakefile</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Preprocessor</source> <translation>Préprocessing</translation> </message> <message> <source>Variable</source> <translation>Variable</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Target</source> <translation>Cible</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> </context> <context> <name>QextScintillaLexerPOV</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Comment line</source> <translation>Ligne commentée</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>String</source> <translation>Chaîne de caractères</translation> </message> <message> <source>Unclosed string</source> <translation>Chaîne de caractères non refermée</translation> </message> <message> <source>Directive</source> <translation>Directive</translation> </message> <message> <source>Bad directive</source> <translation>Mauvaise directive</translation> </message> <message> <source>Objects, CSG and appearance</source> <translation>Objets, CSG et apparence</translation> </message> <message> <source>Types, modifiers and items</source> <translation>Types, modifieurs et éléments</translation> </message> <message> <source>Predefined identifiers</source> <translation>Identifiants prédéfinis</translation> </message> <message> <source>Predefined functions</source> <translation>Fonctions prédéfinies</translation> </message> <message> <source>User defined 1</source> <translation>Définition utilisateur 1</translation> </message> <message> <source>User defined 2</source> <translation>Définition utilisateur 2</translation> </message> <message> <source>User defined 3</source> <translation>Définition utilisateur 3</translation> </message> </context> <context> <name>QextScintillaLexerPerl</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>POD</source> <translation>POD</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Scalar</source> <translation>Scalaire</translation> </message> <message> <source>Array</source> <translation>Tableau</translation> </message> <message> <source>Hash</source> <translation>Hashage</translation> </message> <message> <source>Symbol table</source> <translation>Table de symboles</translation> </message> <message> <source>Regular expression</source> <translation>Expression régulière</translation> </message> <message> <source>Substitution</source> <translation>Substitution</translation> </message> <message> <source>Backticks</source> <translation>Quotes inverses</translation> </message> <message> <source>Data section</source> <translation>Section de données</translation> </message> <message> <source>Here document delimiter</source> <translation>Délimiteur de texte intégré (cat &lt;&lt;EOF....EOF)</translation> </message> <message> <source>Single-quoted here document</source> <translation>Document intégré guillemets simples</translation> </message> <message> <source>Double-quoted here document</source> <translation>Document intégré guillemets doubles</translation> </message> <message> <source>Backtick here document</source> <translation>Document intégré quotes inverses</translation> </message> <message> <source>Quoted string (q)</source> <translation>Chaîne quotée (q)</translation> </message> <message> <source>Quoted string (qq)</source> <translation>Chaîne quotée (qq)</translation> </message> <message> <source>Quoted string (qx)</source> <translation>Chaîne quotée (qx)</translation> </message> <message> <source>Quoted string (qr)</source> <translation>Chaîne quotée (qr)</translation> </message> <message> <source>Quoted string (qw)</source> <translation>Chaîne quotée (qw)</translation> </message> <message> <source>POD verbatim</source> <translation>POD verbatim</translation> </message> </context> <context> <name>QextScintillaLexerProperties</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Section</source> <translation>Section</translation> </message> <message> <source>Assignment</source> <translation>Affectation</translation> </message> <message> <source>Default value</source> <translation>Valeur par défaut</translation> </message> </context> <context> <name>QextScintillaLexerPython</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Triple single-quoted string</source> <translation>Chaîne de caractères HTML (guillemets simples)</translation> </message> <message> <source>Triple double-quoted string</source> <translation>Chaîne de caractères HTML (guillemets simples)</translation> </message> <message> <source>Class name</source> <translation>Nom de classe</translation> </message> <message> <source>Function or method name</source> <translation>Nom de méthode ou de fonction</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Comment block</source> <translation>Block de commentaires</translation> </message> <message> <source>Unclosed string</source> <translation>Chaîne de caractères non refermée</translation> </message> </context> <context> <name>QextScintillaLexerRuby</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Triple double-quoted string</source> <translation>Chaîne de caractères HTML (guillemets simples)</translation> </message> <message> <source>Class name</source> <translation>Nom de classe</translation> </message> <message> <source>Function or method name</source> <translation>Nom de méthode ou de fonction</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Comment block</source> <translation>Block de commentaires</translation> </message> <message> <source>Unclosed string</source> <translation>Chaîne de caractères non refermée</translation> </message> </context> <context> <name>QextScintillaLexerSQL</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Line comment</source> <translation type="obsolete">Commentaire de ligne</translation> </message> <message> <source>Number</source> <translation>Nombre</translation> </message> <message> <source>Keyword</source> <translation>Mot-clé</translation> </message> <message> <source>Single-quoted string</source> <translation>Chaîne de caractères (guillemets simples)</translation> </message> <message> <source>Operator</source> <translation>Opérateur</translation> </message> <message> <source>Identifier</source> <translation>Identificateur</translation> </message> <message> <source>Comment line</source> <translation>Ligne commentée</translation> </message> <message> <source>JavaDoc style comment</source> <translation>Commentaire style JavaDoc</translation> </message> <message> <source>Double-quoted string</source> <translation>Chaîne de caractères (guillemets doubles)</translation> </message> <message> <source>SQL*Plus keyword</source> <translation>Mot-clé SQL*Plus</translation> </message> <message> <source>SQL*Plus prompt</source> <translation>Prompt SQL*Plus</translation> </message> <message> <source>SQL*Plus comment</source> <translation>Commentaire SQL*Plus</translation> </message> <message> <source># comment line</source> <translation># Ligne commentée</translation> </message> <message> <source>JavaDoc keyword</source> <translation>Mot-clé JavaDoc</translation> </message> <message> <source>JavaDoc keyword error</source> <translation>Erreur de mot-clé JavaDoc</translation> </message> <message> <source>User defined 1</source> <translation>Définition utilisateur 1</translation> </message> <message> <source>User defined 2</source> <translation>Définition utilisateur 2</translation> </message> <message> <source>User defined 3</source> <translation>Définition utilisateur 3</translation> </message> <message> <source>User defined 4</source> <translation>Définition utilisateur 4</translation> </message> </context> <context> <name>QextScintillaLexerTeX</name> <message> <source>Default</source> <translation>Par défaut</translation> </message> <message> <source>Special</source> <translation>Spécial</translation> </message> <message> <source>Group</source> <translation>Groupe</translation> </message> <message> <source>Symbol</source> <translation>Symbole</translation> </message> <message> <source>Command</source> <translation>Commande</translation> </message> <message> <source>Text</source> <translation>Texte</translation> </message> </context> <context> <name>QextScintillaLexerXML</name> <message> <source>XML default</source> <translation>XML par défaut</translation> </message> <message> <source>Tag</source> <translation>Balise</translation> </message> <message> <source>Unknown tag</source> <translation>Balise inconnue</translation> </message> <message> <source>Attribute</source> <translation>Attribut</translation> </message> <message> <source>Unknown attribute</source> <translation>Attribut inconnu</translation> </message> <message> <source>XML number</source> <translation>Nombre XML</translation> </message> <message> <source>XML double-quoted string</source> <translation>Chaîne de caractères XML (guillemets doubles)</translation> </message> <message> <source>XML single-quoted string</source> <translation>Chaîne de caractères XML (guillemets simples)</translation> </message> <message> <source>Other text in a tag</source> <translation>Autre texte dans les balises</translation> </message> <message> <source>XML comment</source> <translation>Commentaire XML</translation> </message> <message> <source>Entity</source> <translation>Entité</translation> </message> <message> <source>End of a tag</source> <translation>Balise fermante</translation> </message> <message> <source>Start of an XML fragment</source> <translation>Début de block XML</translation> </message> <message> <source>End of an XML fragment</source> <translation>Fin de block XML</translation> </message> <message> <source>Script tag</source> <translation>Balise de script</translation> </message> <message> <source>Start of an ASP fragment with @</source> <translation>Début de block ASP avec @</translation> </message> <message> <source>Start of an ASP fragment</source> <translation>Début de block ASP</translation> </message> <message> <source>CDATA</source> <translation>CDATA</translation> </message> <message> <source>Start of a PHP fragment</source> <translation>Début de block PHP</translation> </message> <message> <source>Unquoted XML value</source> <translation>Valeur XML sans guillemets</translation> </message> <message> <source>ASP X-Code comment</source> <translation>Commentaire X-Code ASP</translation> </message> <message> <source>SGML default</source> <translation>SGML par défaut</translation> </message> <message> <source>SGML command</source> <translation>Commande SGML</translation> </message> <message> <source>First parameter of an SGML command</source> <translation>Premier paramètre de commande SGML</translation> </message> <message> <source>SGML double-quoted string</source> <translation>Chaîne de caractères SGML (guillemets doubles)</translation> </message> <message> <source>SGML single-quoted string</source> <translation>Chaîne de caractères SGML (guillemets simples)</translation> </message> <message> <source>SGML error</source> <translation>Erreur SGML</translation> </message> <message> <source>SGML special entity</source> <translation>Entité SGML spéciale</translation> </message> <message> <source>SGML comment</source> <translation>Commentaire SGML</translation> </message> <message> <source>First parameter comment of an SGML command</source> <translation>Premier paramètre de commentaire de commande SGML</translation> </message> <message> <source>SGML block default</source> <translation>Block SGML par défaut</translation> </message> <message> <source>Start of a JavaScript fragment</source> <translation>Début de block JavaScript</translation> </message> <message> <source>JavaScript default</source> <translation>JavaScript par défaut</translation> </message> <message> <source>JavaScript comment</source> <translation>Commentaire JavaScript</translation> </message> <message> <source>JavaScript line comment</source> <translation>Commentaire de ligne JavaScript</translation> </message> <message> <source>JavaDoc style JavaScript comment</source> <translation>Commentaire JavaScript de style JavaDoc</translation> </message> <message> <source>JavaScript number</source> <translation>Nombre JavaScript</translation> </message> <message> <source>JavaScript word</source> <translation>Mot JavaScript</translation> </message> <message> <source>JavaScript keyword</source> <translation>Mot-clé JavaScript</translation> </message> <message> <source>JavaScript double-quoted string</source> <translation>Chaîne de caractères JavaScript (guillemets doubles)</translation> </message> <message> <source>JavaScript single-quoted string</source> <translation>Chaîne de caractères JavaScript (guillemets simples)</translation> </message> <message> <source>JavaScript symbol</source> <translation>Symbole JavaScript</translation> </message> <message> <source>JavaScript unclosed string</source> <translation>Chaîne de caractères JavaScript non refermée</translation> </message> <message> <source>JavaScript regular expression</source> <translation>Expression régulière JavaScript</translation> </message> <message> <source>Start of an ASP JavaScript fragment</source> <translation>Début de block JavaScript ASP</translation> </message> <message> <source>ASP JavaScript default</source> <translation>JavaScript ASP par défaut</translation> </message> <message> <source>ASP JavaScript comment</source> <translation>Commentaire JavaScript ASP</translation> </message> <message> <source>ASP JavaScript line comment</source> <translation>Commentaire de ligne JavaScript ASP</translation> </message> <message> <source>JavaDoc style ASP JavaScript comment</source> <translation>Commentaire JavaScript ASP de style JavaDoc</translation> </message> <message> <source>ASP JavaScript number</source> <translation>Nombre JavaScript ASP</translation> </message> <message> <source>ASP JavaScript word</source> <translation>Mot JavaScript ASP</translation> </message> <message> <source>ASP JavaScript keyword</source> <translation>Mot-clé JavaScript ASP </translation> </message> <message> <source>ASP JavaScript double-quoted string</source> <translation>Chaîne de caractères JavaScript ASP (guillemets doubles)</translation> </message> <message> <source>ASP JavaScript single-quoted string</source> <translation>Chaîne de caractères JavaScript ASP (guillemets simples)</translation> </message> <message> <source>ASP JavaScript symbol</source> <translation>Symbole JavaScript ASP</translation> </message> <message> <source>ASP JavaScript unclosed string</source> <translation>Chaîne de caractères JavaScript ASP non refermée</translation> </message> <message> <source>ASP JavaScript regular expression</source> <translation>Expression régulière JavaScript ASP</translation> </message> <message> <source>Start of a VBScript fragment</source> <translation>Début de block VBScript</translation> </message> <message> <source>VBScript default</source> <translation>VBScript par défaut</translation> </message> <message> <source>VBScript comment</source> <translation>Commentaire VBScript</translation> </message> <message> <source>VBScript number</source> <translation>Nombre VBScript</translation> </message> <message> <source>VBScript keyword</source> <translation>Mot-clé VBScript</translation> </message> <message> <source>VBScript string</source> <translation>Chaîne de caractères VBScript</translation> </message> <message> <source>VBScript identifier</source> <translation>Identificateur VBScript</translation> </message> <message> <source>VBScript unclosed string</source> <translation>Chaîne de caractères VBScript non refermée</translation> </message> <message> <source>Start of an ASP VBScript fragment</source> <translation>Début de block VBScript ASP</translation> </message> <message> <source>ASP VBScript default</source> <translation>VBScript ASP par défaut</translation> </message> <message> <source>ASP VBScript comment</source> <translation>Commentaire VBScript ASP</translation> </message> <message> <source>ASP VBScript number</source> <translation>Nombre VBScript ASP</translation> </message> <message> <source>ASP VBScript keyword</source> <translation>Mot-clé VBScript ASP </translation> </message> <message> <source>ASP VBScript string</source> <translation>Chaîne de caractères VBScript ASP</translation> </message> <message> <source>ASP VBScript identifier</source> <translation>Identificateur VBScript ASP</translation> </message> <message> <source>ASP VBScript unclosed string</source> <translation>Chaîne de caractères VBScript ASP non refermée</translation> </message> <message> <source>Start of a Python fragment</source> <translation>Début de block Python</translation> </message> <message> <source>Python default</source> <translation>Python par défaut</translation> </message> <message> <source>Python comment</source> <translation>Commentaire Python</translation> </message> <message> <source>Python number</source> <translation>Nombre Python</translation> </message> <message> <source>Python double-quoted string</source> <translation>Chaîne de caractères Python (guillemets doubles)</translation> </message> <message> <source>Python single-quoted string</source> <translation>Chaîne de caractères Python (guillemets simples)</translation> </message> <message> <source>Python keyword</source> <translation>Mot-clé Python</translation> </message> <message> <source>Python triple double-quoted string</source> <translation>Chaîne de caractères Python (triples guillemets doubles)</translation> </message> <message> <source>Python triple single-quoted string</source> <translation>Chaîne de caractères Python (triples guillemets simples)</translation> </message> <message> <source>Python class name</source> <translation>Nom de classe Python</translation> </message> <message> <source>Python function or method name</source> <translation>Méthode ou fonction Python</translation> </message> <message> <source>Python operator</source> <translation>Opérateur Python</translation> </message> <message> <source>Python identifier</source> <translation>Identificateur Python</translation> </message> <message> <source>Start of an ASP Python fragment</source> <translation>Début de block Python ASP</translation> </message> <message> <source>ASP Python default</source> <translation>Python ASP par défaut</translation> </message> <message> <source>ASP Python comment</source> <translation>Commentaire Python ASP</translation> </message> <message> <source>ASP Python number</source> <translation>Nombre Python ASP</translation> </message> <message> <source>ASP Python double-quoted string</source> <translation>Chaîne de caractères Python ASP (guillemets doubles)</translation> </message> <message> <source>ASP Python single-quoted string</source> <translation>Chaîne de caractères Python ASP (guillemets simples)</translation> </message> <message> <source>ASP Python keyword</source> <translation>Mot-clé Python ASP</translation> </message> <message> <source>ASP Python triple double-quoted string</source> <translation>Chaîne de caractères Python ASP (triples guillemets doubles)</translation> </message> <message> <source>ASP Python triple single-quoted string</source> <translation>Chaîne de caractères Python ASP (triples guillemets simples)</translation> </message> <message> <source>ASP Python class name</source> <translation>Nom de classe Python ASP</translation> </message> <message> <source>ASP Python function or method name</source> <translation>Méthode ou fonction Python ASP</translation> </message> <message> <source>ASP Python operator</source> <translation>Opérateur Python ASP</translation> </message> <message> <source>ASP Python identifier</source> <translation>Identificateur Python ASP</translation> </message> <message> <source>PHP default</source> <translation>PHP par défaut</translation> </message> <message> <source>PHP double-quoted string</source> <translation>Chaîne de caractères PHP (guillemets doubles)</translation> </message> <message> <source>PHP single-quoted string</source> <translation>Chaîne de caractères PHP (guillemets simples)</translation> </message> <message> <source>PHP keyword</source> <translation>Mot-clé PHP</translation> </message> <message> <source>PHP number</source> <translation>Nombre PHP</translation> </message> <message> <source>PHP variable</source> <translation>Variable PHP</translation> </message> <message> <source>PHP comment</source> <translation>Commentaire PHP</translation> </message> <message> <source>PHP line comment</source> <translation>Commentaire de ligne PHP</translation> </message> <message> <source>PHP double-quoted variable</source> <translation>Variable PHP (guillemets doubles)</translation> </message> <message> <source>PHP operator</source> <translation>Opérateur PHP</translation> </message> </context> </TS>
gpl-3.0
flikas/WinAuth7
WinAuth7/BouncyCastle/src/bcpg/ElGamalSecretBcpgKey.cs
1019
using System; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Bcpg { /// <remarks>Base class for an ElGamal secret key.</remarks> public class ElGamalSecretBcpgKey : BcpgObject, IBcpgKey { internal MPInteger x; /** * @param in */ public ElGamalSecretBcpgKey( BcpgInputStream bcpgIn) { this.x = new MPInteger(bcpgIn); } /** * @param x */ public ElGamalSecretBcpgKey( BigInteger x) { this.x = new MPInteger(x); } /// <summary>The format, as a string, always "PGP".</summary> public string Format { get { return "PGP"; } } public BigInteger X { get { return x.Value; } } /// <summary>Return the standard PGP encoding of the key.</summary> public override byte[] GetEncoded() { try { return base.GetEncoded(); } catch (Exception) { return null; } } public override void Encode( BcpgOutputStream bcpgOut) { bcpgOut.WriteObject(x); } } }
gpl-3.0
collectiveaccess/pawtucket2
vendor/hoa/event/Test/Unit/Event.php
9528
<?php /** * Hoa * * * @license * * New BSD License * * Copyright © 2007-2017, Hoa community. 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 the Hoa nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND 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. */ namespace Hoa\Event\Test\Unit; use Hoa\Event as LUT; use Hoa\Event\Event as SUT; use Hoa\Test; /** * Class \Hoa\Event\Test\Unit\Event. * * Test suite of the event class. * * @copyright Copyright © 2007-2017 Hoa community * @license New BSD License */ class Event extends Test\Unit\Suite { public function case_multiton() { $this ->given($eventId = 'hoa://Event/Test') ->when($result = SUT::getEvent($eventId)) ->then ->object($result) ->isInstanceOf('Hoa\Event\Event') ->object(SUT::getEvent($eventId)) ->isIdenticalTo($result); } public function case_register_source_instance() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source() ) ->when($result = SUT::register($eventId, $source)) ->then ->variable($result) ->isNull() ->boolean(SUT::eventExists($eventId)) ->isTrue(); } public function case_register_source_name() { $this ->given( $eventId = 'hoa://Event/Test', $source = 'Mock\Hoa\Event\Source' ) ->when($result = SUT::register($eventId, $source)) ->then ->variable($result) ->isNull() ->boolean(SUT::eventExists($eventId)) ->isTrue(); } public function case_register_redeclare() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), SUT::register($eventId, $source) ) ->exception(function () use ($eventId, $source) { SUT::register($eventId, $source); }) ->isInstanceOf('Hoa\Event\Exception'); } public function case_register_not_a_source_instance() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \StdClass() ) ->exception(function () use ($eventId, $source) { $result = SUT::register($eventId, $source); }) ->isInstanceOf('Hoa\Event\Exception'); } public function case_register_not_a_source_name() { $this ->given( $eventId = 'hoa://Event/Test', $source = 'StdClass' ) ->exception(function () use ($eventId, $source) { $result = SUT::register($eventId, $source); }) ->isInstanceOf('Hoa\Event\Exception'); } public function case_unregister() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), SUT::register($eventId, $source) ) ->when($result = SUT::unregister($eventId)) ->then ->boolean(SUT::eventExists($eventId)) ->isFalse(); } public function case_unregister_hard() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), SUT::register($eventId, $source), $event = SUT::getEvent($eventId) ) ->when($result = SUT::unregister($eventId, true)) ->then ->boolean(SUT::eventExists($eventId)) ->isFalse() ->object(SUT::getEvent($eventId)) ->isNotIdenticalTo($event); } public function case_unregister_not_registered() { $this ->given($eventId = 'hoa://Event/Test') ->when($result = SUT::unregister($eventId)) ->then ->variable($result) ->isNull(); } public function case_attach() { $this ->given( $event = SUT::getEvent('hoa://Event/Test'), $callable = function () { } ) ->when($result = $event->attach($callable)) ->then ->object($result) ->isIdenticalTo($event) ->boolean($event->isListened()) ->isTrue(); } public function case_detach() { $this ->given( $event = SUT::getEvent('hoa://Event/Test'), $callable = function () { }, $event->attach($callable) ) ->when($result = $event->detach($callable)) ->then ->object($result) ->isIdenticalTo($event) ->boolean($event->isListened()) ->isFalse(); } public function case_detach_unattached() { $this ->given( $event = SUT::getEvent('hoa://Event/Test'), $callable = function () { } ) ->when($result = $event->detach($callable)) ->then ->object($result) ->isIdenticalTo($event) ->boolean($event->isListened()) ->isFalse(); } public function case_is_listened() { $this ->given($event = SUT::getEvent('hoa://Event/Test')) ->when($result = $event->isListened()) ->then ->boolean($event->isListened()) ->isFalse(); } public function case_notify() { $self = $this; $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), $bucket = new LUT\Bucket(), SUT::register($eventId, $source), SUT::getEvent($eventId)->attach( function (LUT\Bucket $receivedBucket) use ($self, $source, $bucket, &$called) { $called = true; $this ->object($receivedBucket) ->isIdenticalTo($bucket) ->object($receivedBucket->getSource()) ->isIdenticalTo($source); } ) ) ->when($result = SUT::notify($eventId, $source, $bucket)) ->then ->variable($result) ->isNull() ->boolean($called) ->isTrue(); } public function case_notify_unregistered_event_id() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), $data = new LUT\Bucket() ) ->exception(function () use ($eventId, $source, $data) { SUT::notify($eventId, $source, $data); }) ->isInstanceOf('Hoa\Event\Exception'); } public function case_event_exists() { $this ->given( $eventId = 'hoa://Event/Test', $source = new \Mock\Hoa\Event\Source(), SUT::register($eventId, $source) ) ->when($result = SUT::eventExists($eventId)) ->then ->boolean($result) ->isTrue(); } public function case_event_not_exists() { $this ->given($eventId = 'hoa://Event/Test') ->when($result = SUT::eventExists($eventId)) ->then ->boolean($result) ->isFalse(); } }
gpl-3.0
ThinkUpLLC/ThinkUp
webapp/plugins/insightsgenerator/tests/TestOfOutreachPunchcardInsight.php
18997
<?php /** * * ThinkUp/webapp/plugins/insightsgenerator/tests/TestOfOutreachPunchcardInsight.php * * Copyright (c) 2013 Nilaksh Das, Gina Trapani * * LICENSE: * * This file is part of ThinkUp (http://thinkup.com). * * ThinkUp 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. * * ThinkUp 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 ThinkUp. If not, see * <http://www.gnu.org/licenses/>. * * Test of Outreach Punchcard Insight * * Test for OutreachPunchcardInsight class. * * @license http://www.gnu.org/licenses/gpl.html * @copyright 2013 Nilaksh Das, Gina Trapani * @author Nilaksh Das <nilakshdas [at] gmail [dot] com> */ require_once dirname(__FILE__) . '/../../../../tests/init.tests.php'; require_once THINKUP_WEBAPP_PATH.'_lib/extlib/simpletest/autorun.php'; require_once THINKUP_WEBAPP_PATH.'_lib/extlib/simpletest/web_tester.php'; require_once THINKUP_WEBAPP_PATH.'config.inc.php'; require_once THINKUP_ROOT_PATH. 'webapp/plugins/insightsgenerator/model/class.InsightPluginParent.php'; require_once THINKUP_ROOT_PATH. 'webapp/plugins/insightsgenerator/insights/outreachpunchcard.php'; class TestOfOutreachPunchcardInsight extends ThinkUpInsightUnitTestCase { public function setUp(){ parent::setUp(); } public function tearDown() { parent::tearDown(); } public function testOutreachPunchcardInsightTwitter() { $cfg = Config::getInstance(); $install_timezone = new DateTimeZone($cfg->getValue('timezone')); $owner_timezone = new DateTimeZone($test_timezone='America/Los_Angeles'); $now = new DateTime(); $offset = timezone_offset_get($owner_timezone, $now) - timezone_offset_get($install_timezone, $now); // Get data ready that insight requires $builders = array(); $posts = self::getTestPostObjects(); $post_arrays = self::getTestPostArrays(); foreach ($post_arrays as $post_array) { $builders[] = FixtureBuilder::build('posts', $post_array); } $builders[] = FixtureBuilder::build('users', array('user_id'=>'7654321', 'user_name'=>'twitteruser', 'full_name'=>'Twitter User', 'avatar'=>'avatar.jpg', 'follower_count'=>36000, 'is_protected'=>0, 'network'=>'twitter', 'description'=>'A test Twitter User')); $instance_id = 10; $builders[] = FixtureBuilder::build('owners', array('id'=>1, 'full_name'=>'ThinkUp J. User', 'email'=>'test@example.com', 'is_activated'=>1, 'email_notification_frequency' => 'never', 'is_admin' => 0, 'timezone' => $test_timezone)); $builders[] = FixtureBuilder::build('owner_instances', array('owner_id'=>'1','instance_id'=>$instance_id)); $install_offset = $install_timezone->getOffset(new DateTime()); $date_r = date("Y-m-d",strtotime('-1 day')-$install_offset); // Response between 1pm and 2pm install time $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:11:09')); $builders[] = FixtureBuilder::build('posts', array('id'=>136, 'post_id'=>136, 'author_user_id'=>7654321, 'author_username'=>'twitteruser', 'author_fullname'=>'Twitter User', 'author_avatar'=>'avatar.jpg', 'network'=>'twitter', 'post_text'=>'This is a reply.', 'source'=>'web', 'pub_date'=>$time, 'in_reply_to_post_id'=>133, 'reply_count_cache'=>0, 'is_protected'=>0)); // Response between 1pm and 2pm install time $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:01:13')); $builders[] = FixtureBuilder::build('posts', array('id'=>137, 'post_id'=>137, 'author_user_id'=>7654321, 'author_username'=>'twitteruser', 'author_fullname'=>'Twitter User', 'author_avatar'=>'avatar.jpg', 'network'=>'twitter', 'post_text'=>'This is a reply.', 'source'=>'web', 'pub_date'=>$time, 'in_reply_to_post_id'=>133, 'reply_count_cache'=>0, 'is_protected'=>0)); // Response between 1pm and 2pm install time $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:13:56')); $builders[] = FixtureBuilder::build('posts', array('id'=>138, 'post_id'=>138, 'author_user_id'=>7654321, 'author_username'=>'twitteruser', 'author_fullname'=>'Twitter User', 'author_avatar'=>'avatar.jpg', 'network'=>'twitter', 'post_text'=>'This is a reply.', 'source'=>'web', 'pub_date'=>$time, 'in_reply_to_post_id'=>135, 'reply_count_cache'=>0, 'is_protected'=>0)); // Response between 11am and 12pm install time $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 11:07:42')); $builders[] = FixtureBuilder::build('posts', array('id'=>139, 'post_id'=>139, 'author_user_id'=>7654321, 'author_username'=>'twitteruser', 'author_fullname'=>'Twitter User', 'author_avatar'=>'avatar.jpg', 'network'=>'twitter', 'source'=>'web', 'post_text'=>'RT @testeriffic: New Year\'s Eve! Feeling very gay today, but not very homosexual.', 'pub_date'=>$time, 'in_retweet_of_post_id'=>134, 'reply_count_cache'=>0, 'is_protected'=>0)); $around_time = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_low = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_high = date('ga', (date('U', strtotime($date_r.' 14:00:00')) + $offset)); $time1str = $time1str_low." and ".$time1str_high; $time2str_low = date('ga', (date('U', strtotime($date_r.' 11:00:00')) + $offset)); $time2str_high = date('ga', (date('U', strtotime($date_r.' 12:00:00')) + $offset)); $time2str = $time2str_low." and ".$time2str_high; $instance = new Instance(); $instance->id = $instance_id; $instance->network_username = 'testeriffic'; $instance->network = 'twitter'; $insight_plugin = new OutreachPunchcardInsight(); $insight_plugin->generateInsight($instance, null, $posts, 3); // Assert that insight got inserted with correct punchcard information $insight_dao = new InsightMySQLDAO(); $today = date ('Y-m-d'); $result = $insight_dao->getInsight('outreach_punchcard', 10, $today); //$this->debug(Utils::varDumpToString($result)); $this->assertNotNull($result); $this->assertIsA($result, "Insight"); $this->assertPattern("/\@testeriffic's best time is around $around_time/", $result->headline); $this->assertPattern('/between <strong>'.$time1str.'<\/strong> - 3 replies in all/', $result->text); $this->assertPattern('/That\'s compared to 1 response/', $result->text); $this->assertPattern('/1 response between '.$time2str.'/', $result->text); //Ugh, this number isn't serialized before it's stored, so we have to serialize it here //TODO: Refactor how this number is stored in related_data $result->related_data = serialize($result->related_data); $this->dumpRenderedInsight($result, $instance); } public function testOutreachPunchcardInsightInstagram() { $cfg = Config::getInstance(); $install_timezone = new DateTimeZone($cfg->getValue('timezone')); $owner_timezone = new DateTimeZone($test_timezone='America/Los_Angeles'); $now = new DateTime(); $offset = timezone_offset_get($owner_timezone, $now) - timezone_offset_get($install_timezone, $now); // Get data ready that insight requires $builders = array(); $posts = self::getTestPostObjects('instagram'); $post_arrays = self::getTestPostArrays('instagram'); foreach ($post_arrays as $post_array) { $builders[] = FixtureBuilder::build('posts', $post_array); } $builders[] = FixtureBuilder::build('users', array('user_id'=>'7654321', 'user_name'=>'instagramuser', 'full_name'=>'Instagram User', 'avatar'=>'avatar.jpg', 'follower_count'=>36000, 'is_protected'=>0, 'network'=>'instagram', 'description'=>'A test Instagram User')); $instance_id = 10; $builders[] = FixtureBuilder::build('owners', array('id'=>1, 'full_name'=>'ThinkUp J. User', 'email'=>'test@example.com', 'is_activated'=>1, 'email_notification_frequency' => 'never', 'is_admin' => 0, 'timezone' => $test_timezone)); $builders[] = FixtureBuilder::build('owner_instances', array('owner_id'=>'1','instance_id'=>$instance_id)); $install_offset = $install_timezone->getOffset(new DateTime()); $date_r = date("Y-m-d",strtotime('-1 day')-$install_offset); $around_time = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_low = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_high = date('ga', (date('U', strtotime($date_r.' 14:00:00')) + $offset)); $time1str = $time1str_low." and ".$time1str_high; $time2str_low = date('ga', (date('U', strtotime($date_r.' 17:00:00')) + $offset)); $time2str_high = date('ga', (date('U', strtotime($date_r.' 18:00:00')) + $offset)); $time2str = $time2str_low." and ".$time2str_high; $instance = new Instance(); $instance->id = $instance_id; $instance->network_username = 'testeriffic'; $instance->network = 'instagram'; $insight_plugin = new OutreachPunchcardInsight(); $insight_plugin->generateInsight($instance, null, $posts, 3); // Assert that insight got inserted with correct punchcard information $insight_dao = new InsightMySQLDAO(); $today = date ('Y-m-d'); $result = $insight_dao->getInsight('outreach_punchcard', 10, $today); //$this->debug(Utils::varDumpToString($result)); $this->assertNotNull($result); $this->assertIsA($result, "Insight"); $this->assertPattern("/testeriffic's best time is around $around_time/", $result->headline); $this->assertPattern('/between <strong>'.$time1str .'<\/strong> on Instagram got the most love - 30 likes in all/', $result->text); $this->assertPattern('/That\'s compared to 2 hearts/', $result->text); $this->assertPattern('/2 hearts between '.$time2str.'/', $result->text); //Ugh, this number isn't serialized before it's stored, so we have to serialize it here //TODO: Refactor how this number is stored in related_data $result->related_data = serialize($result->related_data); $this->dumpRenderedInsight($result, $instance); } public function testOutreachPunchcardInsightOneResponse() { $cfg = Config::getInstance(); $install_timezone = new DateTimeZone($cfg->getValue('timezone')); $owner_timezone = new DateTimeZone($test_timezone='America/Los_Angeles'); // Get data ready that insight requires $builders = array(); $posts = self::getTestPostObjects(); $post_arrays = self::getTestPostArrays(); foreach ($post_arrays as $post_array) { $builders[] = FixtureBuilder::build('posts', $post_array); } $post_pub_date = new DateTime($posts[0]->pub_date); $now = new DateTime(); $offset = timezone_offset_get($owner_timezone, $now) - timezone_offset_get($install_timezone, $now); $post_dotw = date('N', (date('U', strtotime($posts[0]->pub_date)))+ timezone_offset_get($owner_timezone, $now)); $post_hotd = date('G', (date('U', strtotime($posts[0]->pub_date)))+ timezone_offset_get($owner_timezone, $now)); $builders[] = FixtureBuilder::build('users', array('user_id'=>'7654321', 'user_name'=>'twitteruser', 'full_name'=>'Twitter User', 'avatar'=>'avatar.jpg', 'follower_count'=>36000, 'is_protected'=>0, 'network'=>'twitter', 'description'=>'A test Twitter User')); $instance_id = 10; $builders[] = FixtureBuilder::build('owners', array('id'=>1, 'full_name'=>'ThinkUp J. User', 'email'=>'test@example.com', 'is_activated'=>1, 'email_notification_frequency' => 'never', 'is_admin' => 0, 'timezone' => $test_timezone)); $builders[] = FixtureBuilder::build('owner_instances', array('owner_id'=>'1','instance_id'=>$instance_id)); $install_offset = $install_timezone->getOffset(new DateTime()); $date_r = date("Y-m-d",strtotime('-1 day')-$install_offset); // Response between 1pm and 2pm install time $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:11:09')); $builders[] = FixtureBuilder::build('posts', array('id'=>136, 'post_id'=>136, 'author_user_id'=>7654321, 'author_username'=>'twitteruser', 'author_fullname'=>'Twitter User', 'author_avatar'=>'avatar.jpg', 'network'=>'twitter', 'post_text'=>'This is a reply.', 'source'=>'web', 'pub_date'=>$time, 'in_reply_to_post_id'=>133, 'reply_count_cache'=>0, 'is_protected'=>0)); $around_time = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_low = date('ga', (date('U', strtotime($date_r.' 13:00:00')) + $offset)); $time1str_high = date('ga', (date('U', strtotime($date_r.' 14:00:00')) + $offset)); $time1str = $time1str_low." and ".$time1str_high; $time2str_low = date('ga', (date('U', strtotime($date_r.' 11:00:00')) + $offset)); $time2str_high = date('ga', (date('U', strtotime($date_r.' 12:00:00')) + $offset)); $time2str = $time2str_low." and ".$time2str_high; $instance = new Instance(); $instance->id = $instance_id; $instance->network_username = 'Tester Person'; $instance->network = 'facebook'; $insight_plugin = new OutreachPunchcardInsight(); $insight_plugin->generateInsight($instance, null, $posts, 3); // Assert that insight did not got inserted for less than 2 responses $insight_dao = new InsightMySQLDAO(); $today = date ('Y-m-d'); $result = $insight_dao->getInsight('outreach_punchcard', 10, $today); $this->debug(Utils::varDumpToString($result)); $this->assertNull($result); } public function testOutreachPunchcardInsightNoResponse() { $instance_id = 10; $builders[] = FixtureBuilder::build('owners', array('id'=>1, 'full_name'=>'ThinkUp J. User', 'email'=>'test@example.com', 'is_activated'=>1, 'email_notification_frequency' => 'never', 'is_admin' => 0, 'timezone' => 'UTC')); $builders[] = FixtureBuilder::build('owner_instances', array('owner_id'=>'1','instance_id'=>$instance_id)); // Get data ready that insight requires $posts = self::getTestPostObjects(); $instance = new Instance(); $instance->id = 10; $instance->network_username = 'testeriffic'; $instance->network = 'twitter'; $insight_plugin = new OutreachPunchcardInsight(); $insight_plugin->generateInsight($instance, null, $posts, 3); // Assert that insight did not got inserted for no responses $insight_dao = new InsightMySQLDAO(); $today = date ('Y-m-d'); $result = $insight_dao->getInsight('outreach_punchcard', 10, $today); $this->debug(Utils::varDumpToString($result)); $this->assertNull($result); } /** * Get test post objects * @return array of post objects for use in testing */ private function getTestPostObjects($network = 'twitter') { $post_text_arr = array(); $post_text_arr[] = "Now that I'm back on Android, realizing just how under sung Google Now is. ". "I want it everywhere."; $post_text_arr[] = "New Year's Eve! Feeling very gay today, but not very homosexual."; $post_text_arr[] = "When @anildash told me he was writing this I was ". "like 'yah whatever cool' then I read it and it knocked my socks off http://bit.ly/W9ASnj "; $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:11:09')); $posts = array(); $counter = 133; foreach ($post_text_arr as $test_text) { $p = new Post(); $p->post_id = $counter++; $p->network = $network; $p->post_text = $test_text; $p->favlike_count_cache = 10; if ($network == 'instagram') { $p->pub_date = $time; } else { $p->pub_date = gmdate("Y-m-d H:i:s", strtotime('-2 days')); } $posts[] = $p; } if ($network == 'instagram') { $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 17:11:09')); $p = new Post(); $p->post_id = $counter++; $p->network = $network; $p->post_text = $test_text; $p->favlike_count_cache = 2; $p->pub_date = $time; $posts[] = $p; } return $posts; } /** * Get test post arrays * @return array of post value arrays */ private function getTestPostArrays($network = 'twitter') { $post_text_arr = array(); $post_text_arr[] = "Now that I'm back on Android, realizing just how under sung Google Now is. ". "I want it everywhere."; $post_text_arr[] = "New Year's Eve! Feeling very gay today, but not very homosexual."; $post_text_arr[] = "When @anildash told me he was writing this I was ". "like 'yah whatever cool' then I read it and it knocked my socks off http://bit.ly/W9ASnj "; $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 13:11:09')); $posts = array(); $counter = 133; foreach ($post_text_arr as $test_text) { $post = array(); $post['post_id'] = $counter++; $post['network'] = $network; $post['author_username'] = 'testeriffic'; $post['favlike_count_cache'] = 10; $post['post_text'] = $test_text; if ($network == 'instagram') { $post['pub_date'] = $time; } else { $post['pub_date'] = gmdate("Y-m-d H:i:s", strtotime('-2 days')); } $posts[] = $post; } if ($network == 'instagram') { $time = gmdate('Y-m-d H:i:s', strtotime('yesterday 17:11:09')); $post = array(); $post['post_id'] = $counter++; $post['network'] = $network; $post['author_username'] = 'testeriffic'; $post['post_text'] = 'asssimov'; $post['favlike_count_cache'] = 2; $post['pub_date'] = $time; $posts[] = $post; } return $posts; } }
gpl-3.0
danmar/cppcheck
test/bug-hunting/cve/CVE-2019-15939/precomp.hpp
2392
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/objdetect.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/core/ocl.hpp" #include "opencv2/core/private.hpp" #endif
gpl-3.0
LeChuckDE/open-expanse-pool
proxy/proto.go
816
package proxy import "encoding/json" type JSONRpcReq struct { Id *json.RawMessage `json:"id"` Method string `json:"method"` Params *json.RawMessage `json:"params"` } type StratumReq struct { JSONRpcReq Worker string `json:"worker"` } // Stratum type JSONPushMessage struct { // FIXME: Temporarily add ID for Claymore compliance Id int64 `json:"id"` Version string `json:"jsonrpc"` Result interface{} `json:"result"` } type JSONRpcResp struct { Id *json.RawMessage `json:"id"` Version string `json:"jsonrpc"` Result interface{} `json:"result"` Error interface{} `json:"error,omitempty"` } type SubmitReply struct { Status string `json:"status"` } type ErrorReply struct { Code int `json:"code"` Message string `json:"message"` }
gpl-3.0
ebukoz/thrive
erpnext/manufacturing/doctype/workstation/workstation.py
4451
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from erpnext.support.doctype.issue.issue import get_holidays from frappe.utils import (flt, cint, getdate, formatdate, comma_and, time_diff_in_seconds, to_timedelta, add_days) from frappe.model.document import Document from dateutil.parser import parse class WorkstationHolidayError(frappe.ValidationError): pass class NotInWorkingHoursError(frappe.ValidationError): pass class OverlapError(frappe.ValidationError): pass class Workstation(Document): def validate(self): self.hour_rate = (flt(self.hour_rate_labour) + flt(self.hour_rate_electricity) + flt(self.hour_rate_consumable) + flt(self.hour_rate_rent)) def on_update(self): self.validate_overlap_for_operation_timings() self.update_bom_operation() def validate_overlap_for_operation_timings(self): """Check if there is no overlap in setting Workstation Operating Hours""" for d in self.get("working_hours"): existing = frappe.db.sql_list("""select idx from `tabWorkstation Working Hour` where parent = %s and name != %s and ( (start_time between %s and %s) or (end_time between %s and %s) or (%s between start_time and end_time)) """, (self.name, d.name, d.start_time, d.end_time, d.start_time, d.end_time, d.start_time)) if existing: frappe.throw(_("Row #{0}: Timings conflicts with row {1}").format(d.idx, comma_and(existing)), OverlapError) def update_bom_operation(self): bom_list = frappe.db.sql("""select DISTINCT parent from `tabBOM Operation` where workstation = %s""", self.name) for bom_no in bom_list: frappe.db.sql("""update `tabBOM Operation` set hour_rate = %s where parent = %s and workstation = %s""", (self.hour_rate, bom_no[0], self.name)) def validate_workstation_holiday(self, schedule_date, skip_holiday_list_check=False): if not skip_holiday_list_check and (not self.holiday_list or cint(frappe.db.get_single_value("Manufacturing Settings", "allow_production_on_holidays"))): return schedule_date if schedule_date in tuple(get_holidays(self.holiday_list)): schedule_date = add_days(schedule_date, 1) self.validate_workstation_holiday(schedule_date, skip_holiday_list_check=True) return schedule_date @frappe.whitelist() def get_default_holiday_list(): return frappe.get_cached_value('Company', frappe.defaults.get_user_default("Company"), "default_holiday_list") def check_if_within_operating_hours(workstation, operation, from_datetime, to_datetime): if from_datetime and to_datetime: if not cint(frappe.db.get_value("Manufacturing Settings", "None", "allow_production_on_holidays")): check_workstation_for_holiday(workstation, from_datetime, to_datetime) if not cint(frappe.db.get_value("Manufacturing Settings", None, "allow_overtime")): is_within_operating_hours(workstation, operation, from_datetime, to_datetime) def is_within_operating_hours(workstation, operation, from_datetime, to_datetime): operation_length = time_diff_in_seconds(to_datetime, from_datetime) workstation = frappe.get_doc("Workstation", workstation) if not workstation.working_hours: return for working_hour in workstation.working_hours: if working_hour.start_time and working_hour.end_time: slot_length = (to_timedelta(working_hour.end_time or "") - to_timedelta(working_hour.start_time or "")).total_seconds() if slot_length >= operation_length: return frappe.throw(_("Operation {0} longer than any available working hours in workstation {1}, break down the operation into multiple operations").format(operation, workstation.name), NotInWorkingHoursError) def check_workstation_for_holiday(workstation, from_datetime, to_datetime): holiday_list = frappe.db.get_value("Workstation", workstation, "holiday_list") if holiday_list and from_datetime and to_datetime: applicable_holidays = [] for d in frappe.db.sql("""select holiday_date from `tabHoliday` where parent = %s and holiday_date between %s and %s """, (holiday_list, getdate(from_datetime), getdate(to_datetime))): applicable_holidays.append(formatdate(d[0])) if applicable_holidays: frappe.throw(_("Workstation is closed on the following dates as per Holiday List: {0}") .format(holiday_list) + "\n" + "\n".join(applicable_holidays), WorkstationHolidayError)
gpl-3.0
hmorrin/uk.ac.nsamr.journal
jsamr/lib/pkp/classes/note/NoteDAO.inc.php
7236
<?php /** * @file classes/note/NoteDAO.inc.php * * Copyright (c) 2014-2016 Simon Fraser University Library * Copyright (c) 2000-2016 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @class NoteDAO * @ingroup note * @see Note * * @brief Operations for retrieving and modifying Note objects. */ import('lib.pkp.classes.note.Note'); define('NOTE_ORDER_DATE_CREATED', 0x0001); define('NOTE_ORDER_ID', 0x0002); class NoteDAO extends DAO { /** * Constructor. */ function __construct() { parent::__construct(); } /** * Create a new data object * @return Note */ function newDataObject() { return new Note(); } /** * Retrieve Note by note id * @param $noteId int Note ID * @return Note object */ function getById($noteId) { $result = $this->retrieve( 'SELECT * FROM notes WHERE note_id = ?', (int) $noteId ); $note = $this->_fromRow($result->GetRowAssoc(false)); $result->Close(); return $note; } /** * Retrieve Notes by user id * @param $userId int User ID * @param $rangeInfo DBResultRange Optional * @return object DAOResultFactory containing matching Note objects */ function getByUserId($userId, $rangeInfo = null) { $result = $this->retrieveRange( 'SELECT * FROM notes WHERE user_id = ? ORDER BY date_created DESC', array((int) $userId), $rangeInfo ); return new DAOResultFactory($result, $this, '_fromRow'); } /** * Retrieve Notes by assoc id/type * @param $assocId int ASSOC_TYPE_... * @param $assocType int Assoc ID (per $assocType) * @param $userId int Optional user ID * @param $orderBy int Optional sorting field constant: NOTE_ORDER_... * @param $sortDirection int Optional sorting order constant: SORT_DIRECTION_... * @return object DAOResultFactory containing matching Note objects */ function getByAssoc($assocType, $assocId, $userId = null, $orderBy = NOTE_ORDER_DATE_CREATED, $sortDirection = SORT_DIRECTION_DESC, $isAdmin = false) { $params = array((int) $assocId, (int) $assocType); if ($userId) $params[] = (int) $userId; // Sanitize sort ordering switch ($orderBy) { case NOTE_ORDER_ID: $orderSanitized = 'note_id'; break; case NOTE_ORDER_DATE_CREATED: default: $orderSanitized = 'date_created'; } switch ($sortDirection) { case SORT_DIRECTION_ASC: $directionSanitized = 'ASC'; break; case SORT_DIRECTION_DESC: default: $directionSanitized = 'DESC'; } $result = $this->retrieve( 'SELECT * FROM notes WHERE assoc_id = ? AND assoc_type = ? ' . ($userId?' AND user_id = ?':'') . ($isAdmin?'':' AND (title IS NOT NULL OR contents IS NOT NULL)') . ' ORDER BY ' . $orderSanitized . ' ' . $directionSanitized, $params ); return new DAOResultFactory($result, $this, '_fromRow'); } /** * Retrieve Notes by assoc id/type * @param $assocId int * @param $assocType int * @param $userId int * @return object DAOResultFactory containing matching Note objects */ function notesExistByAssoc($assocType, $assocId, $userId = null) { $params = array((int) $assocId, (int) $assocType); if ($userId) $params[] = (int) $userId; $result = $this->retrieve( 'SELECT COUNT(*) FROM notes WHERE assoc_id = ? AND assoc_type = ? ' . ($userId?' AND user_id = ?':''), $params ); $returner = isset($result->fields[0]) && $result->fields[0] == 0 ? false : true; $result->Close(); return $returner; } /** * Determine whether or not unread notes exist for a given association * @param $assocType int ASSOC_TYPE_... * @param $assocId int Foreign key, depending on ASSOC_TYPE * @param $userId int User ID */ function unreadNotesExistByAssoc($assocType, $assocId, $userId) { $params = array((int) $assocId, (int) $assocType, (int) $userId); $result = $this->retrieve( 'SELECT COUNT(*) FROM notes n JOIN item_views v ON (v.assoc_type = ? AND v.assoc_id = CAST(n.note_id AS CHAR) AND v.user_id = ?) WHERE n.assoc_type = ? AND n.assoc_id = ? AND v.assoc_id IS NULL', array( (int) ASSOC_TYPE_NOTE, (int) $userId, (int) $assocType, (int) $assocId ) ); $returner = isset($result->fields[0]) && $result->fields[0] == 0 ? false : true; $result->Close(); return $returner; } /** * Creates and returns an note object from a row * @param $row array * @return Note object */ function _fromRow($row) { $note = $this->newDataObject(); $note->setId($row['note_id']); $note->setUserId($row['user_id']); $note->setDateCreated($this->datetimeFromDB($row['date_created'])); $note->setDateModified($this->datetimeFromDB($row['date_modified'])); $note->setContents($row['contents']); $note->setTitle($row['title']); $note->setAssocType($row['assoc_type']); $note->setAssocId($row['assoc_id']); HookRegistry::call('NoteDAO::_fromRow', array(&$note, &$row)); return $note; } /** * Inserts a new note into notes table * @param Note object * @return int Note Id */ function insertObject($note) { if (!$note->getDateCreated()) $note->setDateCreated(Core::getCurrentDate()); $this->update( sprintf('INSERT INTO notes (user_id, date_created, date_modified, title, contents, assoc_type, assoc_id) VALUES (?, %s, %s, ?, ?, ?, ?)', $this->datetimeToDB($note->getDateCreated()), $this->datetimeToDB(Core::getCurrentDate()) ), array( (int) $note->getUserId(), $note->getTitle(), $note->getContents(), (int) $note->getAssocType(), (int) $note->getAssocId() ) ); $note->setId($this->getInsertId()); return $note->getId(); } /** * Update a note in the notes table * @param Note object * @return int Note Id */ function updateObject($note) { return $this->update( sprintf('UPDATE notes SET user_id = ?, date_created = %s, date_modified = %s, title = ?, contents = ?, assoc_type = ?, assoc_id = ? WHERE note_id = ?', $this->datetimeToDB($note->getDateCreated()), $this->datetimeToDB(Core::getCurrentDate()) ), array( (int) $note->getUserId(), $note->getTitle(), $note->getContents(), (int) $note->getAssocType(), (int) $note->getAssocId(), (int) $note->getId() ) ); } /** * Delete a note by note object. * @param $note Note */ function deleteObject($note) { $this->deleteById($note->getId()); } /** * Delete Note by note id * @param $noteId int * @param $userId int optional */ function deleteById($noteId, $userId = null) { $params = array((int) $noteId); if ($userId) $params[] = (int) $userId; $this->update( 'DELETE FROM notes WHERE note_id = ?' . ($userId?' AND user_id = ?':''), $params ); } /** * Delete notes by association * @param $assocType int ASSOC_TYPE_... * @param $assocId int Foreign key, depending on $assocType */ function deleteByAssoc($assocType, $assocId) { $notes = $this->getByAssoc($assocType, $assocId); while ($note = $notes->next()) { $this->deleteObject($note); } } /** * Get the ID of the last inserted note * @return int */ function getInsertId() { return $this->_getInsertId('notes', 'note_id'); } } ?>
gpl-3.0
wfrog/wfrog
wfrender/renderer/openweathermap.py
9177
## Copyright 2013 Jordi Puigsegur <jordi.puigsegur@gmail.com> ## ## This file is part of wfrog ## ## wfrog 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/>. import math import logging import sys import time import httplib import urllib import base64 from wfcommon.formula.base import LastFormula from wfcommon.formula.base import SumFormula try: from wfrender.datasource.accumulator import AccumulatorDatasource except ImportError, e: from datasource.accumulator import AccumulatorDatasource class OpenWeatherMapPublisher(object): """ Render and publisher for www.openweathermap.org. Sends every record published to the storage to openweathermap API. [ Properties ] username [string]: Your openweathermap.org username. password [string]: Your openweathermap.org password. name[string]: Station name. latitude[numeric]: Station latitude (signed degrees format) longitude[numeric]: Station longitude (signed degrees format) altitude [numeric]: Station altitude in m. storage: The storage service. send_uv[boolean] (optional): Send UV data (by default false). send_radiation[boolean] (optional): Send radiation data (by default false). """ username = None password = None name = None longitude = None latitude = None altitude = None storage = None alive = False send_uv = False send_radiation = False logger = logging.getLogger("renderer.openweathermap") def render(self, data={}, context={}): try: assert self.username is not None, "'openweathermap.id' must be set" assert self.password is not None, "'openweathermap.password' must be set" assert self.name is not None, "'openweathermap.name' must be set" assert self.latitude is not None, "'openweathermap.latitude' must be set" assert self.longitude is not None, "'openweathermap.longitude' must be set" assert self.altitude is not None, "'openweathermap.altitude' must be set" self.logger.info("Initializing openweathermap.com (user %s)" % self.username) self.alive = True accu = AccumulatorDatasource() accu.slice = 'day' accu.span = 1 accu.storage = self.storage accu.formulas = {'current': { 'temp' : LastFormula('temp'), 'hum' : LastFormula('hum'), 'pressure' : LastFormula('pressure'), 'dew_point' : LastFormula('dew_point'), 'wind' : LastFormula('wind'), 'wind_gust' : LastFormula('wind_gust'), 'wind_deg' : LastFormula('wind_dir'), 'rain' : SumFormula('rain'), 'utctime' : LastFormula('utctime') } } if self.send_uv: accu.formulas['current']['uv'] = LastFormula('uv') if self.send_radiation: accu.formulas['current']['solar_rad'] = LastFormula('solar_rad') accu24h = AccumulatorDatasource() accu24h.slice = 'hour' accu24h.span = 24 accu24h.storage = self.storage accu24h.formulas = {'current': {'rain': SumFormula('rain')} } accu60min = AccumulatorDatasource() accu60min.slice = 'minute' accu60min.span = 60 accu60min.storage = self.storage accu60min.formulas = {'current': {'rain': SumFormula('rain')} } last_timestamp = None while self.alive: try: data = accu.execute()['current']['series'] index = len(data['lbl'])-1 rain_1h = sum(map(lambda x: x if x is not None else 0, accu60min.execute()['current']['series']['rain'][:60])) rain_24h = sum(map(lambda x: x if x is not None else 0, accu24h.execute()['current']['series']['rain'][:24])) if last_timestamp == None or last_timestamp < data['utctime'][index]: last_timestamp = data['utctime'][index] args = { 'wind_dir': int(round(data['wind_deg'][index])), # grad 'wind_speed': str(data['wind'][index]), # mps 'wind_gust': str(data['wind_gust'][index]), # mps 'temp': str(data['temp'][index]), # grad C #'dewpoint': str(data['dew_point'][index]), # NOT WORKING PROPERLY 'humidity': int(round(data['hum'][index])), # relative humidity % 'pressure': str(data['pressure'][index]), # mb 'rain_1h': rain_1h, # mm 'rain_24h': rain_24h, # mm 'rain_today': str(data['rain'][index]), # mm 'lat': self.latitude, 'long': self.longitude, 'alt': self.altitude, 'name': self.name } if self.send_uv: args['uv'] = str(data['uv'][index]) if self.send_radiation: args['lum'] = str(data['solar_rad'][index]) self.logger.debug("Publishing openweathermap data: %s " % urllib.urlencode(args)) response = self._publish(args, 'openweathermap.org', '/data/post') if response[0] == 200: self.logger.info('Data published successfully') self.logger.debug('Code: %s Status: %s Answer: %s' % response) else: self.logger.error('Error publishing data. Code: %s Status: %s Answer: %s' % response) except Exception, e: if (str(e) == "'NoneType' object has no attribute 'strftime'") or (str(e) == "a float is required"): self.logger.error('Could not publish: no valid values at this time. Retry next run...') else: self.logger.exception(e) time.sleep(60) # each minute we check for new records to send to openweathermap except Exception, e: self.logger.exception(e) raise def close(self): self.alive = False def _publish(self, args, server, uri): uri = uri + "?" + urllib.urlencode(args) self.logger.debug('Connect to: http://%s' % server) self.logger.debug('GET %s' % uri) auth = base64.encodestring("%s:%s" % (self.username, self.password)) conn = httplib.HTTPConnection(server) if not conn: raise Exception, 'Remote server connection timeout!' conn.request("GET", uri, headers = {"Authorization" : "Basic %s" % auth}) conn.sock.settimeout(30.0) # 30 seconds timeout http = conn.getresponse() data = (http.status, http.reason, http.read()) conn.close() if not (data[0] == 200 and data[1] == 'OK'): raise Exception, 'Server returned invalid status: %d %s %s' % data return data # http://openweathermap.org/wiki/API/data_upload # # Data upload API # # The protocol of weather station data transmission Version 1.0 # # This protocol is used for transmission of one measurement from a weather station. # The data is transmitted by HTTP POST request. The http basic authentication is used for authentication. # The server address is http://openweathermap.org/data/post # To connect your station, please register at http://OpenWeatherMap.org/login # The following parameters can be transmitted in POST: # # wind_dir - wind direction, grad # wind_speed - wind speed, mps # temp - temperature, grad C # humidity - relative humidity, % # pressure - atmosphere pressure # wind_gust - speed of wind gust, mps # rain_1h - rain in recent hour, mm # rain_24h - rain in recent 24 hours, mm # rain_today - rain today, mm # snow - snow in recent 24 hours, mm # lum - illumination, W/M2 # lat - latitude # long - longitude # alt - altitude, m # radiation - radiation # dewpoint - dewpoint # uv - UV index # name - station name
gpl-3.0
beppec56/core
qadevOOo/runner/lib/Status.java
4362
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package lib; /** * Status represents a result of a testing activity performed. The result is * described in two ways: state and runtime state. The state describes if the * activity was successful (OK state) or not (FAILED state). The runtime state * describes what happened during the activity: the test can be: * - COMPLETED - the activity completed normally (although it can complete with * FAILED state) * - SKIPPED - the activity was not performed because of a reason (it also can * has OK or FAILED state) * - EXCEPTION - the activity was abnormally terminated because of an * unexpected exception. It always has a FAILED state. * - EXCLUDED - the activity is expected to fail. The state represents how * the state really completed: OK or FAILED. * - other variants are not formalized now and can be represented by * Status.failed() method. They always have a FAILED state. */ public class Status extends SimpleStatus { /** * Construct a status: use runState and state * @param runState either COMPLETED, SKIPPED, etc. * @param bSuccessful OK or FAILED. */ public Status(RunState runState, boolean bSuccessful ) { super(runState, bSuccessful); } /** * Construct a status: use own message and state. * @param message An own message for the status. * @param bSuccessful OK or FAILED. */ public Status(String message, boolean state) { super( message, state ); } /** * This is a factory method for creating a Status representing normal * activity termination. * * @param bSuccessful describes a test state (OK if state == true, FAILED * otherwise). */ public static Status passed( boolean bSuccessful ) { return new Status(RunState.COMPLETED, bSuccessful ); } /** * This is a factory method for creating a Status representing an exception * activity termination. The Status always has FAILED state. * * @param t the exception with that the activity completed. */ public static Status exception( Throwable t ) { return new ExceptionStatus( t ); } /** * This is a factory method for creating a Status representing a skipped * activity. * * @param state describes a test state (OK if state == true, FAILED * otherwise). */ public static Status skipped( boolean bSuccessful ) { return new Status( RunState.SKIPPED, bSuccessful ); } /** * Creates a Status representing an activity failed for an arbitrary reason. * It always has FAILED state. * * @param reason describes why the activity failed */ public static Status failed(final String reason) { return new Status(reason, false/*bSuccessful*/); } /** * The method returns a human-readable description of the status. * The Status implementation of the method returns the status state * description and appends to it the reason, for example: * "FAILED.The getLabel works wrong", "COMPLETED.OK". */ @Override public String toString() { String str = getRunStateString() + "." + getStateString(); return str; } /** * Checks whether the status runstate is completed. */ public boolean isCompleted() { return getRunState() == RunState.COMPLETED; } /** * Checks whether the status state is failed. */ public boolean isFailed() { return !isSuccessful(); } }
gpl-3.0
saddieeiddas/Camelot-Unchained
library/src/components/ErrorBoundary.tsx
1660
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; export interface ErrorBoundaryProps { renderError?: (error: Error, info: { componentStack: string }) => (JSX.Element | React.ReactNode); reloadUIOnError?: boolean; onError?: (error: Error, info: { componentStack: string }) => void; outputErrorToConsole?: boolean; } export interface ErrorBoundaryState { hasError: boolean; error: Error; info: { componentStack: string }; } export class ErrorBoundary extends React.PureComponent<ErrorBoundaryProps, ErrorBoundaryState> { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null, info: null, }; } public componentDidCatch(error: Error, info: { componentStack: string }) { if (this.props.outputErrorToConsole) { console.error(error, info); } if (this.props.onError) { this.props.onError(error, info); } if (this.props.reloadUIOnError && !game.debug) { game.reloadUI(); } this.setState({ error, info, hasError: true, }); } public render() { if (this.state.hasError) { return this.props.renderError ? this.props.renderError(this.state.error, this.state.info) : <h2>Unhandled UI Error! <button data-input-group='block' onClick={this.onReloadUI}>Reload UI</button></h2>; } return this.props.children as any; } private onReloadUI = () => { game.reloadUI(); } }
mpl-2.0
danlrobertson/servo
tests/wpt/web-platform-tests/wasm/jsapi/module/constructor.any.js
1935
// META: global=jsshell // META: script=/wasm/jsapi/wasm-constants.js // META: script=/wasm/jsapi/wasm-module-builder.js // META: script=/wasm/jsapi/assertions.js let emptyModuleBinary; setup(() => { emptyModuleBinary = new WasmModuleBuilder().toBuffer(); }); test(() => { assert_function_name(WebAssembly.Module, "Module", "WebAssembly.Module"); }, "name"); test(() => { assert_function_length(WebAssembly.Module, 1, "WebAssembly.Module"); }, "length"); test(() => { assert_throws(new TypeError(), () => new WebAssembly.Module()); }, "No arguments"); test(() => { assert_throws(new TypeError(), () => WebAssembly.Module(emptyModuleBinary)); }, "Calling"); test(() => { const invalidArguments = [ undefined, null, true, "test", Symbol(), 7, NaN, {}, ArrayBuffer, ArrayBuffer.prototype, Array.from(emptyModuleBinary), ]; for (const argument of invalidArguments) { assert_throws(new TypeError(), () => new WebAssembly.Module(argument), `new Module(${format_value(argument)})`); } }, "Invalid arguments"); test(() => { const buffer = new Uint8Array(); assert_throws(new WebAssembly.CompileError(), () => new WebAssembly.Module(buffer)); }, "Empty buffer"); test(() => { const buffer = new Uint8Array(Array.from(emptyModuleBinary).concat([0, 0])); assert_throws(new WebAssembly.CompileError(), () => new WebAssembly.Module(buffer)); }, "Invalid code"); test(() => { const module = new WebAssembly.Module(emptyModuleBinary); assert_equals(Object.getPrototypeOf(module), WebAssembly.Module.prototype); }, "Prototype"); test(() => { const module = new WebAssembly.Module(emptyModuleBinary); assert_true(Object.isExtensible(module)); }, "Extensibility"); test(() => { const module = new WebAssembly.Module(emptyModuleBinary, {}); assert_equals(Object.getPrototypeOf(module), WebAssembly.Module.prototype); }, "Stray argument");
mpl-2.0
BrunoChauvet/timetrex
classes/smarty/libs/plugins/modifier.number_format.php
628
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty number_format modifier plugin * * Type: modifier<br> * Name: number_format<br> * Purpose: format number via number_format * @link http://smarty.php.net/manual/en/language.modifier.number.format.php * number_format (Smarty online manual) * @param string * @param integer * @param character * @param character * @return string */ function smarty_modifier_number_format($number, $decimals="2", $decpoint=".", $thousandsep="") { return number_format($number, $decimals, $decpoint, $thousandsep); } /* vim: set expandtab: */ ?>
agpl-3.0
arbrandes/edx-platform
openedx/core/djangoapps/api_admin/api/v1/serializers.py
478
""" API v1 serializers. """ from rest_framework import serializers from openedx.core.djangoapps.api_admin.models import ApiAccessRequest class ApiAccessRequestSerializer(serializers.ModelSerializer): """ ApiAccessRequest serializer. """ class Meta: model = ApiAccessRequest fields = ( 'id', 'created', 'modified', 'user', 'status', 'website', 'reason', 'company_name', 'company_address', 'site', 'contacted' )
agpl-3.0
auf/crm_auf_org
cache/modules/TemplateSectionLine/TemplateSectionLinevardefs.php
8796
<?php $GLOBALS["dictionary"]["TemplateSectionLine"]=array ( 'table' => 'templatesectionline', 'audited' => true, 'inline_edit' => true, 'duplicate_merge' => true, 'fields' => array ( 'id' => array ( 'name' => 'id', 'vname' => 'LBL_ID', 'type' => 'id', 'required' => true, 'reportable' => true, 'comment' => 'Unique identifier', 'inline_edit' => false, ), 'name' => array ( 'name' => 'name', 'vname' => 'LBL_NAME', 'type' => 'name', 'link' => true, 'dbType' => 'varchar', 'len' => 255, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 3, ), 'required' => true, 'importable' => 'required', 'duplicate_merge' => 'enabled', 'merge_filter' => 'selected', ), 'date_entered' => array ( 'name' => 'date_entered', 'vname' => 'LBL_DATE_ENTERED', 'type' => 'datetime', 'group' => 'created_by_name', 'comment' => 'Date record created', 'enable_range_search' => true, 'options' => 'date_range_search_dom', 'inline_edit' => false, ), 'date_modified' => array ( 'name' => 'date_modified', 'vname' => 'LBL_DATE_MODIFIED', 'type' => 'datetime', 'group' => 'modified_by_name', 'comment' => 'Date record last modified', 'enable_range_search' => true, 'options' => 'date_range_search_dom', 'inline_edit' => false, ), 'modified_user_id' => array ( 'name' => 'modified_user_id', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_MODIFIED', 'type' => 'assigned_user_name', 'table' => 'users', 'isnull' => 'false', 'group' => 'modified_by_name', 'dbType' => 'id', 'reportable' => true, 'comment' => 'User who last modified record', 'massupdate' => false, 'inline_edit' => false, ), 'modified_by_name' => array ( 'name' => 'modified_by_name', 'vname' => 'LBL_MODIFIED_NAME', 'type' => 'relate', 'reportable' => false, 'source' => 'non-db', 'rname' => 'user_name', 'table' => 'users', 'id_name' => 'modified_user_id', 'module' => 'Users', 'link' => 'modified_user_link', 'duplicate_merge' => 'disabled', 'massupdate' => false, 'inline_edit' => false, ), 'created_by' => array ( 'name' => 'created_by', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_CREATED', 'type' => 'assigned_user_name', 'table' => 'users', 'isnull' => 'false', 'dbType' => 'id', 'group' => 'created_by_name', 'comment' => 'User who created record', 'massupdate' => false, 'inline_edit' => false, ), 'created_by_name' => array ( 'name' => 'created_by_name', 'vname' => 'LBL_CREATED', 'type' => 'relate', 'reportable' => false, 'link' => 'created_by_link', 'rname' => 'user_name', 'source' => 'non-db', 'table' => 'users', 'id_name' => 'created_by', 'module' => 'Users', 'duplicate_merge' => 'disabled', 'importable' => 'false', 'massupdate' => false, 'inline_edit' => false, ), 'description' => array ( 'name' => 'description', 'vname' => 'LBL_DESCRIPTION', 'type' => 'text', 'comment' => 'Full text of the note', 'rows' => 6, 'cols' => 80, ), 'deleted' => array ( 'name' => 'deleted', 'vname' => 'LBL_DELETED', 'type' => 'bool', 'default' => '0', 'reportable' => false, 'comment' => 'Record deletion indicator', ), 'created_by_link' => array ( 'name' => 'created_by_link', 'type' => 'link', 'relationship' => 'templatesectionline_created_by', 'vname' => 'LBL_CREATED_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', ), 'modified_user_link' => array ( 'name' => 'modified_user_link', 'type' => 'link', 'relationship' => 'templatesectionline_modified_user', 'vname' => 'LBL_MODIFIED_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', ), 'assigned_user_id' => array ( 'name' => 'assigned_user_id', 'rname' => 'user_name', 'id_name' => 'assigned_user_id', 'vname' => 'LBL_ASSIGNED_TO_ID', 'group' => 'assigned_user_name', 'type' => 'relate', 'table' => 'users', 'module' => 'Users', 'reportable' => true, 'isnull' => 'false', 'dbType' => 'id', 'audited' => true, 'comment' => 'User ID assigned to record', 'duplicate_merge' => 'disabled', ), 'assigned_user_name' => array ( 'name' => 'assigned_user_name', 'link' => 'assigned_user_link', 'vname' => 'LBL_ASSIGNED_TO_NAME', 'rname' => 'user_name', 'type' => 'relate', 'reportable' => false, 'source' => 'non-db', 'table' => 'users', 'id_name' => 'assigned_user_id', 'module' => 'Users', 'duplicate_merge' => 'disabled', ), 'assigned_user_link' => array ( 'name' => 'assigned_user_link', 'type' => 'link', 'relationship' => 'templatesectionline_assigned_user', 'vname' => 'LBL_ASSIGNED_TO_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', 'duplicate_merge' => 'enabled', 'rname' => 'user_name', 'id_name' => 'assigned_user_id', 'table' => 'users', ), 'thumbnail' => array ( 'required' => false, 'name' => 'thumbnail', 'vname' => 'LBL_THUMBNAIL', 'type' => 'varchar', 'massupdate' => 0, 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => false, 'inline_edit' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', ), 'grp' => array ( 'required' => false, 'name' => 'grp', 'vname' => 'LBL_GRP', 'type' => 'varchar', 'massupdate' => 0, 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => false, 'inline_edit' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', ), 'ord' => array ( 'required' => false, 'name' => 'ord', 'vname' => 'LBL_ORD', 'type' => 'int', 'massupdate' => 0, 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => false, 'inline_edit' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '11', 'size' => '20', ), ), 'relationships' => array ( 'templatesectionline_modified_user' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'TemplateSectionLine', 'rhs_table' => 'templatesectionline', 'rhs_key' => 'modified_user_id', 'relationship_type' => 'one-to-many', ), 'templatesectionline_created_by' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'TemplateSectionLine', 'rhs_table' => 'templatesectionline', 'rhs_key' => 'created_by', 'relationship_type' => 'one-to-many', ), 'templatesectionline_assigned_user' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'TemplateSectionLine', 'rhs_table' => 'templatesectionline', 'rhs_key' => 'assigned_user_id', 'relationship_type' => 'one-to-many', ), ), 'optimistic_locking' => true, 'unified_search' => true, 'indices' => array ( 'id' => array ( 'name' => 'templatesectionlinepk', 'type' => 'primary', 'fields' => array ( 0 => 'id', ), ), ), 'templates' => array ( 'assignable' => 'assignable', 'basic' => 'basic', ), 'custom_fields' => false, );
agpl-3.0
RobertBierbauer/spatial
src/main/java/org/neo4j/gis/spatial/rtree/SpatialIndexWriter.java
1115
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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/>. */ package org.neo4j.gis.spatial.rtree; import org.neo4j.graphdb.Node; public interface SpatialIndexWriter extends SpatialIndexReader { void add(Node geomNode); void remove(long geomNodeId, boolean deleteGeomNode); void removeAll(boolean deleteGeomNodes, Listener monitor); void clear(Listener monitor); }
agpl-3.0
msegado/edx-platform
lms/djangoapps/shoppingcart/migrations/0001_initial.py
18329
# -*- coding: utf-8 -*- import django.db.models.deletion import django.utils.timezone import model_utils.fields from django.conf import settings from django.db import migrations, models from opaque_keys.edx.django.models import CourseKeyField class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('student', '0001_initial'), ] operations = [ migrations.CreateModel( name='Coupon', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(max_length=32, db_index=True)), ('description', models.CharField(max_length=255, null=True, blank=True)), ('course_id', CourseKeyField(max_length=255)), ('percentage_discount', models.IntegerField(default=0)), ('created_at', models.DateTimeField(auto_now_add=True)), ('is_active', models.BooleanField(default=True)), ('expiration_date', models.DateTimeField(null=True, blank=True)), ('created_by', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='CouponRedemption', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('coupon', models.ForeignKey(to='shoppingcart.Coupon', on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='CourseRegCodeItemAnnotation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('course_id', CourseKeyField(unique=True, max_length=128, db_index=True)), ('annotation', models.TextField(null=True)), ], ), migrations.CreateModel( name='CourseRegistrationCode', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(unique=True, max_length=32, db_index=True)), ('course_id', CourseKeyField(max_length=255, db_index=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('mode_slug', models.CharField(max_length=100, null=True)), ('is_valid', models.BooleanField(default=True)), ('created_by', models.ForeignKey(related_name='created_by_user', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='DonationConfiguration', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')), ('enabled', models.BooleanField(default=False, verbose_name='Enabled')), ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')), ], options={ 'ordering': ('-change_date',), 'abstract': False, }, ), migrations.CreateModel( name='Invoice', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('company_name', models.CharField(max_length=255, db_index=True)), ('company_contact_name', models.CharField(max_length=255)), ('company_contact_email', models.CharField(max_length=255)), ('recipient_name', models.CharField(max_length=255)), ('recipient_email', models.CharField(max_length=255)), ('address_line_1', models.CharField(max_length=255)), ('address_line_2', models.CharField(max_length=255, null=True, blank=True)), ('address_line_3', models.CharField(max_length=255, null=True, blank=True)), ('city', models.CharField(max_length=255, null=True)), ('state', models.CharField(max_length=255, null=True)), ('zip', models.CharField(max_length=15, null=True)), ('country', models.CharField(max_length=64, null=True)), ('total_amount', models.FloatField()), ('course_id', CourseKeyField(max_length=255, db_index=True)), ('internal_reference', models.CharField(help_text='Internal reference code for this invoice.', max_length=255, null=True, blank=True)), ('customer_reference_number', models.CharField(help_text="Customer's reference code for this invoice.", max_length=63, null=True, blank=True)), ('is_valid', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='InvoiceHistory', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)), ('snapshot', models.TextField(blank=True)), ('invoice', models.ForeignKey(to='shoppingcart.Invoice', on_delete=models.CASCADE)), ], options={ 'get_latest_by': 'timestamp', }, ), migrations.CreateModel( name='InvoiceItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('qty', models.IntegerField(default=1, help_text='The number of items sold.')), ('unit_price', models.DecimalField(default=0.0, help_text='The price per item sold, including discounts.', max_digits=30, decimal_places=2)), ('currency', models.CharField(default=u'usd', help_text='Lower-case ISO currency codes', max_length=8)), ], ), migrations.CreateModel( name='InvoiceTransaction', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('amount', models.DecimalField(default=0.0, help_text='The amount of the transaction. Use positive amounts for payments and negative amounts for refunds.', max_digits=30, decimal_places=2)), ('currency', models.CharField(default=u'usd', help_text='Lower-case ISO currency codes', max_length=8)), ('comments', models.TextField(help_text='Optional: provide additional information for this transaction', null=True, blank=True)), ('status', models.CharField(default=u'started', help_text="The status of the payment or refund. 'started' means that payment is expected, but money has not yet been transferred. 'completed' means that the payment or refund was received. 'cancelled' means that payment or refund was expected, but was cancelled before money was transferred. ", max_length=32, choices=[(u'started', u'started'), (u'completed', u'completed'), (u'cancelled', u'cancelled')])), ('created_by', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ('invoice', models.ForeignKey(to='shoppingcart.Invoice', on_delete=models.CASCADE)), ('last_modified_by', models.ForeignKey(related_name='last_modified_by_user', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('currency', models.CharField(default=u'usd', max_length=8)), ('status', models.CharField(default=u'cart', max_length=32, choices=[(u'cart', u'cart'), (u'paying', u'paying'), (u'purchased', u'purchased'), (u'refunded', u'refunded'), (u'defunct-cart', u'defunct-cart'), (u'defunct-paying', u'defunct-paying')])), ('purchase_time', models.DateTimeField(null=True, blank=True)), ('refunded_time', models.DateTimeField(null=True, blank=True)), ('bill_to_first', models.CharField(max_length=64, blank=True)), ('bill_to_last', models.CharField(max_length=64, blank=True)), ('bill_to_street1', models.CharField(max_length=128, blank=True)), ('bill_to_street2', models.CharField(max_length=128, blank=True)), ('bill_to_city', models.CharField(max_length=64, blank=True)), ('bill_to_state', models.CharField(max_length=8, blank=True)), ('bill_to_postalcode', models.CharField(max_length=16, blank=True)), ('bill_to_country', models.CharField(max_length=64, blank=True)), ('bill_to_ccnum', models.CharField(max_length=8, blank=True)), ('bill_to_cardtype', models.CharField(max_length=32, blank=True)), ('processor_reply_dump', models.TextField(blank=True)), ('company_name', models.CharField(max_length=255, null=True, blank=True)), ('company_contact_name', models.CharField(max_length=255, null=True, blank=True)), ('company_contact_email', models.CharField(max_length=255, null=True, blank=True)), ('recipient_name', models.CharField(max_length=255, null=True, blank=True)), ('recipient_email', models.CharField(max_length=255, null=True, blank=True)), ('customer_reference_number', models.CharField(max_length=63, null=True, blank=True)), ('order_type', models.CharField(default=u'personal', max_length=32, choices=[(u'personal', u'personal'), (u'business', u'business')])), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('status', models.CharField(default=u'cart', max_length=32, db_index=True, choices=[(u'cart', u'cart'), (u'paying', u'paying'), (u'purchased', u'purchased'), (u'refunded', u'refunded'), (u'defunct-cart', u'defunct-cart'), (u'defunct-paying', u'defunct-paying')])), ('qty', models.IntegerField(default=1)), ('unit_cost', models.DecimalField(default=0.0, max_digits=30, decimal_places=2)), ('list_price', models.DecimalField(null=True, max_digits=30, decimal_places=2)), ('line_desc', models.CharField(default=u'Misc. Item', max_length=1024)), ('currency', models.CharField(default=u'usd', max_length=8)), ('fulfilled_time', models.DateTimeField(null=True, db_index=True)), ('refund_requested_time', models.DateTimeField(null=True, db_index=True)), ('service_fee', models.DecimalField(default=0.0, max_digits=30, decimal_places=2)), ('report_comments', models.TextField(default=u'')), ], ), migrations.CreateModel( name='PaidCourseRegistrationAnnotation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('course_id', CourseKeyField(unique=True, max_length=128, db_index=True)), ('annotation', models.TextField(null=True)), ], ), migrations.CreateModel( name='RegistrationCodeRedemption', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('redeemed_at', models.DateTimeField(auto_now_add=True, null=True)), ('course_enrollment', models.ForeignKey(to='student.CourseEnrollment', null=True, on_delete=models.CASCADE)), ('order', models.ForeignKey(to='shoppingcart.Order', null=True, on_delete=models.CASCADE)), ('redeemed_by', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ('registration_code', models.ForeignKey(to='shoppingcart.CourseRegistrationCode', on_delete=models.CASCADE)), ], ), migrations.CreateModel( name='CertificateItem', fields=[ ('orderitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoppingcart.OrderItem', on_delete=models.CASCADE)), ('course_id', CourseKeyField(max_length=128, db_index=True)), ('mode', models.SlugField()), ('course_enrollment', models.ForeignKey(to='student.CourseEnrollment', on_delete=models.CASCADE)), ], bases=('shoppingcart.orderitem',), ), migrations.CreateModel( name='CourseRegCodeItem', fields=[ ('orderitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoppingcart.OrderItem', on_delete=models.CASCADE)), ('course_id', CourseKeyField(max_length=128, db_index=True)), ('mode', models.SlugField(default=b'honor')), ], bases=('shoppingcart.orderitem',), ), migrations.CreateModel( name='CourseRegistrationCodeInvoiceItem', fields=[ ('invoiceitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoppingcart.InvoiceItem', on_delete=models.CASCADE)), ('course_id', CourseKeyField(max_length=128, db_index=True)), ], bases=('shoppingcart.invoiceitem',), ), migrations.CreateModel( name='Donation', fields=[ ('orderitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoppingcart.OrderItem', on_delete=models.CASCADE)), ('donation_type', models.CharField(default=u'general', max_length=32, choices=[(u'general', u'A general donation'), (u'course', u'A donation to a particular course')])), ('course_id', CourseKeyField(max_length=255, db_index=True)), ], bases=('shoppingcart.orderitem',), ), migrations.CreateModel( name='PaidCourseRegistration', fields=[ ('orderitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoppingcart.OrderItem', on_delete=models.CASCADE)), ('course_id', CourseKeyField(max_length=128, db_index=True)), ('mode', models.SlugField(default=b'honor')), ('course_enrollment', models.ForeignKey(to='student.CourseEnrollment', null=True, on_delete=models.CASCADE)), ], bases=('shoppingcart.orderitem',), ), migrations.AddField( model_name='orderitem', name='order', field=models.ForeignKey(to='shoppingcart.Order', on_delete=models.CASCADE), ), migrations.AddField( model_name='orderitem', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE), ), migrations.AddField( model_name='invoiceitem', name='invoice', field=models.ForeignKey(to='shoppingcart.Invoice', on_delete=models.CASCADE), ), migrations.AddField( model_name='courseregistrationcode', name='invoice', field=models.ForeignKey(to='shoppingcart.Invoice', null=True, on_delete=models.CASCADE), ), migrations.AddField( model_name='courseregistrationcode', name='order', field=models.ForeignKey(related_name='purchase_order', to='shoppingcart.Order', null=True, on_delete=models.CASCADE), ), migrations.AddField( model_name='couponredemption', name='order', field=models.ForeignKey(to='shoppingcart.Order', on_delete=models.CASCADE), ), migrations.AddField( model_name='couponredemption', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE), ), migrations.AddField( model_name='courseregistrationcode', name='invoice_item', field=models.ForeignKey(to='shoppingcart.CourseRegistrationCodeInvoiceItem', null=True, on_delete=models.CASCADE), ), ]
agpl-3.0