code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * Copyright 2015 Wouter van Heeswijk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define( ["geometries/loader", "json!assets/triangle.json"], function (loader, asset) { return loader.load(asset); } );
woutervh-/csgjson
js/assets/triangle.js
JavaScript
apache-2.0
740
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma; /** * Runtime exception used to indicate that the action would create a duplicate. * <p> * A typical use case is when adding data and a similar item already exists. */ public class DataDuplicationException extends OpenGammaRuntimeException { /** Serialization version. */ private static final long serialVersionUID = 1L; /** * Creates an exception with a message. * * @param message the message, may be null */ public DataDuplicationException(final String message) { super(message); } /** * Creates an exception with a message. * * @param message the message, may be null * @param cause the underlying cause, may be null */ public DataDuplicationException(final String message, final Throwable cause) { super(message, cause); } }
McLeodMoores/starling
projects/util/src/main/java/com/opengamma/DataDuplicationException.java
Java
apache-2.0
954
package com.afollestad.appthemeengine.views; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatRadioButton; import com.afollestad.appthemeengine.ATE; import com.afollestad.appthemeengine.R; /** * @author Aidan Follestad (afollestad) */ @PreMadeView public class ATERadioButton extends AppCompatRadioButton { public ATERadioButton(Context context) { super(context); init(context, null); } public ATERadioButton(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ATERadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { setTag("tint_accent_color,text_primary"); String key = null; if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ATERadioButton, 0, 0); try { key = a.getString(R.styleable.ATERadioButton_ateKey_radioButton); } finally { a.recycle(); } } ATE.apply(context, this, key); } }
A-Miracle/QiangHongBao
themelib/src/main/java/com/afollestad/appthemeengine/views/ATERadioButton.java
Java
apache-2.0
1,317
import React from 'react'; import PropTypes from 'prop-types'; import Preselect from 'material-ui-icons/ThumbUp'; import IconWithTooltipButton from '../../common/iconWithTooltipButton'; import withApplicationStatusChange from '../../common/hoc/withApplicationStatusChange'; import { APPLICATION_STATUSES } from '../../../helpers/constants'; const messages = { text: 'Preselect', }; const PreselectButton = (props) => { const { id, status, changeStatus, ...other } = props; return ( <IconWithTooltipButton icon={<Preselect />} name="preselect" text={messages.text} onClick={(event) => { event.stopPropagation(); changeStatus(id); }} {...other} /> ); }; PreselectButton.propTypes = { id: PropTypes.oneOfType([ PropTypes.array, PropTypes.string, ]), status: PropTypes.string, changeStatus: PropTypes.func, }; export default withApplicationStatusChange(APPLICATION_STATUSES.PRE)(PreselectButton);
unicef/un-partner-portal
frontend/src/components/eois/buttons/preselectButton.js
JavaScript
apache-2.0
981
package qj.util.cache; import java.util.ArrayList; import qj.util.funct.F2; public class Cache2<A, B, T> { private final F2<A, B, T> func; ArrayList<Holder> holders = new ArrayList<Holder>(); public Cache2(F2<A, B, T> func) { this.func = func; } public T get(A a, B b) { for (Holder holder : holders) { if (holder.a.equals(a) && holder.b.equals(b)) { return holder.t; } } T t = func.e(a, b); holders.add(new Holder(a, b, t)); return t; } private class Holder { A a; B b; T t; public Holder(A a, B b, T t) { this.a = a; this.b = b; this.t = t; } } }
quanla/quan-util-core
src/main/java/qj/util/cache/Cache2.java
Java
apache-2.0
615
<?php namespace Illuminate\Session; use SessionHandlerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionBagInterface; use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag; class Store implements SessionInterface { /** * The session ID. * * @var string */ protected $id; /** * The session name. * * @var string */ protected $name; /** * The session attributes. * * @var array */ protected $attributes = array(); /** * The session bags. * * @var array */ protected $bags = array(); /** * The meta-data bag instance. * * @var \Symfony\Component\Session\Storage\MetadataBag */ protected $metaBag; /** * Local copies of the session bag data. * * @var array */ protected $bagData = array(); /** * The session handler implementation. * * @var \SessionHandlerInterface */ protected $handler; /** * Create a new session instance. * * @param string $name * @param \SessionHandlerInterface $handler * @param string|null $id * @return void */ public function __construct($name, SessionHandlerInterface $handler, $id = null) { $this->name = $name; $this->handler = $handler; $this->metaBag = new MetadataBag; $this->setId($id ?: $this->generateSessionId()); } /** * {@inheritdoc} */ public function start() { $this->loadSession(); if ( ! $this->has('_token')) $this->put('_token', str_random(40)); return $this->started = true; } /** * Load the session data from the handler. * * @return void */ protected function loadSession() { $this->attributes = $this->readFromHandler(); foreach (array_merge($this->bags, array($this->metaBag)) as $bag) { $this->initializeLocalBag($bag); $bag->initialize($this->bagData[$bag->getStorageKey()]); } } /** * Read the session data from the handler. * * @return array */ protected function readFromHandler() { $data = $this->handler->read($this->getId()); return $data ? unserialize($data) : array(); } /** * Initialize a bag in storage if it doesn't exist. * * @param \Symfony\Component\HttpFoundation\Session\SessionBagInterface $bag * @return void */ protected function initializeLocalBag($bag) { $this->bagData[$bag->getStorageKey()] = $this->get($bag->getStorageKey(), array()); $this->forget($bag->getStorageKey()); } /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function setId($id) { $this->id = $id ?: $this->generateSessionId(); } /** * Get a new, random session ID. * * @return string */ protected function generateSessionId() { return sha1(uniqid(true).str_random(25).microtime(true)); } /** * {@inheritdoc} */ public function getName() { return $this->name; } /** * {@inheritdoc} */ public function setName($name) { $this->name = $name; } /** * {@inheritdoc} */ public function invalidate($lifetime = null) { $this->attributes = array(); $this->migrate(); return true; } /** * {@inheritdoc} */ public function migrate($destroy = false, $lifetime = null) { if ($destroy) $this->handler->destroy($this->getId()); $this->id = $this->generateSessionId(); return true; } /** * Generate a new session identifier. * * @return bool */ public function regenerate() { return $this->migrate(); } /** * {@inheritdoc} */ public function save() { $this->addBagDataToSession(); $this->ageFlashData(); $this->handler->write($this->getId(), serialize($this->attributes)); $this->started = false; } /** * Merge all of the bag data into the session. * * @return void */ protected function addBagDataToSession() { foreach (array_merge($this->bags, array($this->metaBag)) as $bag) { $this->put($bag->getStorageKey(), $this->bagData[$bag->getStorageKey()]); } } /** * Age the flash data for the session. * * @return void */ public function ageFlashData() { foreach ($this->get('flash.old', array()) as $old) { $this->forget($old); } $this->put('flash.old', $this->get('flash.new', array())); $this->put('flash.new', array()); } /** * {@inheritdoc} */ public function has($name) { return ! is_null($this->get($name)); } /** * {@inheritdoc} */ public function get($name, $default = null) { return array_get($this->attributes, $name, $default); } /** * Determine if the session contains old input. * * @param string $key * @return bool */ public function hasOldInput($key = null) { $old = $this->getOldInput($key); return is_null($key) ? count($old) > 0 : ! is_null($old); } /** * Get the requested item from the flashed input array. * * @param string $key * @param mixed $default * @return mixed */ public function getOldInput($key = null, $default = null) { $input = $this->get('_old_input', array()); // Input that is flashed to the session can be easily retrieved by the // developer, making repopulating old forms and the like much more // convenient, since the request's previous input is available. if (is_null($key)) return $input; return array_get($input, $key, $default); } /** * {@inheritdoc} */ public function set($name, $value) { array_set($this->attributes, $name, $value); } /** * Put a key / value pair in the session. * * @param string $key * @param mixed $value * @return void */ public function put($key, $value) { $this->set($key, $value); } /** * Push a value onto a session array. * * @param string $key * @param mixed $value * @return void */ public function push($key, $value) { $array = $this->get($key, array()); $array[] = $value; $this->put($key, $array); } /** * Flash a key / value pair to the session. * * @param string $key * @param mixed $value * @return void */ public function flash($key, $value) { $this->put($key, $value); $this->push('flash.new', $key); $this->removeFromOldFlashData(array($key)); } /** * Flash an input array to the session. * * @param array $value * @return void */ public function flashInput(array $value) { $this->flash('_old_input', $value); } /** * Reflash all of the session flash data. * * @return void */ public function reflash() { $this->mergeNewFlashes($this->get('flash.old', array())); $this->put('flash.old', array()); } /** * Reflash a subset of the current flash data. * * @param array|dynamic $keys * @return void */ public function keep($keys = null) { $keys = is_array($keys) ? $keys : func_get_args(); $this->mergeNewFlashes($keys); $this->removeFromOldFlashData($keys); } /** * Merge new flash keys into the new flash array. * * @param array $keys * @return void */ protected function mergeNewFlashes(array $keys) { $values = array_unique(array_merge($this->get('flash.new', array()), $keys)); $this->put('flash.new', $values); } /** * Remove the given keys from the old flash data. * * @param array $keys * @return void */ protected function removeFromOldFlashData(array $keys) { $this->put('flash.old', array_diff($this->get('flash.old', array()), $keys)); } /** * {@inheritdoc} */ public function all() { return $this->attributes; } /** * {@inheritdoc} */ public function replace(array $attributes) { foreach ($attributes as $key => $value) { $this->put($key, $value); } } /** * {@inheritdoc} */ public function remove($name) { return array_pull($this->attributes, $name); } /** * Remove an item from the session. * * @param string $key * @return void */ public function forget($key) { array_forget($this->attributes, $key); } /** * {@inheritdoc} */ public function clear() { $this->attributes = array(); foreach ($this->bags as $bag) { $bag->clear(); } } /** * Remove all of the items from the session. * * @return void */ public function flush() { $this->clear(); } /** * {@inheritdoc} */ public function isStarted() { return $this->started; } /** * {@inheritdoc} */ public function registerBag(SessionBagInterface $bag) { $this->bags[$bag->getStorageKey()] = $bag; } /** * {@inheritdoc} */ public function getBag($name) { return array_get($this->bags, $name, function() { throw new \InvalidArgumentException("Bag not registered."); }); } /** * {@inheritdoc} */ public function getMetadataBag() { return $this->metaBag; } /** * Get the raw bag data array for a given bag. * * @param string $name * @return array */ public function getBagData($name) { return array_get($this->bagData, $name, array()); } /** * Get the CSRF token value. * * @return string */ public function token() { return $this->get('_token'); } /** * Get the CSRF token value. * * @return string */ public function getToken() { return $this->token(); } /** * Get the underlying session handler implementation. * * @return \SessionHandlerInterface */ public function getHandler() { return $this->handler; } /** * Determine if the session handler needs a request. * * @return bool */ public function handlerNeedsRequest() { return $this->handler instanceof CookieSessionHandler; } /** * Set the request on the handler instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function setRequestOnHandler(Request $request) { if ($this->handlerNeedsRequest()) { $this->handler->setRequest($request); } } }
romeoinbar/MDTB
vendor/laravel/framework/src/Illuminate/Session/Store.php
PHP
apache-2.0
10,290
define([ "less!theme/textmate.less" ], function(cssContent) { return { 'isDark': false, 'cssClass': "ace-tm", 'cssText': cssContent } });
cethap/cbcompiled
addons/cb.files.editor/theme/textmate.js
JavaScript
apache-2.0
174
function PreferencesAssistant() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller should be done in the setup function below. */ this.cookie = new Mojo.Model.Cookie('prefs'); this.model = this.cookie.get(); if (!this.model) { this.model = { useOldInterface: false }; this.cookie.put(this.model); } } PreferencesAssistant.prototype.setup = function() { /* this function is for setup tasks that have to happen when the scene is first created */ /* use Mojo.View.render to render view templates and add them to the scene, if needed */ /* setup widgets here */ this.controller.setupWidget( 'oldInterfaceToggle', { modelProperty: 'useOldInterface', disabledProperty: 'oldInterfaceToggleDisabled' }, this.model ); /* add event handlers to listen to events from widgets */ Mojo.Event.listen( this.controller.get('oldInterfaceToggle'), Mojo.Event.propertyChange, this.handlePrefsChange.bind(this) ); }; PreferencesAssistant.prototype.handlePrefsChange = function(event) { this.cookie.put(this.model); }; PreferencesAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For example, key handlers that are observing the document */ }; PreferencesAssistant.prototype.deactivate = function(event) { /* remove any event handlers you added in activate and do any other cleanup that should happen before this scene is popped or another scene is pushed on top */ }; PreferencesAssistant.prototype.cleanup = function(event) { /* this function should do any cleanup needed before the scene is destroyed as a result of being popped off the scene stack */ Mojo.Event.stopListening( this.controller.get('oldInterfaceToggle'), Mojo.Event.propertyChange, this.handlePrefsChange.bind(this) ); };
brettcannon/oplop
WebOS/app/assistants/preferences-assistant.js
JavaScript
apache-2.0
2,299
import { file as tempfile } from 'tempy' import { SourceModel } from '../src/models/source-model' import { SourceLogModel } from '../src/models/source-log-model' import { ItemModel } from '../src/models/item-model' import { TypeModel } from '../src/models/type-model' import { init, sourceLogs, sources, items, types } from '../src/database' describe('database', () => { describe('before init()', () => { it('should still start with models', () => { expect(sourceLogs).toEqual(jasmine.any(SourceLogModel)) expect(sources).toEqual(jasmine.any(SourceModel)) expect(items).toEqual(jasmine.any(ItemModel)) expect(types).toEqual(jasmine.any(TypeModel)) }) }) describe('init()', () => { it('should create the models', () => { init({ type: 'sqlite3', filename: tempfile() }) // checkModel() is private; this is a hack to get around that return Promise.all([ sourceLogs['checkModel'](), sources['checkModel'](), items['checkModel'](), types['checkModel']() ]) }) it('should use a port when specified', () => { init({ type: 'sqlite3', filename: tempfile(), port: 123456 }) return Promise.all([ sourceLogs['checkModel'](), sources['checkModel'](), items['checkModel'](), types['checkModel']() ]) }) it('should use a socket when specified', () => { init({ type: 'sqlite3', filename: tempfile(), socket: 'testSocket' }) return Promise.all([ sourceLogs['checkModel'](), sources['checkModel'](), items['checkModel'](), types['checkModel']() ]) }) }) })
eheikes/oscar
collector/test/database.spec.ts
TypeScript
apache-2.0
1,755
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jmeter.functions; import java.time.Duration; import java.time.Instant; import java.time.Year; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoField; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jmeter.util.JMeterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * timeShifting Function permit to shift a date * <p> * Parameters: * <ul> * <li>format date @see * https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html * (optional - defaults to epoch time in millisecond)</li> * <li>date to shift formatted * as first param (optional - defaults now)</li> * <li>amount of (seconds, minutes, hours, days ) to add (optional - default nothing is add)</li> * <li>a string of the locale for the format ( optional )</li> * <li>variable name ( optional )</li> * </ul> * Returns: * <p>a formatted date with the specified number of (seconds, minutes, * hours, days or months ) added. Value is also saved in the variable for * later re-use. * * @since 3.3 */ public class TimeShift extends AbstractFunction { private static final Logger log = LoggerFactory.getLogger(TimeShift.class); private static final String KEY = "__timeShift"; // $NON-NLS-1$ private static final List<String> desc = Arrays.asList(JMeterUtils.getResString("time_format_shift"), JMeterUtils.getResString("date_to_shift"), JMeterUtils.getResString("value_to_shift"), JMeterUtils.getResString("locale_format"), JMeterUtils.getResString("function_name_paropt")); // Ensure that these are set, even if no parameters are provided private String format = ""; //$NON-NLS-1$ private CompoundVariable dateToShiftCompound; // $NON-NLS-1$ private CompoundVariable amountToShiftCompound; // $NON-NLS-1$ private Locale locale = JMeterUtils.getLocale(); // $NON-NLS-1$ private String variableName = ""; //$NON-NLS-1$ private ZoneId systemDefaultZoneID = ZoneId.systemDefault(); private static final class LocaleFormatObject { private String format; private Locale locale; public LocaleFormatObject(String format, Locale locale) { this.format = format; this.locale = locale; } public String getFormat() { return format; } public Locale getLocale() { return locale; } @Override public int hashCode() { return format.hashCode() + locale.hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof LocaleFormatObject)) { return false; } LocaleFormatObject otherError = (LocaleFormatObject) other; return format.equals(otherError.getFormat()) && locale.getDisplayName().equals(otherError.getLocale().getDisplayName()); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "LocaleFormatObject [format=" + format + ", locale=" + locale + "]"; } } /** Date time format cache handler **/ private Cache<LocaleFormatObject, DateTimeFormatter> dateTimeFormatterCache = null; public TimeShift() { super(); } /** {@inheritDoc} */ @Override public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String amountToShift = amountToShiftCompound.execute().trim(); String dateToShift = dateToShiftCompound.execute().trim(); ZonedDateTime zonedDateTimeToShift = ZonedDateTime.now(systemDefaultZoneID); DateTimeFormatter formatter = null; if (!StringUtils.isEmpty(format)) { try { LocaleFormatObject lfo = new LocaleFormatObject(format, locale); formatter = dateTimeFormatterCache.get(lfo, this::createFormatter); } catch (IllegalArgumentException ex) { log.error("Format date pattern '{}' is invalid " + "(see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)", format, ex); // $NON-NLS-1$ return ""; } } if (!dateToShift.isEmpty()) { try { if (formatter != null) { zonedDateTimeToShift = ZonedDateTime.parse(dateToShift, formatter); } else { zonedDateTimeToShift = ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateToShift)), systemDefaultZoneID); } } catch (DateTimeParseException | NumberFormatException ex) { log.error("Failed to parse the date '{}' to shift with formatter '{}'", dateToShift, formatter, ex); // $NON-NLS-1$ } } // Check amount value to shift if (!StringUtils.isEmpty(amountToShift)) { try { Duration duration = Duration.parse(amountToShift); zonedDateTimeToShift = zonedDateTimeToShift.plus(duration); } catch (DateTimeParseException ex) { log.error( "Failed to parse the amount duration '{}' to shift " + "(see https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-) ", amountToShift, ex); // $NON-NLS-1$ } } String dateString; if (formatter != null) { dateString = zonedDateTimeToShift.format(formatter); } else { dateString = String.valueOf(zonedDateTimeToShift.toInstant().toEpochMilli()); } if (!StringUtils.isEmpty(variableName)) { JMeterVariables vars = getVariables(); if (vars != null) {// vars will be null on TestPlan vars.put(variableName, dateString); } } return dateString; } private DateTimeFormatter createFormatter(LocaleFormatObject format) { log.debug("Create a new instance of DateTimeFormatter for format '{}' in the cache", format); return new DateTimeFormatterBuilder().appendPattern(format.getFormat()) .parseDefaulting(ChronoField.NANO_OF_SECOND, 0) .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0) .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0) .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1) .parseDefaulting(ChronoField.YEAR_OF_ERA, Year.now().getValue()) .parseDefaulting(ChronoField.OFFSET_SECONDS, ZonedDateTime.now().getOffset().getTotalSeconds()) .toFormatter(format.getLocale()); } /** {@inheritDoc} */ @Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, 4, 5); Object[] values = parameters.toArray(); format = ((CompoundVariable) values[0]).execute().trim(); dateToShiftCompound = (CompoundVariable) values[1]; amountToShiftCompound = (CompoundVariable) values[2]; if (values.length == 4) { variableName = ((CompoundVariable) values[3]).execute().trim(); } else { String localeAsString = ((CompoundVariable) values[3]).execute().trim(); if (!localeAsString.trim().isEmpty()) { locale = LocaleUtils.toLocale(localeAsString); } variableName = ((CompoundVariable) values[4]).execute().trim(); } // Create the cache if (dateTimeFormatterCache == null) { dateTimeFormatterCache = Caffeine.newBuilder() .maximumSize(100).build(); } } /** {@inheritDoc} */ @Override public String getReferenceKey() { return KEY; } /** {@inheritDoc} */ @Override public List<String> getArgumentDesc() { return desc; } }
benbenw/jmeter
src/functions/src/main/java/org/apache/jmeter/functions/TimeShift.java
Java
apache-2.0
9,758
/* Copyright (c) 2010 Aldo J. Nunez Licensed under the Apache License, Version 2.0. See the LICENSE text file for details. */ #include "Common.h" #include "ImageAddrMap.h" namespace MagoST { ImageAddrMap::ImageAddrMap() : mRefCount( 0 ), mSecCount( 0 ) { } void ImageAddrMap::AddRef() { InterlockedIncrement( &mRefCount ); } void ImageAddrMap::Release() { long newRef = InterlockedDecrement( &mRefCount ); _ASSERT( newRef >= 0 ); if ( newRef == 0 ) { delete this; } } uint32_t ImageAddrMap::MapSecOffsetToRVA( uint16_t secIndex, uint32_t offset ) { if ( (secIndex == 0) || (secIndex > mSecCount) ) return 0; uint16_t zSec = secIndex - 1; // zero-based section index return mSections[zSec].RVA + offset; } uint16_t ImageAddrMap::MapRVAToSecOffset( uint32_t rva, uint32_t& offset ) { uint16_t closestSec = USHRT_MAX; uint32_t closestOff = ULONG_MAX; for ( uint16_t i = 0; i < mSecCount; i++ ) { if ( rva >= mSections[i].RVA ) { uint32_t curOff = rva - mSections[i].RVA; if ( curOff < closestOff ) { closestOff = curOff; closestSec = i; } } } if ( closestSec < USHRT_MAX ) { offset = closestOff; return closestSec + 1; // remember it's 1-based } return 0; } uint16_t ImageAddrMap::FindSection( const char* name ) { for ( uint16_t i = 0; i < mSecCount; i++ ) if( strncmp( name, mSections[i].Name, sizeof( mSections[i].Name ) ) == 0 ) return i + 1; // remember it's 1-based return 0; } HRESULT ImageAddrMap::LoadFromSections( uint16_t count, const IMAGE_SECTION_HEADER* secHeaders ) { _ASSERT( secHeaders != NULL ); _ASSERT( mSections.Get() == NULL ); _ASSERT( count != USHRT_MAX ); if ( count == USHRT_MAX ) return E_INVALIDARG; mSections.Attach( new Section[ count ] ); if ( mSections.Get() == NULL ) return E_OUTOFMEMORY; mSecCount = count; for ( uint16_t i = 0; i < count; i++ ) { DWORD size = secHeaders[i].SizeOfRawData; if ( secHeaders[i].Misc.VirtualSize > 0 ) size = secHeaders[i].Misc.VirtualSize; mSections[i].RVA = secHeaders[i].VirtualAddress; mSections[i].Size = size; memcpy( mSections[i].Name, (const char*) secHeaders[i].Name, sizeof( mSections[i].Name ) ); } return S_OK; } }
aBothe/MagoWrapper
CVSym/CVSTI/ImageAddrMap.cpp
C++
apache-2.0
2,933
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.util.javalang; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.util.text.Strings; import com.google.common.collect.ImmutableSet; /** * Utility class for cleaning up stacktraces. */ public class StackTraceSimplifier { private static final Logger log = LoggerFactory.getLogger(StackTraceSimplifier.class); /** comma-separated prefixes (not regexes) */ public static final String DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME = "brooklyn.util.javalang.StackTraceSimplifier.blacklist"; /** @deprecated since 0.6.0 use {@link #DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME} */ @Deprecated public static final String LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME = "groovy.sanitized.stacktraces"; private static final Collection<String> DEFAULT_BLACKLIST; static { ImmutableSet.Builder<String> blacklist = ImmutableSet.builder(); blacklist.addAll(Arrays.asList( System.getProperty(DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME, "java.," + "javax.," + "sun.," + "groovy.," + "org.codehaus.groovy.," + "gjdk.groovy.," ).split("(\\s|,)+"))); String legacyDefaults = System.getProperty(LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME); if (Strings.isNonBlank(legacyDefaults)) { log.warn("Detected ude of legacy system property "+LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME); blacklist.addAll(Arrays.asList(legacyDefaults.split("(\\s|,)+"))); } DEFAULT_BLACKLIST = blacklist.build(); } private static final StackTraceSimplifier DEFAULT_INSTACE = newInstance(); private final Collection<String> blacklist; protected StackTraceSimplifier() { this(true); } protected StackTraceSimplifier(boolean includeDefaultBlacklist, String ...packages) { ImmutableSet.Builder<String> blacklistB = ImmutableSet.builder(); if (includeDefaultBlacklist) blacklistB.addAll(DEFAULT_BLACKLIST); blacklistB.add(packages); blacklist = blacklistB.build(); } public static StackTraceSimplifier newInstance() { return new StackTraceSimplifier(); } public static StackTraceSimplifier newInstance(String ...additionalBlacklistPackagePrefixes) { return new StackTraceSimplifier(true, additionalBlacklistPackagePrefixes); } public static StackTraceSimplifier newInstanceExcludingOnly(String ...blacklistPackagePrefixes) { return new StackTraceSimplifier(false, blacklistPackagePrefixes); } /** @return whether the given element is useful, that is, not in the blacklist */ public boolean isUseful(StackTraceElement el) { for (String s: blacklist){ if (el.getClassName().startsWith(s)) return false;; // gets underscores in some contexts ? if (el.getClassName().replace('_', '.').startsWith(s)) return false; } return true; } /** @return new list containing just the {@link #isUseful(StackTraceElement)} stack trace elements */ public List<StackTraceElement> clean(Iterable<StackTraceElement> st) { List<StackTraceElement> result = new LinkedList<StackTraceElement>(); for (StackTraceElement element: st){ if (isUseful(element)){ result.add(element); } } return result; } /** @return new array containing just the {@link #isUseful(StackTraceElement)} stack trace elements */ public StackTraceElement[] clean(StackTraceElement[] st) { List<StackTraceElement> result = clean(Arrays.asList(st)); return result.toArray(new StackTraceElement[result.size()]); } /** @return first {@link #isUseful(StackTraceElement)} stack trace elements, or null */ public StackTraceElement firstUseful(StackTraceElement[] st) { return nthUseful(0, st); } /** @return (n+1)th {@link #isUseful(StackTraceElement)} stack trace elements (ie 0 is {@link #firstUseful(StackTraceElement[])}), or null */ public StackTraceElement nthUseful(int n, StackTraceElement[] st) { for (StackTraceElement element: st){ if (isUseful(element)) { if (n==0) return element; n--; } } return null; } /** {@link #clean(StackTraceElement[])} the given throwable instance, returning the same instance for convenience */ public <T extends Throwable> T cleaned(T t) { t.setStackTrace(clean(t.getStackTrace())); return t; } // ---- statics /** static convenience for {@link #isUseful(StackTraceElement)} */ public static boolean isStackTraceElementUseful(StackTraceElement el) { return DEFAULT_INSTACE.isUseful(el); } /** static convenience for {@link #clean(Iterable)} */ public static List<StackTraceElement> cleanStackTrace(Iterable<StackTraceElement> st) { return DEFAULT_INSTACE.clean(st); } /** static convenience for {@link #clean(StackTraceElement[])} */ public static StackTraceElement[] cleanStackTrace(StackTraceElement[] st) { return DEFAULT_INSTACE.clean(st); } /** static convenience for {@link #cleaned(Throwable)} */ public static <T extends Throwable> T cleanedStackTrace(T t) { return DEFAULT_INSTACE.cleaned(t); } public static String toString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); return sw.getBuffer().toString(); } }
neykov/incubator-brooklyn
utils/common/src/main/java/brooklyn/util/javalang/StackTraceSimplifier.java
Java
apache-2.0
6,792
/* Copyright 2002-2014 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.propagation.events; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.util.FastMath; import org.orekit.errors.OrekitException; import org.orekit.propagation.SpacecraftState; import org.orekit.propagation.events.handlers.EventHandler; import org.orekit.propagation.events.handlers.StopOnDecreasing; import org.orekit.utils.PVCoordinatesProvider; /** Finder for body entering/exiting dihedral FOV events. * <p>This class finds dihedral field of view events (i.e. body entry and exit in FOV).</p> * <p>The default implementation behavior is to {@link * org.orekit.propagation.events.handlers.EventHandler.Action#CONTINUE continue} * propagation at entry and to {@link * org.orekit.propagation.events.handlers.EventHandler.Action#STOP stop} propagation * at exit. This can be changed by calling * {@link #withHandler(EventHandler)} after construction.</p> * @see org.orekit.propagation.Propagator#addEventDetector(EventDetector) * @see CircularFieldOfViewDetector * @author V&eacute;ronique Pommier-Maurussane */ public class DihedralFieldOfViewDetector extends AbstractDetector<DihedralFieldOfViewDetector> { /** Serializable UID. */ private static final long serialVersionUID = 20131118L; /** Position/velocity provider of the considered target. */ private final PVCoordinatesProvider targetPVProvider; /** Direction of the FOV center. */ private final Vector3D center; /** FOV dihedral axis 1. */ private final Vector3D axis1; /** FOV normal to first center plane. */ private final Vector3D normalCenterPlane1; /** FOV dihedral half aperture angle 1. */ private final double halfAperture1; /** FOV dihedral axis 2. */ private final Vector3D axis2; /** FOV normal to second center plane. */ private final Vector3D normalCenterPlane2; /** FOV dihedral half aperture angle 2. */ private final double halfAperture2; /** Build a new instance. * <p>The maximal interval between distance to FOV boundary checks should * be smaller than the half duration of the minimal pass to handle, * otherwise some short passes could be missed.</p> * @param maxCheck maximal interval in seconds * @param pvTarget Position/velocity provider of the considered target * @param center Direction of the FOV center * @param axis1 FOV dihedral axis 1 * @param halfAperture1 FOV dihedral half aperture angle 1 * @param axis2 FOV dihedral axis 2 * @param halfAperture2 FOV dihedral half aperture angle 2 */ public DihedralFieldOfViewDetector(final double maxCheck, final PVCoordinatesProvider pvTarget, final Vector3D center, final Vector3D axis1, final double halfAperture1, final Vector3D axis2, final double halfAperture2) { this(maxCheck, 1.0e-3, DEFAULT_MAX_ITER, new StopOnDecreasing<DihedralFieldOfViewDetector>(), pvTarget, center, axis1, halfAperture1, axis2, halfAperture2); } /** Private constructor with full parameters. * <p> * This constructor is private as users are expected to use the builder * API with the various {@code withXxx()} methods to set up the instance * in a readable manner without using a huge amount of parameters. * </p> * @param maxCheck maximum checking interval (s) * @param threshold convergence threshold (s) * @param maxIter maximum number of iterations in the event time search * @param handler event handler to call at event occurrences * @param pvTarget Position/velocity provider of the considered target * @param center Direction of the FOV center * @param axis1 FOV dihedral axis 1 * @param halfAperture1 FOV dihedral half aperture angle 1 * @param axis2 FOV dihedral axis 2 * @param halfAperture2 FOV dihedral half aperture angle 2 * @since 6.1 */ private DihedralFieldOfViewDetector(final double maxCheck, final double threshold, final int maxIter, final EventHandler<DihedralFieldOfViewDetector> handler, final PVCoordinatesProvider pvTarget, final Vector3D center, final Vector3D axis1, final double halfAperture1, final Vector3D axis2, final double halfAperture2) { super(maxCheck, threshold, maxIter, handler); this.targetPVProvider = pvTarget; this.center = center; // Computation of the center plane normal for dihedra 1 this.axis1 = axis1; this.normalCenterPlane1 = Vector3D.crossProduct(axis1, center); // Computation of the center plane normal for dihedra 2 this.axis2 = axis2; this.normalCenterPlane2 = Vector3D.crossProduct(axis2, center); this.halfAperture1 = halfAperture1; this.halfAperture2 = halfAperture2; } /** {@inheritDoc} */ @Override protected DihedralFieldOfViewDetector create(final double newMaxCheck, final double newThreshold, final int newMaxIter, final EventHandler<DihedralFieldOfViewDetector> newHandler) { return new DihedralFieldOfViewDetector(newMaxCheck, newThreshold, newMaxIter, newHandler, targetPVProvider, center, axis1, halfAperture1, axis2, halfAperture2); } /** Get the position/velocity provider of the target . * @return the position/velocity provider of the target */ public PVCoordinatesProvider getPVTarget() { return targetPVProvider; } /** Get the direction of FOV center. * @return the direction of FOV center */ public Vector3D getCenter() { return center; } /** Get the direction of FOV 1st dihedral axis. * @return the direction of FOV 1st dihedral axis */ public Vector3D getAxis1() { return axis1; } /** Get the half aperture angle of FOV 1st dihedra. * @return the half aperture angle of FOV 1st dihedras */ public double getHalfAperture1() { return halfAperture1; } /** Get the half aperture angle of FOV 2nd dihedra. * @return the half aperture angle of FOV 2nd dihedras */ public double getHalfAperture2() { return halfAperture2; } /** Get the direction of FOV 2nd dihedral axis. * @return the direction of FOV 2nd dihedral axis */ public Vector3D getAxis2() { return axis2; } /** {@inheritDoc} * g function value is the target signed distance to the closest FOV boundary. * It is positive inside the FOV, and negative outside. */ public double g(final SpacecraftState s) throws OrekitException { // Get position of target at current date in spacecraft frame. final Vector3D targetPosInert = new Vector3D(1, targetPVProvider.getPVCoordinates(s.getDate(), s.getFrame()).getPosition(), -1, s.getPVCoordinates().getPosition()); final Vector3D targetPosSat = s.getAttitude().getRotation().applyTo(targetPosInert); // Compute the four angles from the four FOV boundaries. final double angle1 = FastMath.atan2(Vector3D.dotProduct(targetPosSat, normalCenterPlane1), Vector3D.dotProduct(targetPosSat, center)); final double angle2 = FastMath.atan2(Vector3D.dotProduct(targetPosSat, normalCenterPlane2), Vector3D.dotProduct(targetPosSat, center)); // g function value is distance to the FOV boundary, computed as a dihedral angle. // It is positive inside the FOV, and negative outside. return FastMath.min(halfAperture1 - FastMath.abs(angle1) , halfAperture2 - FastMath.abs(angle2)); } }
wardev/orekit
src/main/java/org/orekit/propagation/events/DihedralFieldOfViewDetector.java
Java
apache-2.0
9,006
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import GlobalContext from .halo_attn import HaloAttn from .lambda_layer import LambdaLayer from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .selective_kernel import SelectiveKernel from .split_attn import SplitAttn from .squeeze_excite import SEModule, EffectiveSEModule def get_attn(attn_type): if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type is not None: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network architecture blocks in addition to existing convolutions. if attn_type == 'se': module_cls = SEModule elif attn_type == 'ese': module_cls = EffectiveSEModule elif attn_type == 'eca': module_cls = EcaModule elif attn_type == 'ecam': module_cls = partial(EcaModule, use_mlp=True) elif attn_type == 'ceca': module_cls = CecaModule elif attn_type == 'ge': module_cls = GatherExcite elif attn_type == 'gc': module_cls = GlobalContext elif attn_type == 'gca': module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'lambda': return LambdaLayer elif attn_type == 'bottleneck': return BottleneckAttn elif attn_type == 'halo': return HaloAttn elif attn_type == 'nl': module_cls = NonLocalAttn elif attn_type == 'bat': module_cls = BatNonLocalAttn # Woops! else: assert False, "Invalid attn module (%s)" % attn_type elif isinstance(attn_type, bool): if attn_type: module_cls = SEModule else: module_cls = attn_type return module_cls def create_attn(attn_type, channels, **kwargs): module_cls = get_attn(attn_type) if module_cls is not None: # NOTE: it's expected the first (positional) argument of all attention layers is the # input channels return module_cls(channels, **kwargs) return None
rwightman/pytorch-image-models
timm/models/layers/create_attn.py
Python
apache-2.0
3,526
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.connect.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.connect.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateUseCaseResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateUseCaseResultJsonUnmarshaller implements Unmarshaller<CreateUseCaseResult, JsonUnmarshallerContext> { public CreateUseCaseResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateUseCaseResult createUseCaseResult = new CreateUseCaseResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createUseCaseResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("UseCaseId", targetDepth)) { context.nextToken(); createUseCaseResult.setUseCaseId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("UseCaseArn", targetDepth)) { context.nextToken(); createUseCaseResult.setUseCaseArn(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createUseCaseResult; } private static CreateUseCaseResultJsonUnmarshaller instance; public static CreateUseCaseResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateUseCaseResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-connect/src/main/java/com/amazonaws/services/connect/model/transform/CreateUseCaseResultJsonUnmarshaller.java
Java
apache-2.0
3,047
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {Animated, Easing} from 'react-native'; var Animation = require('../Popover/Animation'); class TooltipAnimation extends Animation { prepareStyle() { const { placement, open, } = this.props; const tooltipPlacement = placement.split('-'); const verticalPlacement = tooltipPlacement [0]; const horizontalPlacement = tooltipPlacement[1]; const offset = verticalPlacement === 'bottom' ? 5 : -5; const {anim} = this.state; return { opacity: this.interpolate(1), transform: [ {translateY: open ? this.interpolate(offset, -offset) : -10000}, ], }; } } module.exports = TooltipAnimation;
glinjy/react-native-apex-ui
src/Tooltip/TooltipAnimation.js
JavaScript
apache-2.0
728
#!/usr/bin/env python2 #pylint: skip-file # # 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/>. DOCUMENTATION = ''' --- module: ec2_ami_find version_added: 2.0 short_description: Searches for AMIs to obtain the AMI ID and other information description: - Returns list of matching AMIs with AMI ID, along with other useful information - Can search AMIs with different owners - Can search by matching tag(s), by AMI name and/or other criteria - Results can be sorted and sliced author: Tom Bamford notes: - This module is not backwards compatible with the previous version of the ec2_search_ami module which worked only for Ubuntu AMIs listed on cloud-images.ubuntu.com. - See the example below for a suggestion of how to search by distro/release. options: region: description: - The AWS region to use. required: true aliases: [ 'aws_region', 'ec2_region' ] owner: description: - Search AMIs owned by the specified owner - Can specify an AWS account ID, or one of the special IDs 'self', 'amazon' or 'aws-marketplace' - If not specified, all EC2 AMIs in the specified region will be searched. - You can include wildcards in many of the search options. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. You can escape special characters using a backslash (\) before the character. For example, a value of \*amazon\?\\ searches for the literal string *amazon?\. required: false default: null ami_id: description: - An AMI ID to match. default: null required: false ami_tags: description: - A hash/dictionary of tags to match for the AMI. default: null required: false architecture: description: - An architecture type to match (e.g. x86_64). default: null required: false hypervisor: description: - A hypervisor type type to match (e.g. xen). default: null required: false is_public: description: - Whether or not the image(s) are public. choices: ['yes', 'no'] default: null required: false name: description: - An AMI name to match. default: null required: false platform: description: - Platform type to match. default: null required: false sort: description: - Optional attribute which with to sort the results. - If specifying 'tag', the 'tag_name' parameter is required. choices: ['name', 'description', 'tag'] default: null required: false sort_tag: description: - Tag name with which to sort results. - Required when specifying 'sort=tag'. default: null required: false sort_order: description: - Order in which to sort results. - Only used when the 'sort' parameter is specified. choices: ['ascending', 'descending'] default: 'ascending' required: false sort_start: description: - Which result to start with (when sorting). - Corresponds to Python slice notation. default: null required: false sort_end: description: - Which result to end with (when sorting). - Corresponds to Python slice notation. default: null required: false state: description: - AMI state to match. default: 'available' required: false virtualization_type: description: - Virtualization type to match (e.g. hvm). default: null required: false no_result_action: description: - What to do when no results are found. - "'success' reports success and returns an empty array" - "'fail' causes the module to report failure" choices: ['success', 'fail'] default: 'success' required: false requirements: - boto ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Search for the AMI tagged "project:website" - ec2_ami_find: owner: self tags: project: website no_result_action: fail register: ami_find # Search for the latest Ubuntu 14.04 AMI - ec2_ami_find: name: "ubuntu/images/ebs/ubuntu-trusty-14.04-amd64-server-*" owner: 099720109477 sort: name sort_order: descending sort_end: 1 register: ami_find # Launch an EC2 instance - ec2: image: "{{ ami_search.results[0].ami_id }}" instance_type: m4.medium key_name: mykey wait: yes ''' try: import boto.ec2 HAS_BOTO=True except ImportError: HAS_BOTO=False import json def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( region = dict(required=True, aliases = ['aws_region', 'ec2_region']), owner = dict(required=False, default=None), ami_id = dict(required=False), ami_tags = dict(required=False, type='dict', aliases = ['search_tags', 'image_tags']), architecture = dict(required=False), hypervisor = dict(required=False), is_public = dict(required=False), name = dict(required=False), platform = dict(required=False), sort = dict(required=False, default=None, choices=['name', 'description', 'tag']), sort_tag = dict(required=False), sort_order = dict(required=False, default='ascending', choices=['ascending', 'descending']), sort_start = dict(required=False), sort_end = dict(required=False), state = dict(required=False, default='available'), virtualization_type = dict(required=False), no_result_action = dict(required=False, default='success', choices = ['success', 'fail']), ) ) module = AnsibleModule( argument_spec=argument_spec, ) if not HAS_BOTO: module.fail_json(msg='boto required for this module, install via pip or your package manager') ami_id = module.params.get('ami_id') ami_tags = module.params.get('ami_tags') architecture = module.params.get('architecture') hypervisor = module.params.get('hypervisor') is_public = module.params.get('is_public') name = module.params.get('name') owner = module.params.get('owner') platform = module.params.get('platform') sort = module.params.get('sort') sort_tag = module.params.get('sort_tag') sort_order = module.params.get('sort_order') sort_start = module.params.get('sort_start') sort_end = module.params.get('sort_end') state = module.params.get('state') virtualization_type = module.params.get('virtualization_type') no_result_action = module.params.get('no_result_action') filter = {'state': state} if ami_id: filter['image_id'] = ami_id if ami_tags: for tag in ami_tags: filter['tag:'+tag] = ami_tags[tag] if architecture: filter['architecture'] = architecture if hypervisor: filter['hypervisor'] = hypervisor if is_public: filter['is_public'] = is_public if name: filter['name'] = name if platform: filter['platform'] = platform if virtualization_type: filter['virtualization_type'] = virtualization_type ec2 = ec2_connect(module) images_result = ec2.get_all_images(owners=owner, filters=filter) if no_result_action == 'fail' and len(images_result) == 0: module.fail_json(msg="No AMIs matched the attributes: %s" % json.dumps(filter)) results = [] for image in images_result: data = { 'ami_id': image.id, 'architecture': image.architecture, 'description': image.description, 'is_public': image.is_public, 'name': image.name, 'owner_id': image.owner_id, 'platform': image.platform, 'root_device_name': image.root_device_name, 'root_device_type': image.root_device_type, 'state': image.state, 'tags': image.tags, 'virtualization_type': image.virtualization_type, } if image.kernel_id: data['kernel_id'] = image.kernel_id if image.ramdisk_id: data['ramdisk_id'] = image.ramdisk_id results.append(data) if sort == 'tag': if not sort_tag: module.fail_json(msg="'sort_tag' option must be given with 'sort=tag'") results.sort(key=lambda e: e['tags'][sort_tag], reverse=(sort_order=='descending')) elif sort: results.sort(key=lambda e: e[sort], reverse=(sort_order=='descending')) try: if sort and sort_start and sort_end: results = results[int(sort_start):int(sort_end)] elif sort and sort_start: results = results[int(sort_start):] elif sort and sort_end: results = results[:int(sort_end)] except TypeError: module.fail_json(msg="Please supply numeric values for sort_start and/or sort_end") module.exit_json(results=results) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * if __name__ == '__main__': main()
attakei/openshift-ansible
playbooks/aws/openshift-cluster/library/ec2_ami_find.py
Python
apache-2.0
9,777
package com.bingoogol.algorithmhome.dao; public interface UserInfoDao { public int plusPrice(String sellerid, int price); public int minusPrice(String buyerid, int price); }
bingoogolapple/J2EENote
algorithmhome/src/main/java/com/bingoogol/algorithmhome/dao/UserInfoDao.java
Java
apache-2.0
177
<?php class CommonAction extends Action { function _initialize() { import('@.ORG.Util.Cookie'); // 用户权限检查 if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) { import('@.ORG.Util.RBAC'); if (!RBAC::AccessDecision()) { //检查认证识别号 if (!$_SESSION [C('USER_AUTH_KEY')]) { //跳转到认证网关 redirect(PHP_FILE . C('USER_AUTH_GATEWAY')); } // 没有权限 抛出错误 if (C('RBAC_ERROR_PAGE')) { // 定义权限错误页面 redirect(C('RBAC_ERROR_PAGE')); } else { if (C('GUEST_AUTH_ON')) { $this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY')); } // 提示错误信息 $this->error(L('_VALID_ACCESS_')); } } } } public function index() { //列表过滤器,生成查询Map对象 $map = $this->_search(); if (method_exists($this, '_filter')) { $this->_filter($map); } $name = $this->getActionName(); $model = D($name); if (!empty($model)) { $this->_list($model, $map); } $this->display(); return; } /** +---------------------------------------------------------- * 取得操作成功后要返回的URL地址 * 默认返回当前模块的默认操作 * 可以在action控制器中重载 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ function getReturnUrl() { return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION'); } /** +---------------------------------------------------------- * 根据表单生成查询条件 * 进行列表过滤 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 数据对象名称 +---------------------------------------------------------- * @return HashMap +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ protected function _search($name = '') { //生成查询条件 if (empty($name)) { $name = $this->getActionName(); } $name = $this->getActionName(); $model = D($name); $map = array(); foreach ($model->getDbFields() as $key => $val) { if (isset($_REQUEST [$val]) && $_REQUEST [$val] != '') { $map [$val] = $_REQUEST [$val]; } } return $map; } /** +---------------------------------------------------------- * 根据表单生成查询条件 * 进行列表过滤 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param Model $model 数据对象 * @param HashMap $map 过滤条件 * @param string $sortBy 排序 * @param boolean $asc 是否正序 +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ protected function _list($model, $map, $sortBy = '', $asc = false) { //排序字段 默认为主键名 if (isset($_REQUEST ['_order'])) { $order = $_REQUEST ['_order']; } else { $order = !empty($sortBy) ? $sortBy : $model->getPk(); } //排序方式默认按照倒序排列 //接受 sost参数 0 表示倒序 非0都 表示正序 if (isset($_REQUEST ['_sort'])) { $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc'; } else { $sort = $asc ? 'asc' : 'desc'; } //取得满足条件的记录数 $count = $model->where($map)->count('id'); if ($count > 0) { import("@.ORG.Util.Page"); //创建分页对象 if (!empty($_REQUEST ['listRows'])) { $listRows = $_REQUEST ['listRows']; } else { $listRows = ''; } $p = new Page($count, $listRows); //分页查询数据 $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select(); //echo $model->getlastsql(); //分页跳转的时候保证查询条件 foreach ($map as $key => $val) { if (!is_array($val)) { $p->parameter .= "$key=" . urlencode($val) . "&"; } } //分页显示 $page = $p->show(); //列表排序显示 $sortImg = $sort; //排序图标 $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示 $sort = $sort == 'desc' ? 1 : 0; //排序方式 //模板赋值显示 $this->assign('list', $voList); $this->assign('sort', $sort); $this->assign('order', $order); $this->assign('sortImg', $sortImg); $this->assign('sortType', $sortAlt); $this->assign("page", $page); } cookie('_currentUrl_', __SELF__); return; } function insert() { $name = $this->getActionName(); $model = D($name); if (false === $model->create()) { $this->error($model->getError()); } //保存当前数据对象 $list = $model->add(); if ($list !== false) { //保存成功 $this->success('新增成功!',cookie('_currentUrl_')); } else { //失败提示 $this->error('新增失败!'); } } function read() { $this->edit(); } function edit() { $name = $this->getActionName(); $model = M($name); $id = $_REQUEST [$model->getPk()]; $vo = $model->getById($id); $this->assign('vo', $vo); $this->display(); } function update() { $name = $this->getActionName(); $model = D($name); if (false === $model->create()) { $this->error($model->getError()); } // 更新数据 $list = $model->save(); if (false !== $list) { //成功提示 $this->success('编辑成功!',cookie('_currentUrl_')); } else { //错误提示 $this->error('编辑失败!'); } } /** +---------------------------------------------------------- * 默认删除操作 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function delete() { //删除指定记录 $name = $this->getActionName(); $model = M($name); if (!empty($model)) { $pk = $model->getPk(); $id = $_REQUEST [$pk]; if (isset($id)) { $condition = array($pk => array('in', explode(',', $id))); $list = $model->where($condition)->setField('status', - 1); if ($list !== false) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } else { $this->error('非法操作'); } } } public function foreverdelete() { //删除指定记录 $name = $this->getActionName(); $model = D($name); if (!empty($model)) { $pk = $model->getPk(); $id = $_REQUEST [$pk]; if (isset($id)) { $condition = array($pk => array('in', explode(',', $id))); if (false !== $model->where($condition)->delete()) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } else { $this->error('非法操作'); } } $this->forward(); } public function clear() { //删除指定记录 $name = $this->getActionName(); $model = D($name); if (!empty($model)) { if (false !== $model->where('status=1')->delete()) { $this->success(L('_DELETE_SUCCESS_'),$this->getReturnUrl()); } else { $this->error(L('_DELETE_FAIL_')); } } $this->forward(); } /** +---------------------------------------------------------- * 默认禁用操作 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws FcsException +---------------------------------------------------------- */ public function forbid() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_REQUEST [$pk]; $condition = array($pk => array('in', $id)); $list = $model->forbid($condition); if ($list !== false) { $this->success('状态禁用成功',$this->getReturnUrl()); } else { $this->error('状态禁用失败!'); } } public function checkPass() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->checkPass($condition)) { $this->success('状态批准成功!',$this->getReturnUrl()); } else { $this->error('状态批准失败!'); } } public function recycle() { $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->recycle($condition)) { $this->success('状态还原成功!',$this->getReturnUrl()); } else { $this->error('状态还原失败!'); } } public function recycleBin() { $map = $this->_search(); $map ['status'] = - 1; $name = $this->getActionName(); $model = D($name); if (!empty($model)) { $this->_list($model, $map); } $this->display(); } /** +---------------------------------------------------------- * 默认恢复操作 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws FcsException +---------------------------------------------------------- */ function resume() { //恢复指定记录 $name = $this->getActionName(); $model = D($name); $pk = $model->getPk(); $id = $_GET [$pk]; $condition = array($pk => array('in', $id)); if (false !== $model->resume($condition)) { $this->success('状态恢复成功!',$this->getReturnUrl()); } else { $this->error('状态恢复失败!'); } } function saveSort() { $seqNoList = $_POST ['seqNoList']; if (!empty($seqNoList)) { //更新数据对象 $name = $this->getActionName(); $model = D($name); $col = explode(',', $seqNoList); //启动事务 $model->startTrans(); foreach ($col as $val) { $val = explode(':', $val); $model->id = $val [0]; $model->sort = $val [1]; $result = $model->save(); if (!$result) { break; } } //提交事务 $model->commit(); if ($result !== false) { //采用普通方式跳转刷新页面 $this->success('更新成功'); } else { $this->error($model->getError()); } } } }
T649781645/ltbl
Lib/Action/Admin/CommonAction.class.php
PHP
apache-2.0
13,739
# Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for common notifications.""" import copy from oslo.config import cfg from nova.compute import flavors from nova.compute import task_states from nova.compute import vm_states from nova import context from nova import db from nova.network import api as network_api from nova import notifications from nova import test from nova.tests import fake_network from nova.tests import fake_notifier CONF = cfg.CONF CONF.import_opt('compute_driver', 'nova.virt.driver') class NotificationsTestCase(test.TestCase): def setUp(self): super(NotificationsTestCase, self).setUp() self.net_info = fake_network.fake_get_instance_nw_info(self.stubs, 1, 1) def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return self.net_info self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) fake_network.set_stub_network_methods(self.stubs) fake_notifier.stub_notifier(self.stubs) self.addCleanup(fake_notifier.reset) self.flags(compute_driver='nova.virt.fake.FakeDriver', network_manager='nova.network.manager.FlatManager', notify_on_state_change="vm_and_task_state", host='testhost') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.instance = self._wrapped_create() def _wrapped_create(self, params=None): instance_type = flavors.get_flavor_by_name('m1.tiny') sys_meta = flavors.save_flavor_info({}, instance_type) inst = {} inst['image_ref'] = 1 inst['user_id'] = self.user_id inst['project_id'] = self.project_id inst['instance_type_id'] = instance_type['id'] inst['root_gb'] = 0 inst['ephemeral_gb'] = 0 inst['access_ip_v4'] = '1.2.3.4' inst['access_ip_v6'] = 'feed:5eed' inst['display_name'] = 'test_instance' inst['hostname'] = 'test_instance_hostname' inst['node'] = 'test_instance_node' inst['system_metadata'] = sys_meta if params: inst.update(params) return db.instance_create(self.context, inst) def test_send_api_fault_disabled(self): self.flags(notify_api_faults=False) notifications.send_api_fault("http://example.com/foo", 500, None) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_send_api_fault(self): self.flags(notify_api_faults=True) exception = None try: # Get a real exception with a call stack. raise test.TestingException("junk") except test.TestingException as e: exception = e notifications.send_api_fault("http://example.com/foo", 500, exception) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) n = fake_notifier.NOTIFICATIONS[0] self.assertEqual(n.priority, 'ERROR') self.assertEqual(n.event_type, 'api.fault') self.assertEqual(n.payload['url'], 'http://example.com/foo') self.assertEqual(n.payload['status'], 500) self.assertIsNotNone(n.payload['exception']) def test_notif_disabled(self): # test config disable of the notifications self.flags(notify_on_state_change=None) old = copy.copy(self.instance) self.instance["vm_state"] = vm_states.ACTIVE old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) notifications.send_update(self.context, old, self.instance) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_task_notif(self): # test config disable of just the task state notifications self.flags(notify_on_state_change="vm_state") # we should not get a notification on task stgate chagne now old = copy.copy(self.instance) self.instance["task_state"] = task_states.SPAWNING old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) # ok now enable task state notifications and re-try self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update(self.context, old, self.instance) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_send_no_notif(self): # test notification on send no initial vm state: old_vm_state = self.instance['vm_state'] new_vm_state = self.instance['vm_state'] old_task_state = self.instance['task_state'] new_task_state = self.instance['task_state'] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, service="compute", host=None, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_send_on_vm_change(self): # pretend we just transitioned to ACTIVE: params = {"vm_state": vm_states.ACTIVE} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_send_on_task_change(self): # pretend we just transitioned to task SPAWNING: params = {"task_state": task_states.SPAWNING} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_no_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_vm_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.ACTIVE, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] node = self.instance["node"] self.assertEqual(vm_states.BUILDING, payload["old_state"]) self.assertEqual(vm_states.ACTIVE, payload["state"]) self.assertEqual(task_states.SPAWNING, payload["old_task_state"]) self.assertEqual(task_states.SPAWNING, payload["new_task_state"]) self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) self.assertEqual(payload["display_name"], display_name) self.assertEqual(payload["hostname"], hostname) self.assertEqual(payload["node"], node) def test_task_update_with_states(self): self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, verify_states=True) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] self.assertEqual(vm_states.BUILDING, payload["old_state"]) self.assertEqual(vm_states.BUILDING, payload["state"]) self.assertEqual(task_states.SPAWNING, payload["old_task_state"]) self.assertIsNone(payload["new_task_state"]) self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) self.assertEqual(payload["display_name"], display_name) self.assertEqual(payload["hostname"], hostname) def test_update_no_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('compute.testhost', notif.publisher_id) def test_update_with_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, service="testservice") self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('testservice.testhost', notif.publisher_id) def test_update_with_host_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, host="someotherhost") self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('compute.someotherhost', notif.publisher_id) def test_payload_has_fixed_ip_labels(self): info = notifications.info_from_instance(self.context, self.instance, self.net_info, None) self.assertIn("fixed_ips", info) self.assertEqual(info["fixed_ips"][0]["label"], "test1") def test_send_access_ip_update(self): notifications.send_update(self.context, self.instance, self.instance) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) def test_send_name_update(self): param = {"display_name": "new_display_name"} new_name_inst = self._wrapped_create(params=param) notifications.send_update(self.context, self.instance, new_name_inst) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload old_display_name = self.instance["display_name"] new_display_name = new_name_inst["display_name"] self.assertEqual(payload["old_display_name"], old_display_name) self.assertEqual(payload["display_name"], new_display_name) def test_send_no_state_change(self): called = [False] def sending_no_state_change(context, instance, **kwargs): called[0] = True self.stubs.Set(notifications, '_send_instance_update_notification', sending_no_state_change) notifications.send_update(self.context, self.instance, self.instance) self.assertTrue(called[0]) def test_fail_sending_update(self): def fail_sending(context, instance, **kwargs): raise Exception('failed to notify') self.stubs.Set(notifications, '_send_instance_update_notification', fail_sending) notifications.send_update(self.context, self.instance, self.instance) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))
CiscoSystems/nova
nova/tests/test_notifications.py
Python
apache-2.0
13,358
package fr.eurecom.hotspots.web; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import com.googlecode.mp4parser.authoring.tracks.TextTrackImpl.Line; import fr.eurecom.hotspots.core.HotSpotGenerator; import fr.eurecom.hotspots.datastructures.Timeline; public class main { public static void main(String[] args) { String subtitleString = null; String chapterString = null; //Parse Chapters from TED try { subtitleString = FileUtils.readFileToString(new File("./alanna_shaikh/alanna_shaikh.srt")); chapterString = FileUtils.readFileToString(new File ("./alanna_shaikh/alanna_shaikh.ch")); System.out.println(chapterString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } HotSpotGenerator hpG = new HotSpotGenerator ("http://linkedtv.eurecom.fr/video/6c75499e-d840-4914-ad2b-d5ff9511c7f7", false, subtitleString, chapterString, "6c75499e-d840-4914-ad2b-d5ff9511c7f7"); String resultsjson = hpG.generate(); System.out.println(resultsjson); } }
jluisred/HotSpots
src/fr/eurecom/hotspots/web/main.java
Java
apache-2.0
1,105
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.provider.te.tunnel; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onosproject.incubator.net.tunnel.Tunnel; import org.onosproject.incubator.net.tunnel.TunnelDescription; import org.onosproject.incubator.net.tunnel.TunnelId; import org.onosproject.incubator.net.tunnel.TunnelProvider; import org.onosproject.incubator.net.tunnel.TunnelProviderRegistry; import org.onosproject.net.DeviceId; import org.onosproject.net.ElementId; import org.onosproject.net.Path; import org.onosproject.net.provider.AbstractProvider; import org.onosproject.net.provider.ProviderId; import org.onosproject.protocol.restconf.RestConfSBController; import org.onosproject.protocol.restconf.RestconfNotificationEventListener; import org.onosproject.provider.te.utils.DefaultJsonCodec; import org.onosproject.provider.te.utils.YangCompositeEncodingImpl; import org.onosproject.tetopology.management.api.TeTopology; import org.onosproject.tetopology.management.api.TeTopologyKey; import org.onosproject.tetopology.management.api.TeTopologyService; import org.onosproject.tetunnel.api.TeTunnelProviderService; import org.onosproject.tetunnel.api.TeTunnelService; import org.onosproject.tetunnel.api.tunnel.DefaultTeTunnel; import org.onosproject.tetunnel.api.tunnel.TeTunnel; import org.onosproject.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.te.rev20160705.IetfTe; import org.onosproject.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.te.rev20160705.ietfte.tunnelsgrouping.Tunnels; import org.onosproject.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.te.types.rev20160705.IetfTeTypes; import org.onosproject.yms.ych.YangCodecHandler; import org.onosproject.yms.ych.YangCompositeEncoding; import org.onosproject.yms.ych.YangProtocolEncodingFormat; import org.onosproject.yms.ymsm.YmsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import java.util.Optional; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.onosproject.provider.te.utils.CodecTools.jsonToString; import static org.onosproject.provider.te.utils.CodecTools.toJson; import static org.onosproject.tetopology.management.api.TeTopology.BIT_MERGED; import static org.onosproject.teyang.utils.tunnel.TunnelConverter.buildIetfTe; import static org.onosproject.teyang.utils.tunnel.TunnelConverter.yang2TeTunnel; import static org.onosproject.yms.ych.YangProtocolEncodingFormat.JSON; import static org.onosproject.yms.ych.YangResourceIdentifierType.URI; import static org.onosproject.yms.ydt.YmsOperationType.EDIT_CONFIG_REQUEST; import static org.onosproject.yms.ydt.YmsOperationType.QUERY_REPLY; /** * Provider which uses RESTCONF to do cross-domain tunnel creation/deletion/ * update/deletion and so on operations on the domain networks. */ @Component(immediate = true) public class TeTunnelRestconfProvider extends AbstractProvider implements TunnelProvider { private final Logger log = LoggerFactory.getLogger(getClass()); private static final String SCHEMA = "ietf"; private static final String IETF = "ietf"; private static final String TE = "te"; private static final int DEFAULT_INDEX = 1; private static final String TUNNELS = "tunnels"; private static final String TUNNELS_URL = IETF + ":" + TE + "/" + TUNNELS; private static final String IETF_NOTIFICATION_URI = "netconf"; private static final String MEDIA_TYPE_JSON = "json"; private static final String SHOULD_IN_ONE = "Tunnel should be setup in one topo"; private static final String PROVIDER_ID = "org.onosproject.provider.ietf"; private static final String RESTCONF_ROOT = "/onos/restconf"; private static final String TE_TUNNEL_KEY = "TeTunnelKey"; //private final RestconfNotificationEventListener listener = // new InternalTunnelNotificationListener(); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected RestConfSBController controller; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected YmsService ymsService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected TeTunnelService tunnelService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected TeTunnelProviderService providerService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected TeTopologyService topologyService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected TunnelProviderRegistry tunnelProviderRegistry; private YangCodecHandler codecHandler; @Activate public void activate() { tunnelProviderRegistry.register(this); codecHandler = ymsService.getYangCodecHandler(); codecHandler.addDeviceSchema(IetfTe.class); codecHandler.addDeviceSchema(IetfTeTypes.class); codecHandler.registerOverriddenCodec(new DefaultJsonCodec(ymsService), YangProtocolEncodingFormat.JSON); collectInitialTunnels(); subscribe(); log.info("Started"); } @Deactivate public void deactivate() { tunnelProviderRegistry.unregister(this); unsubscribe(); log.info("Stopped"); } public TeTunnelRestconfProvider() { super(new ProviderId(SCHEMA, PROVIDER_ID)); } private void collectInitialTunnels() { for (DeviceId deviceId : controller.getDevices().keySet()) { ObjectNode jsonNodes = executeGetRequest(deviceId); if (jsonNodes == null) { continue; } ObjectNode tunnelsNode = (ObjectNode) jsonNodes.get(TUNNELS); if (tunnelsNode == null) { continue; } Tunnels teTunnels = getYangTunnelsObject(tunnelsNode); if (teTunnels == null) { continue; } updateTeTunnels(teTunnels); } } private void subscribe() { for (DeviceId deviceId : controller.getDevices().keySet()) { try { if (!controller.isNotificationEnabled(deviceId)) { controller.enableNotifications(deviceId, IETF_NOTIFICATION_URI, "application/json", new InternalTunnelNotificationListener()); } else { controller.addNotificationListener(deviceId, new InternalTunnelNotificationListener()); } } catch (Exception e) { log.error("Failed to subscribe for {} : {}", deviceId, e.getMessage()); } } } private void unsubscribe() { controller.getDevices() .keySet() .forEach(deviceId -> controller .removeNotificationListener(deviceId, new InternalTunnelNotificationListener())); } @Override public void setupTunnel(Tunnel tunnel, Path path) { TeTunnel teTunnel = tunnelService.getTeTunnel(tunnel.tunnelId()); long tid = teTunnel.srcNode().topologyId(); checkState(tid == teTunnel.dstNode().topologyId(), SHOULD_IN_ONE); setupTunnel(getOwnDevice(tid), tunnel, path); } @Override public void setupTunnel(ElementId srcElement, Tunnel tunnel, Path path) { if (!tunnel.annotations().keys().contains(TE_TUNNEL_KEY)) { log.warn("No tunnel key info in tunnel {}", tunnel); return; } String teTunnelKey = tunnel.annotations().value(TE_TUNNEL_KEY); Optional<TeTunnel> optTunnel = tunnelService.getTeTunnels() .stream() .filter(t -> t.teTunnelKey().toString().equals(teTunnelKey)) .findFirst(); if (!optTunnel.isPresent()) { log.warn("No te tunnel map to tunnel {}", tunnel); return; } IetfTe ietfTe = buildIetfTe(optTunnel.get(), true); YangCompositeEncoding encoding = codecHandler. encodeCompositeOperation(RESTCONF_ROOT, null, ietfTe, JSON, EDIT_CONFIG_REQUEST); String identifier = encoding.getResourceIdentifier(); String resourceInformation = encoding.getResourceInformation(); if (srcElement == null) { log.error("Can't find remote device for tunnel : {}", tunnel); return; } controller.post((DeviceId) srcElement, identifier, new ByteArrayInputStream(resourceInformation.getBytes()), MEDIA_TYPE_JSON, ObjectNode.class); } @Override public void releaseTunnel(Tunnel tunnel) { //TODO implement release tunnel method } @Override public void releaseTunnel(ElementId srcElement, Tunnel tunnel) { //TODO implement release tunnel with src method } @Override public void updateTunnel(Tunnel tunnel, Path path) { //TODO implement update tunnel method } @Override public void updateTunnel(ElementId srcElement, Tunnel tunnel, Path path) { //TODO implement update tunnel with src method } @Override public TunnelId tunnelAdded(TunnelDescription tunnel) { //TODO implement tunnel add method when te tunnel app merged to core return null; } @Override public void tunnelRemoved(TunnelDescription tunnel) { //TODO implement tunnel remove method when te tunnel app merged to core } @Override public void tunnelUpdated(TunnelDescription tunnel) { //TODO implement tunnel update method when te tunnel app merged to core } @Override public Tunnel tunnelQueryById(TunnelId tunnelId) { return null; } private ObjectNode executeGetRequest(DeviceId deviceId) { //the request url is ietf-te:te/tunnels //the response node will begin with tunnels //be careful here to when get the tunnels data InputStream resultStream = controller.get(deviceId, TUNNELS_URL, MEDIA_TYPE_JSON); return toJson(resultStream); } private Tunnels getYangTunnelsObject(ObjectNode tunnelsNode) { checkNotNull(tunnelsNode, "Input object node should not be null"); YangCompositeEncoding yce = new YangCompositeEncodingImpl(URI, TUNNELS_URL, jsonToString(tunnelsNode)); Object yo = codecHandler.decode(yce, JSON, QUERY_REPLY); if (yo == null) { log.error("YMS decoder returns null"); return null; } IetfTe ietfTe = null; Tunnels tunnels = null; if (yo instanceof List) { List<Object> list = (List<Object>) yo; ietfTe = (IetfTe) list.get(DEFAULT_INDEX); } if (ietfTe != null && ietfTe.te() != null) { tunnels = ietfTe.te().tunnels(); } return tunnels; } private void updateTeTunnels(Tunnels tunnels) { TeTopologyKey key = getTopologyKey(); tunnels.tunnel().forEach(tunnel -> { DefaultTeTunnel teTunnel = yang2TeTunnel(tunnel, key); providerService.updateTeTunnel(teTunnel); }); } private TeTopologyKey getTopologyKey() { TeTopologyKey key = null; Optional<TeTopology> teTopology = topologyService.teTopologies() .teTopologies() .values() .stream() .filter(topology -> topology.flags().get(BIT_MERGED)) .findFirst(); if (teTopology.isPresent()) { TeTopology topology = teTopology.get(); key = topology.teTopologyId(); } return key; } private DeviceId getOwnDevice(long topologyId) { DeviceId deviceId = null; Optional<TeTopology> topoOpt = topologyService.teTopologies() .teTopologies() .values() .stream() .filter(tp -> tp.teTopologyId().topologyId() == topologyId) .findFirst(); if (topoOpt.isPresent()) { deviceId = topoOpt.get().ownerId(); } return deviceId; } private class InternalTunnelNotificationListener implements RestconfNotificationEventListener { @Override public void handleNotificationEvent(DeviceId deviceId, Object eventJsonString) { ObjectNode response = toJson((String) eventJsonString); if (response == null) { return; } JsonNode teNode = response.get(TE); if (teNode == null) { log.error("Illegal te json object from {}", deviceId); return; } JsonNode tunnelsNode = teNode.get(TUNNELS); if (tunnelsNode == null) { log.error("Illegal tunnel json object from {}", deviceId); return; } Tunnels tunnels = getYangTunnelsObject((ObjectNode) tunnelsNode); if (tunnels == null) { return; } updateTeTunnels(tunnels); } } }
LorenzReinhart/ONOSnew
providers/ietfte/tunnel/src/main/java/org/onosproject/provider/te/tunnel/TeTunnelRestconfProvider.java
Java
apache-2.0
14,517
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.remoting.transport.netty4.logging; /** * Holds the results of formatting done by {@link MessageFormatter}. */ class FormattingTuple { static final FormattingTuple NULL = new FormattingTuple(null); private final String message; private final Throwable throwable; private final Object[] argArray; FormattingTuple(String message) { this(message, null, null); } FormattingTuple(String message, Object[] argArray, Throwable throwable) { this.message = message; this.throwable = throwable; if (throwable == null) { this.argArray = argArray; } else { this.argArray = trimmedCopy(argArray); } } static Object[] trimmedCopy(Object[] argArray) { if (argArray == null || argArray.length == 0) { throw new IllegalStateException("non-sensical empty or null argument array"); } final int trimemdLen = argArray.length - 1; Object[] trimmed = new Object[trimemdLen]; System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); return trimmed; } public String getMessage() { return message; } public Object[] getArgArray() { return argArray; } public Throwable getThrowable() { return throwable; } }
dadarom/dubbo
dubbo-remoting/dubbo-remoting-netty4/src/main/java/com/alibaba/dubbo/remoting/transport/netty4/logging/FormattingTuple.java
Java
apache-2.0
2,138
<?php /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define('LOG5PHP_DIR', dirname(__FILE__).'/../../main/php'); define('LOG5PHP_LINE_SEP', "\n"); define('LOG5PHP_CONFIGURATION', dirname(__FILE__).'/ndc.xml'); require_once LOG5PHP_DIR . '/autoload.inc.php'; spl_autoload_register('Log5PHP_autoload'); Log5PHP_NDC::push('Context Message'); $logger = Log5PHP_Manager::getRootLogger(); $logger->debug("Testing NDC"); Log5PHP_NDC::pop(); ?>
teamlazerbeez/PHP
Log5PHP/src/examples/php/ndc.php
PHP
apache-2.0
1,201
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.devicefarm.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.devicefarm.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreateDevicePoolRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateDevicePoolRequestProtocolMarshaller implements Marshaller<Request<CreateDevicePoolRequest>, CreateDevicePoolRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("DeviceFarm_20150623.CreateDevicePool").serviceName("AWSDeviceFarm").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreateDevicePoolRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateDevicePoolRequest> marshall(CreateDevicePoolRequest createDevicePoolRequest) { if (createDevicePoolRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreateDevicePoolRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, createDevicePoolRequest); protocolMarshaller.startMarshalling(); CreateDevicePoolRequestMarshaller.getInstance().marshall(createDevicePoolRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/CreateDevicePoolRequestProtocolMarshaller.java
Java
apache-2.0
2,719
package uk.ac.ucl.eidp.data; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * * @author David Guzman {@literal d.guzman at ucl.ac.uk} */ @Qualifier @Retention(RUNTIME) @Target( {TYPE, METHOD, FIELD, PARAMETER} ) public @interface NodeQualifier { /** * The NodeType value will tell {@link StrategyResolver} how to connect to a database. * @return {@link NodeType} the type of database node to connect to (pool, remote EIDP, jdbc) */ NodeType value(); }
UCL/EIDP-4
eidpdata/src/main/java/uk/ac/ucl/eidp/data/NodeQualifier.java
Java
apache-2.0
823
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ParquetSharp.External { public abstract class FSDataInputStream : InputStream { internal void seek(long footerIndex) { throw new NotImplementedException(); } internal void close() { throw new NotImplementedException(); } } }
CurtHagenlocher/ParquetSharp
ParquetHadoop/src/External/FSDataInputStream.cs
C#
apache-2.0
1,146
/** * DataHibernatorWorker.java * * Created on 24 October 2007, 18:10 * * To change this template, choose Tools | Template Manager and open the template in the editor. */ package uk.co.sleonard.unison.input; import java.util.ArrayList; import java.util.ListIterator; import java.util.concurrent.LinkedBlockingQueue; import org.apache.log4j.Logger; import org.hibernate.Session; import uk.co.sleonard.unison.UNISoNLogger; import uk.co.sleonard.unison.datahandling.HibernateHelper; /** * The Class DataHibernatorWorker. * * @author Stephen <github@leonarduk.com> * @since v1.0.0 * */ public class DataHibernatorWorker extends SwingWorker { /** The logger. */ private static Logger logger = Logger.getLogger("DataHibernatorWorker"); /** The number of hibernators. */ private static int numberofHibernators = 20; /** The log. */ private static UNISoNLogger log; /** The workers. */ private static ArrayList<DataHibernatorWorker> workers = new ArrayList<>(); /** The reader. */ private final NewsGroupReader reader; /** The save to database. */ private boolean saveToDatabase = true; private final HibernateHelper helper; private final LinkedBlockingQueue<NewsArticle> queue; private final Session session; /** * Sets the logger. * * @param logger * the new logger */ public static void setLogger(final UNISoNLogger logger) { DataHibernatorWorker.log = logger; } /** * Start hibernators. * * @param helper2 * @param queue2 * @param session2 */ public synchronized static void startHibernators(final NewsGroupReader nntpReader, final HibernateHelper helper2, final LinkedBlockingQueue<NewsArticle> queue2, final Session session2) { while (DataHibernatorWorker.workers.size() < DataHibernatorWorker.numberofHibernators) { DataHibernatorWorker.workers .add(new DataHibernatorWorker(nntpReader, helper2, queue2, session2)); } } /** * Stop download. */ static void stopDownload() { for (final ListIterator<DataHibernatorWorker> iter = DataHibernatorWorker.workers .listIterator(); iter.hasNext();) { iter.next().interrupt(); } } /** * Creates a new instance of DataHibernatorWorker. * * @param reader * the reader * @param helper2 * @param session */ private DataHibernatorWorker(final NewsGroupReader reader, final HibernateHelper helper2, final LinkedBlockingQueue<NewsArticle> queue, final Session session2) { super("DataHibernatorWorker"); this.helper = helper2; this.reader = reader; this.queue = queue; this.session = session2; DataHibernatorWorker.logger .debug("Creating " + this.getClass() + " " + reader.getNumberOfMessages()); this.start(); } /* * (non-Javadoc) * * @see uk.co.sleonard.unison.input.SwingWorker#construct() */ @Override public Object construct() { DataHibernatorWorker.logger .debug("construct : " + this.saveToDatabase + " queue " + this.queue.size()); try { // HAve one session per worker rather than per message while (this.saveToDatabase) { this.pollQueue(this.queue, this.session); // wait a second Thread.sleep(5000); // completed save so close down if (this.queue.isEmpty()) { this.saveToDatabase = false; } } DataHibernatorWorker.workers.remove(this); if (DataHibernatorWorker.workers.size() == 0) { DataHibernatorWorker.log.alert("Download complete"); } } catch (@SuppressWarnings("unused") final InterruptedException e) { return "Interrupted"; } return "Completed"; } /** * Poll for message. * * @param queue * the queue * @return the news article */ private synchronized NewsArticle pollForMessage(final LinkedBlockingQueue<NewsArticle> queue) { final NewsArticle article = queue.poll(); return article; } private void pollQueue(final LinkedBlockingQueue<NewsArticle> queue, final Session session) throws InterruptedException { while (!queue.isEmpty()) { if (Thread.interrupted()) { this.stopHibernatingData(); throw new InterruptedException(); } final NewsArticle article = this.pollForMessage(queue); if (null != article) { DataHibernatorWorker.logger .debug("Hibernating " + article.getArticleId() + " " + queue.size()); if (this.helper.hibernateData(article, session)) { this.reader.incrementMessagesStored(); } else { this.reader.incrementMessagesSkipped(); } this.reader.showDownloadStatus(); } } } /** * Stop hibernating data. */ private void stopHibernatingData() { DataHibernatorWorker.logger.warn("StopHibernatingData"); this.saveToDatabase = false; } }
leonarduk/unison
src/main/java/uk/co/sleonard/unison/input/DataHibernatorWorker.java
Java
apache-2.0
4,719
package com.ek.mobileapp.model; import java.io.Serializable; public abstract class Entity implements Serializable { protected int id; public int getId() { return id; } protected String cacheKey; public String getCacheKey() { return cacheKey; } public void setCacheKey(String cacheKey) { this.cacheKey = cacheKey; } }
yangjiandong/MobileBase.G
MobileBase/src/main/java/com/ek/mobileapp/model/Entity.java
Java
apache-2.0
380
# Generated by Django 2.1.7 on 2019-04-23 06:03 import diventi.accounts.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0050_auto_20190421_2252'), ] operations = [ migrations.AlterModelManagers( name='diventiuser', managers=[ ('objects', diventi.accounts.models.DiventiUserManager()), ], ), ]
flavoi/diventi
diventi/accounts/migrations/0051_auto_20190423_0803.py
Python
apache-2.0
452
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using WinBeacon.Stack; using WinBeacon.Stack.Hci.Events; namespace WinBeacon { /// <summary> /// Class that represents a Beacon. /// </summary> public class Beacon : IComparable { private const int AppleCompanyId = 0x4C00; /// <summary> /// UUID of the beacon. /// </summary> public string Uuid { get; private set; } /// <summary> /// Bluetooth MAC-address of the beacon. /// </summary> public byte[] Address { get; private set; } /// <summary> /// Major number of the beacon. /// </summary> public int Major { get; private set; } /// <summary> /// Minor number of the beacon. /// </summary> public int Minor { get; private set; } /// <summary> /// RSSI power of the beacon in dB. /// </summary> public int Rssi { get; internal set; } /// <summary> /// Calibrated TX power of the beacon in dB. /// </summary> public int CalibratedTxPower { get; private set; } /// <summary> /// CompanyId of the beacon (0x4C00 for Apple iBeacon). /// </summary> public int CompanyId { get; private set; } /// <summary> /// True if the beacon is an (emulation of) Apple iBeacon. /// </summary> public bool IsAppleIBeacon { get { return CompanyId == AppleCompanyId; } } private Beacon() { } /// <summary> /// Creates a beacon. /// </summary> /// <param name="uuid">UUID of the beacon.</param> /// <param name="major">Major number of the beacon.</param> /// <param name="minor">Minor number of the beacon.</param> /// <param name="companyId">CompanyId, defaults to comapny id of Apple (0x4C00).</param> /// <param name="calibratedTxPower">Calibrated TX power of the beacon in dB.</param> public Beacon(string uuid, int major, int minor, int calibratedTxPower, int companyId = AppleCompanyId) { Uuid = uuid; Major = major; Minor = minor; CalibratedTxPower = calibratedTxPower; CompanyId = companyId; } /// <summary> /// Compare this beacon to an other instance. /// </summary> /// <param name="obj">The other instance.</param> /// <returns>A value that indicates the lexical relationship between the two comparands.</returns> public int CompareTo(object obj) { var other = obj as Beacon; if (other == null) throw new ArgumentException("Must be of type Beacon", "obj"); return Uuid.NullableCompareTo(other.Uuid) ?? Major.NullableCompareTo(other.Major) ?? Minor.CompareTo(other.Minor); } /// <summary> /// Returns a string representation of the beacon data. /// </summary> /// <returns>String representation of the beacon data.</returns> public override string ToString() { return string.Format("UUID: {0}, Address: {1}, Major: {2}, Minor: {3}, RSSI: {4}, TxPower: {5}dB, CompanyId: 0x{6:X}, Distance: {7:0.00}m", Uuid, BitConverter.ToString(Address), Major, Minor, Rssi, CalibratedTxPower, CompanyId, this.GetRange()); } /// <summary> /// Parse low energy advertising event to a beacon instance. /// </summary> /// <param name="e">The event.</param> /// <returns>The beacon or null in case of failure.</returns> internal static Beacon Parse(LeAdvertisingEvent e) { if (e.EventType == LeAdvertisingEventType.ScanRsp) return null; if (e.Payload.Length < 9) return null; var payload = new Queue<byte>(e.Payload); var ad1Length = payload.Dequeue(); var ad1Type = payload.Dequeue(); var flags = payload.Dequeue(); var ad2Length = payload.Dequeue(); var ad2Type = payload.Dequeue(); var companyId = (ushort)((payload.Dequeue() << 8) + payload.Dequeue()); var b0advInd = payload.Dequeue(); var b1advInd = payload.Dequeue(); if (ad1Length != 2 || ad1Type != 0x01 || ad2Length < 26 || ad2Type != 0xFF) return null; var uuid = payload.Dequeue(16); var major = (ushort)((payload.Dequeue() << 8) + payload.Dequeue()); var minor = (ushort)((payload.Dequeue() << 8) + payload.Dequeue()); var txPower = (sbyte)payload.Dequeue(); return new Beacon { Uuid = uuid.ToLittleEndianFormattedUuidString(), Address = e.Address, Major = major, Minor = minor, Rssi = e.Rssi, CalibratedTxPower = txPower, CompanyId = companyId }; } internal byte[] ToAdvertisingData() { var result = new List<byte>(); result.AddRange(new byte[] { 0x02, // ad1Length 0x01, // ad1Type 0x1A, // flags 0x1A, // ad2Length 0xFF, // ad2Type (byte)(CompanyId >> 8), (byte)(CompanyId & 0xFF), 0x02, // b0advInd 0x15 // b1advInd }); result.AddRange(Uuid.FromLittleEndianFormattedUuidString()); result.AddRange(new byte[] { (byte)(Major >> 8), (byte)(Major & 0xFF), (byte)(Minor >> 8), (byte)(Minor & 0xFF), (byte)CalibratedTxPower }); return result.ToArray(); } } }
ghkim69/win-beacon
src/WinBeacon/Beacon.cs
C#
apache-2.0
6,592
<?php header('Content-Type:text/html;charset=utf-8'); //$query=isset($_REQUEST['q'])?$_REQUEST['q']:false; $query="*:*"; $results=false; if($query&&isset($_REQUEST['q'])) { if($_REQUEST['q']=="grobid"||$_REQUEST['q']=="geotopic"||$_REQUEST['q']=="sweet") { require_once('solr-php-client/Apache/Solr/Service.php'); $solr=new Apache_Solr_Service('localhost',8983,'/solr/'.$_REQUEST['q']); if(get_magic_quotes_gpc()==1) { $query=stripslashes($query); } try { $additionalParameters=array( 'indent'=>'true' ); $results=$solr->search($query,$additionalParameters); $output=fopen($_REQUEST['q'].".json","w"); } catch(Exception $e) { die("<html><head><title>SEARCH EXCEPTION</title><body><pre>{$e->__toString()}</pre></body></html>"); } } } ?> <html> <head> <title>Polar-data Visualizations</title> </head> <body> <form accept-charset="utf-8" method="get"> <label for="q">Search:</label> <!--<input id="q" name="q" type="text" value="<?php echo htmlspecialchars($query,ENT_QUOTES,'utf-8');?>"/>--> <select name="q" id="q"> <option value="grobid">Grobid Information(Based on Publications)</option> <option value="metadatascores">Metadata Scores of files</option> <option value="geotopic">Geo Locations found</option> <option value="sweet">Sweet Ontologies Exctracted</option> <option value="measurements1">Measurements units found in 100 files</option> <option value="measurements2">Measurement Units Histogram of all files</option> </select> <input type="submit"/> </form> <?php if($results) { ?> <script> var file="<?php echo $_REQUEST['q']?>"; window.open("http://localhost:786/"+file); </script> <?php } ?> </body> </html>
usc-cs599-group5/Content_Enrichment
Part12/D3VisualizationsWebsite.php
PHP
apache-2.0
1,782
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rao2100.starter.utils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author openetdev */ public class SystemdJournalUtilsTest { public SystemdJournalUtilsTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of send method, of class SystemdJournalUtils. */ @Test public void testSend() { System.out.println("send"); SystemdJournalUtils.send(); } /** * Test of send method, of class SystemdJournalUtils. */ @Test public void testRead() { System.out.println("read"); // SystemdJournalUtils.read(); } }
rao2100/SpringBootStarter
src/test/java/com/rao2100/starter/utils/SystemdJournalUtilsTest.java
Java
apache-2.0
1,156
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ILPathways.Utilities; using IOER.classes; using ILPathways.Business; using LRWarehouse.Business; using IOER.Controllers; using LDAL = LRWarehouse.DAL; using MyManager = Isle.BizServices.AccountServices; using CurrentUser = LRWarehouse.Business.Patron; namespace IOER.secure { public partial class IsleSSO : IOER.Library.BaseAppPage { protected void Page_Load(object sender, EventArgs e) { //if not using admin/login2.aspx template, will need to do the following: //this should be handled by the secure template now, so hide, or make configurable string host = Request.ServerVariables["HTTP_HOST"]; if (Request.IsSecureConnection == false) { if (UtilityManager.GetAppKeyValue("SSLEnable", "0") == "1") { host = host.Replace(":80", ""); //do redirect Response.Redirect("https://" + host + Request.Url.PathAndQuery); } } else { //is secure if (UtilityManager.GetAppKeyValue("SSLEnable", "0") == "0") { //should not be https host = host.Replace(":80", ""); Response.Redirect("http://" + host + Request.Url.PathAndQuery); } } } } }
siuccwd/IOER
Presentation/IOER.web/secure/IsleSSO.aspx.cs
C#
apache-2.0
1,581
package br.ufpe.sabertecnologias.acervoapp.ui.callbacks; import java.util.ArrayList; import br.ufpe.sabertecnologias.acervoapp.modelo.dados.Grupo; /** * Created by joaotrindade on 25/10/16. */ public interface GruposCallback{ public void abrirGrupo(Grupo g); public void exit(); void notifyGrupoController(ArrayList<Grupo> mGrupos); }
Saber-Tecnologias/acervo-app
app/src/main/java/br/ufpe/sabertecnologias/acervoapp/ui/callbacks/GruposCallback.java
Java
apache-2.0
351
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateService', 'ProjectsService', 'QuotaService', 'SecurityCheckService', 'TaskList', 'keyValueEditorUtils', ProcessTemplate ], controllerAs: '$ctrl', bindings: { template: '<', project: '<', onProjectSelected: '<', availableProjects: '<', prefillParameters: '<', isDialog: '<' }, templateUrl: 'views/directives/process-template.html' }); function ProcessTemplate($filter, $q, $scope, $uibModal, APIDiscovery, APIService, DataService, Navigate, NotificationsService, ProcessedTemplateService, ProjectsService, QuotaService, SecurityCheckService, TaskList, keyValueEditorUtils) { var ctrl = this; var context; var displayName = $filter('displayName'); var humanize = $filter('humanize'); ctrl.noProjectsCantCreate = false; function getHelpLinks(template) { var helpLinkName = /^helplink\.(.*)\.title$/; var helpLinkURL = /^helplink\.(.*)\.url$/; var helpLinks = {}; for (var attr in template.annotations) { var match = attr.match(helpLinkName); var link; if (match) { link = helpLinks[match[1]] || {}; link.title = template.annotations[attr]; helpLinks[match[1]] = link; } else { match = attr.match(helpLinkURL); if (match) { link = helpLinks[match[1]] || {}; link.url = template.annotations[attr]; helpLinks[match[1]] = link; } } } return helpLinks; } ctrl.$onInit = function() { ctrl.labels = []; // Make a copy of the template to avoid modifying the original if it's cached. ctrl.template = angular.copy(ctrl.template); ctrl.templateDisplayName = displayName(ctrl.template); ctrl.selectedProject = ctrl.project; $scope.$watch('$ctrl.selectedProject.metadata.name', function() { ctrl.projectNameTaken = false; }); $scope.$on('no-projects-cannot-create', function() { ctrl.noProjectsCantCreate = true; }); setTemplateParams(); }; var processedResources; var createResources = function() { var titles = { started: "Creating " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject), success: "Created " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject), failure: "Failed to create " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject) }; var helpLinks = getHelpLinks(ctrl.template); TaskList.clear(); TaskList.add(titles, helpLinks, ctrl.selectedProject.metadata.name, function() { var chain = $q.when(); var alerts = []; var hasErrors = false; _.each(processedResources, function(obj) { var groupVersionKind = APIDiscovery.toResourceGroupVersion(obj); chain = chain.then(function() { return DataService.create(groupVersionKind, null, obj, context) .then(function() { alerts.push({ type: "success", message: "Created " + humanize(obj.kind).toLowerCase() + " \"" + obj.metadata.name + "\" successfully. " }); }) .catch(function(failure) { hasErrors = true; alerts.push({ type: "error", message: "Cannot create " + humanize(obj.kind).toLowerCase() + " \"" + obj.metadata.name + "\". ", details: failure.message }); }); }); }); return chain.then(function() { return { alerts: alerts, hasErrors: hasErrors }; }); }); if (ctrl.isDialog) { $scope.$emit('templateInstantiated', { project: ctrl.selectedProject, template: ctrl.template }); } else { Navigate.toNextSteps(ctrl.templateDisplayName, ctrl.selectedProject.metadata.name); } }; var launchConfirmationDialog = function(alerts) { var modalInstance = $uibModal.open({ templateUrl: 'views/modals/confirm.html', controller: 'ConfirmModalController', resolve: { modalConfig: function() { return { alerts: alerts, title: "Confirm Creation", details: "We checked your application for potential problems. Please confirm you still want to create this application.", okButtonText: "Create Anyway", okButtonClass: "btn-danger", cancelButtonText: "Cancel" }; } } }); modalInstance.result.then(createResources); }; var alerts = {}; var hideNotificationErrors = function() { NotificationsService.hideNotification("process-template-error"); _.each(alerts, function(alert) { if (alert.id && (alert.type === 'error' || alert.type === 'warning')) { NotificationsService.hideNotification(alert.id); } }); }; var showWarningsOrCreate = function(result) { // Hide any previous notifications when form is resubmitted. hideNotificationErrors(); alerts = SecurityCheckService.getSecurityAlerts(processedResources, ctrl.selectedProject.metadata.name); // Now that all checks are completed, show any Alerts if we need to var quotaAlerts = result.quotaAlerts || []; alerts = alerts.concat(quotaAlerts); var errorAlerts = _.filter(alerts, {type: 'error'}); if (errorAlerts.length) { ctrl.disableInputs = false; _.each(alerts, function(alert) { alert.id = _.uniqueId('process-template-alert-'); NotificationsService.addNotification(alert); }); } else if (alerts.length) { launchConfirmationDialog(alerts); ctrl.disableInputs = false; } else { createResources(); } }; var createProjectIfNecessary = function() { if (_.has(ctrl.selectedProject, 'metadata.uid')) { return $q.when(ctrl.selectedProject); } var newProjName = ctrl.selectedProject.metadata.name; var newProjDisplayName = ctrl.selectedProject.metadata.annotations['new-display-name']; var newProjDesc = $filter('description')(ctrl.selectedProject); return ProjectsService.create(newProjName, newProjDisplayName, newProjDesc); }; var getProcessTemplateVersionForTemplate = function(template) { var rgv = APIService.objectToResourceGroupVersion(template); rgv.resource = 'processedtemplates'; return rgv; }; ctrl.createFromTemplate = function() { ctrl.disableInputs = true; createProjectIfNecessary().then(function(project) { ctrl.selectedProject = project; context = { namespace: ctrl.selectedProject.metadata.name }; ctrl.template.labels = keyValueEditorUtils.mapEntries(keyValueEditorUtils.compactEntries(ctrl.labels)); var rgv = getProcessTemplateVersionForTemplate(ctrl.template); DataService.create(rgv, null, ctrl.template, context).then( function(config) { // success // Cache template parameters and message so they can be displayed in the nexSteps page ProcessedTemplateService.setTemplateData(config.parameters, ctrl.template.parameters, config.message); processedResources = config.objects; QuotaService.getLatestQuotaAlerts(processedResources, context).then(showWarningsOrCreate); }, function(result) { // failure ctrl.disableInputs = false; var details; if (result.data && result.data.message) { details = result.data.message; } NotificationsService.addNotification({ id: "process-template-error", type: "error", message: "An error occurred processing the template.", details: details }); } ); }, function(result) { ctrl.disableInputs = false; if (result.data.reason === 'AlreadyExists') { ctrl.projectNameTaken = true; } else { var details; if (result.data && result.data.message) { details = result.data.message; } NotificationsService.addNotification({ id: "process-template-error", type: "error", message: "An error occurred creating the project.", details: details }); } }); }; // Only called when not in a dialog. ctrl.cancel = function() { hideNotificationErrors(); Navigate.toProjectOverview(ctrl.project.metadata.name); }; // When the process-template component is displayed in a dialog, the create // button is outside the component since it is in the wizard footer. Listen // for an event for when the button is clicked. $scope.$on('instantiateTemplate', ctrl.createFromTemplate); $scope.$on('$destroy', hideNotificationErrors); var shouldAddAppLabel = function() { // If the template defines its own app label, we don't need to add one at all if (_.get(ctrl.template, 'labels.app')) { return false; } // Otherwise check if an object in the template has an app label defined return !_.some(ctrl.template.objects, "metadata.labels.app"); }; function setTemplateParams() { if(ctrl.prefillParameters) { _.each(ctrl.template.parameters, function(parameter) { if (ctrl.prefillParameters[parameter.name]) { parameter.value = ctrl.prefillParameters[parameter.name]; } }); } ctrl.labels = _.map(ctrl.template.labels, function(value, key) { return { name: key, value: value }; }); if (shouldAddAppLabel()) { ctrl.labels.push({ name: 'app', value: ctrl.template.metadata.name }); } } } })();
openshift/origin-web-console
app/scripts/directives/processTemplate.js
JavaScript
apache-2.0
10,871
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.schedassist.web.security; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jasig.schedassist.impl.owner.NotRegisteredException; import org.jasig.schedassist.model.ICalendarAccount; import org.jasig.schedassist.model.IDelegateCalendarAccount; import org.jasig.schedassist.model.IScheduleOwner; import org.springframework.security.core.GrantedAuthority; /** * {@link CalendarAccountUserDetails} implementation for {@link IDelegateCalendarAccount}s. * * @author Nicholas Blair, nblair@doit.wisc.edu * @version $Id: DelegateCalendarAccountUserDetailsImpl.java 2306 2010-07-28 17:20:12Z npblair $ */ public class DelegateCalendarAccountUserDetailsImpl implements CalendarAccountUserDetails { /** * */ private static final long serialVersionUID = 53706L; private static final String EMPTY = ""; private final IDelegateCalendarAccount delegateCalendarAccount; private IScheduleOwner scheduleOwner; /** * * @param delegateCalendarAccount */ public DelegateCalendarAccountUserDetailsImpl(IDelegateCalendarAccount delegateCalendarAccount) { this(delegateCalendarAccount, null); } /** * @param delegateCalendarAccount * @param delegateScheduleOwner */ public DelegateCalendarAccountUserDetailsImpl( IDelegateCalendarAccount delegateCalendarAccount, IScheduleOwner delegateScheduleOwner) { this.delegateCalendarAccount = delegateCalendarAccount; this.scheduleOwner = delegateScheduleOwner; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getAuthorities() */ public Collection<GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if(null != this.delegateCalendarAccount && this.delegateCalendarAccount.isEligible()) { authorities.add(SecurityConstants.DELEGATE_REGISTER); } if(null != this.scheduleOwner) { authorities.add(SecurityConstants.DELEGATE_OWNER); authorities.remove(SecurityConstants.DELEGATE_REGISTER); } return Collections.unmodifiableList(authorities); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getPassword() */ public String getPassword() { return EMPTY; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getUsername() */ public String getUsername() { return this.delegateCalendarAccount.getUsername(); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired() */ public boolean isAccountNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked() */ public boolean isAccountNonLocked() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired() */ public boolean isCredentialsNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isEnabled() */ public boolean isEnabled() { return null != this.delegateCalendarAccount ? this.delegateCalendarAccount.isEligible() : false; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getActiveDisplayName() */ public String getActiveDisplayName() { StringBuilder display = new StringBuilder(); display.append(this.delegateCalendarAccount.getDisplayName()); display.append(" (managed by "); display.append(this.delegateCalendarAccount.getAccountOwner().getUsername()); display.append(")"); return display.toString(); } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getCalendarAccount() */ @Override public ICalendarAccount getCalendarAccount() { return getDelegateCalendarAccount(); } /** * * @return the {@link IDelegateCalendarAccount} */ public IDelegateCalendarAccount getDelegateCalendarAccount() { return this.delegateCalendarAccount; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getScheduleOwner() */ @Override public IScheduleOwner getScheduleOwner() throws NotRegisteredException { if(null == this.scheduleOwner) { throw new NotRegisteredException(this.delegateCalendarAccount + " is not registered"); } else { return this.scheduleOwner; } } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#isDelegate() */ @Override public final boolean isDelegate() { return true; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#updateScheduleOwner(org.jasig.schedassist.model.IScheduleOwner) */ @Override public void updateScheduleOwner(IScheduleOwner owner) { this.scheduleOwner = owner; } }
nblair/sometime
sometime-war/src/main/java/org/jasig/schedassist/web/security/DelegateCalendarAccountUserDetailsImpl.java
Java
apache-2.0
5,819
var zz = { Internal: { Local: { FS: { File: {}, Directory: {} } } } }; zz.Internal.Local.FS.File.read = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.read"); Ti.API.debug("ZZ.Internal.Local.FS.File.read [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var blob = file.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.read unable to read file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.read readed file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.write = function(path, content, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.write"); Ti.API.debug("ZZ.Internal.Local.FS.File.write [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); file.write(content); var blob = file.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.write unable to write file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.write written file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.copy = function(from, to, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.copy"); Ti.API.debug("ZZ.Internal.Local.FS.File.copy [from : " + from + ", to : " + to + "]"); var fromFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, from); var toFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, to); toFile.write(fromFile.read()); var blob = toFile.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.copy unable to copy file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.copy copied to file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.delete = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.delete"); Ti.API.debug("ZZ.Internal.Local.FS.File.delete [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = file.deleteFile(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.File.delete unable to delete file [name : " + file.name + ", nativePath : " + file.nativePath + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.File.delete deleted file [name : " + file.name + ", nativePath : " + file.nativePath + "]"); null != successCallback && successCallback(); return true; }; zz.Internal.Local.FS.Directory.make = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.Directory.make"); Ti.API.debug("ZZ.Internal.Local.FS.Directory.make [path : " + path + "]"); var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = dir.createDirectory(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.Directory.make unable to create directory [name : " + dir.name + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.Directory.make created directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"); null != successCallback && successCallback(); return true; }; zz.Internal.Local.FS.Directory.remove = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove"); var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = dir.deleteDirectory(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.Directory.remove unable to remove directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove removed directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"); null != successCallback && successCallback(); return true; }; exports.ZZ = zz; exports.version = .2; var _manageError = function(error, errorCallback) { Ti.API.trace("ZZ.Internal.Local.FS._manageError"); Ti.API.error(error.errorMessage); null != errorCallback && errorCallback(error); };
Adriano72/ZiriZiri-Daniele
Resources/android/zz.api/zz.internal.local.fs.js
JavaScript
apache-2.0
5,650
# Copyright 2010 http://www.collabq.com import logging from django.conf import settings from django.http import HttpResponseRedirect from common import api from common import exception class VerifyInstallMiddleware(object): def process_request(self, request): logging.info("VerifyInstallMiddleware") logging.info("Path %s" % request.path) if not request.path == '/install': try: root_user = api.actor_get(api.ROOT, settings.ROOT_NICK) logging.info("Root Exists") except: logging.info("Root Does Not Exists") return HttpResponseRedirect('/install')
CollabQ/CollabQ
middleware/verify.py
Python
apache-2.0
608
/* Copyright (C) 2015 Preet Desai (preet.desai@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // stl #include <string> #include <vector> #include <cstdint> #include <unordered_map> #include <algorithm> // glm #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> // ks #include <ks/gl/KsGLVertexBuffer.hpp> namespace ks { namespace gl { const std::vector<GLenum> VertexBuffer::Attribute::list_type_glenums = { GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FLOAT }; const std::vector<u8> VertexBuffer::Attribute::list_type_sizes = { 1, 1, 2, 2, 4 }; // ============================================================= // VertexBuffer::VertexBuffer(std::vector<Attribute::Desc> list_attribs, Usage usage) : Buffer(Target::ArrayBuffer,usage), m_vertex_sz_bytes(calcVertexSize(list_attribs)), m_list_attribs(list_attribs) { } VertexBuffer::~VertexBuffer() { } bool VertexBuffer::GLBindVxBuff(ShaderProgram* shader, uint const offset_bytes) { if(!this->GLBind()) { return false; } std::uintptr_t offset = offset_bytes; // Get the attribute location list for this shader auto attr_it = std::find_if( m_list_shader_attr_locs.begin(), m_list_shader_attr_locs.end(), [shader](AttribLocsByShader const &attrs_by_shader) -> bool { return(attrs_by_shader.first == shader); }); // If we don't already have it cache all attribute // locations for this shader for quick lookup if(attr_it == m_list_shader_attr_locs.end()) { std::vector<GLuint> list_attr_locs; list_attr_locs.reserve(m_list_attribs.size()); for(auto& attr : m_list_attribs) { auto attrib_loc = shader->GetAttributeLocation(attr.m_name); if(attrib_loc < 0) { LOG.Error() << "VertexBuffer::GLBindVxBuff: " "invalid attrib loc: " << attr.m_name; return false; } list_attr_locs.push_back(attrib_loc); } attr_it = m_list_shader_attr_locs.emplace( m_list_shader_attr_locs.end(), shader, list_attr_locs); } // Call glVertexAttribPointer to specify the layout // of the vertex attributes in the buffer data for(size_t i=0; i < m_list_attribs.size(); i++) { GLint const attrib_location = attr_it->second[i]; // TODO // Is it okay to specify vertex attribute locations // out of order? There's no guarantee we specify the // locations (0,1,2...) u8 type_idx = static_cast<u8>(m_list_attribs[i].m_type); // The GLenum that represents the data format of the // attribute (GL_BYTE, GL_UNSIGNED_BYTE, GL_FLOAT, etc) GLenum attrib_type = Attribute::list_type_glenums[type_idx]; glVertexAttribPointer(attrib_location, m_list_attribs[i].m_component_count, attrib_type, m_list_attribs[i].m_normalized, m_vertex_sz_bytes, (const void*)offset); // debug // LOG.Info() << m_log_prefix // << "index: " << attrib_location // << ", size: " << num_components // << ", type: " << attrib_type // << ", normalized: " << m_list_attribs[i].normalized // << ", stride: " << m_vertex_sz // << ", offset: " << 0; offset += m_list_attribs[i].m_sz_bytes; } return true; } u16 VertexBuffer::calcVertexSize( std::vector<Attribute::Desc> const &list_attribs) { u16 vertex_sz_bytes = 0; for(auto &attr_desc : list_attribs) { vertex_sz_bytes += attr_desc.m_sz_bytes; } return vertex_sz_bytes; } } // gl } // ks
preet/ks_gl
ks/gl/KsGLVertexBuffer.cpp
C++
apache-2.0
5,438
/** Copyright 2011-2013 Here's A Hand Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ $(function() { $("input.yes").mouseover(function(){ $(this).attr('value','No'); $(this).removeClass('yes') $(this).addClass('no') }); $("input.yes").mouseout(function(){ $(this).attr('value','Yes'); $(this).removeClass('no') $(this).addClass('yes') }); $("input.no").mouseover(function(){ $(this).attr('value','Yes'); $(this).removeClass('no') $(this).addClass('yes') }); $("input.no").mouseout(function(){ $(this).attr('value','No'); $(this).removeClass('yes') $(this).addClass('no') }); });
Heres-A-Hand/Heres-A-Hand-Web
public_html/js/rollovers.js
JavaScript
apache-2.0
1,099
/** * @license Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; const Runner = require('../../../../runner'); const EstimatedInputLatency = require('../../../../gather/computed/metrics/estimated-input-latency'); // eslint-disable-line const assert = require('assert'); const trace = require('../../../fixtures/traces/progressive-app-m60.json'); const devtoolsLog = require('../../../fixtures/traces/progressive-app-m60.devtools.log.json'); /* eslint-env jest */ describe('Metrics: EIL', () => { it('should compute a simulated value', async () => { const artifacts = Runner.instantiateComputedArtifacts(); const settings = {throttlingMethod: 'simulate'}; const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings}); expect({ timing: Math.round(result.timing), optimistic: Math.round(result.optimisticEstimate.timeInMs), pessimistic: Math.round(result.pessimisticEstimate.timeInMs), }).toMatchSnapshot(); }); it('should compute an observed value', async () => { const artifacts = Runner.instantiateComputedArtifacts(); const settings = {throttlingMethod: 'provided'}; const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings}); assert.equal(Math.round(result.timing * 10) / 10, 17.1); }); describe('#calculateRollingWindowEIL', () => { it('uses a 5s rolling window', async () => { const events = [ {start: 7500, end: 10000, duration: 2500}, {start: 10000, end: 15000, duration: 5000}, ]; assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 4516); }); it('handles continuous tasks', async () => { const events = []; const longTaskDuration = 100; const longTaskNumber = 1000; const shortTaskDuration = 1.1; const shortTaskNumber = 10000; for (let i = 0; i < longTaskNumber; i++) { const start = i * longTaskDuration; events.push({start: start, end: start + longTaskDuration, duration: longTaskDuration}); } const baseline = events[events.length - 1].end; for (let i = 0; i < shortTaskNumber; i++) { const start = i * shortTaskDuration + baseline; events.push({start: start, end: start + shortTaskDuration, duration: shortTaskDuration}); } assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 106); }); }); });
mixed/lighthouse
lighthouse-core/test/gather/computed/metrics/estimated-input-latency-test.js
JavaScript
apache-2.0
2,976
/******************************************************************************\ | | | package-version-file-types-view.js | | | |******************************************************************************| | | | This defines an dialog that is used to select directories within | | package versions. | | | |******************************************************************************| | Copyright (c) 2013 SWAMP - Software Assurance Marketplace | \******************************************************************************/ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'text!templates/packages/info/versions/info/source/dialogs/package-version-file-types.tpl', 'scripts/registry', 'scripts/views/dialogs/error-view', 'scripts/views/files/file-types-list/file-types-list-view' ], function($, _, Backbone, Marionette, Template, Registry, ErrorView, FileTypesListView) { return Backbone.Marionette.LayoutView.extend({ // // attributes // regions: { fileTypes: '#file-types' }, events: { 'click #ok': 'onClickOk', 'keypress': 'onKeyPress' }, // // rendering methods // template: function() { return _.template(Template, { title: this.options.title, packagePath: this.options.packagePath }); }, onRender: function() { this.showFileTypes(); }, showFileTypes: function() { // fetch package version file types // var self = this; this.model.fetchFileTypes({ data: { 'dirname': this.options.packagePath }, // callbacks // success: function(data) { var collection = new Backbone.Collection(); for (var key in data) { collection.add(new Backbone.Model({ 'extension': key, 'count': data[key] })); } self.fileTypes.show( new FileTypesListView({ collection: collection }) ); }, error: function() { // show error dialog // Registry.application.modal.show( new ErrorView({ message: "Could not fetch file types for this package version." }) ); } }); }, // // event handling methods // onClickOk: function() { // apply callback // if (this.options.accept) { this.options.accept(); } }, onKeyPress: function(event) { // respond to enter key press // if (event.keyCode === 13) { this.onClickOk(); this.hide(); } } }); });
OWASP/open-swamp
registry-web-server/var/www/html/scripts/views/packages/info/versions/info/source/dialogs/package-version-file-types-view.js
JavaScript
apache-2.0
2,896
package main import ( "encoding/json" "github.com/coreos/go-raft" "net/http" ) //------------------------------------------------------------- // Handlers to handle raft related request via raft server port //------------------------------------------------------------- // Get all the current logs func GetLogHttpHandler(w http.ResponseWriter, req *http.Request) { debugf("[recv] GET %s/log", r.url) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(r.LogEntries()) } // Response to vote request func VoteHttpHandler(w http.ResponseWriter, req *http.Request) { rvreq := &raft.RequestVoteRequest{} err := decodeJsonRequest(req, rvreq) if err == nil { debugf("[recv] POST %s/vote [%s]", r.url, rvreq.CandidateName) if resp := r.RequestVote(rvreq); resp != nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) return } } warnf("[vote] ERROR: %v", err) w.WriteHeader(http.StatusInternalServerError) } // Response to append entries request func AppendEntriesHttpHandler(w http.ResponseWriter, req *http.Request) { aereq := &raft.AppendEntriesRequest{} err := decodeJsonRequest(req, aereq) if err == nil { debugf("[recv] POST %s/log/append [%d]", r.url, len(aereq.Entries)) if resp := r.AppendEntries(aereq); resp != nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) if !resp.Success { debugf("[Append Entry] Step back") } return } } warnf("[Append Entry] ERROR: %v", err) w.WriteHeader(http.StatusInternalServerError) } // Response to recover from snapshot request func SnapshotHttpHandler(w http.ResponseWriter, req *http.Request) { aereq := &raft.SnapshotRequest{} err := decodeJsonRequest(req, aereq) if err == nil { debugf("[recv] POST %s/snapshot/ ", r.url) if resp := r.RequestSnapshot(aereq); resp != nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) return } } warnf("[Snapshot] ERROR: %v", err) w.WriteHeader(http.StatusInternalServerError) } // Response to recover from snapshot request func SnapshotRecoveryHttpHandler(w http.ResponseWriter, req *http.Request) { aereq := &raft.SnapshotRecoveryRequest{} err := decodeJsonRequest(req, aereq) if err == nil { debugf("[recv] POST %s/snapshotRecovery/ ", r.url) if resp := r.SnapshotRecoveryRequest(aereq); resp != nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) return } } warnf("[Snapshot] ERROR: %v", err) w.WriteHeader(http.StatusInternalServerError) } // Get the port that listening for etcd connecting of the server func EtcdURLHttpHandler(w http.ResponseWriter, req *http.Request) { debugf("[recv] Get %s/etcdURL/ ", r.url) w.WriteHeader(http.StatusOK) w.Write([]byte(argInfo.EtcdURL)) } // Response to the join request func JoinHttpHandler(w http.ResponseWriter, req *http.Request) error { command := &JoinCommand{} if err := decodeJsonRequest(req, command); err == nil { debugf("Receive Join Request from %s", command.Name) return dispatch(command, w, req, false) } else { w.WriteHeader(http.StatusInternalServerError) return nil } } // Response to remove request func RemoveHttpHandler(w http.ResponseWriter, req *http.Request) { if req.Method != "DELETE" { w.WriteHeader(http.StatusMethodNotAllowed) return } nodeName := req.URL.Path[len("/remove/"):] command := &RemoveCommand{ Name: nodeName, } debugf("[recv] Remove Request [%s]", command.Name) dispatch(command, w, req, false) } // Response to the name request func NameHttpHandler(w http.ResponseWriter, req *http.Request) { debugf("[recv] Get %s/name/ ", r.url) w.WriteHeader(http.StatusOK) w.Write([]byte(r.name)) } // Response to the name request func RaftVersionHttpHandler(w http.ResponseWriter, req *http.Request) { debugf("[recv] Get %s/version/ ", r.url) w.WriteHeader(http.StatusOK) w.Write([]byte(r.version)) }
philips/etcd
raft_handlers.go
GO
apache-2.0
3,917
#include "test/integration/filters/process_context_filter.h" #include <memory> #include <string> #include "envoy/http/filter.h" #include "envoy/http/header_map.h" #include "envoy/registry/registry.h" #include "envoy/server/filter_config.h" #include "extensions/filters/http/common/pass_through_filter.h" #include "test/extensions/filters/http/common/empty_http_filter_config.h" namespace Envoy { // A test filter that rejects all requests if the ProcessObject held by the // ProcessContext is unhealthy, and responds OK to all requests otherwise. class ProcessContextFilter : public Http::PassThroughFilter { public: ProcessContextFilter(ProcessContext& process_context) : process_object_(dynamic_cast<ProcessObjectForFilter&>(process_context.get())) {} Http::FilterHeadersStatus decodeHeaders(Http::HeaderMap&, bool) override { if (!process_object_.isHealthy()) { decoder_callbacks_->sendLocalReply(Envoy::Http::Code::InternalServerError, "ProcessObjectForFilter is unhealthy", nullptr, absl::nullopt, ""); return Http::FilterHeadersStatus::StopIteration; } decoder_callbacks_->sendLocalReply(Envoy::Http::Code::OK, "ProcessObjectForFilter is healthy", nullptr, absl::nullopt, ""); return Http::FilterHeadersStatus::StopIteration; } private: ProcessObjectForFilter& process_object_; }; class ProcessContextFilterConfig : public Extensions::HttpFilters::Common::EmptyHttpFilterConfig { public: ProcessContextFilterConfig() : EmptyHttpFilterConfig("process-context-filter") {} Http::FilterFactoryCb createFilter(const std::string&, Server::Configuration::FactoryContext& factory_context) override { return [&factory_context](Http::FilterChainFactoryCallbacks& callbacks) { callbacks.addStreamFilter( std::make_shared<ProcessContextFilter>(*factory_context.processContext())); }; } }; static Registry::RegisterFactory<ProcessContextFilterConfig, Server::Configuration::NamedHttpFilterConfigFactory> register_; } // namespace Envoy
jrajahalme/envoy
test/integration/filters/process_context_filter.cc
C++
apache-2.0
2,187
package eu.tankernn.gameEngine.particles; import java.nio.FloatBuffer; import java.util.List; import java.util.Map; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL31; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import eu.tankernn.gameEngine.entities.Camera; import eu.tankernn.gameEngine.loader.Loader; import eu.tankernn.gameEngine.renderEngine.Vao; import eu.tankernn.gameEngine.renderEngine.Vbo; public class ParticleRenderer { private static final float[] VERTICES = {-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f}; private static final int MAX_INSTANCES = 10000; private static final int INSTANCE_DATA_LENGTH = 21; private static final FloatBuffer buffer = BufferUtils.createFloatBuffer(MAX_INSTANCES * INSTANCE_DATA_LENGTH); private Vao quad; private ParticleShader shader; private Vbo vbo; private int pointer = 0; protected ParticleRenderer(Loader loader, Matrix4f projectionMatrix) { this.vbo = Vbo.create(GL15.GL_ARRAY_BUFFER, GL15.GL_STREAM_DRAW, INSTANCE_DATA_LENGTH * MAX_INSTANCES); quad = loader.loadToVAO(VERTICES, 2); for (int i = 0; i < 5; i++) quad.addInstacedAttribute(vbo, i + 1, 4, INSTANCE_DATA_LENGTH, i * 4); quad.addInstacedAttribute(vbo, 6, 1, INSTANCE_DATA_LENGTH, 20); shader = new ParticleShader(); shader.start(); shader.projectionMatrix.loadMatrix(projectionMatrix); shader.stop(); } protected void render(Map<ParticleTexture, List<IParticle>> particles, Camera camera) { Matrix4f viewMatrix = camera.getViewMatrix(); prepare(); for (ParticleTexture texture: particles.keySet()) { bindTexture(texture); List<IParticle> particleList = particles.get(texture); pointer = 0; float[] vboData = new float[particleList.size() * INSTANCE_DATA_LENGTH]; for (IParticle p: particleList) { updateModelViewMatrix(p.getPosition(), p.getRotation(), p.getScale(), viewMatrix, vboData); updateTexCoordInfo(p, vboData); } vbo.updateData(vboData, buffer); GL31.glDrawArraysInstanced(GL11.GL_TRIANGLE_STRIP, 0, quad.getIndexCount(), particleList.size()); } finishRendering(); } @Override protected void finalize() { shader.finalize(); } private void updateTexCoordInfo(IParticle p, float[] data) { data[pointer++] = p.getTexOffset1().x; data[pointer++] = p.getTexOffset1().y; data[pointer++] = p.getTexOffset2().x; data[pointer++] = p.getTexOffset2().y; data[pointer++] = p.getBlend(); } private void bindTexture(ParticleTexture texture) { int blendType = texture.usesAdditiveBlending() ? GL11.GL_ONE : GL11.GL_ONE_MINUS_SRC_ALPHA; GL11.glBlendFunc(GL11.GL_SRC_ALPHA, blendType); texture.getTexture().bindToUnit(0); shader.numberOfRows.loadFloat(texture.getNumberOfRows()); } private void updateModelViewMatrix(Vector3f position, float rotation, float scale, Matrix4f viewMatrix, float[] vboData) { Matrix4f modelMatrix = new Matrix4f(); Matrix4f.translate(position, modelMatrix, modelMatrix); //Sets rotation of model matrix to transpose of rotation of view matrix modelMatrix.m00 = viewMatrix.m00; modelMatrix.m01 = viewMatrix.m10; modelMatrix.m02 = viewMatrix.m20; modelMatrix.m10 = viewMatrix.m01; modelMatrix.m11 = viewMatrix.m11; modelMatrix.m12 = viewMatrix.m21; modelMatrix.m20 = viewMatrix.m02; modelMatrix.m21 = viewMatrix.m12; modelMatrix.m22 = viewMatrix.m22; Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0, 0, 1), modelMatrix, modelMatrix); Matrix4f.rotate((float) Math.toRadians(180), new Vector3f(1, 0, 0), modelMatrix, modelMatrix); Matrix4f.scale(new Vector3f(scale, scale, scale), modelMatrix, modelMatrix); Matrix4f modelViewMatrix = Matrix4f.mul(viewMatrix, modelMatrix, null); storeMatrixData(modelViewMatrix, vboData); } private void storeMatrixData(Matrix4f matrix, float[] vboData) { vboData[pointer++] = matrix.m00; vboData[pointer++] = matrix.m01; vboData[pointer++] = matrix.m02; vboData[pointer++] = matrix.m03; vboData[pointer++] = matrix.m10; vboData[pointer++] = matrix.m11; vboData[pointer++] = matrix.m12; vboData[pointer++] = matrix.m13; vboData[pointer++] = matrix.m20; vboData[pointer++] = matrix.m21; vboData[pointer++] = matrix.m22; vboData[pointer++] = matrix.m23; vboData[pointer++] = matrix.m30; vboData[pointer++] = matrix.m31; vboData[pointer++] = matrix.m32; vboData[pointer++] = matrix.m33; } private void prepare() { shader.start(); quad.bind(0, 1, 2, 3, 4, 5, 6); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); } private void finishRendering() { GL11.glDepthMask(true); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_CULL_FACE); quad.unbind(0, 1, 2, 3, 4, 5, 6); shader.stop(); } }
Tankernn/TankernnGameEngine
src/main/java/eu/tankernn/gameEngine/particles/ParticleRenderer.java
Java
apache-2.0
4,913
"""schmankerl URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from schmankerlapp import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), #restaurant url(r'^restaurant/sign-in/$', auth_views.login, {'template_name': 'restaurant/sign-in.html'}, name = 'restaurant-sign-in'), url(r'^restaurant/sign-out', auth_views.logout, {'next_page': '/'}, name='restaurant-sign-out'), url(r'^restaurant/sign-up', views.restaurant_sign_up, name='restaurant-sign-up'), url(r'^restaurant/$', views.restaurant_home, name='restaurant-home'), url(r'^restaurant/account/$', views.restaurant_account, name='restaurant-account'), url(r'^restaurant/meal/$', views.restaurant_meal, name='restaurant-meal'), url(r'^restaurant/meal/add$', views.restaurant_add_meal, name='restaurant-add-meal'), url(r'^restaurant/order/$', views.restaurant_order, name='restaurant-order'), url(r'^restaurant/report/$', views.restaurant_report, name='restaurant-report'), #sign-up, sign-in, sign-out url(r'^api/social/', include('rest_framework_social_oauth2.urls')), # /convert-token (sign-in, sign-out) # /revoke-token (sign-out) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MarxDimitri/schmankerl
schmankerl/urls.py
Python
apache-2.0
2,082
package com.ppweather.app.activity; import com.ppweather.app.R; import com.ppweather.app.service.AutoUpdateService; import com.ppweather.app.util.HttpCallbackListener; import com.ppweather.app.util.HttpUtil; import com.ppweather.app.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; /** * 显示城市名 */ private TextView cityNameText; /** * 显示发布时间 */ private TextView publishText; /** * 显示天气描述信息 */ private TextView weatherDespText; /** * 显示气温1 */ private TextView temp1Text; /** * 显示气温2 */ private TextView temp2Text; /** * 显示当前日期 */ private TextView currentDateText; /** * 切换城市 */ private Button switchCity; /** *更新天气 */ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); weatherInfoLayout = (LinearLayout)findViewById(R.id.weather_info_layout); cityNameText = (TextView)findViewById(R.id.city_name); publishText = (TextView)findViewById(R.id.publish_text); weatherDespText = (TextView)findViewById(R.id.weather_desp); temp1Text = (TextView)findViewById(R.id.temp1); temp2Text = (TextView)findViewById(R.id.temp2); currentDateText = (TextView)findViewById(R.id.current_date); switchCity = (Button)findViewById(R.id.switch_city); refreshWeather = (Button)findViewById(R.id.refresh_weather); switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { //有县级代号时就去查询天气 publishText.setText("同步中。。。"); Log.d("ssss", "countyCode = " + countyCode); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { //没有县级代号就直接显示本地天气 showWeather(); } } /** * 查询县级代号对应的天气代号 * @param countyCode */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"; queryFromServer(address, "countyCode"); } /** * 查询天气代号对应的天气 * @param weatherCode */ private void queryWeatherInfo(String weatherCode) { String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; queryFromServer(address, "weatherCode"); } private void queryFromServer(final String address, final String type) { // TODO Auto-generated method stub HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { // TODO Auto-generated method stub if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { String[] array = response.split("\\|"); if (array != null && array.length == 2) { String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if("weatherCode".equals(type)) { Log.d("ssss", "weatherCode run "); Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showWeather(); } }); } } @Override public void onError(Exception e) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub publishText.setText("同步失败"); } }); } }); } /** * 从SharedPreference文件中读取存储的天气信息,并显示到桌面上 */ private void showWeather() { // TODO Auto-generated method stub SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); Log.d("ssss", "cityNameText = " + cityNameText.getText()); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("今天" + prefs.getString("publish_time", "") + "发布"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); //在showWeather中启动AutoUpdateService。这样一旦选中某城市并成功更新天气,AutoUpdateService就会在后台运行,并8小时更新一次天气 Intent intent = new Intent(this,AutoUpdateService.class); startService(intent); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.switch_city: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("同步中..."); //从SharedPreferences中读取天气代号 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } default: break; } } }
mynamecsl/ppweather
src/com/ppweather/app/activity/WeatherActivity.java
Java
apache-2.0
5,935
package move import ( "github.com/oakmound/oak/v3/collision" "github.com/oakmound/oak/v3/physics" "github.com/oakmound/oak/v3/render" ) // A Mover can move its position, renderable, and space. Unless otherwise documented, // functions effecting a mover move all of its logical position, renderable, and space // simultaneously. type Mover interface { Vec() physics.Vector GetRenderable() render.Renderable GetDelta() physics.Vector GetSpace() *collision.Space GetSpeed() physics.Vector }
oakmound/oak
entities/x/move/mover.go
GO
apache-2.0
498
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as _ from 'lodash'; export class ApplicationType { public name: string; public id: string; public description: string; public icon: string; public oauth?: any; public configuration: any; public default_grant_types: Array<any>; public requires_redirect_uris: boolean; public allowed_grant_types: Array<any>; public mandatory_grant_types: Array<any>; constructor({ name, id, description, requires_redirect_uris, allowed_grant_types, default_grant_types, mandatory_grant_types }) { this.id = id; this.name = name; this.description = description; this.requires_redirect_uris = requires_redirect_uris; this.allowed_grant_types = allowed_grant_types; this.default_grant_types = default_grant_types; this.mandatory_grant_types = mandatory_grant_types; this.icon = this.getIcon(); } public isOauth() { return this.id.toLowerCase() !== 'simple'; } public isGrantTypeMandatory(grantType: { type }): boolean { return this.mandatory_grant_types && _.indexOf(this.mandatory_grant_types, grantType.type) !== -1; } private getIcon() { switch (this.id.toUpperCase()) { case 'BROWSER': return 'computer'; case 'WEB': return 'language'; case 'NATIVE': return 'phone_android'; case 'BACKEND_TO_BACKEND': return 'share'; default: return 'pan_tool'; } } }
gravitee-io/gravitee-management-webui
src/entities/application.ts
TypeScript
apache-2.0
2,034
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an AS IS BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and# # limitations under the License. import logging from taskflow.patterns import linear_flow from pumphouse import exceptions from pumphouse import events from pumphouse import task LOG = logging.getLogger(__name__) class RetrieveUser(task.BaseCloudTask): def execute(self, user_id): user = self.cloud.keystone.users.get(user_id) self.cloud.identity.fetch(user.id) return user.to_dict() class EnsureUser(task.BaseCloudTask): def execute(self, user_info, tenant_info): try: user = self.cloud.keystone.users.find(name=user_info["name"]) # TODO(akscram): Current password should be replaced by temporary. except exceptions.keystone_excs.NotFound: user = self.cloud.keystone.users.create( name=user_info["name"], # TODO(akscram): Here we should generate a temporary # password for the user and use them # along the migration process. # The RepairUserPasswords should repair # original after all operations. password="default", email=user_info["email"], tenant_id=tenant_info["id"] if tenant_info else None, enabled=user_info["enabled"], ) self.created_event(user) return user.to_dict() def created_event(self, user): LOG.info("Created user: %s", user) events.emit("create", { "id": user.id, "type": "user", "cloud": self.cloud.name, "data": user.to_dict(), }, namespace="/events") class EnsureOrphanUser(EnsureUser): def execute(self, user_info): super(EnsureOrphanUser, self).execute(user_info, None) class EnsureUserRole(task.BaseCloudTask): def execute(self, user_info, role_info, tenant_info): try: self.cloud.keystone.tenants.add_user(tenant_info["id"], user_info["id"], role_info["id"]) except exceptions.keystone_excs.Conflict: pass else: self.role_assigned_event(role_info, user_info, tenant_info) return user_info def role_assigned_event(self, role_info, user_info, tenant_info): LOG.info("Created role %s assignment for user %s in tenant %s", role_info["id"], user_info["id"], tenant_info["id"]) def migrate_membership(context, user_id, role_id, tenant_id): user_ensure = "user-{}-ensure".format(user_id) role_ensure = "role-{}-ensure".format(role_id) tenant_ensure = "tenant-{}-ensure".format(tenant_id) user_role_ensure = "user-role-{}-{}-{}-ensure".format(user_id, role_id, tenant_id) task = EnsureUserRole(context.dst_cloud, name=user_role_ensure, provides=user_role_ensure, rebind=[user_ensure, role_ensure, tenant_ensure]) context.store[user_role_ensure] = user_role_ensure return task def migrate_user(context, user_id, tenant_id=None): user_binding = "user-{}".format(user_id) user_retrieve = "{}-retrieve".format(user_binding) user_ensure = "{}-ensure".format(user_binding) flow = linear_flow.Flow("migrate-user-{}".format(user_id)) flow.add(RetrieveUser(context.src_cloud, name=user_binding, provides=user_binding, rebind=[user_retrieve])) if tenant_id is not None: tenant_ensure = "tenant-{}-ensure".format(tenant_id) flow.add(EnsureUser(context.dst_cloud, name=user_ensure, provides=user_ensure, rebind=[user_binding, tenant_ensure])) else: flow.add(EnsureUser(context.dst_cloud, name=user_ensure, provides=user_ensure, rebind=[user_binding], inject={"tenant_info": None})) context.store[user_retrieve] = user_id return flow
Mirantis/pumphouse
pumphouse/tasks/user.py
Python
apache-2.0
4,857
package builder import ( "github.com/fsouza/go-dockerclient" "github.com/golang/glog" stiapi "github.com/openshift/source-to-image/pkg/api" sti "github.com/openshift/source-to-image/pkg/build/strategies" "github.com/openshift/origin/pkg/build/api" ) // STIBuilder performs an STI build given the build object type STIBuilder struct { dockerClient DockerClient dockerSocket string authPresent bool auth docker.AuthConfiguration build *api.Build } // NewSTIBuilder creates a new STIBuilder instance func NewSTIBuilder(client DockerClient, dockerSocket string, authCfg docker.AuthConfiguration, authPresent bool, build *api.Build) *STIBuilder { return &STIBuilder{ dockerClient: client, dockerSocket: dockerSocket, authPresent: authPresent, auth: authCfg, build: build, } } // Build executes the STI build func (s *STIBuilder) Build() error { tag := s.build.Parameters.Output.DockerImageReference request := &stiapi.Request{ BaseImage: s.build.Parameters.Strategy.STIStrategy.Image, DockerSocket: s.dockerSocket, Source: s.build.Parameters.Source.Git.URI, ContextDir: s.build.Parameters.Source.ContextDir, Tag: tag, ScriptsURL: s.build.Parameters.Strategy.STIStrategy.Scripts, Environment: getBuildEnvVars(s.build), Incremental: s.build.Parameters.Strategy.STIStrategy.Incremental, } if s.build.Parameters.Revision != nil && s.build.Parameters.Revision.Git != nil && s.build.Parameters.Revision.Git.Commit != "" { request.Ref = s.build.Parameters.Revision.Git.Commit } else if s.build.Parameters.Source.Git.Ref != "" { request.Ref = s.build.Parameters.Source.Git.Ref } glog.V(2).Infof("Creating a new STI builder with build request: %#v\n", request) builder, err := sti.GetStrategy(request) if err != nil { return err } defer removeImage(s.dockerClient, tag) if _, err = builder.Build(request); err != nil { return err } if len(s.build.Parameters.Output.DockerImageReference) != 0 { return pushImage(s.dockerClient, tag, s.auth) } return nil }
sdodson/origin
pkg/build/builder/sti.go
GO
apache-2.0
2,069
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Profiler to check if there are any bottlenecks in your code.""" import logging import os from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union from pytorch_lightning.utilities.cloud_io import get_filesystem log = logging.getLogger(__name__) class AbstractProfiler(ABC): """Specification of a profiler.""" @abstractmethod def start(self, action_name: str) -> None: """Defines how to start recording an action.""" @abstractmethod def stop(self, action_name: str) -> None: """Defines how to record the duration once an action is complete.""" @abstractmethod def summary(self) -> str: """Create profiler summary in text format.""" @abstractmethod def setup(self, **kwargs: Any) -> None: """Execute arbitrary pre-profiling set-up steps as defined by subclass.""" @abstractmethod def teardown(self, **kwargs: Any) -> None: """Execute arbitrary post-profiling tear-down steps as defined by subclass.""" class BaseProfiler(AbstractProfiler): """ If you wish to write a custom profiler, you should inherit from this class. """ def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, ) -> None: self.dirpath = dirpath self.filename = filename self._output_file: Optional[TextIO] = None self._write_stream: Optional[Callable] = None self._local_rank: Optional[int] = None self._log_dir: Optional[str] = None self._stage: Optional[str] = None @contextmanager def profile(self, action_name: str) -> Generator: """ Yields a context manager to encapsulate the scope of a profiled action. Example:: with self.profile('load training data'): # load training data code The profiler will start once you've entered the context and will automatically stop once you exit the code block. """ try: self.start(action_name) yield action_name finally: self.stop(action_name) def profile_iterable(self, iterable: Iterable, action_name: str) -> Generator: iterator = iter(iterable) while True: try: self.start(action_name) value = next(iterator) self.stop(action_name) yield value except StopIteration: self.stop(action_name) break def _rank_zero_info(self, *args, **kwargs) -> None: if self._local_rank in (None, 0): log.info(*args, **kwargs) def _prepare_filename( self, action_name: Optional[str] = None, extension: str = ".txt", split_token: str = "-" ) -> str: args = [] if self._stage is not None: args.append(self._stage) if self.filename: args.append(self.filename) if self._local_rank is not None: args.append(str(self._local_rank)) if action_name is not None: args.append(action_name) filename = split_token.join(args) + extension return filename def _prepare_streams(self) -> None: if self._write_stream is not None: return if self.filename: filepath = os.path.join(self.dirpath, self._prepare_filename()) fs = get_filesystem(filepath) file = fs.open(filepath, "a") self._output_file = file self._write_stream = file.write else: self._write_stream = self._rank_zero_info def describe(self) -> None: """Logs a profile report after the conclusion of run.""" # there are pickling issues with open file handles in Python 3.6 # so to avoid them, we open and close the files within this function # by calling `_prepare_streams` and `teardown` self._prepare_streams() summary = self.summary() if summary: self._write_stream(summary) if self._output_file is not None: self._output_file.flush() self.teardown(stage=self._stage) def _stats_to_str(self, stats: Dict[str, str]) -> str: stage = f"{self._stage.upper()} " if self._stage is not None else "" output = [stage + "Profiler Report"] for action, value in stats.items(): header = f"Profile stats for: {action}" if self._local_rank is not None: header += f" rank: {self._local_rank}" output.append(header) output.append(value) return os.linesep.join(output) def setup( self, stage: Optional[str] = None, local_rank: Optional[int] = None, log_dir: Optional[str] = None ) -> None: """Execute arbitrary pre-profiling set-up steps.""" self._stage = stage self._local_rank = local_rank self._log_dir = log_dir self.dirpath = self.dirpath or log_dir def teardown(self, stage: Optional[str] = None) -> None: """ Execute arbitrary post-profiling tear-down steps. Closes the currently open file and stream. """ self._write_stream = None if self._output_file is not None: self._output_file.close() self._output_file = None # can't pickle TextIOWrapper def __del__(self) -> None: self.teardown(stage=self._stage) def start(self, action_name: str) -> None: raise NotImplementedError def stop(self, action_name: str) -> None: raise NotImplementedError def summary(self) -> str: raise NotImplementedError @property def local_rank(self) -> int: return 0 if self._local_rank is None else self._local_rank class PassThroughProfiler(BaseProfiler): """ This class should be used when you don't want the (small) overhead of profiling. The Trainer uses this class by default. """ def start(self, action_name: str) -> None: pass def stop(self, action_name: str) -> None: pass def summary(self) -> str: return ""
williamFalcon/pytorch-lightning
pytorch_lightning/profiler/base.py
Python
apache-2.0
6,875
/* * Copyright (c) 2017-2019 Arrow Electronics, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License 2.0 * which accompanies this distribution, and is available at * http://apache.org/licenses/LICENSE-2.0 * * Contributors: * Arrow Electronics, Inc. * Konexios, Inc. */ package com.konexios.api.models; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Objects; public class AuditLogModel implements Parcelable { @SuppressWarnings("unused") public static final Parcelable.Creator<AuditLogModel> CREATOR = new Parcelable.Creator<AuditLogModel>() { @NonNull @Override public AuditLogModel createFromParcel(@NonNull Parcel in) { return new AuditLogModel(in); } @NonNull @Override public AuditLogModel[] newArray(int size) { return new AuditLogModel[size]; } }; @SerializedName("createdBy") @Expose private String createdBy; @SerializedName("createdString") @Expose private String createdString; @SerializedName("objectHid") @Expose private String objectHid; @SerializedName("parameters") @Expose private JsonElement parameters; @SerializedName("productName") @Expose private String productName; @SerializedName("type") @Expose private String type; public AuditLogModel() { } protected AuditLogModel(@NonNull Parcel in) { createdBy = in.readString(); createdString = (String) in.readValue(String.class.getClassLoader()); objectHid = in.readString(); JsonParser parser = new JsonParser(); parameters = parser.parse(in.readString()).getAsJsonObject(); productName = in.readString(); type = in.readString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AuditLogModel that = (AuditLogModel) o; return Objects.equals(createdBy, that.createdBy) && Objects.equals(createdString, that.createdString) && Objects.equals(objectHid, that.objectHid) && Objects.equals(parameters, that.parameters) && Objects.equals(productName, that.productName) && Objects.equals(type, that.type); } @Override public int hashCode() { return Objects.hash(createdBy, createdString, objectHid, parameters, productName, type); } /** * @return The createdBy */ public String getCreatedBy() { return createdBy; } /** * @param createdBy The createdBy */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * @return The createdString */ public String getCreatedString() { return createdString; } /** * @param String The String */ public void setCreatedString(String String) { this.createdString = String; } /** * @return The objectHid */ public String getObjectHid() { return objectHid; } /** * @param objectHid The objectHid */ public void setObjectHid(String objectHid) { this.objectHid = objectHid; } /** * @return The parameters */ public JsonElement getParameters() { if (parameters == null) { parameters = new JsonObject(); } return parameters; } /** * @param parameters The parameters */ public void setParameters(JsonElement parameters) { this.parameters = parameters; } /** * @return The productName */ public String getProductName() { return productName; } /** * @param productName The productName */ public void setProductName(String productName) { this.productName = productName; } /** * @return The type */ public String getType() { return type; } /** * @param type The type */ public void setType(String type) { this.type = type; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeString(createdBy); dest.writeValue(createdString); dest.writeString(objectHid); String str = new Gson().toJson(getParameters()); dest.writeString(str); dest.writeString(productName); dest.writeString(type); } }
arrow-acs/acn-sdk-android
sdk/src/main/java/com/konexios/api/models/AuditLogModel.java
Java
apache-2.0
4,939
package com.tqmars.cardrecycle.application.User.dto; /** * Created by jjh on 1/14/17. */ public class CreateUserInput { private String account; private String pwd; private String qq; private String tel; private String businessId; private String businessPwd; private String smsCode; private String withdrawPwd; public String getWithdrawPwd() { return withdrawPwd; } public void setWithdrawPwd(String withdrawPwd) { this.withdrawPwd = withdrawPwd; } public String getSmsCode() { return smsCode; } public void setSmsCode(String smsCode) { this.smsCode = smsCode; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getBusinessPwd() { return businessPwd; } public void setBusinessPwd(String businessPwd) { this.businessPwd = businessPwd; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } @Override public String toString() { return "CreateUserInput{" + "account='" + account + '\'' + ", pwd='" + pwd + '\'' + ", qq='" + qq + '\'' + ", tel='" + tel + '\'' + ", businessId='" + businessId + '\'' + ", businessPwd='" + businessPwd + '\'' + ", smsCode='" + smsCode + '\'' + ", withdrawPwd='" + withdrawPwd + '\'' + '}'; } }
huahuajjh/card_recycle
src/main/java/com/tqmars/cardrecycle/application/User/dto/CreateUserInput.java
Java
apache-2.0
2,014
package com.unidev.myip.web; import com.unidev.myip.MyIPService; import com.unidev.platform.web.WebUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * Frontend controller */ @Controller public class IndexController { @Autowired private HttpServletRequest request; @Autowired private MyIPService myIPService; @RequestMapping("/") public ModelAndView index() { String ip = myIPService.extractClinetIp(request); List<Map.Entry<String, Object>> headers = myIPService.extractHeaders(request); ModelAndView modelAndView = new ModelAndView("index"); modelAndView.addObject("ip", ip); modelAndView.addObject("headers", headers); return modelAndView; } }
universal-development/myip-app
webapp/src/main/java/com/unidev/myip/web/IndexController.java
Java
apache-2.0
1,013
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Lockscreen</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.6 --> <link rel="stylesheet" href="{{ url('/public/bootstrap/css/bootstrap.min.css') }}"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="{{ url('/public/dist/css/AdminLTE.min.css') }}"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition lockscreen"> <!-- Automatic element centering --> <div class="lockscreen-wrapper"> <div class="lockscreen-logo"> <a href="../../index2.html"><b>Admin</b>Espíndola</a> </div> <!-- User name --> <div class="lockscreen-name "> <img src="{{ url('/public/dist/img/upload/profile/user-default-avatar.jpg') }}" class="profile-user-img img-responsive img-circle" alt="User Image" width="128"> <p style="margin: 10px; padding: 5px;">{{$user->nick}}</p> </div> <div class="lockscreen-image"> </div> <!-- START LOCK SCREEN ITEM --> <div class=""> <!-- lockscreen image --> <!-- /.lockscreen-image --> <!-- lockscreen credentials (contains the form) --> {{Form::open(array('url'=> '/alterar-senha', 'class'=>'' , 'onsubmit' => 'return conf_password()'))}} <div class="form-group"> <input type="password" class="form-control" name="password" id="passwords" required="" placeholder="Senha"> <input type="hidden" name="id" value="{{$user->id}}" > </div> <!-- /.lockscreen credentials --> <div class="form-group"> {{-- --}} <div class="input-group"> <input type="password" class="form-control" name="password" id="confirmacao" required="" placeholder="Confirmar Senha"> <span class="input-group-btn"> <button type="submit" class="btn btn-default" type="button"><i class="fa fa-arrow-right" aria-hidden="true"></i></button> </span> </div><!-- /input-group -- </div> </div> {{Form::close()}} <!-- /.lockscreen-item --> <div class="help-block text-center"> Digite o seu password para acesso ao sistema </div> <div class="text-center"> <a href="{{url('/imobiliaria/login')}}">Já sou cadastrado</a> </div> <div class="lockscreen-footer text-center"> Copyright &copy; 2015-2016 <b><a href="http://excellencesoft.com.br" class="text-black">Espíndola imobiliária</a></b><br> </div> </div> <!-- /.center --> <!-- jQuery 2.2.0 --> <script src="{{ url('/public/plugins/jQuery/jQuery-2.2.0.min.js') }}"></script> <!-- Bootstrap 3.3.6 --> <script src="{{ url('/public/bootstrap/js/bootstrap.min.js') }}"></script> <script src="{{ url('/public/dist/js/funcao.js') }}"></script> </body> </html>
Junior-Shyko/admin
resources/views/profile/reset_password.blade.php
PHP
apache-2.0
3,507
/* * Copyright 2015 hilemz * * http://www.wykop.pl/ludzie/hilemz/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.hilemz.yahoofinanceapi; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; /** * <p> * Date: 22.09.2015 * </p> * * <p> * Complex set of tools useful for parsing data provided by Yahoo Finance API. * </p> * * @author hilemz */ public class ParseUtils { /** * This method parse date from String object to LocalDate object. * * @param dateValue * Data value in format "MM/dd/yyyy". * @return Parsed date to LocalDate object. */ public static LocalDate toLocalDate(String dateValue) { return LocalDate.parse(trimQuotes(dateValue), DateTimeFormatter.ofPattern("M/dd/yyyy")); } /** * This method parse time from String object to LocalTime object. * * @param timeValue * Time value in format "h:ma" - "4:00pm". * @return Parsed time to LocalTime object. */ public static LocalTime toLocalTime(String timeValue) { return LocalTime.parse(trimQuotes(timeValue).toUpperCase(), DateTimeFormatter.ofPattern("h:ma")); } /** * This method parse date and time from String objects to LocalDateTime object. * * @param dateValue * Data value in format "MM/dd/yyyy". * @param timeValue * Time value in format "K:ma" - "4:00pm". * @return Parsed date and time to LocalDateTime object. */ public static LocalDateTime toLocalDateTime(String dateValue, String timeValue) { return LocalDateTime.of(toLocalDate(dateValue), toLocalTime(timeValue)); } /** * This method parse date and time from String objects to UNIX EPOCH timestamp. * * @param dateValue * Data value in format "MM/dd/yyyy". * @param timeValue * Time value in format "K:ma" - "4:00pm". * @return Parsed date and time to UNIX EPOCH timestamp object. */ public static long toTimestamp(String dateValue, String timeValue) { return toLocalDateTime(dateValue, timeValue).toInstant(ZoneOffset.UTC).toEpochMilli(); } /** * <p> * This method converts {@link DataType#CHANGE_PERCENT} String object to Tuple of double objects. Example value that * can be passed: * </p> * * <p> * "13.65 - 2.12%" * </p> * * @param value * Value for convertions. * @return Converted value. */ public static Tuple<Double, Double> changePercentToTuple(String value) { String[] elements = splitValue(value); if (elements.length != 2 || !value.matches("^(\"[0-9]+|\"-[0-9]+|[0-9]+|-[0-9]+).*-+.*([0-9]+%|[0-9]+%\")$")) { throw new IllegalArgumentException("Illegal arguments. Value should be in format: \"13.65 - 2.12%\"."); } return new Tuple<>(Double.parseDouble(elements[0]), Double.parseDouble(trimPercent(elements[1]))); } /** * <p> * This method converts {@link DataType#LAST_TRADE_WITH_TIME} String object to Tuple of LocalTime and double * objects. Example value that can be passed: * </p> * * <p> * "4:00pm - <b>629.25</b>" * </p> * * @param value * Value for convertions. * @return Converted value. */ public static Tuple<LocalTime, Double> tradeWithTimeToTuple(String value) { String[] elements = splitValue(value); if (elements.length != 2 || !value.matches("^(\"[0-9]+|\"-[0-9]+|[0-9]+|-[0-9]+).*-+.*([0-9]+</b>|[0-9]+</b>\")$")) { throw new IllegalArgumentException("Illegal arguments. Value should be in format: \"4" + ":00pm - <b>629.25</b>\"."); } return new Tuple<>(toLocalTime(elements[0]), Double.parseDouble(trimBold(elements[1]))); } /** * <p> * This method converts {@link DataType#DAYS_RANGE} String object to Tuple of double objects. Example value that can * be passed: * </p> * * <p> * "627.02 - 640.00" * </p> * * @param value * Value for convertions. * @return Converted value. */ public static Tuple<Double, Double> priceRangeToTuple(String value) { String[] elements = splitValue(value); if (elements.length != 2 || !value.matches("^(\"[0-9]+|\"-[0-9]+|[0-9]+|-[0-9]+).*-+.*([0-9]+|[0-9]+\")$")) { throw new IllegalArgumentException("Illegal arguments. Value should be in format: \"627.02 - 640.00\"."); } return new Tuple<>(Double.parseDouble(elements[0]), Double.parseDouble(elements[1])); } /** * This method converts big number passed by Yahoo Finance API with symbols at the end. It supports M and B suffix. * * @param value * Value for convertions. * @return Converted value. */ public static long bigNumberToLong(String value) { if (!isParsable(value)) { throw new IllegalArgumentException("Illegal argument value."); } if (!value.matches("(([0-9]*.[0-9]*)|([0-9]*))[a-zA-Z]{1}$")) { return Long.parseLong(value); } char suffix = value.charAt(value.length() - 1); value = value.substring(0, value.length() - 1); if (suffix == 'B') { return (long) (Double.parseDouble(value) * 1000000000); } else if (suffix == 'M') { return (long) (Double.parseDouble(value) * 1000000); } throw new IllegalArgumentException("Number couldn't be resolved."); } /** * This method converts 3.45% String object value to double object. In result return double value in form - 3.45. * * @param value * Value for convertions. * @return Converted value. */ public static double percentValueToDouble(String value) { if (!isParsable(value)) { throw new IllegalArgumentException("Illegal argument value."); } return Double.parseDouble(trimPercent(value)); } /** * This method splits passed value with delimiter "-". * * @param value * Value to split. * @return Splitted value. */ public static String[] splitValue(String value) { return trimQuotes(value).split(" - "); } /** * This method trim " from passed value. * * @param value * Value to trim. * @return Trimmed value. */ public static String trimQuotes(String value) { if (!isParsable(value)) { throw new IllegalArgumentException("Illegal argument value."); } return value.replaceAll("^\"|\"$", ""); } /** * This method trim % symbol from passed value. * * @param value * Value to trim. * @return Trimmed value. */ public static String trimPercent(String value) { if (!isParsable(value)) { throw new IllegalArgumentException("Illegal argument value."); } return value.replaceAll("%", ""); } /** * This method trim <code><b></b></code> from passed value. * * @param value * Value to trim. * @return Trimmed value. */ public static String trimBold(String value) { if (!isParsable(value)) { throw new IllegalArgumentException("Illegal argument value."); } return value.replaceAll("<b>|</b>", ""); } /** * This method verificate if passed value is appropriate for parsing. * * @param value * Value to check. * @return Result of verification. */ public static boolean isParsable(String value) { return !(value == null || value.equals("N/A") || value.equals("") || value.equals("\"\"")); } }
hilemz/yahoo-finance-api
yahoo-finance-api/src/main/java/pl/hilemz/yahoofinanceapi/ParseUtils.java
Java
apache-2.0
7,707
/* * Copyright (C) 2015 pengjianbo(pengjianbosoft@gmail.com), Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.finalteam.okhttpfinal; /** * Desction: * Author:pengjianbo * Date:15/12/10 下午8:13 */ public class StringHttpRequestCallback extends BaseHttpRequestCallback<String> { public StringHttpRequestCallback() { super(); type = String.class; } }
dufangyu1990/NewFarmTool
OkHttpFinal/src/main/java/cn/finalteam/okhttpfinal/StringHttpRequestCallback.java
Java
apache-2.0
918
package com.nouribygi.masnavi.database; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import com.nouribygi.masnavi.util.MasnaviSettings; public class MasnaviDataProvider extends ContentProvider { public static String AUTHORITY = "com.nouribygi.masnavi.database.MasnaviDataProvider"; public static final Uri SEARCH_URI = Uri.parse("content://" + AUTHORITY + "/masnavi/search"); public static final String VERSES_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.nouribygi.masnavi"; public static final String AYAH_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.nouribygi.masnavi"; // UriMatcher stuff private static final int SEARCH_VERSES = 0; private static final int GET_VERSE = 1; private static final int SEARCH_SUGGEST = 2; private static final UriMatcher sURIMatcher = buildUriMatcher(); private DatabaseHandler mDatabase = null; private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); matcher.addURI(AUTHORITY, "masnavi/search", SEARCH_VERSES); matcher.addURI(AUTHORITY, "masnavi/search/*", SEARCH_VERSES); matcher.addURI(AUTHORITY, "masnavi/search/*/*", SEARCH_VERSES); matcher.addURI(AUTHORITY, "masnavi/verse/#/#", GET_VERSE); matcher.addURI(AUTHORITY, "masnavi/verse/*/#/#", GET_VERSE); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { mDatabase = DatabaseHandler.getInstance(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String query = ""; if (selectionArgs.length >= 1) query = selectionArgs[0]; int bookCode = MasnaviSettings.getSelectedBook(getContext()); return mDatabase.search(query, bookCode); } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case SEARCH_VERSES: return VERSES_MIME_TYPE; case GET_VERSE: return AYAH_MIME_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URL " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } }
nouribygi/Masnavi
app/src/main/java/com/nouribygi/masnavi/database/MasnaviDataProvider.java
Java
apache-2.0
3,332
/// <reference types="angular" /> /// <reference types="angular-route" /> export default function ($locationProvider: angular.ILocationProvider, $routeProvider: angular.route.IRouteProvider): void;
mouss2010/ztocosiumcomp
build/dist/lib-esm/core/configurations/route.d.ts
TypeScript
apache-2.0
198
package com.notronix.lw.impl.method.orders; import com.google.gson.Gson; import com.notronix.lw.api.model.UserOrderView; import com.notronix.lw.impl.method.AbstractLinnworksAPIMethod; import java.util.Arrays; import java.util.List; public class GetOrderViewsMethod extends AbstractLinnworksAPIMethod<List<UserOrderView>> { @Override public String getURI() { return "Orders/GetOrderViews"; } @Override public List<UserOrderView> getResponse(Gson gson, String jsonPayload) { return Arrays.asList(gson.fromJson(jsonPayload, UserOrderView[].class)); } }
Notronix/JaLAPI
src/main/java/com/notronix/lw/impl/method/orders/GetOrderViewsMethod.java
Java
apache-2.0
615
/** Copyright (c) 2011, Cisco Systems, Inc. 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 Cisco Systems, Inc. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.cisco.qte.jdtn.bp; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.cisco.qte.jdtn.component.AbstractStartableComponent; import com.cisco.qte.jdtn.general.GeneralManagement; import com.cisco.qte.jdtn.general.JDtnException; import com.cisco.qte.jdtn.general.Utils; import com.cisco.qte.jdtn.general.XmlRDParser; import com.cisco.qte.jdtn.general.XmlRdParserException; /** * Mappings from IPN: to DTN: EndPointIds. Maintains two-way mappings * (equivalences) between a set of IPN: EndPointId and DTN: EndPointIds. */ public class EidMap extends AbstractStartableComponent { private static final Logger _logger = Logger.getLogger(EidMap.class.getCanonicalName()); private static EidMap _instance = null; private HashMap<EndPointId, IpnEndpointId> _dtnToIpnMap = new HashMap<EndPointId, IpnEndpointId>(); private HashMap<IpnEndpointId, EndPointId> _ipnToDtnMap = new HashMap<IpnEndpointId, EndPointId>(); /** * Get singleton Instance * @return Singleton instance */ public static EidMap getInstance() { if (_instance == null) { _instance = new EidMap(); } return _instance; } /** * Protected access constructor */ protected EidMap() { super("EidMap"); if (GeneralManagement.isDebugLogging()) { _logger.finer("EidMap()"); } } /** * Start this component */ @Override protected void startImpl() { if (GeneralManagement.isDebugLogging()) { _logger.finer("startImpl()"); } addDefaultMapping(); } /** * Stop this component */ @Override protected void stopImpl() { if (GeneralManagement.isDebugLogging()) { _logger.finer("stopImpl()"); } removeDefaultMapping(); } /** * Set to default state; clears all mappings */ public void setDefaults() { if (GeneralManagement.isDebugLogging()) { _logger.finer("setDefaults()"); } _dtnToIpnMap.clear(); _ipnToDtnMap.clear(); addDefaultMapping(); } /** * Parse from config file. It is assume that the parse is sitting on the * &lt; EidMap &gt; element. We parse all contained &lt; EidMapEntry &gt; * sub-elements, adding a Dtn <-> Ipn EID Mapping for each. We also * parse the ending &lt; /EidMap &gt; tag. * @param parser The config file parser * @throws XmlPullParserException on general parsing errors * @throws IOException On general I/O errors * @throws JDtnException on JDTN specific errors */ public void parse(XmlRDParser parser) throws XmlRdParserException, IOException, JDtnException { if (GeneralManagement.isDebugLogging()) { _logger.finer("parse()"); } // General structure of EidMap info: // <EidMap> // <EidMapEntry dtnEid='dtnEid' ipnEid='ipnEid /> // ... // </EidMap> // Parse each <EidMapEntry> XmlRDParser.EventType event = Utils.nextNonTextEvent(parser); while (event == XmlRDParser.EventType.START_ELEMENT) { if (!parser.getElementTag().equals("EidMapEntry")) { throw new BPException("Expecting <EidMapEntry>"); } // Get 'dtnEid' attribute String dtnEidStr = Utils.getStringAttribute(parser, "dtnEid"); if (dtnEidStr == null) { throw new BPException("Missing attribute 'dtnEid'"); } EndPointId dtnEid = EndPointId.createEndPointId(dtnEidStr); if (!dtnEid.getScheme().equals(EndPointId.DEFAULT_SCHEME)) { throw new BPException("First argument not 'dtn' Eid"); } // Get 'ipnEid' attribute String ipnEidStr = Utils.getStringAttribute(parser, "ipnEid"); if (ipnEidStr == null) { throw new BPException("Missing attribute 'ipnEid'"); } EndPointId ipnEid = EndPointId.createEndPointId(ipnEidStr); if (!ipnEid.getScheme().equals(IpnEndpointId.SCHEME_NAME) || !(ipnEid instanceof IpnEndpointId)) { throw new BPException("Second argument not 'ipn' Eid"); } // Add the mapping addMapping(dtnEid, (IpnEndpointId)ipnEid); // Parse </EidMapEntry> event = Utils.nextNonTextEvent(parser); if (event != XmlRDParser.EventType.END_ELEMENT || !parser.getElementTag().equals("EidMapEntry")) { throw new BPException("Expecting </EidMapEntry>"); } event = Utils.nextNonTextEvent(parser); } // Parse </EidMap> if (event != XmlRDParser.EventType.END_ELEMENT || !parser.getElementTag().equals("EidMap")) { throw new JDtnException("Expecting '</EidMap>'"); } } /** * Write EidMap to config file. We only do this if there are entries * in the map. * @param pw PrintWrite to output to */ public void writeConfig(PrintWriter pw) { if (GeneralManagement.isDebugLogging()) { _logger.finer("writeConfig()"); } if (EidMap.getInstance().size() > 0) { pw.println(" <EidMap>"); for (EndPointId dtnEid : _dtnToIpnMap.keySet()) { IpnEndpointId ipnEid = _dtnToIpnMap.get(dtnEid); if (!isDefaultMapping(dtnEid, ipnEid)) { pw.println(" <EidMapEntry"); pw.println(" dtnEid='" + dtnEid.getEndPointIdString() + "'"); pw.println(" ipnEid='" + ipnEid.getEndPointIdString() + "'"); pw.println(" />"); } } pw.println(" </EidMap>"); } } // Add an entry to map 'dtn:none' to 'ipn:0.0' private void addDefaultMapping() { if (GeneralManagement.isDebugLogging()) { _logger.finer("addDefaultMapping()"); } try { addMapping( EndPointId.DEFAULT_ENDPOINT_ID_STRING, IpnEndpointId.DEFAULT_IPNEID_STR); } catch (BPException e) { _logger.log(Level.SEVERE, "EidMap default mapping", e); } } // Remove entry mapping 'dtn:none' to 'ipn:0.0' private void removeDefaultMapping() { if (GeneralManagement.isDebugLogging()) { _logger.finer("removeDefaultMapping()"); } try { removeMapping(EndPointId.DEFAULT_ENDPOINT_ID_STRING); } catch (BPException e) { _logger.log(Level.SEVERE, "EidMap default mapping", e); } } // Determine if given mapping is 'dtn:none' <=> 'ipn:0.0' private boolean isDefaultMapping(EndPointId dtnEid, IpnEndpointId ipnEid) { if (dtnEid.getEndPointIdString().equalsIgnoreCase(EndPointId.DEFAULT_ENDPOINT_ID_STRING) && ipnEid.getEndPointIdString().equalsIgnoreCase(IpnEndpointId.DEFAULT_IPNEID_STR)) { return true; } return false; } /** * Add a mapping between a 'dtn' Eid and an 'ipn' Eid * @param dtnEidStr String containing the 'dtn' Eid * @param ipnEidStr String containing the 'ipn' Eid * @throws BPException if there is already a mapping for dtnEid <=> ipnEid, * or if dtnEidStr is not a valid 'dtn' scheme EndPointId, * or if ipnEidStr is not a valid 'ipn' scheme EndPointId. */ public void addMapping(String dtnEidStr, String ipnEidStr) throws BPException { if (GeneralManagement.isDebugLogging()) { _logger.finer("addMapping(<String>" + dtnEidStr + " <=> " + ipnEidStr + ")"); } EndPointId dtnEid = EndPointId.createEndPointId(dtnEidStr); IpnEndpointId ipnEid = new IpnEndpointId(ipnEidStr); addMapping(dtnEid, ipnEid); } /** * Add a mapping between a 'dtn' Eid and an 'ipn' Eid * @param dtnEid The 'dtn' Eid * @param ipnEid The 'ipn' Eid * @throws BPException if there is already a mapping for dtnEid <=> ipnEid, * or if dtnEid is not a 'dtn' scheme EndPointId. */ public synchronized void addMapping(EndPointId dtnEid, IpnEndpointId ipnEid) throws BPException { if (GeneralManagement.isDebugLogging()) { _logger.finer("addMapping(" + dtnEid.getEndPointIdString() + " <=> " + ipnEid.getEndPointIdString() + ")"); } if (!dtnEid.getScheme().equals(EndPointId.DEFAULT_SCHEME)) { throw new BPException("First argument is not a 'dtn' EndPointId"); } if (_dtnToIpnMap.containsKey(dtnEid)) { if (_ipnToDtnMap.containsKey(ipnEid)) { // Full Mapping already exists; silently ignore return; } if (GeneralManagement.isDebugLogging()) { _logger.finer("addMapping(" + dtnEid.getEndPointIdString() + " <=> " + ipnEid.getEndPointIdString() + ") Entry already exists"); _logger.finest(dump("", true)); } throw new BPException("There is already a mapping for DTN EID: " + dtnEid.getEndPointIdString()); } if (_ipnToDtnMap.containsKey(ipnEid)) { throw new BPException("There is already a mapping for IPN EID: " + ipnEid.getEndPointIdString()); } _dtnToIpnMap.put(dtnEid, ipnEid); _ipnToDtnMap.put(ipnEid, dtnEid); } /** * Remove a mapping between a 'dtn' Eid and an 'ipn' Eid * @param dtnEidStr The 'dtn' Eid String * @throws BPException If no mapping, or dtnEidStr poorly formatted */ public synchronized void removeMapping(String dtnEidStr) throws BPException { if (GeneralManagement.isDebugLogging()) { _logger.finer("removeMapping(" + dtnEidStr + ")"); } EndPointId dtnEid = EndPointId.createEndPointId(dtnEidStr); IpnEndpointId ipnEid = getIpnEid(dtnEid); if (ipnEid == null) { throw new BPException("No mapping for " + dtnEid.getEndPointIdString()); } removeMapping(dtnEid, ipnEid); } /** * Remove a mapping between a 'dtn' Eid and an 'ipn' Eid * @param dtnEid The 'dtn' Eid * @param ipnEid The 'ipn' Eid * @throws BPException if there is not a mapping for dtnEid <=> ipnEid, * or if dtnEid is not a 'dtn' scheme EndPointId. */ public synchronized void removeMapping(EndPointId dtnEid, IpnEndpointId ipnEid) throws BPException { if (GeneralManagement.isDebugLogging()) { _logger.finer("removeMapping(" + dtnEid.getEndPointIdString() + " <=> " + ipnEid.getEndPointIdString() + ")"); } if (!_dtnToIpnMap.containsKey(dtnEid)) { throw new BPException("There is not a mapping for DTN EID: " + dtnEid.getEndPointIdString()); } if (!_ipnToDtnMap.containsKey(ipnEid)) { throw new BPException("There is not a mapping for IPN EID: " + ipnEid.getEndPointIdString()); } _dtnToIpnMap.remove(dtnEid); _ipnToDtnMap.remove(ipnEid); } /** * Dump this object * @param indent Amount of indentation * @param detailed if want detailed dump * @return String containing dump */ @Override public synchronized String dump(String indent, boolean detailed) { StringBuilder sb = new StringBuilder(indent + "EidMap\n"); for (EndPointId dtnEid : _dtnToIpnMap.keySet()) { sb.append( indent + " DtnEid=" + dtnEid.getEndPointIdString() + " <=> IpnEid=" + _dtnToIpnMap.get(dtnEid).getEndPointIdString() + "\n"); } return sb.toString(); } /** * Get the IPN Eid mapped to given DTN Eid * @param dtnEidStr Given DTN Eid String * @return Mapped IPN Eid or null if none mapped * @throws BPException if dtnEidStr is poorly formed */ public String getIpnEidStr(String dtnEidStr) throws BPException { if (GeneralManagement.isDebugLogging()) { _logger.finer("getIpnEidStr(" + dtnEidStr + ")"); } EndPointId dtnEid = EndPointId.createEndPointId(dtnEidStr); IpnEndpointId ipnEid = getIpnEid(dtnEid); if (ipnEid == null) { if (GeneralManagement.isDebugLogging()) { _logger.finer("getIpnEidStr(" + dtnEidStr + ") = null"); } return null; } if (GeneralManagement.isDebugLogging()) { _logger.finer("removeMapping(" + dtnEidStr + ") = " + ipnEid.getEndPointIdString()); } return ipnEid.getEndPointIdString(); } /** * Get the IPN Eid mapped to given DTN Eid * @param dtnEid Given DTN Eid * @return Mapped IPN Eid or null if none mapped */ public synchronized IpnEndpointId getIpnEid(EndPointId dtnEid) { IpnEndpointId ipnEid = _dtnToIpnMap.get(dtnEid); if (ipnEid == null) { if (GeneralManagement.isDebugLogging()) { _logger.finer("getIpnEid(" + dtnEid.getEndPointIdString() + ") = null"); } return null; } if (GeneralManagement.isDebugLogging()) { _logger.finer("getIpnEid(" + dtnEid.getEndPointIdString() + ") = " + ipnEid.getEndPointIdString()); } return ipnEid; } /** * Get the DTN Eid mapped to given IPN Eid * @param ipnEidStr Given IPN Eid String * @return Mapped DTN Eid String or null if none mapped * @throws BPException if ipnEidStr is poorly formed */ public String getDtnEidStr(String ipnEidStr) throws BPException { IpnEndpointId ipnEid = new IpnEndpointId(ipnEidStr); EndPointId dtnEid = getDtnEid(ipnEid); if (dtnEid == null) { if (GeneralManagement.isDebugLogging()) { _logger.finer("getDtnEidStr(" + ipnEidStr + ") = null"); } return null; } if (GeneralManagement.isDebugLogging()) { _logger.finer("getDtnEidStr(" + ipnEidStr + ") = " + dtnEid.getEndPointIdString()); } return dtnEid.getEndPointIdString(); } /** * Get the DTN Eid mapped to given IPN Eid * @param ipnEid Given IPN Eid * @return Mapped DTN Eid or null if none mapped */ public synchronized EndPointId getDtnEid(IpnEndpointId ipnEid) { EndPointId dtnEid = _ipnToDtnMap.get(ipnEid); if (dtnEid == null) { if (GeneralManagement.isDebugLogging()) { _logger.finer("getDtnEid(" + ipnEid.getEndPointIdString() + ") = null"); } return null; } if (GeneralManagement.isDebugLogging()) { _logger.finer("getDtnEid(" + ipnEid.getEndPointIdString() + ") = " + dtnEid.getEndPointIdString()); } return dtnEid; } /** * Get the number of mappings * @return Number of mappings */ public int size() { return _dtnToIpnMap.size(); } }
KritikalFabric/corefabric.io
src/contrib/java/com/cisco/qte/jdtn/bp/EidMap.java
Java
apache-2.0
14,806
(function() { var port = 8080; if (window.location.search) { var params = window.location.search.match(/port=(\d+)/); if (params) { port = params[1]; } // How often to poll params = window.location.search.match(/pollInterval=(\d+)/); if (params) { window.JOLOKIA_POLL_INTERVAL = parseInt(params[1]); } } window.JOLOKIA_URL = "http://localhost:" + port + "/jolokia"; })();
jolokia-org/jolokia-client-javascript
test/qunit/js/jolokia-env.js
JavaScript
apache-2.0
470
package org.luapp.practise.leetcode; /** * Created by lum on 2015/3/16. */ public class RemoveNthNodeFromEndOfList { public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public static ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) { return head; } // 移动指示针 ListNode nPointer = head; int i = 0; while (nPointer != null && i < n) { nPointer = nPointer.next; i++; } // 如果指定n大于队列长度,报错 if (i != n) { System.out.println("error"); return null; } ListNode pre = head; ListNode lPointer = head; while (nPointer != null) { nPointer = nPointer.next; pre = lPointer; lPointer = lPointer.next; } if(lPointer == head) { head = head.next; } else { pre.next = lPointer.next; } return head; } public static void print(ListNode head) { if (head == null) { System.out.println("null"); } else { System.out.print(head.val); ListNode temp = head.next; while (temp != null) { System.out.print("->" + temp.val); temp = temp.next; } System.out.println(); } } public static void main(String[] args) { ListNode head = new ListNode(1); ListNode temp = head; for (int i = 2; i <= 5; i++) { temp.next = new ListNode(i); temp = temp.next; } print(head); print(removeNthFromEnd(head, -1)); } }
lumeng689/luapp
practise/src/main/java/org/luapp/practise/leetcode/RemoveNthNodeFromEndOfList.java
Java
apache-2.0
1,829
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package leap.core.security; import java.util.Collections; import java.util.Map; public interface UserPrincipal extends Principal { /** * Returns the user's display name. */ String getName(); /** * Returns the user's login name. */ String getLoginName(); /** * Returns the details property. */ default Map<String, Object> getProperties() { return Collections.emptyMap(); } }
leapframework/framework
base/core/src/main/java/leap/core/security/UserPrincipal.java
Java
apache-2.0
1,031
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Objeto com os serviços disponiveis para os usuários. * @author Caio de Freitas Adriano * @since 2017/11/02 */ class Book extends CI_Controller { /** * Edita os dados de um livro no sistema. * @author Caio de Freitas Adriano * @since 2017/11/07 * @param Object - Objeto Book com os dados do livro * @return Json - retorna um json os dados da resposta da requisição */ public function edit() { // pega os dados do usuário que vieram da requisição $token = getToken(); $this->auth->setUserLevel($token[3]); $this->auth->setPagePermission([1,2]); // verifica se o usuário tem permissão para utilizar o serviço if (!$this->auth->hasPermission()) { header('HTTP/1.1 401 Unauthorized'); exit(); } $data = file_get_contents("php://input"); $book = json_decode($data); // manipulações no objeto book $book->name = strtolower(trim($book->name)); $book->publishDate = brToSqlDate($book->publishDate); if ($book->publishingCompany) $book->publishingCompany = $book->publishingCompany[0]->id; $book->cover = filename($book->cover); $this->db->trans_start(); $this->Book_model->update($book); $this->Book_model->clearCategory($book); // adiciona as categorias ao livro foreach ($book->categories as $category) $this->Book_model->setCategory($book,$category); $this->Book_model->clearAuthor($book); // adiciona os autores ao livro foreach ($book->authors as $author) $this->Book_model->setAuthor($book,$author); $this->db->trans_complete(); $result = $this->db->trans_status(); $responseMsg = ($result) ? 'Editou os dados do livro':'Ocorreu um erro ao editar os dados do livro'; $log = createLog($token[0],$responseMsg); $this->Log_model->insert($log); $response['result'] = $result; $response['msg'] = $responseMsg; print(json_encode($response)); } /** * deleta um livro do sistema * @author Caio de Freitas Adriano * @since 2017/11/06 * @param Int - ID do livro * @return Json - retorna um json com o resultado da requisição */ public function delete($id) { // pega os dados do usuário que vieram da requisição $token = getToken(); $this->auth->setUserLevel($token[3]); $this->auth->setPagePermission([1]); // verifica se o usuário tem permissão para utilizar o serviço if (!$this->auth->hasPermission()) { header('HTTP/1.1 401 Unauthorized'); exit(); } $hasLibrary = $this->Book_model->hasLibrary($id); if (!$hasLibrary) { $result = $this->Book_model->setDeleted($id,true); $msg = ($result) ? 'Livro deletado com sucesso' : 'Ocorreu um erro ao deletar o livro'; } else { $result = false; $msg = 'O livro não pode ser deletado'; } $log = createLog($token[0],$msg); $this->Log_model->insert($log); $response['msg'] = $msg; $response['result'] = $result; print(json_encode($response)); } /** * Busca os dados de um livro. * @author Caio de Freitas Adriano * @since 2017/11/06 * @param Int - ID do livro * @return Json - Retona um objeto json com os dados do livro. */ public function getById ($id,$withLibrary=false) { $this->db->trans_start(); $book = $this->Book_model->getById($id); $book->publishingCompany = $this->PublishingCompany_model->getById($book->publishingCompany); $book->categories = $this->Book_model->getCategories($book); $book->authors = $this->Book_model->getAuthors($book); if ($withLibrary) { $book->libraries = $this->Book_model->getLibraries($book); foreach ($book->libraries as $library) { $library->address = $this->Address_model->getById($library->address); $library->address->City = $this->City_model->getById($library->address->City); } } $this->db->trans_complete(); print(json_encode($book)); } /** * adiciona um atributo picture com a tag img com a capa do livro. * @author Caio de Freitas Adriano * @since 2017/11/05 * @param Array - Vetor com os objetos books * @return Array - Retorna o vetor com os objetos book com o novo atributo * picture. */ private function setPicture($books) { foreach ($books as $book) { $book->picture = '<img src="'.base_url('upload/books/'.$book->cover).'">'; } return $books; } /** * Busca todos os livros cadastrados no sistema * @author Caio de Freitas Adriano * @since 2017/11/5 * @param Boolean (with_picture) - caso sejá true, será criado um atributo com * a tag img com a capa do livro. * @return Json - retorna um json com os livros. */ public function getAll () { $params = (object) $this->input->get(); $books = $this->Book_model->getAll(); foreach ($books as $book) { $book->categories = $this->Book_model->getCategories($book); $book->authors = $this->Book_model->getAuthors($book); } // verifica os parametros da requisição if (isset($params->with_picture)) $books = $this->setPicture($books); print(json_encode($books)); } /** * função para cadastrar um novo livro no sistema * @author Caio de Freitas Adriano * @since 2017/10/31 * @param Object - Objeto Book com os dados do livro. * @return Json - Retorna um json com o resultado da requisição. */ public function save () { // pega os dados do usuário que vieram da requisição $token = getToken(); $this->auth->setUserLevel($token[3]); $this->auth->setPagePermission([1,2]); // verifica se o usuário tem permissão para utilizar o serviço if (!$this->auth->hasPermission()) { header('HTTP/1.1 401 Unauthorized'); exit(); } $data = file_get_contents("php://input"); $book = json_decode($data); // Fazer todas as monipulações necessárias no objeto. $book->name = strtolower(trim($book->name)); $book->publishDate = brToSqlDate($book->publishDate); if ($book->publishingCompany) $book->publishingCompany = $book->publishingCompany[0]->id; $book->cover = filename($book->cover); $this->db->trans_start(); $this->Book_model->insert($book); $book->id = $this->db->insert_id(); // adiciona os autores ao livro foreach ($book->authors as $author) $this->Book_model->setAuthor($book,$author); // adiciona as categorias ao livro foreach ($book->categories as $category) $this->Book_model->setCategory($book,$category); $this->db->trans_complete(); $result = $this->db->trans_status(); $msg = ($result) ? 'Cadastrou um livro' : 'Ocorreu um erro ao cadastrar um livro'; $log = createLog($token[0],$msg); $this->Log_model->insert($log); $response['result'] = $result; print(json_encode($response)); } /** * Faz o upload da imagem do capa do livro * @author Caio de Freitas Adriano * @since 2017/11/01 * @param File - Recebe a imagem. * @return Json - retorna um json com o resultado da requisição */ public function saveCover() { // pega os dados do usuário que vieram da requisição $token = getToken(); $this->auth->setUserLevel($token[3]); $this->auth->setPagePermission([1,2]); // verifica se o usuário tem permissão para utilizar o serviço if (!$this->auth->hasPermission()) { header('HTTP/1.1 401 Unauthorized'); exit(); } // verifica se existe o diretorio "upload/books" // caso não exista, ele será criado. if (!file_exists('./upload/books')) mkdir('./upload/books',0777,true); // criando as configurações para o upload da imagem $config['upload_path'] = './upload/books'; // diretório de onde será gravado os dados. $config['allowed_types'] = 'jpg|png|jpeg'; // tipos de arquivos aceitos. $config['file_ext_tolower'] = true; // a extenção dos arquivos será em minusculo $config['max_size'] = 2048; // tamanho máximo do arquivo 2048Kb (2Mb) $config['max_filename'] = 255; // tamanho máximo do nome do arquivo $config['overwrite'] = true; // permite sobrescrever arquivos de mesmo nome $config['file_name'] = filename($_FILES['cover']['name']); // carrega a lib de upload $this->load->library('upload',$config); $result = $this->upload->do_upload('cover'); $response['result'] = $result; $msg = ($result) ? 'Fez upload de uma capa de livro' : 'Ocorreu um erro ao carregar a capa de um livro'; $log = createLog($token[0],$msg); $this->Log_model->insert($log); print(json_encode($response)); } } ?>
cronodev/hotlibrary
application/controllers/Book.php
PHP
apache-2.0
8,703
package eu.newsreader.conversion; import eu.newsreader.util.Util; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; /** * Created by piek on 12/15/14. */ public class ReduceConllResponse { static public void main (String[] args) { try { String pathToKeyFolder = ""; String pathToResponseFolder = ""; pathToKeyFolder = "/Users/piek/Desktop/NWR/NWR-benchmark/coreference/corpus_CONLL/corpus_airbus/events/key"; pathToResponseFolder = "/Users/piek/Desktop/NWR/NWR-benchmark/coreference/corpus_CONLL/corpus_airbus/events/response"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equalsIgnoreCase("--key") && args.length>(i+1)) { pathToKeyFolder = args[i+1]; } else if (arg.equalsIgnoreCase("--response") && args.length>(i+1)) { pathToResponseFolder = args[i+1]; } } ArrayList<File> keyFiles = Util.makeFlatFileList(new File(pathToKeyFolder)); ArrayList<File> responseFiles = Util.makeFlatFileList(new File(pathToResponseFolder)); System.out.println("keyFiles = " + keyFiles.size()); System.out.println("responseFiles = " + responseFiles.size()); for (int i = 0; i < keyFiles.size(); i++) { File keyFile = keyFiles.get(i); ArrayList<String> sentenceIds = Util.getSentenceIdsConllFile(keyFile); // System.out.println("sentenceIds.toString() = " + sentenceIds.toString()); String keyS1 = Util.readFirstSentence(keyFile); boolean MATCH = false; for (int j = 0; j < responseFiles.size(); j++) { File responseFile = responseFiles.get(j); String responseS1 = Util.readFirstSentence(responseFile); if (keyS1.equals(responseS1)) { String reducedResponse = Util.reduceConllFileForSentenceIds(responseFile, sentenceIds); // System.out.println("reducedResponse = " + reducedResponse); OutputStream responseFos = new FileOutputStream(responseFile); responseFos.write(reducedResponse.getBytes()); responseFos.close(); MATCH = true; break; } } if (!MATCH) { System.out.println("NO MATCH for keyFile = " + keyFile.getName()); System.out.println("sentenceIds = " + sentenceIds.toString()); } // break; } } catch (Exception e) { //e.printStackTrace(); } } }
cltl/coreference-evaluation
src/main/java/eu/newsreader/conversion/ReduceConllResponse.java
Java
apache-2.0
2,884
package me.nithanim.netty.packetlib.handler; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.util.Arrays; import me.nithanim.netty.packetlib.packets.Packet; import me.nithanim.netty.packetlib.testpackets.TestPacketEmpty; import me.nithanim.netty.packetlib.testpackets.TestPacketFull; import me.nithanim.netty.packetlib.testpackets.TestPacketReferenceCounted; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class PacketEncoderTest { private static PacketEncoder encoder; @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { encoder = new PacketEncoder(); } @After public void tearDown() { } @Test public void testEncodeEmpty() throws Exception { Packet packet = new TestPacketEmpty(); ByteBuf expected = packetAsBuffer(packet); ByteBuf encoded = getExactByteBuffer(packet.getPacketSize()); encoder.encode(null, packet, encoded); assertEquals(expected, encoded); } @Test public void testEncodeFull() throws Exception { Packet packet = new TestPacketFull(456253454, 53634); ByteBuf expected = packetAsBuffer(packet); ByteBuf encoded = getExactByteBuffer(packet.getPacketSize()); encoder.encode(null, packet, encoded); System.out.println(Arrays.toString(expected.array())); System.out.println(Arrays.toString(encoded.array())); assertEquals(expected, encoded); } @Test public void testEncodeMultiple() throws Exception { Packet[] packets = new Packet[] { new TestPacketEmpty(), new TestPacketFull(32, 34234), new TestPacketEmpty(), new TestPacketFull(234234235, 214421), new TestPacketEmpty() }; int sizeOfPackets = getSizeOfPacketArray(packets); ByteBuf encoded = Unpooled.buffer(sizeOfPackets); for(Packet packet : packets) { encoder.encode(null, packet, encoded); } ByteBuf expected = Unpooled.buffer(sizeOfPackets); for(Packet packet : packets) { expected.writeBytes(packetAsBuffer(packet)); } System.out.println(Arrays.toString(expected.array())); System.out.println(Arrays.toString(encoded.array())); assertEquals(expected, encoded); } @Test public void testReferenceCountDecrease() throws Exception { TestPacketReferenceCounted packet = new TestPacketReferenceCounted(); ByteBuf buffer = getExactByteBuffer(packet.getPacketSize()); assertTrue(packet.refCnt() == 1); encoder.encode(null, packet, buffer); assertTrue(packet.refCnt() == 0); } private int getSizeOfPacketArray(Packet[] packets) { int size = 0; for(Packet packet : packets) { size += packet.getPacketSize(); } return size; } private ByteBuf packetAsBuffer(Packet packet) { ByteBuf buffer = getExactByteBuffer(packet.getPacketSize()); writePacketMetaToByteBuf(packet, buffer); packet.pack(buffer); return buffer; } private void writePacketMetaToByteBuf(Packet packet, ByteBuf buf) { buf.writeByte(packet.getId()); buf.writeShort(packet.getPayloadSize()); } private ByteBuf getExactByteBuffer(int payloadSize) { return Unpooled.buffer(payloadSize, payloadSize); } }
Nithanim/netty-packet-library
library/src/test/java/me/nithanim/netty/packetlib/handler/PacketEncoderTest.java
Java
apache-2.0
3,734
/* * Copyright 2010-2013 OrientDB LTD (info--at--orientdb.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.storage.cluster.v1; import static com.orientechnologies.orient.core.config.OGlobalConfiguration.DISK_CACHE_PAGE_SIZE; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.serialization.types.OByteSerializer; import com.orientechnologies.common.serialization.types.OIntegerSerializer; import com.orientechnologies.common.serialization.types.OLongSerializer; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.compression.OCompression; import com.orientechnologies.orient.core.compression.OCompressionFactory; import com.orientechnologies.orient.core.compression.impl.ONothingCompression; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.config.OStorageClusterConfiguration; import com.orientechnologies.orient.core.config.OStoragePaginatedClusterConfiguration; import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy; import com.orientechnologies.orient.core.encryption.OEncryption; import com.orientechnologies.orient.core.encryption.OEncryptionFactory; import com.orientechnologies.orient.core.encryption.impl.ONothingEncryption; import com.orientechnologies.orient.core.exception.NotEmptyComponentCanNotBeRemovedException; import com.orientechnologies.orient.core.exception.OPaginatedClusterException; import com.orientechnologies.orient.core.exception.ORecordNotFoundException; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.OMetadataInternal; import com.orientechnologies.orient.core.storage.OPhysicalPosition; import com.orientechnologies.orient.core.storage.ORawBuffer; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.storage.cache.OCacheEntry; import com.orientechnologies.orient.core.storage.cluster.OClusterPage; import com.orientechnologies.orient.core.storage.cluster.OClusterPageDebug; import com.orientechnologies.orient.core.storage.cluster.OClusterPositionMap; import com.orientechnologies.orient.core.storage.cluster.OClusterPositionMapBucket; import com.orientechnologies.orient.core.storage.cluster.OPaginatedCluster; import com.orientechnologies.orient.core.storage.cluster.OPaginatedClusterDebug; import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; import com.orientechnologies.orient.core.storage.impl.local.OClusterBrowseEntry; import com.orientechnologies.orient.core.storage.impl.local.OClusterBrowsePage; import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperation; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 10/7/13 */ public final class OPaginatedClusterV1 extends OPaginatedCluster { private static final int STATE_ENTRY_INDEX = 0; private static final int BINARY_VERSION = 1; private static final int DISK_PAGE_SIZE = DISK_CACHE_PAGE_SIZE.getValueAsInteger(); @SuppressWarnings("deprecation") private static final int LOWEST_FREELIST_BOUNDARY = OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger(); private static final int FREE_LIST_SIZE = DISK_PAGE_SIZE - LOWEST_FREELIST_BOUNDARY; private static final int PAGE_INDEX_OFFSET = 16; private static final int RECORD_POSITION_MASK = 0xFFFF; private static final int ONE_KB = 1024; private volatile OCompression compression = ONothingCompression.INSTANCE; private volatile OEncryption encryption = ONothingEncryption.INSTANCE; private final boolean systemCluster; private final OClusterPositionMapV1 clusterPositionMap; private volatile int id; private long fileId; private ORecordConflictStrategy recordConflictStrategy; private static final class AddEntryResult { private final long pageIndex; private final int pagePosition; private final int recordVersion; private final int recordsSizeDiff; private AddEntryResult( final long pageIndex, final int pagePosition, final int recordVersion, final int recordsSizeDiff) { this.pageIndex = pageIndex; this.pagePosition = pagePosition; this.recordVersion = recordVersion; this.recordsSizeDiff = recordsSizeDiff; } } private static final class FindFreePageResult { private final long pageIndex; private final int freePageIndex; private final boolean allocateNewPage; private FindFreePageResult( final long pageIndex, final int freePageIndex, final boolean allocateNewPage) { this.pageIndex = pageIndex; this.freePageIndex = freePageIndex; this.allocateNewPage = allocateNewPage; } } public OPaginatedClusterV1(final String name, final OAbstractPaginatedStorage storage) { this(name, OPaginatedCluster.DEF_EXTENSION, OClusterPositionMap.DEF_EXTENSION, storage); } public OPaginatedClusterV1( final String name, final String dataExtension, final String cpmExtension, final OAbstractPaginatedStorage storage) { super(storage, name, dataExtension, name + dataExtension); systemCluster = OMetadataInternal.SYSTEM_CLUSTER.contains(name); clusterPositionMap = new OClusterPositionMapV1(storage, getName(), getFullName(), cpmExtension); } @Override public void configure(final int id, final String clusterName) throws IOException { acquireExclusiveLock(); try { final OContextConfiguration ctxCfg = storage.getConfiguration().getContextConfiguration(); final String cfgCompression = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD); @SuppressWarnings("deprecation") final String cfgEncryption = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD); final String cfgEncryptionKey = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); init(id, clusterName, cfgCompression, cfgEncryption, cfgEncryptionKey, null); } finally { releaseExclusiveLock(); } } @Override public boolean exists() { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); return isFileExists(atomicOperation, getFullName()); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public int getBinaryVersion() { return BINARY_VERSION; } @Override public OStoragePaginatedClusterConfiguration generateClusterConfig() { acquireSharedLock(); try { return new OStoragePaginatedClusterConfiguration( id, getName(), null, true, OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR, OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR, compression.name(), encryption.name(), null, Optional.ofNullable(recordConflictStrategy) .map(ORecordConflictStrategy::getName) .orElse(null), OStorageClusterConfiguration.STATUS.ONLINE, BINARY_VERSION); } finally { releaseSharedLock(); } } @Override public void configure(final OStorage storage, final OStorageClusterConfiguration config) throws IOException { acquireExclusiveLock(); try { final OContextConfiguration ctxCfg = storage.getConfiguration().getContextConfiguration(); final String cfgCompression = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD); @SuppressWarnings("deprecation") final String cfgEncryption = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD); final String cfgEncryptionKey = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); init( config.getId(), config.getName(), cfgCompression, cfgEncryption, cfgEncryptionKey, ((OStoragePaginatedClusterConfiguration) config).conflictStrategy); } finally { releaseExclusiveLock(); } } @Override public void create(final OAtomicOperation atomicOperation) { executeInsideComponentOperation( atomicOperation, operation -> { acquireExclusiveLock(); try { fileId = addFile(atomicOperation, getFullName()); initCusterState(atomicOperation); clusterPositionMap.create(atomicOperation); } finally { releaseExclusiveLock(); } }); } @Override public void open(OAtomicOperation atomicOperation) throws IOException { acquireExclusiveLock(); try { fileId = openFile(atomicOperation, getFullName()); clusterPositionMap.open(atomicOperation); } finally { releaseExclusiveLock(); } } @Override public void close() { close(true); } @Override public void close(final boolean flush) { acquireExclusiveLock(); try { if (flush) { synch(); } readCache.closeFile(fileId, flush, writeCache); clusterPositionMap.close(flush); } finally { releaseExclusiveLock(); } } @Override public void delete(OAtomicOperation atomicOperation) { executeInsideComponentOperation( atomicOperation, operation -> { acquireExclusiveLock(); try { final long entries = getEntries(); if (entries > 0) { throw new NotEmptyComponentCanNotBeRemovedException( getName() + " : Not empty cluster can not be deleted. Cluster has " + entries + " records"); } deleteFile(atomicOperation, fileId); clusterPositionMap.delete(atomicOperation); } finally { releaseExclusiveLock(); } }); } @Override public boolean isSystemCluster() { return systemCluster; } @Override public String compression() { acquireSharedLock(); try { return compression.name(); } finally { releaseSharedLock(); } } @Override public String encryption() { acquireSharedLock(); try { return encryption.name(); } finally { releaseSharedLock(); } } @Override public OPhysicalPosition allocatePosition( final byte recordType, final OAtomicOperation operation) { return calculateInsideComponentOperation( operation, atomicOperation -> { acquireExclusiveLock(); try { return createPhysicalPosition(recordType, clusterPositionMap.allocate(operation), -1); } finally { releaseExclusiveLock(); } }); } @Override public OPhysicalPosition createRecord( byte[] content, final int recordVersion, final byte recordType, final OPhysicalPosition allocatedPosition, final OAtomicOperation atomicOperation) { content = compression.compress(content); final byte[] encryptedContent = encryption.encrypt(content); return calculateInsideComponentOperation( atomicOperation, operation -> { acquireExclusiveLock(); try { final int entryContentLength = getEntryContentLength(encryptedContent.length); if (entryContentLength < OClusterPage.MAX_RECORD_SIZE) { final byte[] entryContent = new byte[entryContentLength]; int entryPosition = 0; entryContent[entryPosition] = recordType; entryPosition++; OIntegerSerializer.INSTANCE.serializeNative( encryptedContent.length, entryContent, entryPosition); entryPosition += OIntegerSerializer.INT_SIZE; System.arraycopy( encryptedContent, 0, entryContent, entryPosition, encryptedContent.length); entryPosition += encryptedContent.length; entryContent[entryPosition] = 1; entryPosition++; OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryPosition); final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, atomicOperation); updateClusterState(1, addEntryResult.recordsSizeDiff, atomicOperation); final long clusterPosition; if (allocatedPosition != null) { clusterPositionMap.update( allocatedPosition.clusterPosition, new OClusterPositionMapBucket.PositionEntry( addEntryResult.pageIndex, addEntryResult.pagePosition), atomicOperation); clusterPosition = allocatedPosition.clusterPosition; } else { clusterPosition = clusterPositionMap.add( addEntryResult.pageIndex, addEntryResult.pagePosition, atomicOperation); } return createPhysicalPosition( recordType, clusterPosition, addEntryResult.recordVersion); } else { final int entrySize = encryptedContent.length + OIntegerSerializer.INT_SIZE + OByteSerializer.BYTE_SIZE; int fullEntryPosition = 0; final byte[] fullEntry = new byte[entrySize]; fullEntry[fullEntryPosition] = recordType; fullEntryPosition++; OIntegerSerializer.INSTANCE.serializeNative( encryptedContent.length, fullEntry, fullEntryPosition); fullEntryPosition += OIntegerSerializer.INT_SIZE; System.arraycopy( encryptedContent, 0, fullEntry, fullEntryPosition, encryptedContent.length); long prevPageRecordPointer = -1; long firstPageIndex = -1; int firstPagePosition = -1; int version = 0; int from = 0; int to = from + (OClusterPage.MAX_RECORD_SIZE - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE); int recordsSizeDiff = 0; do { final byte[] entryContent = new byte[to - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE]; System.arraycopy(fullEntry, from, entryContent, 0, to - from); if (from > 0) { entryContent[ entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0; } else { entryContent[ entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1; } OLongSerializer.INSTANCE.serializeNative( -1L, entryContent, entryContent.length - OLongSerializer.LONG_SIZE); final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, atomicOperation); recordsSizeDiff += addEntryResult.recordsSizeDiff; if (firstPageIndex == -1) { firstPageIndex = addEntryResult.pageIndex; firstPagePosition = addEntryResult.pagePosition; version = addEntryResult.recordVersion; } final long addedPagePointer = createPagePointer(addEntryResult.pageIndex, addEntryResult.pagePosition); if (prevPageRecordPointer >= 0) { final long prevPageIndex = getPageIndex(prevPageRecordPointer); final int prevPageRecordPosition = getRecordPosition(prevPageRecordPointer); final OCacheEntry prevPageCacheEntry = loadPageForWrite(atomicOperation, fileId, prevPageIndex, false, true); try { final OClusterPage prevPage = new OClusterPage(prevPageCacheEntry); prevPage.setRecordLongValue( prevPageRecordPosition, -OLongSerializer.LONG_SIZE, addedPagePointer); } finally { releasePageFromWrite(atomicOperation, prevPageCacheEntry); } } prevPageRecordPointer = addedPagePointer; from = to; to = to + (OClusterPage.MAX_RECORD_SIZE - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE); if (to > fullEntry.length) { to = fullEntry.length; } } while (from < to); updateClusterState(1, recordsSizeDiff, atomicOperation); final long clusterPosition; if (allocatedPosition != null) { clusterPositionMap.update( allocatedPosition.clusterPosition, new OClusterPositionMapBucket.PositionEntry(firstPageIndex, firstPagePosition), atomicOperation); clusterPosition = allocatedPosition.clusterPosition; } else { clusterPosition = clusterPositionMap.add(firstPageIndex, firstPagePosition, atomicOperation); } return createPhysicalPosition(recordType, clusterPosition, version); } } finally { releaseExclusiveLock(); } }); } private static int getEntryContentLength(final int grownContentSize) { return grownContentSize + 2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE; } @Override public ORawBuffer readRecord(final long clusterPosition, final boolean prefetchRecords) throws IOException { int pagesToPrefetch = 1; if (prefetchRecords) { pagesToPrefetch = OGlobalConfiguration.QUERY_SCAN_PREFETCH_PAGES.getValueAsInteger(); } return readRecord(clusterPosition, pagesToPrefetch); } private ORawBuffer readRecord(final long clusterPosition, final int pageCount) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, pageCount, atomicOperation); if (positionEntry == null) { return null; } return internalReadRecord( clusterPosition, positionEntry.getPageIndex(), positionEntry.getRecordPosition(), pageCount, atomicOperation); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } private ORawBuffer internalReadRecord( final long clusterPosition, final long pageIndex, final int recordPosition, int pageCount, final OAtomicOperation atomicOperation) throws IOException { if (pageCount > 1) { final OCacheEntry stateCacheEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, false); try { final OPaginatedClusterStateV1 state = new OPaginatedClusterStateV1(stateCacheEntry); pageCount = (int) Math.min(state.getFileSize() + 1 - pageIndex, pageCount); } finally { releasePageFromRead(atomicOperation, stateCacheEntry); } } int recordVersion; final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false, pageCount); try { final OClusterPage localPage = new OClusterPage(cacheEntry); recordVersion = localPage.getRecordVersion(recordPosition); } finally { releasePageFromRead(atomicOperation, cacheEntry); } final byte[] fullContent = readFullEntry(clusterPosition, pageIndex, recordPosition, atomicOperation, pageCount); if (fullContent == null) { return null; } int fullContentPosition = 0; final byte recordType = fullContent[fullContentPosition]; fullContentPosition++; final int readContentSize = OIntegerSerializer.INSTANCE.deserializeNative(fullContent, fullContentPosition); fullContentPosition += OIntegerSerializer.INT_SIZE; byte[] recordContent = Arrays.copyOfRange(fullContent, fullContentPosition, fullContentPosition + readContentSize); recordContent = encryption.decrypt(recordContent); recordContent = compression.uncompress(recordContent); return new ORawBuffer(recordContent, recordVersion, recordType); } @Override public ORawBuffer readRecordIfVersionIsNotLatest( final long clusterPosition, final int recordVersion) throws IOException, ORecordNotFoundException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, atomicOperation); if (positionEntry == null) { throw new ORecordNotFoundException( new ORecordId(id, clusterPosition), "Record for cluster with id " + id + " and position " + clusterPosition + " is absent."); } final int recordPosition = positionEntry.getRecordPosition(); final long pageIndex = positionEntry.getPageIndex(); int loadedRecordVersion; final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false); try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (localPage.isDeleted(recordPosition)) { throw new ORecordNotFoundException( new ORecordId(id, clusterPosition), "Record for cluster with id " + id + " and position " + clusterPosition + " is absent."); } loadedRecordVersion = localPage.getRecordVersion(recordPosition); } finally { releasePageFromRead(atomicOperation, cacheEntry); } if (loadedRecordVersion > recordVersion) { return readRecord(clusterPosition, false); } return null; } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public boolean deleteRecord(OAtomicOperation operation, final long clusterPosition) { return calculateInsideComponentOperation( operation, atomicOperation -> { acquireExclusiveLock(); try { final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, operation); if (positionEntry == null) { return false; } long pageIndex = positionEntry.getPageIndex(); int recordPosition = positionEntry.getRecordPosition(); long nextPagePointer; int removedContentSize = 0; do { boolean cacheEntryReleased = false; OCacheEntry cacheEntry = loadPageForWrite(operation, fileId, pageIndex, false, true); int initialFreePageIndex; try { OClusterPage localPage = new OClusterPage(cacheEntry); initialFreePageIndex = calculateFreePageIndex(localPage); if (localPage.isDeleted(recordPosition)) { if (removedContentSize == 0) { cacheEntryReleased = true; releasePageFromWrite(operation, cacheEntry); return false; } else { throw new OPaginatedClusterException( "Content of record " + new ORecordId(id, clusterPosition) + " was broken", this); } } else if (removedContentSize == 0) { releasePageFromWrite(operation, cacheEntry); cacheEntry = loadPageForWrite(operation, fileId, pageIndex, false, true); localPage = new OClusterPage(cacheEntry); } final byte[] content = localPage.deleteRecord(recordPosition, true); operation.addDeletedRecordPosition(id, cacheEntry.getPageIndex(), recordPosition); assert content != null; final int initialFreeSpace = localPage.getFreeSpace(); localPage.deleteRecord(recordPosition, true); operation.addDeletedRecordPosition(id, cacheEntry.getPageIndex(), recordPosition); removedContentSize += localPage.getFreeSpace() - initialFreeSpace; nextPagePointer = OLongSerializer.INSTANCE.deserializeNative( content, content.length - OLongSerializer.LONG_SIZE); } finally { if (!cacheEntryReleased) { releasePageFromWrite(operation, cacheEntry); } } updateFreePagesIndex(initialFreePageIndex, pageIndex, operation); pageIndex = getPageIndex(nextPagePointer); recordPosition = getRecordPosition(nextPagePointer); } while (nextPagePointer >= 0); updateClusterState(-1, -removedContentSize, operation); clusterPositionMap.remove(clusterPosition, operation); return true; } finally { releaseExclusiveLock(); } }); } @Override public void updateRecord( final long clusterPosition, byte[] content, final int recordVersion, final byte recordType, final OAtomicOperation atomicOperation) { content = compression.compress(content); content = encryption.encrypt(content); final byte[] encryptedContent = content; executeInsideComponentOperation( atomicOperation, operation -> { acquireExclusiveLock(); try { final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, atomicOperation); if (positionEntry == null) { return; } int nextRecordPosition = positionEntry.getRecordPosition(); long nextPageIndex = positionEntry.getPageIndex(); int newRecordPosition = -1; long newPageIndex = -1; long prevPageIndex = -1; int prevRecordPosition = -1; long nextEntryPointer = -1; int from = 0; int to; long sizeDiff = 0; byte[] updateEntry = null; do { final int entrySize; final int updatedEntryPosition; if (updateEntry == null) { if (from == 0) { entrySize = Math.min( getEntryContentLength(encryptedContent.length), OClusterPage.MAX_RECORD_SIZE); to = entrySize - (2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE); } else { entrySize = Math.min( encryptedContent.length - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE, OClusterPage.MAX_RECORD_SIZE); to = from + entrySize - (OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE); } updateEntry = new byte[entrySize]; int entryPosition = 0; if (from == 0) { updateEntry[entryPosition] = recordType; entryPosition++; OIntegerSerializer.INSTANCE.serializeNative( encryptedContent.length, updateEntry, entryPosition); entryPosition += OIntegerSerializer.INT_SIZE; } System.arraycopy(encryptedContent, from, updateEntry, entryPosition, to - from); entryPosition += to - from; if (nextPageIndex == positionEntry.getPageIndex()) { updateEntry[entryPosition] = 1; } entryPosition++; OLongSerializer.INSTANCE.serializeNative(-1, updateEntry, entryPosition); assert to >= encryptedContent.length || entrySize == OClusterPage.MAX_RECORD_SIZE; } else { entrySize = updateEntry.length; if (from == 0) { to = entrySize - (2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE); } else { to = from + entrySize - (OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE); } } int freePageIndex = -1; final boolean isNew; if (nextPageIndex < 0) { final FindFreePageResult findFreePageResult = findFreePage(entrySize, atomicOperation); nextPageIndex = findFreePageResult.pageIndex; freePageIndex = findFreePageResult.freePageIndex; isNew = findFreePageResult.allocateNewPage; } else { isNew = false; } final OCacheEntry cacheEntry; if (isNew) { final OCacheEntry stateCacheEntry = loadPageForWrite(atomicOperation, fileId, STATE_ENTRY_INDEX, false, true); try { final OPaginatedClusterStateV1 clusterState = new OPaginatedClusterStateV1(stateCacheEntry); final int fileSize = clusterState.getFileSize(); final long filledUpTo = getFilledUpTo(atomicOperation, fileId); if (fileSize == filledUpTo - 1) { cacheEntry = addPage(atomicOperation, fileId); } else { assert fileSize < filledUpTo - 1; cacheEntry = loadPageForWrite(atomicOperation, fileId, fileSize + 1, false, false); } clusterState.setFileSize(fileSize + 1); } finally { releasePageFromWrite(atomicOperation, stateCacheEntry); } } else { cacheEntry = loadPageForWrite(atomicOperation, fileId, nextPageIndex, false, true); } try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (isNew) { localPage.init(); } final int pageFreeSpace = localPage.getFreeSpace(); if (freePageIndex < 0) { freePageIndex = calculateFreePageIndex(localPage); } else { assert isNew || freePageIndex == calculateFreePageIndex(localPage); } if (nextRecordPosition >= 0) { if (localPage.isDeleted(nextRecordPosition)) { throw new OPaginatedClusterException( "Record with rid " + new ORecordId(id, clusterPosition) + " was deleted", this); } final int currentEntrySize = localPage.getRecordSize(nextRecordPosition); nextEntryPointer = localPage.getRecordLongValue( nextRecordPosition, currentEntrySize - OLongSerializer.LONG_SIZE); if (currentEntrySize == entrySize) { localPage.replaceRecord(nextRecordPosition, updateEntry, recordVersion); updatedEntryPosition = nextRecordPosition; } else { localPage.deleteRecord(nextRecordPosition, true); atomicOperation.addDeletedRecordPosition( id, cacheEntry.getPageIndex(), nextRecordPosition); if (localPage.getMaxRecordSize() >= entrySize) { updatedEntryPosition = localPage.appendRecord( recordVersion, updateEntry, -1, atomicOperation.getBookedRecordPositions( id, cacheEntry.getPageIndex())); } else { updatedEntryPosition = -1; } } if (nextEntryPointer >= 0) { nextRecordPosition = getRecordPosition(nextEntryPointer); nextPageIndex = getPageIndex(nextEntryPointer); } else { nextPageIndex = -1; nextRecordPosition = -1; } } else { assert localPage.getFreeSpace() >= entrySize; updatedEntryPosition = localPage.appendRecord( recordVersion, updateEntry, -1, atomicOperation.getBookedRecordPositions(id, cacheEntry.getPageIndex())); nextPageIndex = -1; nextRecordPosition = -1; } sizeDiff += pageFreeSpace - localPage.getFreeSpace(); } finally { releasePageFromWrite(atomicOperation, cacheEntry); } updateFreePagesIndex(freePageIndex, cacheEntry.getPageIndex(), atomicOperation); if (updatedEntryPosition >= 0) { if (from == 0) { newPageIndex = cacheEntry.getPageIndex(); newRecordPosition = updatedEntryPosition; } from = to; if (prevPageIndex >= 0) { final OCacheEntry prevCacheEntry = loadPageForWrite(atomicOperation, fileId, prevPageIndex, false, true); try { final OClusterPage prevPage = new OClusterPage(prevCacheEntry); prevPage.setRecordLongValue( prevRecordPosition, -OLongSerializer.LONG_SIZE, createPagePointer(cacheEntry.getPageIndex(), updatedEntryPosition)); } finally { releasePageFromWrite(atomicOperation, prevCacheEntry); } } prevPageIndex = cacheEntry.getPageIndex(); prevRecordPosition = updatedEntryPosition; updateEntry = null; } } while (to < encryptedContent.length || updateEntry != null); // clear unneeded pages while (nextEntryPointer >= 0) { nextPageIndex = getPageIndex(nextEntryPointer); nextRecordPosition = getRecordPosition(nextEntryPointer); final int freePagesIndex; final int freeSpace; final OCacheEntry cacheEntry = loadPageForWrite(atomicOperation, fileId, nextPageIndex, false, true); try { final OClusterPage localPage = new OClusterPage(cacheEntry); freeSpace = localPage.getFreeSpace(); freePagesIndex = calculateFreePageIndex(localPage); nextEntryPointer = localPage.getRecordLongValue(nextRecordPosition, -OLongSerializer.LONG_SIZE); localPage.deleteRecord(nextRecordPosition, true); atomicOperation.addDeletedRecordPosition( id, cacheEntry.getPageIndex(), nextRecordPosition); sizeDiff += freeSpace - localPage.getFreeSpace(); } finally { releasePageFromWrite(atomicOperation, cacheEntry); } updateFreePagesIndex(freePagesIndex, nextPageIndex, atomicOperation); } assert newPageIndex >= 0; assert newRecordPosition >= 0; if (newPageIndex != positionEntry.getPageIndex() || newRecordPosition != positionEntry.getRecordPosition()) { clusterPositionMap.update( clusterPosition, new OClusterPositionMapBucket.PositionEntry(newPageIndex, newRecordPosition), atomicOperation); } updateClusterState(0, sizeDiff, atomicOperation); } finally { releaseExclusiveLock(); } }); } @Override public long getTombstonesCount() { return 0; } @Override public OPhysicalPosition getPhysicalPosition(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long clusterPosition = position.clusterPosition; final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, atomicOperation); if (positionEntry == null) { return null; } final long pageIndex = positionEntry.getPageIndex(); final int recordPosition = positionEntry.getRecordPosition(); final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false); try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (localPage.isDeleted(recordPosition)) { return null; } if (localPage.getRecordByteValue( recordPosition, -OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE) == 0) { return null; } final OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.recordSize = -1; physicalPosition.recordType = localPage.getRecordByteValue(recordPosition, 0); physicalPosition.recordVersion = localPage.getRecordVersion(recordPosition); physicalPosition.clusterPosition = position.clusterPosition; return physicalPosition; } finally { releasePageFromRead(atomicOperation, cacheEntry); } } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public boolean isDeleted(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long clusterPosition = position.clusterPosition; final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, atomicOperation); if (positionEntry == null) { return false; } final long pageIndex = positionEntry.getPageIndex(); final int recordPosition = positionEntry.getRecordPosition(); final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false); try { final OClusterPage localPage = new OClusterPage(cacheEntry); return localPage.isDeleted(recordPosition); } finally { releasePageFromRead(atomicOperation, cacheEntry); } } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public long getEntries() { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OCacheEntry pinnedStateEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, true); try { return new OPaginatedClusterStateV1(pinnedStateEntry).getSize(); } finally { releasePageFromRead(atomicOperation, pinnedStateEntry); } } finally { releaseSharedLock(); } } catch (final IOException ioe) { throw OException.wrapException( new OPaginatedClusterException( "Error during retrieval of size of '" + getName() + "' cluster", this), ioe); } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public long getFirstPosition() throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); return clusterPositionMap.getFirstPosition(atomicOperation); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public long getLastPosition() throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); return clusterPositionMap.getLastPosition(atomicOperation); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public long getNextPosition() throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); return clusterPositionMap.getNextPosition(atomicOperation); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public String getFileName() { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { return writeCache.fileNameById(fileId); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public int getId() { return id; } /** Returns the fileId used in disk cache. */ public long getFileId() { return fileId; } @Override public void synch() { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { writeCache.flush(fileId); clusterPositionMap.flush(); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public long getRecordsSize() throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OCacheEntry pinnedStateEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, true); try { return new OPaginatedClusterStateV1(pinnedStateEntry).getRecordsSize(); } finally { releasePageFromRead(atomicOperation, pinnedStateEntry); } } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public OPhysicalPosition[] higherPositions(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long[] clusterPositions = clusterPositionMap.higherPositions(position.clusterPosition, atomicOperation); return convertToPhysicalPositions(clusterPositions); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public OPhysicalPosition[] ceilingPositions(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long[] clusterPositions = clusterPositionMap.ceilingPositions(position.clusterPosition, atomicOperation); return convertToPhysicalPositions(clusterPositions); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public OPhysicalPosition[] lowerPositions(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long[] clusterPositions = clusterPositionMap.lowerPositions(position.clusterPosition, atomicOperation); return convertToPhysicalPositions(clusterPositions); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public OPhysicalPosition[] floorPositions(final OPhysicalPosition position) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final long[] clusterPositions = clusterPositionMap.floorPositions(position.clusterPosition, atomicOperation); return convertToPhysicalPositions(clusterPositions); } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } @Override public ORecordConflictStrategy getRecordConflictStrategy() { return recordConflictStrategy; } @Override public void setRecordConflictStrategy(final String stringValue) { acquireExclusiveLock(); try { recordConflictStrategy = Orient.instance().getRecordConflictStrategy().getStrategy(stringValue); } finally { releaseExclusiveLock(); } } private void updateClusterState( final long sizeDiff, final long recordsSizeDiff, final OAtomicOperation atomicOperation) throws IOException { final OCacheEntry pinnedStateEntry = loadPageForWrite(atomicOperation, fileId, STATE_ENTRY_INDEX, false, true); try { final OPaginatedClusterStateV1 paginatedClusterState = new OPaginatedClusterStateV1(pinnedStateEntry); paginatedClusterState.setSize((int) (paginatedClusterState.getSize() + sizeDiff)); paginatedClusterState.setRecordsSize( (int) (paginatedClusterState.getRecordsSize() + recordsSizeDiff)); } finally { releasePageFromWrite(atomicOperation, pinnedStateEntry); } } private void init( final int id, final String name, final String compression, final String encryption, final String encryptionKey, final String conflictStrategy) throws IOException { OFileUtils.checkValidName(name); this.compression = OCompressionFactory.INSTANCE.getCompression(compression, null); this.encryption = OEncryptionFactory.INSTANCE.getEncryption(encryption, encryptionKey); if (conflictStrategy != null) { this.recordConflictStrategy = Orient.instance().getRecordConflictStrategy().getStrategy(conflictStrategy); } this.id = id; } @Override public void setEncryption(final String method, final String key) { acquireExclusiveLock(); try { encryption = OEncryptionFactory.INSTANCE.getEncryption(method, key); } catch (final IllegalArgumentException e) { //noinspection deprecation throw OException.wrapException( new OPaginatedClusterException( "Invalid value for " + ATTRIBUTES.ENCRYPTION + " attribute", this), e); } finally { releaseExclusiveLock(); } } @Override public void setClusterName(final String newName) { acquireExclusiveLock(); try { writeCache.renameFile(fileId, newName + getExtension()); clusterPositionMap.rename(newName); setName(newName); } catch (IOException e) { throw OException.wrapException( new OPaginatedClusterException("Error during renaming of cluster", this), e); } finally { releaseExclusiveLock(); } } private static OPhysicalPosition createPhysicalPosition( final byte recordType, final long clusterPosition, final int version) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.recordType = recordType; physicalPosition.recordSize = -1; physicalPosition.clusterPosition = clusterPosition; physicalPosition.recordVersion = version; return physicalPosition; } private byte[] readFullEntry( final long clusterPosition, long pageIndex, int recordPosition, final OAtomicOperation atomicOperation, int pageCount) throws IOException { final List<byte[]> recordChunks = new ArrayList<>(2); int contentSize = 0; if (pageCount > 1) { final OCacheEntry stateCacheEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, false); try { final OPaginatedClusterStateV1 state = new OPaginatedClusterStateV1(stateCacheEntry); pageCount = (int) Math.min(state.getFileSize() + 1 - pageIndex, pageCount); } finally { releasePageFromRead(atomicOperation, stateCacheEntry); } } long nextPagePointer; boolean firstEntry = true; do { final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false, pageCount); try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (localPage.isDeleted(recordPosition)) { if (recordChunks.isEmpty()) { return null; } else { throw new OPaginatedClusterException( "Content of record " + new ORecordId(id, clusterPosition) + " was broken", this); } } final byte[] content = localPage.getRecordBinaryValue( recordPosition, 0, localPage.getRecordSize(recordPosition)); assert content != null; if (firstEntry && content[content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] == 0) { return null; } recordChunks.add(content); nextPagePointer = OLongSerializer.INSTANCE.deserializeNative( content, content.length - OLongSerializer.LONG_SIZE); contentSize += content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; firstEntry = false; } finally { releasePageFromRead(atomicOperation, cacheEntry); } pageIndex = getPageIndex(nextPagePointer); recordPosition = getRecordPosition(nextPagePointer); } while (nextPagePointer >= 0); return convertRecordChunksToSingleChunk(recordChunks, contentSize); } private static byte[] convertRecordChunksToSingleChunk( final List<byte[]> recordChunks, final int contentSize) { final byte[] fullContent; if (recordChunks.size() == 1) { fullContent = recordChunks.get(0); } else { fullContent = new byte[contentSize + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE]; int fullContentPosition = 0; for (final byte[] recordChuck : recordChunks) { System.arraycopy( recordChuck, 0, fullContent, fullContentPosition, recordChuck.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE); fullContentPosition += recordChuck.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; } } return fullContent; } private static long createPagePointer(final long pageIndex, final int pagePosition) { return pageIndex << PAGE_INDEX_OFFSET | pagePosition; } private static int getRecordPosition(final long nextPagePointer) { return (int) (nextPagePointer & RECORD_POSITION_MASK); } private static long getPageIndex(final long nextPagePointer) { return nextPagePointer >>> PAGE_INDEX_OFFSET; } private AddEntryResult addEntry( final int recordVersion, final byte[] entryContent, final OAtomicOperation atomicOperation) throws IOException { int recordSizesDiff; int position; int finalVersion = 0; long pageIndex; do { final FindFreePageResult findFreePageResult = findFreePage(entryContent.length, atomicOperation); final int freePageIndex = findFreePageResult.freePageIndex; pageIndex = findFreePageResult.pageIndex; final boolean newPage = findFreePageResult.allocateNewPage; final OCacheEntry cacheEntry; if (newPage) { final OCacheEntry stateCacheEntry = loadPageForWrite(atomicOperation, fileId, STATE_ENTRY_INDEX, false, true); try { final OPaginatedClusterStateV1 clusterState = new OPaginatedClusterStateV1(stateCacheEntry); final int fileSize = clusterState.getFileSize(); final long filledUpTo = getFilledUpTo(atomicOperation, fileId); if (fileSize == filledUpTo - 1) { cacheEntry = addPage(atomicOperation, fileId); } else { assert fileSize < filledUpTo - 1; cacheEntry = loadPageForWrite(atomicOperation, fileId, fileSize + 1, false, false); } clusterState.setFileSize(fileSize + 1); } finally { releasePageFromWrite(atomicOperation, stateCacheEntry); } } else { cacheEntry = loadPageForWrite(atomicOperation, fileId, pageIndex, false, true); } try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (newPage) { localPage.init(); } assert newPage || freePageIndex == calculateFreePageIndex(localPage); final int initialFreeSpace = localPage.getFreeSpace(); position = localPage.appendRecord( recordVersion, entryContent, -1, atomicOperation.getBookedRecordPositions(id, cacheEntry.getPageIndex())); final int freeSpace = localPage.getFreeSpace(); recordSizesDiff = initialFreeSpace - freeSpace; if (position >= 0) { finalVersion = localPage.getRecordVersion(position); } } finally { releasePageFromWrite(atomicOperation, cacheEntry); } updateFreePagesIndex(freePageIndex, pageIndex, atomicOperation); } while (position < 0); return new AddEntryResult(pageIndex, position, finalVersion, recordSizesDiff); } private FindFreePageResult findFreePage( final int contentSize, final OAtomicOperation atomicOperation) throws IOException { int freePageIndex = contentSize / ONE_KB; //noinspection deprecation freePageIndex -= OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger(); if (freePageIndex < 0) { freePageIndex = 0; } long pageIndex; final OCacheEntry pinnedStateEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, true); try { final OPaginatedClusterStateV1 freePageLists = new OPaginatedClusterStateV1(pinnedStateEntry); do { pageIndex = freePageLists.getFreeListPage(freePageIndex); freePageIndex++; } while (pageIndex < 0 && freePageIndex < FREE_LIST_SIZE); } finally { releasePageFromRead(atomicOperation, pinnedStateEntry); } final boolean allocateNewPage; if (pageIndex < 0) { final int fileSize; final OCacheEntry stateCacheEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, false); try { final OPaginatedClusterStateV1 clusterState = new OPaginatedClusterStateV1(stateCacheEntry); fileSize = clusterState.getFileSize(); } finally { releasePageFromRead(atomicOperation, stateCacheEntry); } allocateNewPage = true; pageIndex = fileSize + 1; } else { allocateNewPage = false; freePageIndex--; } return new FindFreePageResult(pageIndex, freePageIndex, allocateNewPage); } private void updateFreePagesIndex( final int prevFreePageIndex, final long pageIndex, final OAtomicOperation atomicOperation) throws IOException { final OCacheEntry cacheEntry = loadPageForWrite(atomicOperation, fileId, pageIndex, false, true); try { final OClusterPage localPage = new OClusterPage(cacheEntry); final int newFreePageIndex = calculateFreePageIndex(localPage); if (prevFreePageIndex == newFreePageIndex) { return; } final long nextPageIndex = localPage.getNextPage(); final long prevPageIndex = localPage.getPrevPage(); if (prevPageIndex >= 0) { final OCacheEntry prevPageCacheEntry = loadPageForWrite(atomicOperation, fileId, prevPageIndex, false, true); try { final OClusterPage prevPage = new OClusterPage(prevPageCacheEntry); assert calculateFreePageIndex(prevPage) == prevFreePageIndex; prevPage.setNextPage(nextPageIndex); } finally { releasePageFromWrite(atomicOperation, prevPageCacheEntry); } } if (nextPageIndex >= 0) { final OCacheEntry nextPageCacheEntry = loadPageForWrite(atomicOperation, fileId, nextPageIndex, false, true); try { final OClusterPage nextPage = new OClusterPage(nextPageCacheEntry); if (calculateFreePageIndex(nextPage) != prevFreePageIndex) { calculateFreePageIndex(nextPage); } assert calculateFreePageIndex(nextPage) == prevFreePageIndex; nextPage.setPrevPage(prevPageIndex); } finally { releasePageFromWrite(atomicOperation, nextPageCacheEntry); } } localPage.setNextPage(-1); localPage.setPrevPage(-1); if (prevFreePageIndex < 0 && newFreePageIndex < 0) { return; } if (prevFreePageIndex >= 0 && prevFreePageIndex < FREE_LIST_SIZE) { if (prevPageIndex < 0) { updateFreePagesList(prevFreePageIndex, nextPageIndex, atomicOperation); } } if (newFreePageIndex >= 0) { long oldFreePage; final OCacheEntry pinnedStateEntry = loadPageForRead(atomicOperation, fileId, STATE_ENTRY_INDEX, true); try { final OPaginatedClusterStateV1 clusterFreeList = new OPaginatedClusterStateV1(pinnedStateEntry); oldFreePage = clusterFreeList.getFreeListPage(newFreePageIndex); } finally { releasePageFromRead(atomicOperation, pinnedStateEntry); } if (oldFreePage >= 0) { final OCacheEntry oldFreePageCacheEntry = loadPageForWrite(atomicOperation, fileId, oldFreePage, false, true); try { final OClusterPage oldFreeLocalPage = new OClusterPage(oldFreePageCacheEntry); assert calculateFreePageIndex(oldFreeLocalPage) == newFreePageIndex; oldFreeLocalPage.setPrevPage(pageIndex); } finally { releasePageFromWrite(atomicOperation, oldFreePageCacheEntry); } localPage.setNextPage(oldFreePage); localPage.setPrevPage(-1); } updateFreePagesList(newFreePageIndex, pageIndex, atomicOperation); } } finally { releasePageFromWrite(atomicOperation, cacheEntry); } } private void updateFreePagesList( final int freeListIndex, final long pageIndex, final OAtomicOperation atomicOperation) throws IOException { final OCacheEntry pinnedStateEntry = loadPageForWrite(atomicOperation, fileId, STATE_ENTRY_INDEX, true, true); try { final OPaginatedClusterStateV1 paginatedClusterState = new OPaginatedClusterStateV1(pinnedStateEntry); paginatedClusterState.setFreeListPage(freeListIndex, (int) pageIndex); } finally { releasePageFromWrite(atomicOperation, pinnedStateEntry); } } private static int calculateFreePageIndex(final OClusterPage localPage) { int newFreePageIndex; if (localPage.isEmpty()) { newFreePageIndex = FREE_LIST_SIZE - 1; } else { newFreePageIndex = (localPage.getMaxRecordSize() - (ONE_KB - 1)) / ONE_KB; newFreePageIndex -= LOWEST_FREELIST_BOUNDARY; } return newFreePageIndex; } private void initCusterState(final OAtomicOperation atomicOperation) throws IOException { final OCacheEntry stateEntry; if (getFilledUpTo(atomicOperation, fileId) == 0) { stateEntry = addPage(atomicOperation, fileId); } else { stateEntry = loadPageForWrite(atomicOperation, fileId, STATE_ENTRY_INDEX, false, false); } assert stateEntry.getPageIndex() == 0; try { final OPaginatedClusterStateV1 paginatedClusterState = new OPaginatedClusterStateV1(stateEntry); paginatedClusterState.setSize(0); paginatedClusterState.setRecordsSize(0); paginatedClusterState.setFileSize(0); for (int i = 0; i < FREE_LIST_SIZE; i++) { paginatedClusterState.setFreeListPage(i, -1); } } finally { releasePageFromWrite(atomicOperation, stateEntry); } } private static OPhysicalPosition[] convertToPhysicalPositions(final long[] clusterPositions) { final OPhysicalPosition[] positions = new OPhysicalPosition[clusterPositions.length]; for (int i = 0; i < positions.length; i++) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.clusterPosition = clusterPositions[i]; positions[i] = physicalPosition; } return positions; } public OPaginatedClusterDebug readDebug(final long clusterPosition) throws IOException { final OPaginatedClusterDebug debug = new OPaginatedClusterDebug(); debug.clusterPosition = clusterPosition; debug.fileId = fileId; final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition, 1, atomicOperation); if (positionEntry == null) { debug.empty = true; return debug; } long pageIndex = positionEntry.getPageIndex(); int recordPosition = positionEntry.getRecordPosition(); debug.pages = new ArrayList<>(2); int contentSize = 0; long nextPagePointer; boolean firstEntry = true; do { final OClusterPageDebug debugPage = new OClusterPageDebug(); debugPage.pageIndex = pageIndex; final OCacheEntry cacheEntry = loadPageForRead(atomicOperation, fileId, pageIndex, false); try { final OClusterPage localPage = new OClusterPage(cacheEntry); if (localPage.isDeleted(recordPosition)) { if (debug.pages.isEmpty()) { debug.empty = true; return debug; } else { throw new OPaginatedClusterException( "Content of record " + new ORecordId(id, clusterPosition) + " was broken", this); } } debugPage.inPagePosition = recordPosition; debugPage.inPageSize = localPage.getRecordSize(recordPosition); final byte[] content = localPage.getRecordBinaryValue(recordPosition, 0, debugPage.inPageSize); assert content != null; debugPage.content = content; if (firstEntry && content[content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] == 0) { debug.empty = true; return debug; } debug.pages.add(debugPage); nextPagePointer = OLongSerializer.INSTANCE.deserializeNative( content, content.length - OLongSerializer.LONG_SIZE); contentSize += content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; firstEntry = false; } finally { releasePageFromRead(atomicOperation, cacheEntry); } pageIndex = getPageIndex(nextPagePointer); recordPosition = getRecordPosition(nextPagePointer); } while (nextPagePointer >= 0); debug.contentSize = contentSize; return debug; } public RECORD_STATUS getRecordStatus(final long clusterPosition) throws IOException { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); acquireSharedLock(); try { final byte status = clusterPositionMap.getStatus(clusterPosition, atomicOperation); switch (status) { case OClusterPositionMapBucket.NOT_EXISTENT: return RECORD_STATUS.NOT_EXISTENT; case OClusterPositionMapBucket.ALLOCATED: return RECORD_STATUS.ALLOCATED; case OClusterPositionMapBucket.FILLED: return RECORD_STATUS.PRESENT; case OClusterPositionMapBucket.REMOVED: return RECORD_STATUS.REMOVED; } // UNREACHABLE return null; } finally { releaseSharedLock(); } } @Override public void acquireAtomicExclusiveLock() { atomicOperationsManager.acquireExclusiveLockTillOperationComplete(this); } @Override public String toString() { return "plocal cluster: " + getName(); } @Override public OClusterBrowsePage nextPage(final long lastPosition) throws IOException { atomicOperationsManager.acquireReadLock(this); try { acquireSharedLock(); try { final OAtomicOperation atomicOperation = atomicOperationsManager.getCurrentOperation(); final OClusterPositionMapV1.OClusterPositionEntry[] nextPositions = clusterPositionMap.higherPositionsEntries(lastPosition, atomicOperation); if (nextPositions.length > 0) { final long newLastPosition = nextPositions[nextPositions.length - 1].getPosition(); final List<OClusterBrowseEntry> nexv = new ArrayList<>(nextPositions.length); for (final OClusterPositionMapV1.OClusterPositionEntry pos : nextPositions) { final ORawBuffer buff = internalReadRecord( pos.getPosition(), pos.getPage(), pos.getOffset(), 1, atomicOperation); nexv.add(new OClusterBrowseEntry(pos.getPosition(), buff)); } return new OClusterBrowsePage(nexv, newLastPosition); } else { return null; } } finally { releaseSharedLock(); } } finally { atomicOperationsManager.releaseReadLock(this); } } }
orientechnologies/orientdb
core/src/main/java/com/orientechnologies/orient/core/storage/cluster/v1/OPaginatedClusterV1.java
Java
apache-2.0
69,403
package cn.hicc.information.sensorsignin.utils; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; import android.widget.TextView; import java.util.ArrayList; import cn.hicc.information.sensorsignin.MyApplication; /** * 工具类 */ public class Utils { /** * 判断网络情况 * * @param context 上下文 * @return false 表示没有网络 true 表示有网络 */ public static boolean isNetworkAvalible(Context context) { // 获得网络状态管理器 ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return false; } else { // 建立网络数组 NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo(); if (net_info != null) { for (int i = 0; i < net_info.length; i++) { // 判断获得的网络状态是否是处于连接状态 if (net_info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } // 如果没有网络,则弹出网络设置对话框 public static void checkNetwork(final Activity activity) { if (!Utils.isNetworkAvalible(activity)) { TextView msg = new TextView(activity); msg.setText(" 当前没有可以使用的网络,部分功能可能无法使用,请设置网络!"); new AlertDialog.Builder(activity) //.setIcon(R.mipmap.ic_launcher) .setTitle("网络状态提示") .setView(msg) .setNegativeButton("朕知道了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setPositiveButton("开启网络", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 跳转到设置界面 activity.startActivityForResult(new Intent( Settings.ACTION_WIRELESS_SETTINGS), 0); } }).create().show(); } return; } // 判断服务是否在运行 public static boolean ServiceIsWorked(String name) { ActivityManager myManager = (ActivityManager) MyApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE); ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList <ActivityManager.RunningServiceInfo>)myManager.getRunningServices(300); for (int i = 0; i < runningService.size(); i++) { if (runningService.get(i).service.getClassName().toString().equals(name)) { return true; } } return false; } }
KnowledgeAndAction/-
app/src/main/java/cn/hicc/information/sensorsignin/utils/Utils.java
Java
apache-2.0
3,608
package cgeo.calendar; public interface ICalendar { static final String CALENDAR_ADDON_URI = "market://details?id=cgeo.calendar"; static final String INTENT = "cgeo.calendar.RESERVE"; static final String URI_SCHEME = "add"; static final String URI_HOST = "cgeo.org"; static final String PARAM_SHORT_DESC = "shortDesc"; // cache short description static final String PARAM_HIDDEN_DATE = "hiddenDate"; // cache hidden date in milliseconds static final String PARAM_URL = "url"; // cache URL static final String PARAM_NOTE = "note"; // personal note static final String PARAM_NAME = "name"; // cache name static final String PARAM_LOCATION = "location"; // cache location, or empty string static final String PARAM_COORDS = "coords"; // cache coordinates, or empty string static final String PARAM_START_TIME_MINUTES = "time"; // time of start }
eric-stanley/cgeo
main/src/cgeo/calendar/ICalendar.java
Java
apache-2.0
895
#include <iostream> #include <cstdlib> #include <map> using std::map; using std::cout; using std::endl; using std::cerr; using std::string; #define MAXROMAN 7 typedef map<char,int> roman_mapvals; typedef roman_mapvals::const_iterator roman_mapiter; int RTABLE_VALUES[]={ 1, 5, 10, 50, 100, 500, 1000 }; char RTABLE_CHARS[] ={ 'I','V','X','L','C','D','M' }; int usage(const char *name){ cout << "usage: "<< name << " <roman number> " << endl; exit(EXIT_SUCCESS); } int roman_to_decimal(const string &input, const roman_mapvals &romanreftable) { if( input.size() == 1 ){ roman_mapiter itr_roman_num = romanreftable.find(input[0]); if( itr_roman_num == romanreftable.end()) return EXIT_FAILURE; return itr_roman_num->second; } int sum=0, prefix=0, suffix =0, previous=0; string::const_iterator itr_input = input.begin(); for(int i=0,j=1; i != input.size() && j != input.size(); ++i,++j){ roman_mapiter itr_firstroman_num = romanreftable.find(itr_input[i]); roman_mapiter itr_secondroman_num = romanreftable.find(itr_input[j]); if( itr_firstroman_num == romanreftable.end() || itr_secondroman_num == romanreftable.end() ) // only valid roman characters in RTABLE_CHARS return EXIT_FAILURE; prefix = itr_firstroman_num->second; suffix = itr_secondroman_num->second; if( prefix < suffix ) sum = ( sum - prefix ) + ( suffix - prefix ); else{ if( i != 0 ) // not first time around sum += suffix; else // first time around sum = prefix + suffix; } previous = prefix; } return sum; } int main( int argc, char *argv[]) { if( argc < 2 ) usage(argv[0]); std::string roman_number(argv[1]); roman_mapvals reference_table; for(int i=0; i != MAXROMAN; ++i) // build lookup table reference_table[ RTABLE_CHARS[i] ] = RTABLE_VALUES[i]; int result = roman_to_decimal(roman_number, reference_table); if( result == EXIT_FAILURE ){ cerr << "FAILED: input contains non-Roman character "<< endl; exit(EXIT_FAILURE); } cout << "Arabic number " << result << endl; return EXIT_SUCCESS; }
xfdz/fragments
cpp/roman_to_decimal.cpp
C++
apache-2.0
2,429
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202202; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Updates the specified {@link CustomFieldOption} objects. * * @param customFieldOptions the custom field options to update * @return the updated custom field options * * * <p>Java class for updateCustomFieldOptions element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="updateCustomFieldOptions"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="customFieldOptions" type="{https://www.google.com/apis/ads/publisher/v202202}CustomFieldOption" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "customFieldOptions" }) @XmlRootElement(name = "updateCustomFieldOptions") public class CustomFieldServiceInterfaceupdateCustomFieldOptions { protected List<CustomFieldOption> customFieldOptions; /** * Gets the value of the customFieldOptions property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the customFieldOptions property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCustomFieldOptions().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CustomFieldOption } * * */ public List<CustomFieldOption> getCustomFieldOptions() { if (customFieldOptions == null) { customFieldOptions = new ArrayList<CustomFieldOption>(); } return this.customFieldOptions; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202202/CustomFieldServiceInterfaceupdateCustomFieldOptions.java
Java
apache-2.0
2,990
package com.senla.bolkunets.autoservice.api.managers; import java.util.Comparator; import java.util.Date; import java.util.List; import com.senla.bolkunets.autoservice.api.beans.IOrder; import com.senla.bolkunets.autoservice.api.enums.OrderStatus; public interface IOrdersManager { List<IOrder> getOrders(); void addOrder(IOrder order); boolean changeOrderStatus(long id, OrderStatus orderStatus); List<IOrder> getSortedListProgressOrders(Comparator<IOrder> orderComparator); List<IOrder> getSortedListAllOrders(Comparator<IOrder> orderComparator); IOrder getOrder(long idMaster); void setGarageToOrder(long idGarage, long idOrder); void removeGarageFromOrder(long idOrder); boolean addMasterToOrder(long idMaster, long idOrder); void removeMasterFromOrder(long idMaster, long idOrder); List<IOrder> getOrders(OrderStatus status, Date dateLeft, Date dateRight, Comparator<IOrder> comp); public int getCountFreePlace(Date date); Date getNextFreeDate(); void shiftOrders(long orderId, int countDay); void save(); }
BolkunetsAlexandr/java-training
task 5/autoservice-api/src/com/senla/bolkunets/autoservice/api/managers/IOrdersManager.java
Java
apache-2.0
1,054
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.requirement.module.admin.healthsystem.extension; import org.apache.wicket.markup.html.panel.Panel; import org.opensingular.requirement.module.admin.healthsystem.panel.JobPanel; public class JobsAdminEntry implements AdministrationEntryExtension { @Override public String name() { return "Jobs"; } @Override public Panel makePanel(String id) { return new JobPanel(id); } }
opensingular/singular-server
requirement/requirement-module/src/main/java/org/opensingular/requirement/module/admin/healthsystem/extension/JobsAdminEntry.java
Java
apache-2.0
1,087
/** * Symbol Art Editor * * @author malulleybovo (since 2021) * @license GNU General Public License v3.0 * * @licstart The following is the entire license notice for the * JavaScript code in this page. * * Copyright (C) 2021 Arthur Malulley B. de O. * * * The JavaScript code in this page is free software: you can * redistribute it and/or modify it under the terms of the GNU * General Public License (GNU GPL) as published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. The code is distributed WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. * * As additional permission under GNU GPL version 3 section 7, you * may distribute non-source (e.g., minimized or compacted) forms of * that code without the copy of the GNU GPL normally required by * section 4, provided you include this license notice and a URL * through which recipients can access the Corresponding Source. * * @licend The above is the entire license notice * for the JavaScript code in this page. * */ class UIAsset extends UIView { get viewPath() { return 'res/templates/asset.html' } _onTap = null; get onTap() { return this._onTap } set onTap(value) { if (typeof value !== 'function' && value !== null) return; this._onTap = value; } get assetFilePath() { return this.view.attr('src'); } _resourceLoaded = false; get loaded() { return this.view instanceof jQuery && this.view[0] instanceof HTMLElement && this._resourceLoaded; } constructor({ filePath = null } = {}) { super(); let path = filePath; this.didLoad(_ => { this.view.on('load', _ => { this._resourceLoaded = true; }); this.view.attr('src', path); this.gestureRecognizer = new UITapGestureRecognizer({ targetHtmlElement: this.view[0], onTap: () => { if (this._onTap) { this._onTap(this); } } }); }); } }
malulleybovo/SymbolArtEditorOnline
src/components/ui/UIAsset.js
JavaScript
apache-2.0
2,250
import Vue, { PluginObject } from 'vue'; import { Component } from 'vue-property-decorator'; import { TEXTAREA_NAME } from '../component-names'; import WithRender from './textarea.sandbox.html'; import TextareaPlugin from './textarea'; @WithRender @Component export class MTextareaSandbox extends Vue { public test4Model: string = ''; } const TextareaSandboxPlugin: PluginObject<any> = { install(v, options): void { v.use(TextareaPlugin); v.component(`${TEXTAREA_NAME}-sandbox`, MTextareaSandbox); } }; export default TextareaSandboxPlugin;
ulaval/modul-components
src/components/textarea/textarea.sandbox.ts
TypeScript
apache-2.0
573
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializable; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.CacheTransactionManager; import org.apache.geode.cache.TransactionDataNodeHasDepartedException; import org.apache.geode.cache.TransactionId; import org.apache.geode.cache.execute.Execution; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.internal.cache.TXId; import org.apache.geode.internal.logging.LogService; /** * This function can be used by GemFire clients and peers to rollback an existing transaction. A * {@link TransactionId} corresponding to the transaction to be rolledback must be provided as an * argument while invoking this function.<br /> * * This function should execute only on one server. If the transaction is not hosted on the server * where the function is invoked then this function decides to invoke a * {@link NestedTransactionFunction} which executes on the member where transaction is hosted.<br /> * * This function returns a single Boolean as result, whose value is <code>Boolean.TRUE</code> if the * transaction rolled back successfully otherwise the return value is * <code>Boolean.FALSE</code>.<br /> * * To execute this function, it is recommended to use the {@link Execution} obtained by using * TransactionFunctionService. <br /> * * To summarize, this function should be used as follows: * * <pre> * Execution exe = TransactionFunctionService.onTransaction(txId); * List l = (List) exe.execute(rollbackFunction).getResult(); * Boolean result = (Boolean) l.get(0); * </pre> * * This function is <b>not</b> registered on the cache servers by default, and it is the user's * responsibility to register this function. see {@link FunctionService#registerFunction(Function)} * * @since GemFire 6.6.1 */ public class RollbackFunction implements Function, DataSerializable { private static final Logger logger = LogService.getLogger(); private static final long serialVersionUID = 1377183180063184795L; public RollbackFunction() {} public boolean hasResult() { return true; } public void execute(FunctionContext context) { Cache cache = CacheFactory.getAnyInstance(); TXId txId = null; try { txId = (TXId) context.getArguments(); } catch (ClassCastException e) { logger.info( "RollbackFunction should be invoked with a TransactionId as an argument i.e. setArguments(txId).execute(function)"); throw e; } DistributedMember member = txId.getMemberId(); Boolean result = false; final boolean isDebugEnabled = logger.isDebugEnabled(); if (cache.getDistributedSystem().getDistributedMember().equals(member)) { if (isDebugEnabled) { logger.debug("RollbackFunction: for transaction: {} rolling back locally", txId); } CacheTransactionManager txMgr = cache.getCacheTransactionManager(); if (txMgr.tryResume(txId)) { if (isDebugEnabled) { logger.debug("RollbackFunction: resumed transaction: {}", txId); } txMgr.rollback(); result = true; } } else { ArrayList args = new ArrayList(); args.add(txId); args.add(NestedTransactionFunction.ROLLBACK); Execution ex = FunctionService.onMember(member).setArguments(args); if (isDebugEnabled) { logger.debug( "RollbackFunction: for transaction: {} executing NestedTransactionFunction on member: {}", txId, member); } try { List list = (List) ex.execute(new NestedTransactionFunction()).getResult(); result = (Boolean) list.get(0); } catch (FunctionException fe) { throw new TransactionDataNodeHasDepartedException("Could not Rollback on member:" + member); } } if (isDebugEnabled) { logger.debug("RollbackFunction: for transaction: {} returning result: {}", txId, result); } context.getResultSender().lastResult(result); } public String getId() { return getClass().getName(); } public boolean optimizeForWrite() { return true; } public boolean isHA() { // GEM-207 return true; } @Override public void toData(DataOutput out) throws IOException { } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { } }
smanvi-pivotal/geode
geode-core/src/test/java/org/apache/geode/internal/cache/RollbackFunction.java
Java
apache-2.0
5,585
package com.sequenceiq.cloudbreak.orchestrator.salt; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.sequenceiq.cloudbreak.util.FileReaderUtils; @Component public class SaltErrorResolver { private static final Logger LOGGER = LoggerFactory.getLogger(SaltErrorResolver.class); private Map<String, String> errorMessages; private List<String> commandsWithStderrFailures; private String resolveErrorMessage(Map<String, String> errors) { String name = errors.get("Name"); Optional<String> found = errorMessages.keySet().stream().filter(name::contains).findFirst(); if (found.isPresent()) { return errorMessages.get(found.get()); } else { found = commandsWithStderrFailures.stream().filter(name::contains).findFirst(); if (found.isPresent() && errors.containsKey("Stderr")) { return errors.get("Stderr"); } } return "Failed to execute: " + errors; } private String resolveMessageIfAvailable(Map<String, String> value) { if (value.containsKey("Name")) { return resolveErrorMessage(value); } if (value.size() == 1) { return value.values().iterator().next(); } return value.toString(); } @PostConstruct public void init() { try { String file = FileReaderUtils.readFileFromClasspath("salt/errormessages.yaml"); errorMessages = new Yaml().load(file); LOGGER.info("Error messages for salt: {}", errorMessages); file = FileReaderUtils.readFileFromClasspath("salt/stderrcommands.yaml"); commandsWithStderrFailures = new Yaml().load(file); LOGGER.info("Salt commands that will pull the failure from stderr: {}", commandsWithStderrFailures); } catch (IOException e) { throw new RuntimeException("Can't load salt error messsages", e); } } public Multimap<String, String> resolveErrorMessages(Multimap<String, Map<String, String>> missingNodesWithReason) { LOGGER.info("Original missing nodes: {}", missingNodesWithReason); Multimap<String, String> missingTargetsWithReplacedReasons = ArrayListMultimap.create(); missingNodesWithReason.entries().forEach(entry -> { String value = resolveMessageIfAvailable(entry.getValue()); missingTargetsWithReplacedReasons.put(entry.getKey(), value); }); LOGGER.info("Missing nodes after replace: {}", missingTargetsWithReplacedReasons); return missingTargetsWithReplacedReasons; } }
hortonworks/cloudbreak
orchestrator-salt/src/main/java/com/sequenceiq/cloudbreak/orchestrator/salt/SaltErrorResolver.java
Java
apache-2.0
2,954
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.dataformat.bindy.format; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Locale; import org.apache.camel.dataformat.bindy.PatternFormat; import org.apache.camel.util.ObjectHelper; public class LocalDatePatternFormat implements PatternFormat<LocalDate> { private String pattern; private Locale locale; public LocalDatePatternFormat() { } public LocalDatePatternFormat(String pattern, Locale locale) { this.pattern = pattern; this.locale = locale; } public String format(LocalDate object) throws Exception { ObjectHelper.notNull(this.pattern, "pattern"); return this.getDateFormat().format(object); } public LocalDate parse(String string) throws Exception { LocalDate date; DateTimeFormatter df = this.getDateFormat(); ObjectHelper.notNull(this.pattern, "pattern"); if (doesStringFitLengthOfPattern(string)) { date = LocalDate.parse(string, df); return date; } else { throw new FormatException("Date provided does not fit the pattern defined"); } } private boolean doesStringFitLengthOfPattern(String string) { return string.length() <= this.pattern.length(); } protected DateTimeFormatter getDateFormat() { DateTimeFormatter result; if (locale != null) { result = DateTimeFormatter.ofPattern(pattern, locale); } else { result = DateTimeFormatter.ofPattern(pattern); } return result; } public String getPattern() { return pattern; } /** * Sets the pattern * * @param pattern the pattern */ public void setPattern(String pattern) { this.pattern = pattern; } }
arnaud-deprez/camel
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/format/LocalDatePatternFormat.java
Java
apache-2.0
2,642
package com.sunjian.android_pickview_lib.view; import java.util.TimerTask; final class SmoothScrollTimerTask extends TimerTask { int realTotalOffset; int realOffset; int offset; final WheelView loopView; SmoothScrollTimerTask(WheelView loopview, int offset) { this.loopView = loopview; this.offset = offset; realTotalOffset = Integer.MAX_VALUE; realOffset = 0; } @Override public final void run() { if (realTotalOffset == Integer.MAX_VALUE) { realTotalOffset = offset; } //把要滚动的范围细分成十小份,按是小份单位来重绘 realOffset = (int) ((float) realTotalOffset * 0.1F); if (realOffset == 0) { if (realTotalOffset < 0) { realOffset = -1; } else { realOffset = 1; } } if (Math.abs(realTotalOffset) <= 1) { loopView.cancelFuture(); loopView.handler.sendEmptyMessage(MessageHandler.WHAT_ITEM_SELECTED); } else { loopView.totalScrollY = loopView.totalScrollY + realOffset; //这里如果不是循环模式,则点击空白位置需要回滚,不然就会出现选到-1 item的 情况 if (!loopView.isLoop) { float itemHeight = loopView.itemHeight; float top = (float) (-loopView.initPosition) * itemHeight; float bottom = (float) (loopView.getItemsCount() - 1 - loopView.initPosition) * itemHeight; if (loopView.totalScrollY <= top||loopView.totalScrollY >= bottom) { loopView.totalScrollY = loopView.totalScrollY - realOffset; loopView.cancelFuture(); loopView.handler.sendEmptyMessage(MessageHandler.WHAT_ITEM_SELECTED); return; } } loopView.handler.sendEmptyMessage(MessageHandler.WHAT_INVALIDATE_LOOP_VIEW); realTotalOffset = realTotalOffset - realOffset; } } }
crazysunj/Android-PickerView
android-pickerdialog/src/main/java/com/sunjian/android_pickview_lib/view/SmoothScrollTimerTask.java
Java
apache-2.0
2,075
/** * Copyright (c) 2008 Pyxis Technologies inc. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU 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, * or see the FSF site: http://www.fsf.org. * * @author oaouattara * @version $Id: $Id */ package com.greenpepper.server.rpc.runner.report; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import com.greenpepper.server.domain.Execution; import com.greenpepper.server.rpc.runner.XmlRpcRemoteRunner; import com.greenpepper.util.ExceptionImposter; import com.greenpepper.util.ExceptionUtils; public class HtmlReport implements Report { private final String name; private Execution execution; private Throwable exception; /** * <p>newInstance.</p> * * @param name a {@link java.lang.String} object. * @return a {@link com.greenpepper.server.rpc.runner.report.HtmlReport} object. */ public static HtmlReport newInstance(String name) { return new HtmlReport(name); } /** * <p>Constructor for HtmlReport.</p> * * @param name a {@link java.lang.String} object. */ public HtmlReport(String name) { this.name = name; } /** * <p>Getter for the field <code>name</code>.</p> * * @return a {@link java.lang.String} object. */ public String getName() { return name; } /** * <p>getType.</p> * * @return a {@link java.lang.String} object. */ public String getType() { return "html"; } /** {@inheritDoc} */ public void printTo(Writer writer) throws IOException { if (exception != null) { writer.write(ExceptionUtils.stackTrace(exception, "\n")); writer.flush(); return; } if (execution != null) { writer.write(toHtml(execution, true)); writer.flush(); } } /** {@inheritDoc} */ public void renderException(Throwable t) { this.exception = t; } /** {@inheritDoc} */ public void generate(Execution execution) { this.execution = execution; } private String toHtml(Execution execution, boolean includeStyle) throws IOException { StringBuilder html = new StringBuilder(); String results = execution.getResults(); if (includeStyle) { html.append("<html>\n") .append(" <head>\n") .append(" <title>").append(getName()).append("</title>\n") .append("<style>\n") .append(getStyleContent()) .append("\n</style>\n") .append("</head>\n") .append("<body>\n") .append("<div id=\"Content\" style=\"text-align:left; padding: 5px;\">") .append(results.replace("<html>", "").replace("</html>", "")) .append("</div>\n") .append("</body>\n") .append("</html>"); } else { html.append(results); } return html.toString(); } private String getStyleContent() { try { InputStream is = XmlRpcRemoteRunner.class.getResource("style.css").openStream(); byte[] bytes = new byte[is.available()]; if (is.read(bytes) > 0) { return new String(bytes); } else { throw new Exception("Cannot read style.css resource from jar"); } } catch (Exception ex) { throw ExceptionImposter.imposterize(ex); } } }
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/rpc/runner/report/HtmlReport.java
Java
apache-2.0
3,703
package com.locompas.edd.bl.model.bd.session; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.http.HttpSession; import com.locomaps.edd.bl.model.User; import com.locomaps.edd.bl.model.db.Persistance; import com.locomaps.edd.bl.model.db.PersistanceManager; import com.locomaps.edd.bl.model.db.PersistanceParameter; public class SessionConnection { //implements Persistance{ // public SessionConnection() { // super(); // } // // Boolean activeConnection; // HttpSession sessionScope; // // public HttpSession getSessionScope() { // return sessionScope; // } // // private void setSessionScope(HttpSession sessionScope) { // if (sessionScope == null){ // this.activeConnection = false; // } else { // this.activeConnection = true; // } // // this.sessionScope = sessionScope; // } // // @Override // public HashMap<String, User> listAllUser() { // HashMap<String,User> listeUser = (HashMap<String, User>) sessionScope.getAttribute("listeUser"); // if (listeUser == null) { // listeUser = new HashMap<String,User>(); // } // return listeUser; // } // // @Override // public User getUserByEMail(String email) { // HashMap<String,User> listeUser = listAllUser(); // User userSession = listeUser.get(email); // // return userSession; // } // // @Override // public boolean change(User user) { // HashMap<String,User> listeUser = listAllUser(); // listeUser.put(user.getEmail(),user); // // return true; // } // // @Override // public boolean addUser(User user) { // HashMap<String,User> listeUser = listAllUser(); // // Ajout du nouvel utilisateur dans la session // listeUser.put(user.getEmail(),user); // // return true; // } // // @Override // public boolean initDB(Object chaineDeConnexion) { // boolean retour = false; // // if (chaineDeConnexion instanceof String) { // retour = false; // } else if (chaineDeConnexion instanceof HttpSession) { // this.setSessionScope((HttpSession)chaineDeConnexion); // retour = this.activeConnection; // } // return retour; // } // }
nmalesic/LocoMaps
src/com/locompas/edd/bl/model/bd/session/SessionConnection.java
Java
apache-2.0
2,053
/* * Copyright 2007-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.persistence.jdbc.base.impl; import net.ymate.platform.commons.util.ExpressionUtils; import net.ymate.platform.core.persistence.base.Type; import net.ymate.platform.persistence.jdbc.IDatabaseConnectionHolder; import net.ymate.platform.persistence.jdbc.IDatabaseDataSourceConfig; import net.ymate.platform.persistence.jdbc.base.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 数据库存储过程操作器接口实现 * * @param <T> 元素类型 * @author 刘镇 (suninformation@163.com) on 16/12/8 上午1:04 */ public class DefaultProcedureOperator<T> extends AbstractOperator implements IProcedureOperator<T> { private static final Log LOG = LogFactory.getLog(DefaultProcedureOperator.class); /** * 存储过程OUT参数类型集合 */ private final List<Integer> outParams = new ArrayList<>(); private IOutResultProcessor resultProcessor; private IResultSetHandler<T> resultSetHandler; private final List<List<T>> resultSets = new ArrayList<>(); public DefaultProcedureOperator(String sql, IDatabaseConnectionHolder connectionHolder) { super(sql, connectionHolder); } public DefaultProcedureOperator(String sql, IDatabaseConnectionHolder connectionHolder, IAccessorConfig accessorConfig) { super(sql, connectionHolder, accessorConfig); } @Override public void execute() throws Exception { if (!this.executed) { StopWatch time = new StopWatch(); time.start(); try { doExecute(); // 执行过程未发生异常将标记已执行,避免重复执行 this.executed = true; } finally { time.stop(); this.expenseTime = time.getTime(); // if (LOG.isInfoEnabled()) { IDatabaseDataSourceConfig dataSourceConfig = this.getConnectionHolder().getDataSourceConfig(); if (dataSourceConfig.isShowSql()) { String logStr = ExpressionUtils.bind("[${sql}]${param}[${count}][${time}]") .set("sql", StringUtils.defaultIfBlank(this.sql, "@NULL")) .set("param", serializeParameters()) .set("count", "N/A") .set("time", this.expenseTime + "ms").getResult(); if (dataSourceConfig.isStackTraces()) { StringBuilder stackBuilder = new StringBuilder(logStr); doAppendStackTraces(dataSourceConfig, stackBuilder); LOG.info(stackBuilder.toString()); } else { LOG.info(logStr); } } } } } } @Override public IProcedureOperator<T> execute(IResultSetHandler<T> resultSetHandler) throws Exception { this.resultSetHandler = resultSetHandler; this.execute(); return this; } @Override public IProcedureOperator<T> execute(IOutResultProcessor resultProcessor) throws Exception { this.resultProcessor = resultProcessor; this.execute(); return this; } @Override protected int doExecute() throws Exception { CallableStatement statement = null; AccessorEventContext eventContext = null; boolean hasEx = false; try { IAccessor accessor = new BaseAccessor(this.getAccessorConfig()); statement = accessor.getCallableStatement(this.getConnectionHolder().getConnection(), doBuildCallSql()); doSetParameters(statement); doRegisterOutParams(statement); if (this.getAccessorConfig() != null) { eventContext = new AccessorEventContext(statement, Type.OPT.PROCEDURE); this.getAccessorConfig().beforeStatementExecution(eventContext); } boolean flag = statement.execute(); if (flag) { do { ResultSet resultSet = statement.getResultSet(); if (resultSet != null) { resultSets.add(resultSetHandler.handle(resultSet)); resultSet.close(); } } while (statement.getMoreResults()); } else { int idx = this.getParameters().size() + 1; for (Integer paramType : outParams) { resultProcessor.process(idx, paramType, statement.getObject((idx))); idx++; } } return -1; } catch (Exception ex) { hasEx = true; throw ex; } finally { if (!hasEx && this.getAccessorConfig() != null && eventContext != null) { this.getAccessorConfig().afterStatementExecution(eventContext); } if (statement != null) { statement.close(); } } } /** * 构建存储过程CALL语句(根据不同的数据库, 可由子类重新实现) * * @return 返回CALL语句 */ protected String doBuildCallSql() { List<String> params = new ArrayList<>(); for (int i = 0; i < this.getParameters().size() + this.outParams.size(); i++) { params.add("?"); } this.sql = String.format("{CALL %s%s}", this.getSQL(), params.isEmpty() ? "()" : String.format("(%s)", StringUtils.join(params, ','))); return this.sql; } /** * 注册存储过程输出的参数(从最后一个输入参数后开始, 根据不同的数据库,可由子类重新实现) * * @param statement CallableStatement * @throws SQLException 可能产生的任何异常 */ protected void doRegisterOutParams(CallableStatement statement) throws SQLException { int idx = this.getParameters().size() + 1; for (Integer type : outParams) { statement.registerOutParameter(idx++, type); } } @Override @SuppressWarnings("unchecked") public IProcedureOperator<T> addParameter(SQLParameter parameter) { return (IProcedureOperator<T>) super.addParameter(parameter); } @Override @SuppressWarnings("unchecked") public IProcedureOperator<T> addParameter(Object parameter) { return (IProcedureOperator<T>) super.addParameter(parameter); } @Override public IProcedureOperator<T> addOutParameter(Integer sqlParamType) { this.outParams.add(sqlParamType); return this; } @Override public IProcedureOperator<T> setOutResultProcessor(IOutResultProcessor outResultProcessor) { resultProcessor = outResultProcessor; return this; } @Override public IProcedureOperator<T> setResultSetHandler(IResultSetHandler<T> resultSetHandler) { this.resultSetHandler = resultSetHandler; return this; } @Override public List<List<T>> getResultSets() { return Collections.unmodifiableList(resultSets); } }
suninformation/ymate-platform-v2
ymate-platform-persistence-jdbc/src/main/java/net/ymate/platform/persistence/jdbc/base/impl/DefaultProcedureOperator.java
Java
apache-2.0
8,131
// @flow /* eslint-env node */ /* global Restivus */ // Import Meteor :3 and Mongo :3 import { Meteor } from 'meteor/meteor' // Import fs and path to access the filesystem. And mime to get MIMETypes. import { readdirSync, lstatSync, readFileSync } from 'fs' import { join, sep, basename } from 'path' import { lookup } from 'mime' // Create the Meteor methods. Meteor.methods({ // This method enables the client to get the contents of any folder. getFolderContents (folder: string): Array<{ name: string, type: string }> { // Get folder contents and create initial variables the loop will write to. const folderContents: Array<string> = readdirSync(folder) const folderContentsWithTypes = [] let i // Define the function to get the type of a directory item. const getType = () => { if (lstatSync(`${folder}/${folderContents[i]}`).isDirectory()) { return 'folder' } return 'file' } // Start the loop to push folderContents. for (i = 0; i < folderContents.length; i += 1) { // Push objects to folderContentsWithTypes. folderContentsWithTypes.push({ name: folderContents[i], type: getType() }) } // Return folderContentsWithTypes. return folderContentsWithTypes }, // Pass it some paths and get a combination of those paths. joinPaths (...paths): string { return join(...paths) }, goUpOneDirectory (pathy: string): string { const pathyArray: Array<string> = pathy.split(sep) if (pathyArray[0] === '') { pathyArray[0] = '/' } const newArray = [] for (let x = 0; x < pathyArray.length - 1; x += 1) { newArray.push(pathyArray[x]) } return join(...newArray) } }) // Create a Restivus API. // flow-disable-next-line const Api = new Restivus({ prettyJson: true }) Api.addRoute('/file/:_filePath', { get () { // Get basename. const filename = basename(this.urlParams._filePath) const mimetype = lookup(this.urlParams._filePath) // Set em' headers. this.response.writeHead({ // Filename. 'Content-disposition': `attachment; filename=${filename}`, // Type of file. 'Content-type': mimetype }) // Read the file and write data to response to client. const file = readFileSync(this.urlParams._filePath) this.response.write(file) // this.done() is quite self-explanatory. this.done() } })
ibujs/Area51
server/main.js
JavaScript
apache-2.0
2,481
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/linear_chain_crf_op.h" #include <memory> namespace paddle { namespace operators { class LinearChainCRFOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Emission", "(LoDTensor/Tensor<float>). When a LoDTensor input,A 2-D LoDTensor" " with shape [N x D], where N is the size of the " "mini-batch and D is the total tag number. The unscaled emission " "weight matrix for the linear chain CRF. When a Tensor input," "A Tensor with shape [N x S x D], where N is batch number," "S is max length of sequences, D is the total tag number." "A LoDTensor or Tensor with type float32, float64."); AddInput("Transition", "(Tensor, default Tensor<float>) A 2-D Tensor with shape " "[(D + 2) x D]. The learnable parameter for the linear_chain_crf " "operator. See more details in the operator's comments."); AddInput("Label", "(LoDTensor/Tensor<int64_t>), when a LoDTensor input, " "[N x 1], where N is the total element number in a mini-batch. " "when a Tensor input, [N x S], where N is batch number. " "S is max length of sequences. The ground truth." "A LoDTensor or Tensor with int64."); AddInput("Length", "(Tensor, default Tensor<int64_t>) A Tensor with shape " "[M x 1], where M is the sequence number in a mini-batch." "A Tensor with type int64.") .AsDispensable(); AddOutput( "Alpha", "(Tensor, default Tensor<float>), the same shape with Emission. " "The forward vectors for the entire batch. Denote it as $\alpha$. " "$\alpha$ is a memo table used to calculate the normalization " "factor in CRF. $\alpha[k, v]$ stores the unnormalized " "probabilites of all possible unfinished sequences of tags that end at " "position $k$ with tag $v$. For each $k$, " "$\alpha[k, v]$ is a vector of length $D$ with a component for " "each tag value $v$. This vector is called a forward vecotr and " "will also be used in backward computations.") .AsIntermediate(); AddOutput( "EmissionExps", "(Tensor, default Tensor<float>), the same shape with Emission. " "The exponentials of Input(Emission). This is an intermediate " "computational result in forward computation, and will be reused in " "backward computation." "A LoDTensor or Tensor with type float32, float64.") .AsIntermediate(); AddOutput( "TransitionExps", "(Tensor, default Tensor<float>) A 2-D Tensor with shape " "[(D + 2) x D]. The exponentials of Input(Transition). This is an " "intermediate computational result in forward computation, and " "will be reused in backward computation." "A LoDTensor or Tensor with type float32, float64.") .AsIntermediate(); AddOutput( "LogLikelihood", "(Tensor, default Tensor<float>) The logarithm of the conditional " "likelihood of each training sample in a mini-batch. This is a 2-D " "tensor with shape [S x 1], where S is the sequence number in a " "mini-batch. Note: S is equal to the sequence number in a mini-batch. " "A Tensor with type float32, float64."); AddComment(R"DOC( Conditional Random Field defines an undirected probabilistic graph with nodes denoting random variables and edges denoting dependencies between these variables. CRF learns the conditional probability $P(Y|X)$, where $X = (x_1, x_2, ... , x_n)$ are structured inputs and $Y = (y_1, y_2, ... , y_n)$ are labels for the inputs. Linear chain CRF is a special case of CRF that is useful for sequence labeling task. Sequence labeling tasks do not assume a lot of conditional independences among inputs. The only constraint they impose is that the input and output must be linear sequences. Thus, the graph of such a CRF is a simple chain or a line, which results in the linear chain CRF. This operator implements the Forward-Backward algorithm for the linear chain CRF. Please refer to http://www.cs.columbia.edu/~mcollins/fb.pdf and http://cseweb.ucsd.edu/~elkan/250Bwinter2012/loglinearCRFs.pdf for details. Equation: 1. Denote Input(Emission) to this operator as $x$ here. 2. The first D values of Input(Transition) to this operator are for starting weights, denoted as $a$ here. 3. The next D values of Input(Transition) of this operator are for ending weights, denoted as $b$ here. 4. The remaning values of Input(Transition) are for transition weights, denoted as $w$ here. 5. Denote Input(Label) as $s$ here. The probability of a sequence $s$ of length $L$ is defined as: $$P(s) = (1/Z) \exp(a_{s_1} + b_{s_L} + \sum_{l=1}^L x_{s_l} + \sum_{l=2}^L w_{s_{l-1},s_l})$$ where $Z$ is a normalization value so that the sum of $P(s)$ over all possible sequences is 1, and $x$ is the emission feature weight to the linear chain CRF. Finally, the linear chain CRF operator outputs the logarithm of the conditional likelihood of each training sample in a mini-batch. NOTE: 1. The feature function for a CRF is made up of the emission features and the transition features. The emission feature weights are NOT computed in this operator. They MUST be computed first before this operator is called. 2. Because this operator performs global normalization over all possible sequences internally, it expects UNSCALED emission feature weights. Please do not call this op with the emission feature being output of any nonlinear activation. 3. The 2nd dimension of Input(Emission) MUST be equal to the tag number. )DOC"); } }; class LinearChainCRFOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("Emission"), "Input(Emission) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Transition"), "Input(Transition) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Alpha"), "Output(Alpha) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("EmissionExps"), "Output(EmissionExps) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("TransitionExps"), "Output(TransitionExps) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("LogLikelihood"), "Output(LogLikelihood) should be not null."); auto transition_dims = ctx->GetInputDim("Transition"); PADDLE_ENFORCE_EQ(transition_dims.size(), 2, "The Input(Transition) should be a 2-D tensor."); bool check = true; if ((!ctx->IsRuntime()) && (transition_dims[0] <= 0 || transition_dims[1] <= 0)) { check = false; } if (check) { PADDLE_ENFORCE_EQ( transition_dims[0] - 2, transition_dims[1], "An invalid dimension for the Input(Transition), which should " "be a 2-D tensor with shape [(D + 2) x D]."); } auto emission_dims = ctx->GetInputDim("Emission"); PADDLE_ENFORCE_NE(emission_dims[0], 0, "An empty mini-batch is not allowed."); if (ctx->HasInput("Length")) { PADDLE_ENFORCE_EQ(emission_dims.size(), 3, "The Input(Emission) should be a 3-D tensor."); auto label_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ( (label_dims.size() == 3UL && label_dims[2] == 1) || (label_dims.size() == 2UL), true, "The Input(Label) should be a 3-D tensor with last " "dimension fixed to 1 or a 2-D tensor in padding mode."); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ(emission_dims[0], label_dims[0], "The batch size of Input(Emission) and Input(Label) " "should be the same."); PADDLE_ENFORCE_EQ(emission_dims[1], label_dims[1], "The max length of Input(Emission) and Input(Label) " "should be the same."); } } else { PADDLE_ENFORCE_EQ(emission_dims.size(), 2, "The Input(Emission) should be a 2-D tensor."); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ(emission_dims[1], transition_dims[1], "The 2nd dimension of the Input(Emission) and the " "Input(Transition) " "should be equal to the tag number."); } auto label_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ(label_dims.size(), 2, "The Input(Label) should be a 2-D tensor with the 2nd " "dimensions fixed to 1."); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ( emission_dims[0], label_dims[0], "The height of Input(Emission) and the height of Input(Label) " "should be the same."); } } ctx->SetOutputDim("Alpha", emission_dims); ctx->SetOutputDim("EmissionExps", emission_dims); ctx->SetOutputDim("TransitionExps", transition_dims); // TODO(caoying) This is tricky. The 1st dimension of Output(LogLikelihood) // is the sequence number in a mini-batch. The dimension set here should be // resized to its correct size in the function Compute. Fix this once we can // get LoD information in the InferShape interface. ctx->SetOutputDim("LogLikelihood", {emission_dims[0], 1}); } protected: // Explicitly set that the data type of computation kernel of linear_chain_crf // is determined by its input "Emission". framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "Emission"), platform::CPUPlace()); } }; class LinearChainCRFGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("EmissionExps"), "Input(EmissionExps) should be not null."); PADDLE_ENFORCE(ctx->HasInput("TransitionExps"), "Input(TransitionExps) should be not null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("LogLikelihood")), "Input(LogLikelihood@GRAD) shoudl be not null."); auto transition_exps_dims = ctx->GetInputDim("TransitionExps"); auto emission_exps_dims = ctx->GetInputDim("EmissionExps"); if (ctx->HasOutput(framework::GradVarName("Emission"))) { ctx->SetOutputDim(framework::GradVarName("Emission"), emission_exps_dims); if (ctx->HasInput("Length") == false) { ctx->ShareLoD("Emission", framework::GradVarName("Emission")); } } if (ctx->HasOutput(framework::GradVarName("Transition"))) { ctx->SetOutputDim(framework::GradVarName("Transition"), transition_exps_dims); ctx->ShareLoD("Transition", framework::GradVarName("Transition")); } } protected: // Explicitly set that the data type of output of the linear_chain_crf_grad // operator is determined by its input: gradients of LogLikelihood. framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("LogLikelihood")), platform::CPUPlace()); } }; class LinearChainCRFGradDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("linear_chain_crf_grad"); op->SetAttrMap(Attrs()); op->SetInput("Emission", Input("Emission")); op->SetInput("Transition", Input("Transition")); op->SetInput("Label", Input("Label")); op->SetInput("Alpha", Output("Alpha")); op->SetInput("EmissionExps", Output("EmissionExps")); op->SetInput("TransitionExps", Output("TransitionExps")); if (ForwardOp().Inputs().count("Length") > 0) { op->SetInput("Length", Input("Length")); } op->SetInput(framework::GradVarName("LogLikelihood"), OutputGrad("LogLikelihood")); op->SetOutput(framework::GradVarName("Emission"), InputGrad("Emission")); op->SetOutput(framework::GradVarName("Transition"), InputGrad("Transition")); return op; } }; DECLARE_NO_NEED_BUFFER_VARS_INFERENCE( LinearChainCRFGradNoNeedBufferVarsInference, "Transition", "Emission"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(linear_chain_crf, ops::LinearChainCRFOp, ops::LinearChainCRFOpMaker, ops::LinearChainCRFGradDescMaker); REGISTER_OPERATOR(linear_chain_crf_grad, ops::LinearChainCRFGradOp, ops::LinearChainCRFGradNoNeedBufferVarsInference); REGISTER_OP_CPU_KERNEL( linear_chain_crf, ops::LinearChainCRFOpKernel<paddle::platform::CPUDeviceContext, float>, ops::LinearChainCRFOpKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_CPU_KERNEL( linear_chain_crf_grad, ops::LinearChainCRFGradOpKernel<paddle::platform::CPUDeviceContext, float>, ops::LinearChainCRFGradOpKernel<paddle::platform::CPUDeviceContext, double>);
chengduoZH/Paddle
paddle/fluid/operators/linear_chain_crf_op.cc
C++
apache-2.0
14,511
/** */ package CIM15.IEC61968.AssetModels; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Conductor Usage Kind</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see CIM15.IEC61968.AssetModels.AssetModelsPackage#getConductorUsageKind() * @generated */ public enum ConductorUsageKind implements Enumerator { /** * The '<em><b>Secondary</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SECONDARY_VALUE * @generated * @ordered */ SECONDARY(0, "secondary", "secondary"), /** * The '<em><b>Other</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OTHER_VALUE * @generated * @ordered */ OTHER(1, "other", "other"), /** * The '<em><b>Distribution</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DISTRIBUTION_VALUE * @generated * @ordered */ DISTRIBUTION(2, "distribution", "distribution"), /** * The '<em><b>Transmission</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #TRANSMISSION_VALUE * @generated * @ordered */ TRANSMISSION(3, "transmission", "transmission"); /** * The '<em><b>Secondary</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Secondary</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SECONDARY * @generated * @ordered */ public static final int SECONDARY_VALUE = 0; /** * The '<em><b>Other</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Other</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OTHER * @generated * @ordered */ public static final int OTHER_VALUE = 1; /** * The '<em><b>Distribution</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Distribution</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DISTRIBUTION * @generated * @ordered */ public static final int DISTRIBUTION_VALUE = 2; /** * The '<em><b>Transmission</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Transmission</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #TRANSMISSION * @generated * @ordered */ public static final int TRANSMISSION_VALUE = 3; /** * An array of all the '<em><b>Conductor Usage Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ConductorUsageKind[] VALUES_ARRAY = new ConductorUsageKind[] { SECONDARY, OTHER, DISTRIBUTION, TRANSMISSION, }; /** * A public read-only list of all the '<em><b>Conductor Usage Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<ConductorUsageKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Conductor Usage Kind</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ConductorUsageKind get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ConductorUsageKind result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Conductor Usage Kind</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ConductorUsageKind getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ConductorUsageKind result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Conductor Usage Kind</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ConductorUsageKind get(int value) { switch (value) { case SECONDARY_VALUE: return SECONDARY; case OTHER_VALUE: return OTHER; case DISTRIBUTION_VALUE: return DISTRIBUTION; case TRANSMISSION_VALUE: return TRANSMISSION; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ConductorUsageKind(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //ConductorUsageKind
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61968/AssetModels/ConductorUsageKind.java
Java
apache-2.0
5,925
/* * Copyright 2015 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.client.http; import java.net.URI; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; /** * A container for information to send in an HTTP request. This is a simpler version of {@link FullHttpRequest} * which only uses a byte array to avoid callers having to worry about memory management. */ public class SimpleHttpRequest { private final URI uri; private final HttpMethod method; private final HttpHeaders headers; private final byte[] content; SimpleHttpRequest(URI uri, HttpMethod method, HttpHeaders headers, byte[] content) { this.uri = uri; this.method = method; this.headers = new ImmutableHttpHeaders(headers); this.content = content; } /** * Returns this request's URI. */ public URI uri() { return uri; } /** * Returns this request's HTTP method. */ public HttpMethod method() { return method; } /** * Returns this request's HTTP headers. */ public HttpHeaders headers() { return headers; } /** * Returns the length of this requests's content. */ public int contentLength() { return content.length; } /** * Reads this request's content into the destination buffer. */ public void readContent(byte[] dst, int offset, int length) { System.arraycopy(content, 0, dst, offset, length); } byte[] content() { return content; } @Override public String toString() { return toString(uri, method, headers, content); } static String toString(URI uri, HttpMethod method, HttpHeaders headers, byte[] content) { StringBuilder buf = new StringBuilder(); buf.append('('); buf.append("uri: ").append(uri); buf.append(", method: ").append(method); buf.append(", headers: ").append(headers); buf.append(", content: "); if (content.length > 0) { buf.append("<length: ").append(content.length).append('>'); } else { buf.append("<none>"); } buf.append(')'); return buf.toString(); } }
brant-hwang/armeria
src/main/java/com/linecorp/armeria/client/http/SimpleHttpRequest.java
Java
apache-2.0
2,958
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.internal.gosu.parser; import gw.internal.ext.org.objectweb.asm.Opcodes; import gw.internal.gosu.parser.java.classinfo.JavaSourceDefaultValue; import gw.lang.Deprecated; import gw.lang.GosuShop; import gw.lang.PublishedName; import gw.lang.javadoc.IClassDocNode; import gw.lang.javadoc.IDocRef; import gw.lang.javadoc.IExceptionNode; import gw.lang.javadoc.IMethodNode; import gw.lang.javadoc.IParamNode; import gw.lang.parser.GosuParserTypes; import gw.lang.parser.TypeVarToTypeMap; import gw.lang.reflect.IAnnotationInfo; import gw.lang.reflect.IExceptionInfo; import gw.lang.reflect.IFeatureInfo; import gw.lang.reflect.IMethodCallHandler; import gw.lang.reflect.IParameterInfo; import gw.lang.reflect.IScriptabilityModifier; import gw.lang.reflect.IType; import gw.lang.reflect.SimpleParameterInfo; import gw.lang.reflect.TypeInfoUtil; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.gs.IGenericTypeVariable; import gw.lang.reflect.gs.IGosuClass; import gw.lang.reflect.java.ClassInfoUtil; import gw.lang.reflect.java.IJavaAnnotatedElement; import gw.lang.reflect.java.IJavaClassGenericArrayType; import gw.lang.reflect.java.IJavaClassInfo; import gw.lang.reflect.java.IJavaClassMethod; import gw.lang.reflect.java.IJavaClassParameterizedType; import gw.lang.reflect.java.IJavaClassType; import gw.lang.reflect.java.IJavaClassTypeVariable; import gw.lang.reflect.java.IJavaClassWildcardType; import gw.lang.reflect.java.IJavaMethodDescriptor; import gw.lang.reflect.java.IJavaMethodInfo; import gw.lang.reflect.java.JavaExceptionInfo; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; /** */ public class JavaMethodInfo extends JavaBaseFeatureInfo implements IJavaMethodInfo { private static final int UNINITED = 0; private static final int TRUE_ENC = 1; private static final int FALSE_ENC = 2; private IJavaMethodDescriptor _md; private boolean _forceHidden; private IParameterInfo[] _paramsWithoutTypeVars; private IParameterInfo[] _paramsWithTypeVars; private IType _retTypeWithTypeVars; private IType _retTypeWithoutTypeVars; private IMethodCallHandler _callHandler; private IGenericTypeVariable[] _typeVars; private int _staticCache = UNINITED; private List<IExceptionInfo> _exceptions; private IDocRef<IMethodNode> _methodDocs = new IDocRef<IMethodNode>() { @Override public IMethodNode get() { if (getContainer() instanceof JavaTypeInfo) { IClassDocNode classDocs = ((JavaTypeInfo) getContainer()).getDocNode().get(); return classDocs == null ? null : classDocs.getMethod(_md); } else { return null; } } }; private String _name; private String _signature; /** * @param container Typically this will be the containing ITypeInfo * @param md The method descriptor (from BeanInfo) */ public JavaMethodInfo(IFeatureInfo container, IJavaMethodDescriptor md, boolean forceHidden) { super(container); _md = md; _forceHidden = forceHidden; _name = _md.getName(); if (_md.getMethod().isAnnotationPresent( PublishedName.class)) { _name = (String) _md.getMethod().getAnnotation( PublishedName.class).getFieldValue("value"); } _signature = makeSignature(); } @Override public IParameterInfo[] getGenericParameters() { return getParameters( true ); } @Override public IParameterInfo[] getParameters() { IType ownerType = getOwnersType(); return getParameters( !ownerType.isGenericType() || ownerType.isParameterizedType() ); } private IParameterInfo[] getParameters( boolean bKeepTypeVars ) { if( bKeepTypeVars ) { if( _paramsWithTypeVars == null ) { _paramsWithTypeVars = convertParameterDescriptors( bKeepTypeVars ); } return _paramsWithTypeVars; } else { if( _paramsWithoutTypeVars == null ) { _paramsWithoutTypeVars = convertParameterDescriptors( bKeepTypeVars ); } return _paramsWithoutTypeVars; } } @Override public IType getGenericReturnType() { return getReturnType( true ); } @Override public IType getReturnType() { IType ownerType = getOwnersType(); return getReturnType( !ownerType.isGenericType() || ownerType.isParameterizedType() ); } private IType getReturnType( boolean bKeepTypeVars ) { return bKeepTypeVars ? getReturnTypeWithTypeVars() : getReturnTypeWithoutTypeVars(); } private IType getReturnTypeWithoutTypeVars() { if( _retTypeWithoutTypeVars != null ) { return _retTypeWithoutTypeVars; } IType declaringClass = _md.getMethod().getEnclosingClass().getJavaType(); TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( getOwnersType(), declaringClass, false ); actualParamByVarName = addEnclosingTypeParams( declaringClass, actualParamByVarName ); for( IGenericTypeVariable tv : getTypeVariables() ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), tv.getBoundingType() ); } IType retType = ClassInfoUtil.getActualReturnType( _md.getMethod().getGenericReturnType(), actualParamByVarName, false ); if( TypeSystem.isDeleted( retType ) ) { return null; } if( retType.isGenericType() && !retType.isParameterizedType() ) { retType = TypeLord.getDefaultParameterizedType( retType ); } retType = ClassInfoUtil.getPublishedType(retType, _md.getMethod().getEnclosingClass()); _retTypeWithoutTypeVars = retType; return retType; } private IType getReturnTypeWithTypeVars() { if( _retTypeWithTypeVars != null ) { return _retTypeWithTypeVars; } IType declaringClass = _md.getMethod().getEnclosingClass().getJavaType(); TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( getOwnersType(), declaringClass, true ); actualParamByVarName = addEnclosingTypeParams( declaringClass, actualParamByVarName ); for( IGenericTypeVariable tv : getTypeVariables() ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), tv.getTypeVariableDefinition() != null ? tv.getTypeVariableDefinition().getType() : new TypeVariableType( getOwnersType(), tv ) ); } IType retType = ClassInfoUtil.getActualReturnType( _md.getMethod().getGenericReturnType(), actualParamByVarName, true ); if( TypeSystem.isDeleted( retType ) ) { return null; } if( retType.isGenericType() && !retType.isParameterizedType() ) { retType = TypeLord.getDefaultParameterizedType( retType ); } retType = ClassInfoUtil.getPublishedType(retType, _md.getMethod().getEnclosingClass()); _retTypeWithTypeVars = retType; return retType; } public static TypeVarToTypeMap addEnclosingTypeParams( IType declaringClass, TypeVarToTypeMap actualParamByVarName ) { while( declaringClass.getEnclosingType() != null && !Modifier.isStatic( declaringClass.getModifiers() ) ) { declaringClass = declaringClass.getEnclosingType(); IGenericTypeVariable[] typeVariables = declaringClass.getGenericTypeVariables(); if( typeVariables != null ) { for( IGenericTypeVariable typeVariable : typeVariables ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } actualParamByVarName.put( typeVariable.getTypeVariableDefinition().getType(), typeVariable.getTypeVariableDefinition() != null ? typeVariable.getTypeVariableDefinition().getType() : new TypeVariableType( declaringClass, typeVariable ) ); } } } return actualParamByVarName; } @Override public List<IAnnotationInfo> getDeclaredAnnotations() { List<IAnnotationInfo> annotations = super.getDeclaredAnnotations(); if (getMethodDocs().get() != null && getMethodDocs().get().isDeprecated()) { annotations.add(GosuShop.getAnnotationInfoFactory().createJavaAnnotation(makeDeprecated(getMethodDocs().get().getDeprecated()), this)); } return annotations; } @Override public IGenericTypeVariable[] getTypeVariables() { if( _typeVars == null ) { _typeVars = _md.getMethod().getTypeVariables(this); } return _typeVars; } @Override public IType getParameterizedReturnType( IType... typeParams ) { TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( getOwnersType(), _md.getMethod().getEnclosingClass().getJavaType(), true ); int i = 0; for( IGenericTypeVariable tv : getTypeVariables() ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } actualParamByVarName.putByString( tv.getName(), typeParams[i++] ); } return _md.getMethod().getGenericReturnType().getActualType(actualParamByVarName, true); } public IType[] getParameterizedParameterTypes( IType... typeParams ) { return getParameterizedParameterTypes2( null, typeParams ); } public IType[] getParameterizedParameterTypes2( IGosuClass ownersType, IType... typeParams ) { IType ot = ownersType == null ? getOwnersType() : ownersType; TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( ot, _md.getMethod().getEnclosingClass().getJavaType(), true ); int i = 0; for( IGenericTypeVariable tv : getTypeVariables() ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } actualParamByVarName.putByString( tv.getName(), typeParams[i++] ); } return ClassInfoUtil.getActualTypes(_md.getMethod().getGenericParameterTypes(), actualParamByVarName, true); } // <T extends CharSequence> T[] foo( ArrayList<? extends T>[] s ) { return null; } @Override public TypeVarToTypeMap inferTypeParametersFromArgumentTypes( IType... argTypes ) { return inferTypeParametersFromArgumentTypes2( null, argTypes ); } @Override public TypeVarToTypeMap inferTypeParametersFromArgumentTypes2( IGosuClass ownersType, IType... argTypes ) { IJavaClassType[] genParamTypes = _md.getMethod().getGenericParameterTypes(); IType ot = ownersType == null ? getOwnersType() : ownersType; TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( ot, _md.getMethod().getEnclosingClass().getJavaType(), true ); IGenericTypeVariable[] typeVars = getTypeVariables(); for( IGenericTypeVariable tv : typeVars ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } if( !TypeLord.isRecursiveType( tv.getTypeVariableDefinition().getType(), tv.getBoundingType() ) ) { actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), tv.getBoundingType() ); } else { actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), TypeLord.getPureGenericType( tv.getBoundingType() ) ); } } TypeVarToTypeMap map = new TypeVarToTypeMap(); for( int i = 0; i < argTypes.length; i++ ) { if( genParamTypes.length > i ) { IType argType = argTypes[i]; IJavaClassType genParamType = genParamTypes[i]; inferTypeVariableTypesFromGenParamTypeAndConcreteType( genParamType, argType, map ); ensureInferredTypeAssignableToBoundingType( actualParamByVarName, map ); } } return map; } private void ensureInferredTypeAssignableToBoundingType( TypeVarToTypeMap actualParamByVarName, TypeVarToTypeMap map ) { for( Object s : map.keySet() ) { IType inferredType = map.getRaw( s ); IType boundingType = actualParamByVarName.getRaw( s ); if( !boundingType.isAssignableFrom( inferredType ) ) { map.putRaw( s, boundingType ); } } } private void inferTypeVariableTypesFromGenParamTypeAndConcreteType( IJavaClassType genParamType, IType argType, TypeVarToTypeMap map ) { if( argType == GosuParserTypes.NULL_TYPE() ) { return; } if( genParamType instanceof IJavaClassGenericArrayType) { //## todo: DON'T allow a null component type here; we do it now as a hack that enables gosu arrays to be compatible with java arrays //## todo: same as TypeLord.inferTypeVariableTypesFromGenParamTypeAndConcreteType() if( argType.getComponentType() == null || !argType.getComponentType().isPrimitive() ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( ((IJavaClassGenericArrayType)genParamType).getGenericComponentType(), argType.getComponentType(), map ); } } else if( genParamType instanceof IJavaClassParameterizedType) { IJavaClassParameterizedType parameterizedType = (IJavaClassParameterizedType)genParamType; IType argTypeInTermsOfParamType = TypeLord.findParameterizedType( argType, genParamType.getActualType( TypeVarToTypeMap.EMPTY_MAP ) ); if( argTypeInTermsOfParamType == null ) { return; } IType[] concreteTypeParams = argTypeInTermsOfParamType.getTypeParameters(); if( concreteTypeParams != null && concreteTypeParams.length > 0 ) { int i = 0; for( IJavaClassType typeArg : parameterizedType.getActualTypeArguments() ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( typeArg, concreteTypeParams[i++], map ); } } } else if( genParamType instanceof IJavaClassTypeVariable) { String strTypeVarName = genParamType.getName(); IType type = map.getByString( strTypeVarName ); if( type == null || type instanceof TypeVariableType ) { // Infer the type map.putByString( strTypeVarName, argType ); } } else if( genParamType instanceof IJavaClassWildcardType) { IJavaClassWildcardType wildcardType = (IJavaClassWildcardType)genParamType; inferTypeVariableTypesFromGenParamTypeAndConcreteType( wildcardType.getUpperBound(), argType, map ); } } @Override public IMethodCallHandler getCallHandler() { if( _callHandler != null ) { return _callHandler; } IJavaClassMethod method = this._md.getMethod(); if (!(method instanceof MethodJavaClassMethod)) { return null; } return _callHandler = new MethodCallAdapter( ((MethodJavaClassMethod)method).getJavaMethod() ); } @Override public String getReturnDescription() { return getMethodDocs().get() == null ? "" : getMethodDocs().get().getReturnDescription(); } @Override public List<IExceptionInfo> getExceptions() { if( _exceptions == null ) { IJavaClassMethod method = _md.getMethod(); IJavaClassInfo[] classes = method.getExceptionTypes(); _exceptions = new ArrayList<IExceptionInfo>(); for (int i = 0; i < classes.length; i++) { final IJavaClassInfo exceptionClass = classes[i]; _exceptions.add(new JavaExceptionInfo(this, exceptionClass, new IDocRef<IExceptionNode>() { @Override public IExceptionNode get() { return getMethodDocs().get() == null ? null : getMethodDocs().get().getException(exceptionClass); } })); } } // merge in methods exceptions with the annotations return _exceptions; } @Override public String getName() { return _signature; } private String makeSignature() { String name = getDisplayName(); name += TypeInfoUtil.getTypeVarList( this, true ); name += "("; IParameterInfo[] parameterInfos = getGenericParameters(); if (parameterInfos.length > 0) { name += " "; for (int i = 0; i < parameterInfos.length; i++) { IParameterInfo iParameterInfo = parameterInfos[i]; if (i != 0) { name += ", "; } name += iParameterInfo.getFeatureType().getName(); } name += " "; } name += ")"; return name; } @Override public String getDisplayName() { return _name; } @Override public String getShortDescription() { return getMethodDocs().get() == null ? null : getMethodDocs().get().getDescription(); } @Override public String getDescription() { return getMethodDocs().get() == null ? null : getMethodDocs().get().getDescription(); } @Override public boolean isHidden() { return _forceHidden || super.isHidden(); } @Override protected boolean isDefaultEnumFeature() { if( getOwnersType().isEnum() ) { String name = getName(); return isStatic() && (name.equals( "values()" ) || name.equals( "valueOf( java.lang.String )" )); } else { return false; } } @Override public boolean isVisible(IScriptabilityModifier constraint) { return !_forceHidden && super.isVisible(constraint); } @Override public boolean isStatic() { if( _staticCache == UNINITED ) { synchronized( this ) { if( _staticCache == UNINITED ) { if( Modifier.isStatic( _md.getMethod().getModifiers() ) ) { _staticCache = TRUE_ENC; } else { _staticCache = FALSE_ENC; } } } } return _staticCache == TRUE_ENC; } @Override public boolean isPrivate() { return Modifier.isPrivate( _md.getMethod().getModifiers() ); } @Override public boolean isInternal() { return !isPrivate() && !isPublic() && !isProtected(); } @Override public boolean isProtected() { return Modifier.isProtected( _md.getMethod().getModifiers() ); } @Override public boolean isPublic() { return Modifier.isPublic( _md.getMethod().getModifiers() ); } @Override public boolean isAbstract() { return Modifier.isAbstract( _md.getMethod().getModifiers() ); } @Override public boolean isFinal() { return Modifier.isFinal( _md.getMethod().getModifiers() ); } @Override public boolean isDeprecated() { return isJavadocDeprecated() || super.isDeprecated() || getMethod().isAnnotationPresent( Deprecated.class ) || getMethod().isAnnotationPresent( java.lang.Deprecated.class ); } private boolean isJavadocDeprecated() { return (getModifiers() & Opcodes.ACC_DEPRECATED) > 0; } @Override public String getDeprecatedReason() { String deprecated = super.getDeprecatedReason(); if (isDeprecated() && deprecated == null) { IAnnotationInfo gwDeprecated = getMethod().getAnnotation( Deprecated.class ); return gwDeprecated == null ? null : (String) gwDeprecated.getFieldValue( "value" ); } return deprecated; } @Override public boolean hasAnnotationDefault() { Object defaultValue = getMethod().getDefaultValue(); return defaultValue != null && defaultValue != JavaSourceDefaultValue.NULL; } @Override public Object getAnnotationDefault() { return getMethod().getDefaultValue(); } private IParameterInfo[] convertParameterDescriptors( boolean bKeepTypeVars ) { IType declaringClass = _md.getMethod().getEnclosingClass().getJavaType(); TypeVarToTypeMap actualParamByVarName = TypeLord.mapTypeByVarName( getOwnersType(), declaringClass, bKeepTypeVars ); actualParamByVarName = addEnclosingTypeParams( declaringClass, actualParamByVarName ); for( IGenericTypeVariable tv : getTypeVariables() ) { if( actualParamByVarName.isEmpty() ) { actualParamByVarName = new TypeVarToTypeMap(); } if( bKeepTypeVars ) { actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), tv.getTypeVariableDefinition() != null ? tv.getTypeVariableDefinition().getType() : new TypeVariableType( getOwnersType(), tv ) ); } else { actualParamByVarName.put( tv.getTypeVariableDefinition().getType(), tv.getBoundingType() ); } } IJavaClassType[] paramTypes = _md.getMethod().getGenericParameterTypes(); return convertGenericParameterTypes( this, actualParamByVarName, paramTypes, bKeepTypeVars, _md.getMethod().getEnclosingClass()); } static IParameterInfo[] convertGenericParameterTypes( IFeatureInfo container, TypeVarToTypeMap actualParamByVarName, IJavaClassType[] paramTypes, boolean bKeepTypeVars, IJavaClassInfo declaringClass ) { if( paramTypes == null ) { return null; } IParameterInfo[] pi = new IParameterInfo[paramTypes.length]; for( int i = 0; i < paramTypes.length; i++ ) { IType parameterType = null; if(paramTypes[i] != null) { parameterType = paramTypes[i].getActualType( actualParamByVarName, bKeepTypeVars ); } if (parameterType == null) { parameterType = TypeSystem.getErrorType(); } parameterType = ClassInfoUtil.getPublishedType(parameterType, declaringClass); pi[i] = new SimpleParameterInfo( container, parameterType, i ); } return pi; } @Override public IJavaClassMethod getMethod() { return _md.getMethod(); } @Override public String toString() { return getName(); } @Override protected IJavaAnnotatedElement getAnnotatedElement() { return _md.getMethod(); } @Override protected boolean isVisibleViaFeatureDescriptor(IScriptabilityModifier constraint) { return _md.isVisibleViaFeatureDescriptor(constraint); } @Override protected boolean isHiddenViaFeatureDescriptor() { return _md.isHiddenViaFeatureDescriptor(); } @Override public IDocRef<IParamNode> getDocsForParam(final int paramIndex) { return new IDocRef<IParamNode>() { @Override public IParamNode get() { if (getMethodDocs().get() != null) { List<? extends IParamNode> list = getMethodDocs().get().getParams(); if (list.size() > paramIndex) { return list.get(paramIndex); } } return null; } }; } @Override public IDocRef<IMethodNode> getMethodDocs() { return _methodDocs; } @Override public Method getRawMethod() { return ((MethodJavaClassMethod)_md.getMethod()).getJavaMethod(); } @Override public int getModifiers() { return _md.getMethod().getModifiers(); } }
dumitru-petrusca/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/JavaMethodInfo.java
Java
apache-2.0
23,088
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli- -cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ package me.adaptive.arp.api; import java.io.Serializable; /** Structure representing the personal info data elements of a contact. @author Francisco Javier Martin Bueno @since v2.0 @version 1.0 */ public class ContactPersonalInfo extends APIBean implements Serializable { /** Java serialization support. @since 2.2.13 */ private static final long serialVersionUID = 100391943L; /** The title of the Contact */ private ContactPersonalInfoTitle title; /** The last name of the Contact */ private String lastName; /** The middle name of the Contact if it proceeds */ private String middleName; /** The name of the Contact */ private String name; /** Default constructor @since v2.0 */ public ContactPersonalInfo() { } /** The Constructor used by the implementation @param name of the Contact @param middleName of the Contact @param lastName of the Contact @param title of the Contact @since v2.0 */ public ContactPersonalInfo(String name, String middleName, String lastName, ContactPersonalInfoTitle title) { super(); this.name = name; this.middleName = middleName; this.lastName = lastName; this.title = title; } /** Returns the title of the Contact @return Title @since v2.0 */ public ContactPersonalInfoTitle getTitle() { return this.title; } /** Set the Title of the Contact @param title of the Contact @since v2.0 */ public void setTitle(ContactPersonalInfoTitle title) { this.title = title; } /** Returns the last name of the Contact @return lastName @since v2.0 */ public String getLastName() { return this.lastName; } /** Set the last name of the Contact @param lastName of the Contact @since v2.0 */ public void setLastName(String lastName) { this.lastName = lastName; } /** Returns the middle name of the Contact @return middelName @since v2.0 */ public String getMiddleName() { return this.middleName; } /** Set the middle name of the Contact @param middleName of the Contact @since v2.0 */ public void setMiddleName(String middleName) { this.middleName = middleName; } /** Returns the name of the Contact @return name @since v2.0 */ public String getName() { return this.name; } /** Set the name of the Contact @param name of the Contact @since v2.0 */ public void setName(String name) { this.name = name; } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
AdaptiveMe/adaptive-arp-api-lib-java
src/main/java/me/adaptive/arp/api/ContactPersonalInfo.java
Java
apache-2.0
4,402
package com.example.dell.texttwo.ui; import com.example.dell.texttwo.R; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class FragmentBase extends Fragment { protected ListView mListView; protected View mLoadingLayout; protected MainActivity mParent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mParent = (MainActivity) getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_file, container, false); mListView = (ListView) v.findViewById(android.R.id.list); mLoadingLayout = v.findViewById(R.id.loading); return v; } public boolean onBackPressed() { return false; } public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { if (mParent != null) mParent.registerReceiver(receiver, filter); } public void unregisterReceiver(BroadcastReceiver receiver) { if (mParent != null) mParent.unregisterReceiver(receiver); } public void registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer) { if (mParent != null) mParent.getContentResolver().registerContentObserver(uri, notifyForDescendents, observer); } public void unregisterContentObserver(ContentObserver observer) { if (mParent != null) mParent.getContentResolver().unregisterContentObserver(observer); } }
YiNPNG/test
TextTwo/app/src/main/java/com/example/dell/texttwo/ui/FragmentBase.java
Java
apache-2.0
1,735
package br.com.dlp.jazzav.produto; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import br.com.dlp.jazzav.AbstractLogEntityVO; /** * * @author darcio * */ @Entity public class MarcaVO extends AbstractLogEntityVO<Long> { private static final long serialVersionUID = 6715916803586893459L; private String nome; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Override public Long getPK() { return this.pk; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
darciopacifico/omr
modules/JazzAV/core/src/main/java/br/com/dlp/jazzav/produto/MarcaVO.java
Java
apache-2.0
644
require 'test_helper' class JobPostingsTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
sarahmonster/suitor
test/models/job_postings_test.rb
Ruby
apache-2.0
125
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* ONOS GUI -- Widget -- Table Detail Panel Service */ (function () { 'use strict'; // injected refs var $log, $interval, $timeout, fs, wss; // constants // var refreshInterval = 2000; function noop() {} // TODO: describe the input object for the main function // example params to (functionX): // { // ... // } function buildBasePanel(opts) { var popTopF = fs.isF(opts.popTop) || noop, popMidF = fs.isF(opts.popMid) || noop, popBotF = fs.isF(opts.popBot) || noop; $log.debug('options are', opts); // TODO use panel service to create base panel // TODO: create divs, and pass into invocations of popTopF(div), etc. } // more functions // TODO: add ref to PanelService angular.module('onosWidget') .factory('TableDetailService', ['$log', '$interval', '$timeout', 'FnService', 'WebSocketService', function (_$log_, _$interval_, _$timeout_, _fs_, _wss_) { $log = _$log_; $interval = _$interval_; $timeout = _$timeout_; fs = _fs_; wss = _wss_; return { buildBasePanel: buildBasePanel }; }]); }());
sdnwiselab/onos
web/gui/src/main/webapp/app/fw/widget/tableDetail.js
JavaScript
apache-2.0
1,833
package com.dream.plmm.bean; /** * Created by likun on 16/8/19. */ public class HealthyInfoDetailEntity { /** * count : 1754 * description : 平时要注意开窗通风,要多吃“补氧”食物,例如葵花子油、杏仁、奇异果、红薯等,还要多进行一些慢跑等有氧运动,这些都助于身体吸纳氧气 * fcount : 0 * id : 10 * img : /lore/150731/af4811aaf581c7369c4c425d449ab94d.jpg * keywords : 身体 缺氧 症状 心功能不全 内分泌系统 * loreclass : 12 * message : <p> </p> <p> 现在,制氧机已经超越了医疗抢救机器这一概念,成为家庭中一件时髦的健康器材,尤其受到老人的青睐。那么,怎么知道自己身体是否缺氧,又如何为身体补氧呢? </p> <p> 以下这些症状就预示我们身体可能出现了缺氧。神经系统:精神差、打哈欠、整天感觉疲倦、无力、记忆力变差、注意力不能集中、工作能力下降、失眠、痴呆。心血管系统:经常头晕、心慌、胸闷、憋气、血压不正常、面色灰暗、眼睑或肢体水肿。胃肠、内分泌系统:食欲变差、经常便秘、胃胀痛、烦躁、易感冒。肌肉骨骼系统:容易抽筋、腰腿酸痛或关节痛。皮肤黏膜:容易口腔溃烂、咽喉发炎、牙龈出血等。 </p> <p> 如果身体出现一些缺氧的症状该怎么办呢?平时要注意开窗通风,要多吃“补氧”食物,例如葵花子油、杏仁、奇异果、红薯等,还要多进行一些慢跑等有氧运动,这些都助于身体吸纳氧气。 </p> <p> 当身体有明显缺氧症,并经过开窗、食补、运动等方式仍不能缓解症状时,尤其是有明确的慢性缺氧性疾病如慢性阻塞性肺病、心功能不全等,采用家庭吸氧比较好。 </p> <br> * rcount : 0 * status : true * time : 1438305244000 * title : 身体缺氧五大信号又该如何为身体补氧呢? * url : http://www.tngou.net/lore/show/10 */ private int count; private String description; private int fcount; private int id; private String img; private String keywords; private int loreclass; private String message; private int rcount; private boolean status; private long time; private String title; private String url; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFcount() { return fcount; } public void setFcount(int fcount) { this.fcount = fcount; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public int getLoreclass() { return loreclass; } public void setLoreclass(int loreclass) { this.loreclass = loreclass; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getRcount() { return rcount; } public void setRcount(int rcount) { this.rcount = rcount; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
dreamseekerkun/EnjoyLife
app/src/main/java/com/dream/plmm/bean/HealthyInfoDetailEntity.java
Java
apache-2.0
4,203
package uk.ac.ebi.atlas.profiles; import com.google.common.collect.MinMaxPriorityQueue; import uk.ac.ebi.atlas.commons.streams.ObjectInputStream; import uk.ac.ebi.atlas.model.GeneProfilesList; import uk.ac.ebi.atlas.model.Profile; import java.util.Comparator; import java.util.function.Supplier; public class MinMaxProfileRanking<T extends Profile, L extends GeneProfilesList<T>> implements SelectProfiles<T, L> { private final Comparator<T> comparator; private final Supplier<L> newList; public MinMaxProfileRanking(Comparator<T> comparator, Supplier<L> newList) { this.comparator = comparator; this.newList = newList; } @Override public L select(ObjectInputStream<T> profiles, int maxSize) { MinMaxPriorityQueue<T> rankingQueue = maxSize > 0 ? MinMaxPriorityQueue.orderedBy(comparator).maximumSize(maxSize).create() : MinMaxPriorityQueue.orderedBy(comparator).create(); int count = 0; for (T profile : new IterableObjectInputStream<>(profiles)) { rankingQueue.add(profile); count++; } L list = newList.get(); T profile; while ((profile = rankingQueue.poll()) != null) { list.add(profile); } list.setTotalResultCount(count); return list; } }
gxa/atlas
base/src/main/java/uk/ac/ebi/atlas/profiles/MinMaxProfileRanking.java
Java
apache-2.0
1,377
/* * Copyright 2017 - 2019 Roman Borris (pcfreak9000), Paul Hagedorn (Panzer1119) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.omnikryptec.old.util; import de.codemakers.io.file.AdvancedFile; import de.omnikryptec.old.main.OmniKryptecEngine; import de.omnikryptec.old.util.logger.LogLevel; import de.omnikryptec.old.util.logger.Logger; import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.jar.JarFile; /** * @author Panzer1119 */ public class OSUtil { private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final AdvancedFile USER_HOME = AdvancedFile.folderOfPath(System.getProperty("user.home")); private static final String ENGINE_FOLDER_NAME = "." + OmniKryptecEngine.class.getSimpleName() + "_3-1-5"; private static final String PATHSEPARATOR = "/"; public static final OS OPERATING_SYSTEM = detectOS(); public static final AdvancedFile STANDARD_APPDATA_FOLDER = getStandardAppDataEngineFolder(); public static enum OS { WINDOWS("windows"), MAC("macosx"), UNIX("linux"), SOLARIS("solaris"), ERROR(null); private final String name; OS(String name) { this.name = name; } public String getName() { return name; } public String toPathForResource(String nativesPath) { return (nativesPath.startsWith(PATHSEPARATOR) ? "" : PATHSEPARATOR) + nativesPath + (nativesPath.endsWith(PATHSEPARATOR) ? "" : PATHSEPARATOR) + name; } @Override public String toString() { return name; } } public static final OS getOS() { return OPERATING_SYSTEM; } private static final OS detectOS() { if (OS_NAME.contains("win")) { return OS.WINDOWS; } else if (OS_NAME.contains("mac")) { return OS.MAC; } else if (OS_NAME.contains("nix") || OS_NAME.contains("nux") || OS_NAME.contains("aix")) { return OS.UNIX; } else if (OS_NAME.contains("sunos")) { return OS.SOLARIS; } else { return OS.ERROR; } } public static final boolean createStandardFolders() { try { return (STANDARD_APPDATA_FOLDER.createAdvancedFile() && STANDARD_APPDATA_FOLDER.isDirectory()); } catch (Exception ex) { Logger.logErr("Error while creating standard folders: " + ex, ex); return false; } } public static final AdvancedFile getStandardAppDataEngineFolder() { return getAppDataFolder(ENGINE_FOLDER_NAME); } public static final AdvancedFile getAppDataFolder(String folderName) { AdvancedFile file = null; switch (OPERATING_SYSTEM) { case WINDOWS: file = new AdvancedFile(false, USER_HOME, "AppData", "Roaming", folderName); break; case MAC: file = new AdvancedFile(false, USER_HOME, "Library", "Application Support", folderName); // TODO Needs // confirmation! break; case UNIX: file = new AdvancedFile(false, USER_HOME, folderName); break; case SOLARIS: file = new AdvancedFile(false, USER_HOME, folderName); break; case ERROR: break; default: break; } if (file != null) { file.setShouldBeFile(false); } return file; } public static final boolean extractFolderFromJar(AdvancedFile folder, String path) { try { boolean allGood = true; final AdvancedFile jarFile = getJarFile(); if (jarFile.isFile()) { if (path.startsWith("/")) { path = path.substring("/".length()); } final String path_ = path; final JarFile jar = new JarFile(jarFile.toFile()); allGood = jar.stream() .filter((jarEntry) -> !jarEntry.isDirectory() && jarEntry.getName().startsWith(path_)) .allMatch((jarEntry) -> { try { final File file_ = getFileOfPath(folder, jarEntry.getName()).toFile().getAbsoluteFile(); if (!file_.exists()) { final InputStream inputStream = jar.getInputStream(jarEntry); Files.copy(inputStream, file_.toPath()); inputStream.close(); } return true; } catch (Exception ex) { Logger.logErr("Error while extracting file from jar: " + ex, ex); return false; } }); jar.close(); } else { final URL url = OSUtil.class.getResource(path); if (url != null) { final AdvancedFile apps = AdvancedFile.folderOfPath(url.toURI().getPath()); for (AdvancedFile app : apps.listAdvancedFiles()) { try { Files.copy(app.toFile().toPath(), new AdvancedFile(false, folder, app.getName()).toFile().toPath(), StandardCopyOption.COPY_ATTRIBUTES); } catch (java.nio.file.FileAlreadyExistsException faex) { } catch (Exception ex) { allGood = false; Logger.log("Error while extracting file from folder from jar: " + ex, LogLevel.WARNING); } } } else { allGood = false; } } return allGood; } catch (Exception ex) { Logger.logErr("Error while extracting folder from jar: " + ex, ex); return false; } } public static final AdvancedFile getFileOfPath(AdvancedFile folder, String path) { String name = path; if (path.contains(PATHSEPARATOR)) { name = name.substring(name.lastIndexOf(PATHSEPARATOR) + PATHSEPARATOR.length()); } return new AdvancedFile(false, folder, name); } public static final AdvancedFile getJarFile() { return new AdvancedFile(false, OSUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath()); } public static final boolean isJarFile() { return getJarFile().isFile(); } public static final boolean isIDE() { return !isJarFile(); } }
OmniKryptec/OmniKryptec-Engine
src/main/java/de/omnikryptec/old/util/OSUtil.java
Java
apache-2.0
6,117
using System; namespace FluentCassandra.Connections { public class CassandraConnectionException : CassandraException { public CassandraConnectionException(string message) : base(message) { } public CassandraConnectionException(string message, Exception innerException) : base(message, innerException) { } } }
fluentcassandra/fluentcassandra
src/Connections/CassandraConnectionException.cs
C#
apache-2.0
327
// Copyright (C) 2004, 2006 International Business Machines and others. // All Rights Reserved. // This code is published under the Common Public License. // // $Id: IpRestoMinC_1Nrm.cpp 759 2006-07-07 03:07:08Z andreasw $ // // Authors: Carl Laird, Andreas Waechter IBM 2004-08-13 #include "IpRestoMinC_1Nrm.hpp" #include "IpCompoundVector.hpp" #include "IpRestoIpoptNLP.hpp" #include "IpDefaultIterateInitializer.hpp" namespace Ipopt { #ifdef IP_DEBUG static const Index dbg_verbosity = 0; #endif MinC_1NrmRestorationPhase::MinC_1NrmRestorationPhase (IpoptAlgorithm& resto_alg, const SmartPtr<EqMultiplierCalculator>& eq_mult_calculator) : resto_alg_(&resto_alg), eq_mult_calculator_(eq_mult_calculator), resto_options_(NULL) { DBG_ASSERT(IsValid(resto_alg_)); } MinC_1NrmRestorationPhase::~MinC_1NrmRestorationPhase() {} void MinC_1NrmRestorationPhase::RegisterOptions(SmartPtr<RegisteredOptions> roptions) { roptions->AddLowerBoundedNumberOption( "bound_mult_reset_threshold", "Threshold for resetting bound multipliers after the restoration phase.", 0.0, false, 1e3, "After returning from the restoration phase, the bound multipliers are " "updated with a Newton step for complementarity. Here, the " "change in the primal variables during the entire restoration " "phase is taken to be the corresponding primal Newton step. " "However, if after the update the largest bound multiplier " "exceeds the threshold specified by this option, the multipliers " "are all reset to 1."); roptions->AddLowerBoundedNumberOption( "constr_mult_reset_threshold", "Threshold for resetting equality and inequality multipliers after restoration phase.", 0.0, false, 0e3, "After returning from the restoration phase, the constraint multipliers " "are recomputed by a least square estimate. This option triggers when " "those least-square estimates should be ignored."); } bool MinC_1NrmRestorationPhase::InitializeImpl(const OptionsList& options, const std::string& prefix) { // keep a copy of these options to use when setting up the // restoration phase resto_options_ = new OptionsList(options); options.GetNumericValue("constr_mult_reset_threshold", constr_mult_reset_threshold_, prefix); options.GetNumericValue("bound_mult_reset_threshold", bound_mult_reset_threshold_, prefix); options.GetBoolValue("expect_infeasible_problem", expect_infeasible_problem_, prefix); // Avoid that the restoration phase is trigged by user option in // first iteration of the restoration phase resto_options_->SetStringValue("resto.start_with_resto", "no"); // We want the default for the theta_max_fact in the restoration // phase higher than for the regular phase Number theta_max_fact; if (!options.GetNumericValue("resto.theta_max_fact", theta_max_fact, "")) { resto_options_->SetNumericValue("resto.theta_max_fact", 1e8); } count_restorations_ = 0; bool retvalue = true; if (IsValid(eq_mult_calculator_)) { retvalue = eq_mult_calculator_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(), options, prefix); } return retvalue; } bool MinC_1NrmRestorationPhase::PerformRestoration() { DBG_START_METH("MinC_1NrmRestorationPhase::PerformRestoration", dbg_verbosity); // Increase counter for restoration phase calls count_restorations_++; Jnlst().Printf(J_DETAILED, J_MAIN, "Starting Restoration Phase for the %d. time\n", count_restorations_); DBG_ASSERT(IpCq().curr_constraint_violation()>0.); // ToDo set those up during initialize? // Create the restoration phase NLP etc objects SmartPtr<IpoptData> resto_ip_data = new IpoptData(); SmartPtr<IpoptNLP> resto_ip_nlp = new RestoIpoptNLP(IpNLP(), IpData(), IpCq()); SmartPtr<IpoptCalculatedQuantities> resto_ip_cq = new IpoptCalculatedQuantities(resto_ip_nlp, resto_ip_data); // Determine if this is a square problem bool square_problem = IpCq().IsSquareProblem(); // Decide if we want to use the original option or want to make // some changes SmartPtr<OptionsList> actual_resto_options = resto_options_; if(square_problem) { actual_resto_options = new OptionsList(*resto_options_); // If this is a square problem, the want the restoration phase // never to be left until the problem is converged actual_resto_options->SetNumericValue("resto.required_infeasibility_reduction", 0.); } else if (expect_infeasible_problem_ && count_restorations_==1) { if (IpCq().curr_constraint_violation()>1e-3) { actual_resto_options = new OptionsList(*resto_options_); // Ask for significant reduction of infeasibility, in the hope // that we do not return from the restoration phase is the // problem is infeasible actual_resto_options->SetNumericValue("resto.required_infeasibility_reduction", 1e-3); } } // Initialize the restoration phase algorithm resto_alg_->Initialize(Jnlst(), *resto_ip_nlp, *resto_ip_data, *resto_ip_cq, *actual_resto_options, "resto."); // Set iteration counter and info field for the restoration phase resto_ip_data->Set_iter_count(IpData().iter_count()+1); resto_ip_data->Set_info_regu_x(IpData().info_regu_x()); resto_ip_data->Set_info_alpha_primal(IpData().info_alpha_primal()); resto_ip_data->Set_info_alpha_primal_char(IpData().info_alpha_primal_char()); resto_ip_data->Set_info_alpha_dual(IpData().info_alpha_dual()); resto_ip_data->Set_info_ls_count(IpData().info_ls_count()); // Call the optimization algorithm to solve the restoration phase // problem SolverReturn resto_status = resto_alg_->Optimize(); int retval=-1; if (resto_status == SUCCESS) { if (Jnlst().ProduceOutput(J_DETAILED, J_LINE_SEARCH)) { Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "\nRESTORATION PHASE RESULTS\n"); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "\n\nOptimal solution found! \n"); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Optimal Objective Value = %.16E\n", resto_ip_cq->curr_f()); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Number of Iterations = %d\n", resto_ip_data->iter_count()); } if (Jnlst().ProduceOutput(J_VECTOR, J_LINE_SEARCH)) { resto_ip_data->curr()->Print(Jnlst(), J_VECTOR, J_LINE_SEARCH, "curr"); } retval = 0; } else if (resto_status == STOP_AT_TINY_STEP || resto_status == STOP_AT_ACCEPTABLE_POINT) { Number orig_primal_inf = IpCq().curr_primal_infeasibility(NORM_MAX); // ToDo make the factor in following line an option if (orig_primal_inf <= 1e2*IpData().tol()) { Jnlst().Printf(J_WARNING, J_LINE_SEARCH, "Restoration phase converged to a point with small primal infeasibility.\n"); THROW_EXCEPTION(RESTORATION_CONVERGED_TO_FEASIBLE_POINT, "Restoration phase converged to a point with small primal infeasibility"); } else { THROW_EXCEPTION(LOCALLY_INFEASIBLE, "Restoration phase converged to a point of local infeasibility"); } } else if (resto_status == MAXITER_EXCEEDED) { THROW_EXCEPTION(RESTORATION_MAXITER_EXCEEDED, "Maximal number of iterations exceeded in restoration phase."); } else if (resto_status == LOCAL_INFEASIBILITY) { // converged to locally infeasible point - pass this on to the outer algorithm... THROW_EXCEPTION(LOCALLY_INFEASIBLE, "Restoration phase converged to a point of local infeasibility"); } else if (resto_status == RESTORATION_FAILURE) { Jnlst().Printf(J_WARNING, J_LINE_SEARCH, "Restoration phase in the restoration phase failed.\n"); THROW_EXCEPTION(RESTORATION_FAILED, "Restoration phase in the restoration phase failed."); } else if (resto_status == USER_REQUESTED_STOP) { // Use requested stop during restoration phase - rethrow exception THROW_EXCEPTION(RESTORATION_USER_STOP, "User requested stop during restoration phase"); } else { Jnlst().Printf(J_ERROR, J_MAIN, "Sorry, things failed ?!?!\n"); retval = 1; } if (retval == 0) { // Copy the results into the trial fields;. They will be // accepted later in the full algorithm SmartPtr<const CompoundVector> cx = dynamic_cast<const CompoundVector*>(GetRawPtr(resto_ip_data->curr()->x())); DBG_ASSERT(IsValid(cx)); SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer(); trial->Set_primal(*cx->GetComp(0), *resto_ip_data->curr()->s()); IpData().set_trial(trial); // If this is a square problem, we are done because a // sufficiently feasible point has been found if (square_problem) { Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Recursive restoration phase algorithm termined successfully for square problem.\n"); IpData().AcceptTrialPoint(); THROW_EXCEPTION(FEASIBILITY_PROBLEM_SOLVED, "Restoration phase converged to sufficiently feasible point of original square problem."); } // Update the bound multiplers, pretending that the entire // progress in x and s in the restoration phase has been one // [rimal-dual Newton step (and therefore the result of solving // an augmented system) SmartPtr<IteratesVector> delta = IpData().curr()->MakeNewIteratesVector(true); delta->Set(0.0); ComputeBoundMultiplierStep(*delta->z_L_NonConst(), *IpData().curr()->z_L(), *IpCq().curr_slack_x_L(), *IpCq().trial_slack_x_L()); ComputeBoundMultiplierStep(*delta->z_U_NonConst(), *IpData().curr()->z_U(), *IpCq().curr_slack_x_U(), *IpCq().trial_slack_x_U()); ComputeBoundMultiplierStep(*delta->v_L_NonConst(), *IpData().curr()->v_L(), *IpCq().curr_slack_s_L(), *IpCq().trial_slack_s_L()); ComputeBoundMultiplierStep(*delta->v_U_NonConst(), *IpData().curr()->v_U(), *IpCq().curr_slack_s_U(), *IpCq().trial_slack_s_U()); DBG_PRINT_VECTOR(1, "delta_z_L", *delta->z_L()); DBG_PRINT_VECTOR(1, "delta_z_U", *delta->z_U()); DBG_PRINT_VECTOR(1, "delta_v_L", *delta->v_L()); DBG_PRINT_VECTOR(1, "delta_v_U", *delta->v_U()); Number alpha_dual = IpCq().dual_frac_to_the_bound(IpData().curr_tau(), *delta->z_L_NonConst(), *delta->z_U_NonConst(), *delta->v_L_NonConst(), *delta->v_U_NonConst()); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Step size for bound multipliers: %8.2e\n", alpha_dual); IpData().SetTrialBoundMultipliersFromStep(alpha_dual, *delta->z_L(), *delta->z_U(), *delta->v_L(), *delta->v_U() ); // ToDo: Check what to do here: Number bound_mult_max = Max(IpData().trial()->z_L()->Amax(), IpData().trial()->z_U()->Amax(), IpData().trial()->v_L()->Amax(), IpData().trial()->v_U()->Amax()); if (bound_mult_max > bound_mult_reset_threshold_) { trial = IpData().trial()->MakeNewContainer(); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Bound multipliers after restoration phase too large (max=%8.2e). Set all to 1.\n", bound_mult_max); trial->create_new_z_L(); trial->create_new_z_U(); trial->create_new_v_L(); trial->create_new_v_U(); trial->z_L_NonConst()->Set(1.0); trial->z_U_NonConst()->Set(1.0); trial->v_L_NonConst()->Set(1.0); trial->v_U_NonConst()->Set(1.0); IpData().set_trial(trial); } DefaultIterateInitializer::least_square_mults( Jnlst(), IpNLP(), IpData(), IpCq(), eq_mult_calculator_, constr_mult_reset_threshold_); DBG_PRINT_VECTOR(2, "y_c", *IpData().curr()->y_c()); DBG_PRINT_VECTOR(2, "y_d", *IpData().curr()->y_d()); IpData().Set_iter_count(resto_ip_data->iter_count()-1); // Skip the next line, because it would just replicate the first // on during the restoration phase. IpData().Set_info_skip_output(true); } return (retval == 0); } void MinC_1NrmRestorationPhase::ComputeBoundMultiplierStep(Vector& delta_z, const Vector& curr_z, const Vector& curr_slack, const Vector& trial_slack) { Number mu = IpData().curr_mu(); delta_z.Copy(curr_slack); delta_z.Axpy(-1., trial_slack); delta_z.ElementWiseMultiply(curr_z); delta_z.AddScalar(mu); delta_z.ElementWiseDivide(curr_slack); delta_z.Axpy(-1., curr_z); } } // namespace Ipopt
chrisdembia/simbody
SimTKmath/Optimizers/src/IpOpt/IpRestoMinC_1Nrm.cpp
C++
apache-2.0
13,577