repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
rashiatmarklogic/entity-services | entity-services-functionaltests/src/test/java/com/marklogic/entityservices/EntityServicesTestBase.java | 4487 | /*
* Copyright 2016 MarkLogic Corporation
*
* 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.marklogic.entityservices;
import java.io.*;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.eval.EvalResult;
import com.marklogic.client.eval.EvalResultIterator;
import com.marklogic.client.eval.ServerEvaluationCall;
import com.marklogic.client.io.marker.AbstractReadHandle;
public abstract class EntityServicesTestBase {
protected static DatabaseClient client, modulesClient, schemasClient;
protected static Set<String> entityTypes;
protected static Set<String> sourceFileUris;
protected static Logger logger = LoggerFactory.getLogger(EntityServicesTestBase.class);
protected static DocumentBuilder builder;
protected static void setupClients() {
TestSetup testSetup = TestSetup.getInstance();
client = testSetup.getClient();
modulesClient = testSetup.getModulesClient();
schemasClient = testSetup.getSchemasClient();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
entityTypes = testSetup.getEntityTypes();
sourceFileUris = testSetup.getSourceFileUris();
}
//@AfterClass
public static void removeContent() {
TestSetup testSetup = TestSetup.getInstance();
testSetup.teardownClass();
}
protected static EvalResultIterator eval(String imports, String functionCall) throws TestEvalException {
String entityServicesImport =
"import module namespace es = 'http://marklogic.com/entity-services' at '/MarkLogic/entity-services/entity-services.xqy';\n" +
"import module namespace esi = 'http://marklogic.com/entity-services-impl' at '/MarkLogic/entity-services/entity-services-impl.xqy';\n" +
"import module namespace i = 'http://marklogic.com/entity-services-instance' at '/MarkLogic/entity-services/entity-services-instance.xqy';\n" +
"import module namespace sem = 'http://marklogic.com/semantics' at '/MarkLogic/semantics.xqy';\n";
String option = "declare option xdmp:mapping \"false\";";
ServerEvaluationCall call =
client.newServerEval().xquery(entityServicesImport + imports + option + functionCall);
EvalResultIterator results = null;
try {
results = call.eval();
} catch (FailedRequestException e) {
throw new TestEvalException(e);
}
return results;
}
protected static <T extends AbstractReadHandle> T evalOneResult(String imports, String functionCall, T handle) throws TestEvalException {
EvalResultIterator results = eval(imports, functionCall);
EvalResult result = null;
if (results.hasNext()) {
result = results.next();
return result.get(handle);
} else {
return null;
}
}
protected void debugOutput(Document xmldoc) throws TransformerException {
debugOutput(xmldoc, System.out);
}
protected void debugOutput(Document xmldoc, OutputStream os) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(xmldoc), new StreamResult(os));
}
}
| apache-2.0 |
tpserver/talentpool | app/controllers/migrateController.php | 13398 | <?php
class migrateController extends \BaseController {
public function __construct()
{
$first_name;
include("app/includes/db_csv_pharser.php");
// print_r($first_name);
//echo $row;
for($i=1;$i<$row;$i++){
$void_array=array();
$data = array('first_name'=>$first_name[$i]['first_name'],
'last_name'=>$last_name[$i]['last_name'],
'email'=> $email[$i]['email'],
'password'=>$password[$i]['password']
);
//print_r($data);die();
$validator = Validator::make($data,User::$validationRules);
//if( $validator->fails() )
//{
// return Redirect::back()->withErrors($validator)->withInput();
//}
$workOptions = Option::where('category_id', '=', 1)->get();
$user = new User;
$user->first_name = $first_name[$i]['first_name'];
$user->last_name = $last_name[$i]['last_name'];
$user->email = $email[$i]['email'];
$user->password = $password[$i]['password'];
$user->group_id = 1;
$user->agnostic = 0;
$user->desired_payment = 4;
$user->english_level = $language_levels[$i][0];
$user->ethnicity_id = $ethnicity[$i][0];
$user->dob = $dob[$i][0];
$user->gender =$gender[$i][0];
$user->contact_frequency = $user_contact_freq[$i][0];
//print_r($user);die();
if( isset($data['availability']) )
{
$user->availability = $data['availability'];
$availabilityDate = date('Y-m-d');
if($data['availability'] == 'other')
{
$availabilityDate = $data['availability_year'].'-'.sprintf("%02s", $data['availability_month']).'-01';
$user->availability_date = $availabilityDate;
}
}
else
{
$user->availability = 0;
}
if( isset($data['payment']) )
{
$user->desired_payment = array_sum($data['payment']);
}
//$qual_type[$i],$school_subjects[$i], $school_qualifications_subject[$i], $school_qualification_results_name[$i]
//print_r($qual_type[$i]);
for($j=0;$j<count($qual_type[$i]);$j++)
{
if($qual_type[$i][$j]==0 || $qual_type[$i][$j]=='0')
{
unset( $qual_type[$i][$j]);
unset( $school_subjects[$i][$j]);
unset( $school_qualifications_subject[$i][$j]);
unset( $school_qualification_results_name[$i][$j]);
}
}
for($j=0;$j<count($degree_type[$i]);$j++)
{
if($degree_type[$i][$j]==0)
{
unset( $degree_type[$i][$j]);
unset( $degree_uni[$i][$j]);
unset( $degree_result[$i][$j]);
unset( $degree_subject_name[$i][$j]);
unset( $degree_graduation[$i][$j]);
unset( $degree_subject_type[$i][$j]);
}
}
for($j=0;$j<count($sport_names_talent[$i]);$j++)
{
if($sport_names_talent[$i][$j]==0)
{
unset( $sport_names_talent[$i][$j]);
unset( $sport_level[$i][$j]);
unset( $sport_position[$i][$j]);
}
}
for($j=0;$j<count($work_type[$i]);$j++)
{
if($work_type[$i][$j]==0)
{
unset( $work_type[$i][$j]);
unset( $work_durations[$i][$j]);
unset( $work_sector_id[$i][$j]);
unset( $works_name_talent[$i][$j]);
}
}
echo "</br>";
echo "<pre>";
echo "<h4>";
print_r( $sport_names_talent[$i]);
print_r( $sport_level[$i]);
print_r( $sport_position[$i]);
//print_r( $works_name_talent[$i]);
// print_r( $degree_result[$i]);
// print_r( $degree_graduation[$i]);
echo $i;
echo "</h4>";
// print_r( $degree_graduation[$i]);
// echo "</br>";
// print_r( $degree_subject_type[$i])*/;
// echo "</br>";
// print_r( $degree_graduation[$i])*/;
//
//die();
$user->save();
if( isset($languages[$i]) )
{
$user->massUpdateLanguage($languages[$i], $language_level_other[$i], $void_array);
}
$user->massUpdateSport($sport_names_talent[$i],$sport_level[$i],$sport_position[$i],$void_array);
if( isset($degree_type[$i]) )
{
$user->massUpdateDegree($degree_type[$i], $degree_uni[$i], $degree_subject_type[$i],
$degree_subject_name[$i],$degree_result[$i],$degree_graduation[$i],
$void_array);
}
if( isset($society_category[$i]) )
{
$user->massUpdateSocial($society_category[$i], $society_position[$i], $society_name[$i], $void_array);
}
if( isset($work_type[$i]) )
{
$user->massUpdateWork($work_type[$i], $work_durations[$i], $work_sector_id[$i],
$works_name_talent[$i], $void_array);
}
//if( isset($data['desired_job_type']) )
//{
// $_i = 0;
//
// $user->desiredWorkType()->attach(1);
//
//}
//if( isset($data['job_location']) )
//{
// foreach($data['job_location'] as $location)
// {
// $user->desiredLocation()->attach($location);
// }
//}
//if( isset($data['skills']) )
//{
// $_i = 0;
// foreach($data['skills'] as $skill)
// {
// if(isset($data['skill_levels'][$_i]))
// $level = $data['skill_levels'][$_i];
// else
// $level = 0;
// $user->skill()->attach($skill, ['level' => $level]);
// $_i++;
// }
//}
if(isset($sector_interest[$i]))
{
foreach($sector_interest[$i] as $work_option)
{
$user->option()->attach($work_option);
}
}
//if( isset($data['attributes']) )
//{
// foreach($data['attributes'] as $attribute)
// {
// $user->option()->attach($attribute);
// }
//}
//if( isset($data['experience']) )
//{
// foreach($data['experience'] as $experience)
// {
// $user->option()->attach($experience);
// }
//}
//if( isset($data['capabilities']) )
//{
// foreach($data['capabilities'] as $attribute)
// {
// $user->option()->attach($attribute);
// }
//}
$options = array();
foreach ($workOptions as $workOption)
{
if( isset($data[str_replace( ' ', '-', strtolower($workOption->group->name) )]) )
{
$paramName = str_replace( ' ', '-', strtolower($workOption->group->name) );
foreach ($data[$paramName] as $param)
{
$options[] = Option::find($param);
}
}
}
$user->massUpdateSchoolQualification($qual_type[$i],$school_subjects[$i], $school_qualifications_subject[$i], $school_qualification_results_name[$i],$void_array);
if( !empty($options) )
$user->option()->saveMany(array_unique($options));
echo "success";
}
}
public function data_migrate()
{
$row=1;
//print_r($first_name);
}
public function submit($row)
{
$void_array=array();
$data = $all_data;
$workOptions = Option::where('category_id', '=', 1)->get();
$user = new User;
$user->first_name = $first_name[$row]['first_name'];
$user->last_name = $$last_name[$row]['last_name'];
$user->email = $email[$row]['email'];
$user->password = $password[$row]['password'];
$user->group_id = 1;
$user->agnostic = 0;
$user->desired_payment = 4;
$user->english_level = $language_levels[$row][0];
$user->ethnicity_id = $data['ethnicity'];
$user->dob = $data['year_dob'] . '-' . $data['month_dob'] . '-' . $data['date_dob'];
$user->gender = $data['gender'];
$user->contact_frequency = $data['emails_per_week'];
if( isset($data['availability']) )
{
$user->availability = $data['availability'];
$availabilityDate = date('Y-m-d');
if($data['availability'] == 'other')
{
$availabilityDate = $data['availability_year'].'-'.sprintf("%02s", $data['availability_month']).'-01';
$user->availability_date = $availabilityDate;
}
}
else
{
$user->availability = 0;
}
//if( isset($data['payment']) )
//{
// $user->desired_payment = array_sum($data['payment']);
//}
$user->save();
//die();
if( isset($languages[$row]) )
{
$user->massUpdateLanguage($languages[$row], $language_level_other[$row], $void_array);
}
$user->massUpdateSport($sport_names_talent[$row],$sport_level[$row],$sport_position[$row],$void_array);
if( isset($degree_type[$row]) )
{
$user->massUpdateDegree($degree_type[$row], $degree_uni[$row], $degree_result[$row],
$degree_subject_name[$row],$degree_result[$row],$degrees_degree_year[$row],
$void_array);
}
if( isset($society_category[$row]) )
{
$user->massUpdateSocial($society_category[$row], $society_position[$row], $society_name[$row], $void_array);
}
if( isset($work_type[$row]) )
{
$user->massUpdateWork($work_type[$row], $work_durations[$row], $work_sector_id[$row],
$works_name_talent[$row], $void_array);
}
//if( isset($data['desired_job_type']) )
//{
// $_i = 0;
//
// $user->desiredWorkType()->attach(1);
//
//}
//if( isset($data['job_location']) )
//{
// foreach($data['job_location'] as $location)
// {
// $user->desiredLocation()->attach($location);
// }
//}
//if( isset($data['skills']) )
//{
// $_i = 0;
// foreach($data['skills'] as $skill)
// {
// if(isset($data['skill_levels'][$_i]))
// $level = $data['skill_levels'][$_i];
// else
// $level = 0;
// $user->skill()->attach($skill, ['level' => $level]);
// $_i++;
// }
//}
if(isset($sector_interest[$row]))
{
foreach($sector_interest[$row] as $work_option)
{
$user->option()->attach($work_option);
}
}
//if( isset($data['attributes']) )
//{
// foreach($data['attributes'] as $attribute)
// {
// $user->option()->attach($attribute);
// }
//}
//if( isset($data['experience']) )
//{
// foreach($data['experience'] as $experience)
// {
// $user->option()->attach($experience);
// }
//}
//if( isset($data['capabilities']) )
//{
// foreach($data['capabilities'] as $attribute)
// {
// $user->option()->attach($attribute);
// }
//}
$options = array();
foreach ($workOptions as $workOption)
{
if( isset($data[str_replace( ' ', '-', strtolower($workOption->group->name) )]) )
{
$paramName = str_replace( ' ', '-', strtolower($workOption->group->name) );
foreach ($data[$paramName] as $param)
{
$options[] = Option::find($param);
}
}
}
$user->massUpdateSchoolQualification($qual_type[$row],$school_subjects[$row], $school_qualifications_subject[$row], $school_qualification_results_name[$row],$void_array);
if( !empty($options) )
$user->option()->saveMany(array_unique($options));
//$user = Sentry::findUserById($user->id);
////echo $user->activation_code;die();
////echo $user->getActivationCode();die();
//Mail::send('email.activate-html', ['siteName' => 'gradslist.co.uk', 'username'=> $user->first_name, 'email' => $user->email, 'code' => $user->getActivationCode(), 'activationPeriod' => 48], function($message) use($user)
//{
// $message->to($user->email)->subject('Welcome to GradList');
//});
//
//return Redirect::route('signup.success')->with('email', $user->email);
}
} | apache-2.0 |
klklmoon/pipishow | bll/model/consume/MedalListModel.php | 872 | <?php
/**
* 勋章管理
*
* the last known user to change this file in the repository <$LastChangedBy: guoshaobo $>
* @author guoshaobo <guoshaobo@pipi.cn>
* @version $Id: UserCheckinModel.php 9657 2013-05-06 12:59:31Z guoshaobo $
* @package model
* @subpackage consume
*/
class MedalListModel extends PipiActiveRecord{
/**
*
* @param unknown_type $className
* @return MedalListModel
*/
public static function model($className = __CLASS__){
return parent::model($className);
}
public function tableName(){
return '{{medal_list}}';
}
public function getDbConnection(){
return Yii::app()->db_consume;
}
public function getMedalList($condition = array()){
$criteria = $this->getDbCriteria();
if (!empty($condition['mid'])){
$criteria->compare('mid', intval($condition['mid']));
}
return $this->findAll($criteria);
}
}
?> | apache-2.0 |
kalikov/lighthouse | app/src/main/java/ru/radiomayak/http/util/EncodingUtils.java | 4932 | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ru.radiomayak.http.util;
import java.io.UnsupportedEncodingException;
/**
* The home for utility methods that handle various encoding tasks.
*
*
* @since 4.0
*/
public final class EncodingUtils {
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(
final byte[] data,
final int offset,
final int length,
final String charset) {
Args.notNull(data, "Input");
Args.notEmpty(charset, "Charset");
try {
return new String(data, offset, length, charset);
} catch (final UnsupportedEncodingException e) {
return new String(data, offset, length);
}
}
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(final byte[] data, final String charset) {
Args.notNull(data, "Input");
return getString(data, 0, data.length, charset);
}
/**
* Converts the specified string to a byte array. If the charset is not supported the
* default system charset is used.
*
* @param data the string to be encoded
* @param charset the desired character encoding
* @return The resulting byte array.
*/
public static byte[] getBytes(final String data, final String charset) {
Args.notNull(data, "Input");
Args.notEmpty(charset, "Charset");
try {
return data.getBytes(charset);
} catch (final UnsupportedEncodingException e) {
return data.getBytes();
}
}
/**
* Converts the specified string to byte array of ASCII characters.
*
* @param data the string to be encoded
* @return The string as a byte array.
*/
public static byte[] getAsciiBytes(final String data) {
Args.notNull(data, "Input");
return data.getBytes(ru.radiomayak.http.Consts.ASCII);
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data, final int offset, final int length) {
Args.notNull(data, "Input");
return new String(data, offset, length, ru.radiomayak.http.Consts.ASCII);
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data) {
Args.notNull(data, "Input");
return getAsciiString(data, 0, data.length);
}
/**
* This class should not be instantiated.
*/
private EncodingUtils() {
}
}
| apache-2.0 |
kennykwok1/PlaygroundOSS | CSharpVersion/EnginePrototype/Wrappers/CKLBAsyncLoader.cs | 3776 | /*
Copyright 2013 KLab 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.
*/
using System;
using System.Runtime.InteropServices;
namespace EnginePrototype
{
public class CKLBAsyncLoader : CKLBTask
{
#region DllImports
// pParentTask : CKLBTask
// assets : const char**
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
private extern static IntPtr CKLBAsyncLoader_create(IntPtr pParentTask, IntPtr[] assets, uint count, uint datasetID);
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
private extern static uint CKLBAsyncLoader_getProcessCount(IntPtr p);
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
private extern static uint CKLBAsyncLoader_getTotalCount(IntPtr p);
#endregion
#region Constructors
static uint s_classID = __FrameworkUtils.RegisterClass("UTIL_AsyncLoader"/*, typeof(CKLBAsyncLoader)*/);
public CKLBAsyncLoader(CKLBTask pParent, String[] assets, uint datasetID, CallBack callback)
: base(s_classID)
{
NativeManagement.resetCppError();
IntPtr ptr = CKLBAsyncLoader_create((pParent != null) ? pParent.CppObject : IntPtr.Zero,
__MarshallingUtils.NativeUtf8ArrayFromStringArray(assets, assets.Length), (uint)assets.Length, datasetID);
NativeManagement.intercepCppError();
m_callback = callback;
bind(ptr);
}
public CKLBAsyncLoader() : base(s_classID) { }
#endregion
#region CallBacks
public delegate void CallBack(CKLBAsyncLoader caller, uint loaded, uint total);
private CallBack m_callback;
protected override void doSetupCallbacks()
{
registerCallBack(new NativeManagement.FunctionPointerUU(callBackFunction));
}
public override void setDelegate(Delegate anyDelegate, String delegateName = null)
{
m_callback = (CallBack)anyDelegate;
}
public virtual void callBackFunction(uint loaded, uint total)
{
if(m_callback != null) {
m_callback(this, loaded, total);
} else {
throw new CKLBException("Delegate NULL for this callback : Virtual function in subclass not implemented or delegate is null");
}
}
#endregion
public uint ProcessCount
{
get
{
if(CppObject != IntPtr.Zero) {
return CKLBAsyncLoader_getProcessCount(CppObject);
} else {
throw new CKLBExceptionNullCppObject();
}
}
//set { throw new CKLBExceptionForbiddenMethod(); }
}
public uint TotalCount
{
get
{
if(CppObject != IntPtr.Zero) {
return CKLBAsyncLoader_getTotalCount(CppObject);
} else {
throw new CKLBExceptionNullCppObject();
}
}
//set { throw new CKLBExceptionForbiddenMethod(); }
}
}
}
| apache-2.0 |
citizenmatt/gallio | src/Gallio/Gallio/Model/Helpers/TestController.cs | 4987 | // Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Model.Commands;
using Gallio.Model.Contexts;
using Gallio.Model.Tree;
using Gallio.Runtime.ProgressMonitoring;
namespace Gallio.Model.Helpers
{
/// <summary>
/// A test controller executes tests defined by a tree of <see cref="ITestCommand" />s.
/// </summary>
/// <remarks>
/// <para>
/// A test controller may be stateful because it is used for only one test run then disposed.
/// </para>
/// <para>
/// Subclasses of this class provide the algorithm used to execute the commands.
/// </para>
/// </remarks>
public abstract class TestController : IDisposable
{
/// <summary>
/// Disposes the test controller.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the test controller.
/// </summary>
/// <param name="disposing">True if <see cref="Dispose()" /> was called directly.</param>
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// Runs the tests.
/// </summary>
/// <remarks>
/// <para>
/// This method can be called at most once during the lifetime of a test controller.
/// </para>
/// </remarks>
/// <param name="rootTestCommand">The root test monitor.</param>
/// <param name="parentTestStep">The parent test step, or null if starting a root step.</param>
/// <param name="options">The test execution options.</param>
/// <param name="progressMonitor">The progress monitor.</param>
/// <returns>The combined result of the root test command.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="rootTestCommand"/>
/// <paramref name="progressMonitor"/>, or <paramref name="options"/> is null.</exception>
public TestResult Run(ITestCommand rootTestCommand, TestStep parentTestStep, TestExecutionOptions options, IProgressMonitor progressMonitor)
{
if (rootTestCommand == null)
throw new ArgumentNullException("rootTestCommand");
if (progressMonitor == null)
throw new ArgumentNullException("progressMonitor");
if (options == null)
throw new ArgumentNullException("options");
return RunImpl(rootTestCommand, parentTestStep, options, progressMonitor);
}
/// <summary>
/// Implementation of <see cref="Run" /> called after argument validation has taken place.
/// </summary>
/// <param name="rootTestCommand">The root test command, not null.</param>
/// <param name="parentTestStep">The parent test step, or null if none.</param>
/// <param name="options">The test execution options, not null.</param>
/// <param name="progressMonitor">The progress monitor, not null.</param>
/// <returns>The combined result of the root test command.</returns>
protected internal abstract TestResult RunImpl(ITestCommand rootTestCommand, TestStep parentTestStep, TestExecutionOptions options, IProgressMonitor progressMonitor);
/// <summary>
/// Recursively generates single test steps for each <see cref="ITestCommand" /> and
/// sets the final outcome to <see cref="TestOutcome.Skipped" />.
/// </summary>
/// <remarks>
/// <para>
/// This is useful for implementing fallback behavior when
/// <see cref="TestExecutionOptions.SkipTestExecution" /> is true.
/// </para>
/// </remarks>
/// <param name="rootTestCommand">The root test command.</param>
/// <param name="parentTestStep">The parent test step.</param>
/// <returns>The combined result of the test commands.</returns>
protected static TestResult SkipAll(ITestCommand rootTestCommand, TestStep parentTestStep)
{
ITestContext context = rootTestCommand.StartPrimaryChildStep(parentTestStep);
foreach (ITestCommand child in rootTestCommand.Children)
SkipAll(child, context.TestStep);
return context.FinishStep(TestOutcome.Skipped, null);
}
}
} | apache-2.0 |
aeolusproject/conductor | src/app/controllers/provider_realms_controller.rb | 2499 | #
# Copyright 2012 Red Hat, 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.
#
class ProviderRealmsController < ApplicationController
before_filter :require_user
before_filter :load_realms, :only =>[:index, :show]
def index
clear_breadcrumbs
save_breadcrumb(provider_realms_path)
respond_to do |format|
format.html
format.js { render :partial => 'list' }
format.xml { render :partial => 'list.xml' }
end
end
def show
@provider_realm = ProviderRealm.find(params[:id])
@title = @provider_realm.name
@tab_captions = [_('Properties'), _('Mapping')]
@details_tab = params[:details_tab].blank? ? 'properties' : params[:details_tab]
@details_tab = 'properties' unless ['properties', 'mapping'].include?(@details_tab)
@frontend_realms_for_provider = @provider_realm.provider.frontend_realms
@frontend_realms = @provider_realm.frontend_realms
@provider_accounts = @provider_realm.provider_accounts
save_breadcrumb(provider_realm_path(@provider_realm), @provider_realm.name)
respond_to do |format|
format.html { render :action => 'show' }
format.js do
if params.delete :details_pane
render :partial => 'layouts/details_pane' and return
end
render :partial => @details_tab
end
format.json { render :json => @provider_realm }
format.xml { render :show, :locals => { :provider_realm => @provider_realm } }
end
end
def filter
redirect_to_original({"provider_realms_preset_filter" => params[:provider_realms_preset_filter], "provider_realms_search" => params[:provider_realms_search]})
end
protected
def load_realms
@header = [
{:name => '', :sortable => false},
{:name => _('Provider Realm Name'), :sort_attr => :name},
]
@provider_realms = ProviderRealm.apply_filters(:preset_filter_id => params[:provider_realms_preset_filter], :search_filter => params[:provider_realms_search])
end
end
| apache-2.0 |
McOmghall/game-development-coursera-exercises | A Fireball For Your Friends/Assets/Scripts/Camera & Input/InputControl.cs | 5493 | using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;
public class InputControl : MonoBehaviour {
private Vector3 movementDirection;
// the world-relative desired move direction, calculated from the camForward and user input.
private bool jump; // whether the jump button is currently pressed
public MovementInputData movementInputData;
private Vector3 fireballTo;
private Vector3 lookAt;
private ShootableFireball firing;
private float nextFireballTime = 0;
private float turnSpeed = 0;
private bool fireButtonPressed = false;
private bool secondaryFireButtonPressed = false;
public ExplosiveFireball explosiveFireballPrefab;
public ChargeableMultiNormalFireball fireballPrefab;
public NormalFireballInputManager normalFireballInputManager;
public ExplosiveFireballInputManager explosiveFireballInputManager;
public DebugText debugPosition;
public DebugText feedbackPosition;
private float score = 0;
private void OnValidate() {
if (explosiveFireballPrefab == null) {
throw new Exception("You need to attach an explosive fireball prefab");
}
if (fireballPrefab == null) {
throw new Exception("You need to attach a fireball prefab");
}
if (debugPosition == null) {
throw new Exception("You need to attach a debug position");
}
}
private void Update() {
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
jump = CrossPlatformInputManager.GetButton("Jump");
bool fireButtonCheck = CrossPlatformInputManager.GetButton("Fire1");
bool secondFireButtonCheck = CrossPlatformInputManager.GetButton("Fire2");
Vector3 camForward = Vector3.Scale(Camera.main.transform.up, new Vector3(1, 0, 1)).normalized;
Vector3 camRight = Vector3.Scale(Camera.main.transform.right, new Vector3(1, 0, 1)).normalized;
movementDirection = (v * camForward + h * camRight).normalized;
float distanceToHit;
Ray mouseDirection = Camera.main.ScreenPointToRay(CrossPlatformInputManager.mousePosition);
if (new Plane(Vector3.up, Vector3.zero).Raycast(mouseDirection, out distanceToHit)) {
fireballTo = mouseDirection.GetPoint(distanceToHit);
lookAt = fireballTo + Vector3.up;
debugPosition.setInfo("Mouse", CrossPlatformInputManager.mousePosition.ToString());
debugPosition.setInfo("Fireball", fireballTo.ToString());
debugPosition.setInfo("Direction", mouseDirection.ToString());
Debug.DrawRay(fireballTo, Vector3.up, Color.blue);
}
// Shooting control, primary fire takes precedence
if (fireButtonCheck) {
fireButtonPressed = true;
normalFireballInputManager.fireButtonPressed(transform, fireballPrefab, fireballTo);
}
if (secondFireButtonCheck) {
secondaryFireButtonPressed = true;
explosiveFireballInputManager.fireButtonPressed(transform, explosiveFireballPrefab);
}
// Handling of releasing fire buttons
if (fireButtonPressed && !fireButtonCheck) {
fireButtonPressed = false;
normalFireballInputManager.fireButtonReleased(fireballTo);
}
if (secondaryFireButtonPressed && !secondFireButtonCheck) {
secondaryFireButtonPressed = false;
explosiveFireballInputManager.fireButtonReleased(fireballTo);
}
}
private void FixedUpdate() {
move();
feedback();
}
private void feedback() {
feedbackPosition.setInfo("Controls", "WASD for movement, mouse for firing");
Health health = GetComponent<Health>();
feedbackPosition.setInfo("Health", health.healthAmount.ToString("0000"));
float timeOfNextNormalShot = Time.time - normalFireballInputManager.timeOfNextShot;
float timeOfNextExplosiveShot = Time.time - explosiveFireballInputManager.timeOfNextShot;
feedbackPosition.setInfo("Normal fire (left mouse)", (timeOfNextNormalShot > 0 ? "NOW" : Math.Abs(timeOfNextNormalShot).ToString("F3") + " s"));
feedbackPosition.setInfo("Explosive fire (right mouse)", (timeOfNextExplosiveShot > 0 ? "NOW" : Math.Abs(timeOfNextExplosiveShot).ToString("F3") + " s"));
feedbackPosition.setInfo("Score", score.ToString("0000"));
}
public void move() {
transform.position += movementDirection * movementInputData.movementSpeed * Time.deltaTime;
Quaternion rotationToTurn = Quaternion.LookRotation(lookAt - transform.position);
float angleToTurn = Quaternion.Angle(transform.rotation, rotationToTurn);
//speed is in degrees/sec = angle, to pass angle in 1 seconds. our speed can be increased only 'turnSpeedChange' degrees/sec^2, but don't increase it if needn't
turnSpeed = Mathf.Min(angleToTurn, turnSpeed + movementInputData.turnSpeedChange * Time.fixedDeltaTime);
transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
transform.rotation = Quaternion.Lerp(transform.rotation, rotationToTurn, angleToTurn > 0 ? turnSpeed * Time.fixedDeltaTime / angleToTurn : 0f);
transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
Debug.DrawRay(transform.position, transform.rotation * Vector3.forward, Color.red);
}
public Vector3 getLookAtPosition() {
return lookAt;
}
public float addScore (float add) {
score = score + add;
return score;
}
void OnDestroy () {
// Restart on death
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
| apache-2.0 |
shamanDevel/jME3-OpenCL-Library | src/main/java/org/shaman/jmecl/particles/DefaultAdvectionStrategy.java | 7683 | /*
* 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 org.shaman.jmecl.particles;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
import com.jme3.opencl.Buffer;
import com.jme3.opencl.CommandQueue;
import com.jme3.opencl.Kernel;
import com.jme3.opencl.Program;
import com.jme3.scene.VertexBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.shaman.jmecl.OpenCLSettings;
/**
* A default advection strategy.
* <p>
* Particles can have:
* <ul>
* <li>a position</li>
* <li>a velocity</li>
* <li>an acceleration, or a global acceleration</li>
* <li>a mass, or a global mass</li>
* <li>a color</li>
* </ul>
* <p>
* Deletion by (multiple can be specified):
* <ul>
* <li>axis aligned bounding box</li>
* <li>bounding sphere</li>
* <li>lower density threshold</li>
* </ul>
* <p>
* Advection equation: <br>
* <code> v = v + dt * (alpha*density*gravity - beta * temperature * gravity + velocity_field(x)/density </code> <br>
* <code> x = x + dt * v </code>
* <p>
* Exponential decay: <br>
* <code> temperature = temperature - dt * temperature * lambda </code> <br>
* <code> density = density - dt * temperature * mu </code> <br>
* It must hold that <code>dt * lambda < 1</code>, <code>dt * my < 1</code> for the largest possible timestep <code>dt</code>
*/
public class DefaultAdvectionStrategy implements AdvectionStrategy {
private static final String SOURCE_FILE = "org/shaman/jmecl/particles/DefaultAdvectionStrategy.cl";
private static final Map<OpenCLSettings, Kernels> kernelMap = new HashMap<>();
private ParticleController controller;
private Kernels kernels;
private final ArrayList<DeletionCondition> deletionConditions;
private float alpha;
private float beta;
private Vector4f gravity;
private float lambda;
private float mu;
public DefaultAdvectionStrategy() {
this.deletionConditions = new ArrayList<>();
this.gravity = new Vector4f();
}
public void addDeletionCondition(DeletionCondition condition) {
deletionConditions.add(condition);
}
public boolean removeDeletionCondition(DeletionCondition condition) {
return deletionConditions.remove(condition);
}
public void clearDeletionConditions() {
deletionConditions.clear();
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
}
public float getBeta() {
return beta;
}
public void setBeta(float beta) {
this.beta = beta;
}
public Vector3f getGravity() {
return new Vector3f(gravity.x, gravity.y, gravity.z);
}
public void setGravity(Vector3f gravity) {
this.gravity.x = gravity.x;
this.gravity.y = gravity.y;
this.gravity.z = gravity.z;
}
public float getLambda() {
return lambda;
}
public void setLambda(float lambda) {
this.lambda = lambda;
}
public float getMu() {
return mu;
}
public void setMu(float mu) {
this.mu = mu;
}
@Override
public void init(ParticleController controller) {
this.controller = controller;
OpenCLSettings settings = controller.getCLSettings();
synchronized(kernelMap) {
kernels = kernelMap.get(settings);
if (kernels == null) {
//create it
kernels = new Kernels();
kernels.clQueue = settings.getClCommandQueue();
String cacheID = DefaultAdvectionStrategy.class.getName();
Program program = settings.getProgramCache().loadFromCache(cacheID);
if (program == null) {
program = settings.getClContext().createProgramFromSourceFiles(settings.getAssetManager(), SOURCE_FILE);
program.build();
settings.getProgramCache().saveToCache(cacheID, program);
}
program.register();
kernels.DeletionBoxKernel = program.createKernel("DeletionBox").register();
kernels.DeletionSphereKernel = program.createKernel("DeletionSphere").register();
kernels.DeletionDensityThresholdKernel = program.createKernel("DeletionDensityThreshold").register();
kernels.AdvectKernel = program.createKernel("Advect").register();
kernelMap.put(settings, kernels);
}
}
}
@Override
public void resized(int newSize) {
//nothing to do
}
@Override
public void advect(float tpf, int count, Buffer deletionBuffer) {
Kernel.WorkSize ws = new Kernel.WorkSize(count);
Buffer positionBuffer = controller.getBuffer(VertexBuffer.Type.Position).getCLBuffer();
Buffer velocityBuffer = controller.getBuffer(VertexBuffer.Type.TexCoord2).getCLBuffer();
Buffer temperatureBuffer = controller.getBuffer(VertexBuffer.Type.TexCoord3).getCLBuffer();
//advect
kernels.AdvectKernel.Run1NoEvent(kernels.clQueue, ws,
positionBuffer, velocityBuffer, temperatureBuffer,
alpha, beta, gravity, lambda, mu, tpf);
//fill deletion buffer
for (DeletionCondition c : deletionConditions) {
if (c instanceof BoxDeletionCondition) {
kernels.DeletionBoxKernel.Run1NoEvent(kernels.clQueue, ws,
positionBuffer, deletionBuffer,
((BoxDeletionCondition) c).min, ((BoxDeletionCondition) c).max);
} else if (c instanceof SphereDeletionCondition) {
kernels.DeletionSphereKernel.Run1NoEvent(kernels.clQueue, ws,
positionBuffer, deletionBuffer,
((SphereDeletionCondition) c).centerAndRadius);
} else if (c instanceof DensityThresholdDeletionCondition) {
kernels.DeletionDensityThresholdKernel.Run1NoEvent(kernels.clQueue, ws,
positionBuffer, deletionBuffer,
((DensityThresholdDeletionCondition) c).densityThreshold);
}
}
}
public static interface DeletionCondition {
//marker interface
}
public static class BoxDeletionCondition implements DeletionCondition {
private final Vector4f min;
private final Vector4f max;
public BoxDeletionCondition(Vector3f min, Vector3f max) {
this.min = new Vector4f(min.x, min.y, min.z, 0);
this.max = new Vector4f(max.x, max.y, max.z, 0);
}
public Vector3f getMin() {
return new Vector3f(min.x, min.y, min.z);
}
public Vector3f getMax() {
return new Vector3f(max.x, max.y, max.z);
}
@Override
public String toString() {
return "BoxDeletionCondition{" + "min=" + getMin() + ", max=" + getMax() + '}';
}
}
public static class SphereDeletionCondition implements DeletionCondition {
private final Vector4f centerAndRadius;
public SphereDeletionCondition(Vector3f center, float radius) {
this.centerAndRadius = new Vector4f(center.x, center.y, center.z, radius);
}
public Vector3f getCenter() {
return new Vector3f(centerAndRadius.x, centerAndRadius.y, centerAndRadius.z);
}
public float getRadius() {
return centerAndRadius.w;
}
@Override
public String toString() {
return "SphereDeletionCondition{" + "center=" + getCenter() + ", radius=" + getRadius() + '}';
}
}
public static class DensityThresholdDeletionCondition implements DeletionCondition {
private final float densityThreshold;
/**
* A particle is deleted when its density falls below the specified threshold
* @param densityThreshold the threshold on the density
*/
public DensityThresholdDeletionCondition(float densityThreshold) {
this.densityThreshold = densityThreshold;
}
public float getDensityThreshold() {
return densityThreshold;
}
@Override
public String toString() {
return "DensityThresholdDeletionCondition{" + "densityThreshold=" + densityThreshold + '}';
}
}
private static class Kernels {
private Kernel DeletionBoxKernel;
private Kernel DeletionSphereKernel;
private Kernel DeletionDensityThresholdKernel;
private Kernel AdvectKernel;
private CommandQueue clQueue;
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramViewBookmarkManager.java | 12640 | /* ###
* IP: GHIDRA
*
* 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 ghidra.trace.database.program;
import java.awt.Color;
import java.util.*;
import java.util.function.Predicate;
import javax.swing.ImageIcon;
import org.apache.commons.collections4.IteratorUtils;
import com.google.common.collect.Iterators;
import com.google.common.collect.Range;
import generic.NestedIterator;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.Bookmark;
import ghidra.program.model.listing.BookmarkType;
import ghidra.trace.database.DBTraceUtils;
import ghidra.trace.database.bookmark.*;
import ghidra.trace.model.Trace;
import ghidra.trace.model.bookmark.*;
import ghidra.trace.model.program.TraceProgramView;
import ghidra.trace.model.program.TraceProgramViewBookmarkManager;
import ghidra.util.LockHold;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
public class DBTraceProgramViewBookmarkManager implements TraceProgramViewBookmarkManager {
protected static final String[] EMPTY_STRING_ARRAY = new String[0];
protected static final Bookmark[] EMPTY_BOOKMARK_ARRAY = new Bookmark[0];
protected final DBTraceProgramView program;
protected final DBTraceBookmarkManager bookmarkManager;
public DBTraceProgramViewBookmarkManager(DBTraceProgramView program) {
this.program = program;
this.bookmarkManager = program.trace.getBookmarkManager();
}
@Override
public BookmarkType defineType(String type, ImageIcon icon, Color color, int priority) {
return bookmarkManager.defineBookmarkType(type, icon, color, priority);
}
@Override
public BookmarkType[] getBookmarkTypes() {
Collection<? extends TraceBookmarkType> types = bookmarkManager.getDefinedBookmarkTypes();
return types.toArray(new BookmarkType[types.size()]);
}
@Override
public BookmarkType getBookmarkType(String type) {
return bookmarkManager.getBookmarkType(type);
}
@Override
public String[] getCategories(String type) {
TraceBookmarkType bmt = bookmarkManager.getBookmarkType(type);
if (bmt == null) {
return EMPTY_STRING_ARRAY;
}
Collection<String> categories = bmt.getCategories();
return categories.toArray(new String[categories.size()]);
}
@Override
public Bookmark setBookmark(Address addr, String type, String category, String comment) {
try (LockHold hold = program.trace.lockWrite()) {
TraceBookmarkType bmt = bookmarkManager.getOrDefineBookmarkType(type);
TraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(addr.getAddressSpace(), true);
// TODO: How to let user modify time? I think by deletion at a later snap....
return space.addBookmark(Range.atLeast(program.snap), addr, bmt, category, comment);
}
}
@Override
public Bookmark getBookmark(Address addr, String type, String category) {
try (LockHold hold = program.trace.lockRead()) {
DBTraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(addr.getAddressSpace(), false);
if (space == null) {
return null;
}
for (long s : program.viewport.getOrderedSnaps()) {
for (TraceBookmark bm : space.getBookmarksAt(s, addr)) {
if (!type.equals(bm.getTypeString())) {
continue;
}
if (!category.equals(bm.getCategory())) {
continue;
}
return bm;
}
}
return null;
}
}
protected void doDeleteOrTruncateLifespan(TraceBookmark bm) {
Range<Long> lifespan = bm.getLifespan();
if (!lifespan.contains(program.snap)) {
throw new IllegalArgumentException("Given bookmark is not present at this view's snap");
}
if (DBTraceUtils.lowerEndpoint(lifespan) == program.snap) {
bm.delete();
}
else {
bm.setLifespan(lifespan.intersection(Range.lessThan(program.snap)));
}
}
@Override
public void removeBookmark(Bookmark bookmark) {
if (!(bookmark instanceof DBTraceBookmark)) {
throw new IllegalArgumentException("Given bookmark is not part of this trace");
}
DBTraceBookmark dbBookmark = (DBTraceBookmark) bookmark;
if (dbBookmark.getTrace() != program.trace) {
throw new IllegalArgumentException("Given bookmark is not part of this trace");
}
doDeleteOrTruncateLifespan(dbBookmark);
}
@Override
public void removeBookmarks(String type) {
try (LockHold hold = program.trace.lockWrite()) {
for (DBTraceBookmark bm : bookmarkManager.getBookmarksByType(type)) {
if (!bm.getLifespan().contains(program.snap)) {
continue;
}
doDeleteOrTruncateLifespan(bm);
}
}
}
@Override
public void removeBookmarks(String type, String category, TaskMonitor monitor)
throws CancelledException {
try (LockHold hold = program.trace.lockWrite()) {
Collection<DBTraceBookmark> bookmarks = bookmarkManager.getBookmarksByType(type);
monitor.initialize(bookmarks.size());
for (DBTraceBookmark bm : bookmarks) {
monitor.checkCanceled();
monitor.incrementProgress(1);
if (!bm.getLifespan().contains(program.snap)) {
continue;
}
if (!category.equals(bm.getCategory())) {
continue;
}
doDeleteOrTruncateLifespan(bm);
}
}
}
protected void doRemoveByAddressSet(AddressSetView set, TaskMonitor monitor,
Predicate<? super TraceBookmark> predicate) throws CancelledException {
try (LockHold hold = program.trace.lockWrite()) {
monitor.initialize(set.getNumAddresses());
for (AddressRange rng : set) {
monitor.checkCanceled();
monitor.incrementProgress(rng.getLength());
DBTraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(rng.getAddressSpace(), false);
if (space == null) {
continue;
}
for (TraceBookmark bm : space.getBookmarksIntersecting(
Range.closed(program.snap, program.snap), rng)) {
monitor.checkCanceled();
if (!bm.getLifespan().contains(program.snap)) {
continue;
}
if (!predicate.test(bm)) {
continue;
}
doDeleteOrTruncateLifespan(bm);
}
}
}
}
@Override
public void removeBookmarks(AddressSetView set, TaskMonitor monitor) throws CancelledException {
doRemoveByAddressSet(set, monitor, bm -> true);
}
@Override
public void removeBookmarks(AddressSetView set, String type, TaskMonitor monitor)
throws CancelledException {
// TODO: May want to add two two-field indices to trace bookmark manager:
// <Type,Location> and <Location,Type>
doRemoveByAddressSet(set, monitor, bm -> type.equals(bm.getTypeString()));
}
@Override
public void removeBookmarks(AddressSetView set, String type, String category,
TaskMonitor monitor) throws CancelledException {
doRemoveByAddressSet(set, monitor,
bm -> type.equals(bm.getTypeString()) && category.equals(bm.getCategory()));
}
@Override
public Bookmark[] getBookmarks(Address addr) {
try (LockHold hold = program.trace.lockRead()) {
DBTraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(addr.getAddressSpace(), false);
if (space == null) {
return EMPTY_BOOKMARK_ARRAY;
}
List<Bookmark> list = new ArrayList<>();
for (long s : program.viewport.getOrderedSnaps()) {
for (TraceBookmark bm : space.getBookmarksAt(s, addr)) {
if (!bm.getLifespan().contains(program.snap)) {
continue;
}
list.add(bm);
}
}
return list.toArray(new Bookmark[list.size()]);
}
}
@Override
public Bookmark[] getBookmarks(Address address, String type) {
try (LockHold hold = program.trace.lockRead()) {
DBTraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(address.getAddressSpace(), false);
if (space == null) {
return EMPTY_BOOKMARK_ARRAY;
}
List<Bookmark> list = new ArrayList<>();
for (long s : program.viewport.getOrderedSnaps()) {
for (TraceBookmark bm : space.getBookmarksAt(s, address)) {
if (!type.equals(bm.getTypeString())) {
continue;
}
list.add(bm);
}
}
return list.toArray(new Bookmark[list.size()]);
}
}
@Override
public AddressSetView getBookmarkAddresses(String type) {
try (LockHold hold = program.trace.lockRead()) {
// TODO: Implement the interface to be lazy?
AddressSet result = new AddressSet();
TraceBookmarkType bmt = bookmarkManager.getBookmarkType(type);
if (bmt == null) {
return result;
}
for (TraceBookmark bm : bmt.getBookmarks()) {
if (bm.getAddress().getAddressSpace().isRegisterSpace()) {
continue;
}
if (!program.viewport.containsAnyUpper(bm.getLifespan())) {
continue;
}
result.add(bm.getAddress());
}
return result;
}
}
/**
* A less restrictive casting of
* {@link IteratorUtils#filteredIterator(Iterator, org.apache.commons.collections4.Predicate)}.
*
* This one understands that the predicate will be testing things of the (possibly
* more-specific) type of elements in the original iterator, not thatof the returned iterator.
*
* @param it
* @param predicate
* @return
*/
@SuppressWarnings("unchecked")
protected static <T, U extends T> Iterator<T> filteredIterator(Iterator<U> it,
Predicate<? super U> predicate) {
return (Iterator<T>) Iterators.filter(it, e -> predicate.test(e));
}
@Override
public Iterator<Bookmark> getBookmarksIterator(String type) {
TraceBookmarkType bmt = bookmarkManager.getBookmarkType(type);
if (bmt == null) {
return Collections.emptyIterator();
}
// TODO: May want to offer memory-only and/or register-only bookmark iterators
return filteredIterator(bmt.getBookmarks().iterator(),
bm -> !bm.getAddress().getAddressSpace().isRegisterSpace() &&
program.viewport.containsAnyUpper(bm.getLifespan()));
}
@Override
public Iterator<Bookmark> getBookmarksIterator() {
// TODO: This seems terribly inefficient. We'll have to see how/when it's used.
return NestedIterator.start(bookmarkManager.getActiveMemorySpaces().iterator(),
space -> filteredIterator(space.getAllBookmarks().iterator(),
bm -> program.viewport.containsAnyUpper(bm.getLifespan())));
}
protected Comparator<Bookmark> getBookmarkComparator(boolean forward) {
return forward
? (b1, b2) -> b1.getAddress().compareTo(b2.getAddress())
: (b1, b2) -> -b1.getAddress().compareTo(b2.getAddress());
}
@Override
public Iterator<Bookmark> getBookmarksIterator(Address startAddress, boolean forward) {
AddressFactory factory = program.getAddressFactory();
AddressSet allMemory = factory.getAddressSet();
AddressSet within = forward ? factory.getAddressSet(startAddress, allMemory.getMaxAddress())
: factory.getAddressSet(allMemory.getMinAddress(), startAddress);
return NestedIterator.start(within.iterator(forward), rng -> {
DBTraceBookmarkSpace space =
bookmarkManager.getBookmarkSpace(rng.getAddressSpace(), false);
if (space == null) {
return Collections.emptyIterator();
}
return program.viewport.mergedIterator(
s -> space.getBookmarksIntersecting(Range.closed(s, s), rng).iterator(),
getBookmarkComparator(forward));
});
}
@Override
public Bookmark getBookmark(long id) {
TraceBookmark bm = bookmarkManager.getBookmark(id);
if (bm == null || !bm.getLifespan().contains(program.snap)) {
return null;
}
return bm;
}
@Override
public boolean hasBookmarks(String type) {
// TODO: Filter by snap?
// Not really used anywhere, anyway.
return bookmarkManager.getOrDefineBookmarkType(type).hasBookmarks();
}
@Override
public int getBookmarkCount(String type) {
// TODO: Filter by snap?
// Most uses of this are for initializing monitors or as heuristics in analyzers.
return bookmarkManager.getOrDefineBookmarkType(type).countBookmarks();
}
@Override
public int getBookmarkCount() {
// TODO: Filter by snap?
// Not doing so here causes a slight display error in the bookmark table.
// It will say "Row i of n", but n will be greater than the actual number of rows.
int sum = 0;
for (DBTraceBookmarkSpace space : bookmarkManager.getActiveMemorySpaces()) {
sum += space.getAllBookmarks().size();
}
return sum;
}
@Override
public Trace getTrace() {
return program.trace;
}
@Override
public long getSnap() {
return program.snap;
}
@Override
public TraceProgramView getProgram() {
return program;
}
}
| apache-2.0 |
yiwent/Staudy | chapter1/HelloWorld/app/src/test/java/com/yiwen/helloworld/ExampleUnitTest.java | 398 | package com.yiwen.helloworld;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
robinsteel/Sqawsh | src/main/java/squash/booking/lambdas/RestoreBookingsAndBookingRulesLambda.java | 4554 | /**
* Copyright 2015-2017 Robin Steel
*
* 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 squash.booking.lambdas;
import squash.booking.lambdas.core.BackupManager;
import squash.booking.lambdas.core.BookingManager;
import squash.booking.lambdas.core.IBackupManager;
import squash.booking.lambdas.core.IBookingManager;
import squash.booking.lambdas.core.ILifecycleManager;
import squash.booking.lambdas.core.IRuleManager;
import squash.booking.lambdas.core.LifecycleManager;
import squash.booking.lambdas.core.RuleManager;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import java.util.Optional;
/**
* AWS Lambda function to restore bookings and booking rules to the database.
*
* <p>This is manually invoked at the lambda console, passing in the set
* of bookings and booking rules to be restored in the same JSON format
* as provided by the database backup lambda.
*
* @author robinsteel19@outlook.com (Robin Steel)
*/
public class RestoreBookingsAndBookingRulesLambda {
private Optional<IBackupManager> backupManager;
private Optional<IRuleManager> ruleManager;
private Optional<ILifecycleManager> lifecycleManager;
private Optional<IBookingManager> bookingManager;
public RestoreBookingsAndBookingRulesLambda() {
backupManager = Optional.empty();
ruleManager = Optional.empty();
lifecycleManager = Optional.empty();
bookingManager = Optional.empty();
}
/**
* Returns the {@link squash.booking.lambdas.core.IRuleManager}.
*/
protected IRuleManager getRuleManager(LambdaLogger logger) throws Exception {
// Use a getter here so unit tests can substitute a mock manager
if (!ruleManager.isPresent()) {
ruleManager = Optional.of(new RuleManager());
ruleManager.get().initialise(getBookingManager(logger), getLifecycleManager(logger), logger);
}
return ruleManager.get();
}
/**
* Returns the {@link squash.booking.lambdas.core.ILifecycleManager}.
*/
protected ILifecycleManager getLifecycleManager(LambdaLogger logger) throws Exception {
// Use a getter here so unit tests can substitute a mock manager
if (!lifecycleManager.isPresent()) {
lifecycleManager = Optional.of(new LifecycleManager());
lifecycleManager.get().initialise(logger);
}
return lifecycleManager.get();
}
/**
* Returns the {@link squash.booking.lambdas.core.IBookingManager}.
*/
protected IBookingManager getBookingManager(LambdaLogger logger) throws Exception {
// Use a getter here so unit tests can substitute a mock manager
if (!bookingManager.isPresent()) {
bookingManager = Optional.of(new BookingManager());
bookingManager.get().initialise(logger);
}
return bookingManager.get();
}
/**
* Returns the {@link squash.booking.lambdas.core.IBackupManager}.
*/
protected IBackupManager getBackupManager(LambdaLogger logger) throws Exception {
// Use a getter here so unit tests can substitute a mock manager
if (!backupManager.isPresent()) {
backupManager = Optional.of(new BackupManager());
backupManager.get().initialise(getBookingManager(logger), getRuleManager(logger), logger);
}
return backupManager.get();
}
/**
* Restore bookings and booking rules to the database.
*
* @param request containing bookings and booking rules to restore.
* @return response.
*/
public RestoreBookingsAndBookingRulesLambdaResponse restoreBookingsAndBookingRules(
RestoreBookingsAndBookingRulesLambdaRequest request, Context context) throws Exception {
LambdaLogger logger = context.getLogger();
logger.log("Restoring bookings and booking rules for request: " + request.toString());
getBackupManager(logger).restoreAllBookingsAndBookingRules(request.getBookings(),
request.getBookingRules(), request.getClearBeforeRestore());
logger.log("Finished restoring bookings and booking rules");
return new RestoreBookingsAndBookingRulesLambdaResponse();
}
} | apache-2.0 |
stackify/stackify-api-java | src/test/java/com/stackify/api/EnvironmentDetailTest.java | 2274 | /*
* Copyright 2013 Stackify
*
* 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.stackify.api;
import org.junit.Assert;
import org.junit.Test;
/**
* EnvironmentDetail JUnit Test
*
* @author Eric Martin
*/
public class EnvironmentDetailTest {
/**
* testBuilder
*/
@Test
public void testBuilder() {
String deviceName = "device";
String appName = "app";
String appLocation = "location";
String configuredAppName = "configuredAppName";
String configuredEnvironmentName = "configuredEnvironmentName";
EnvironmentDetail.Builder builder = EnvironmentDetail.newBuilder();
builder.deviceName(deviceName);
builder.appName(appName);
builder.appLocation(appLocation);
builder.configuredAppName(configuredAppName);
builder.configuredEnvironmentName(configuredEnvironmentName);
EnvironmentDetail environment = builder.build();
Assert.assertNotNull(environment);
Assert.assertEquals(deviceName, environment.getDeviceName());
Assert.assertEquals(appName, environment.getAppName());
Assert.assertEquals(appLocation, environment.getAppLocation());
Assert.assertEquals(configuredAppName, environment.getConfiguredAppName());
Assert.assertEquals(configuredEnvironmentName, environment.getConfiguredEnvironmentName());
EnvironmentDetail environmentCopy = environment.toBuilder().build();
Assert.assertNotNull(environmentCopy);
Assert.assertEquals(deviceName, environmentCopy.getDeviceName());
Assert.assertEquals(appName, environmentCopy.getAppName());
Assert.assertEquals(appLocation, environmentCopy.getAppLocation());
Assert.assertEquals(configuredAppName, environmentCopy.getConfiguredAppName());
Assert.assertEquals(configuredEnvironmentName, environmentCopy.getConfiguredEnvironmentName());
}
}
| apache-2.0 |
concourse/baggageclaim | uidgid/uidgidfakes/fake_translator.go | 4554 | // Code generated by counterfeiter. DO NOT EDIT.
package uidgidfakes
import (
"os"
"os/exec"
"sync"
"github.com/concourse/baggageclaim/uidgid"
)
type FakeTranslator struct {
TranslateCommandStub func(*exec.Cmd)
translateCommandMutex sync.RWMutex
translateCommandArgsForCall []struct {
arg1 *exec.Cmd
}
TranslatePathStub func(string, os.FileInfo, error) error
translatePathMutex sync.RWMutex
translatePathArgsForCall []struct {
arg1 string
arg2 os.FileInfo
arg3 error
}
translatePathReturns struct {
result1 error
}
translatePathReturnsOnCall map[int]struct {
result1 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeTranslator) TranslateCommand(arg1 *exec.Cmd) {
fake.translateCommandMutex.Lock()
fake.translateCommandArgsForCall = append(fake.translateCommandArgsForCall, struct {
arg1 *exec.Cmd
}{arg1})
fake.recordInvocation("TranslateCommand", []interface{}{arg1})
fake.translateCommandMutex.Unlock()
if fake.TranslateCommandStub != nil {
fake.TranslateCommandStub(arg1)
}
}
func (fake *FakeTranslator) TranslateCommandCallCount() int {
fake.translateCommandMutex.RLock()
defer fake.translateCommandMutex.RUnlock()
return len(fake.translateCommandArgsForCall)
}
func (fake *FakeTranslator) TranslateCommandCalls(stub func(*exec.Cmd)) {
fake.translateCommandMutex.Lock()
defer fake.translateCommandMutex.Unlock()
fake.TranslateCommandStub = stub
}
func (fake *FakeTranslator) TranslateCommandArgsForCall(i int) *exec.Cmd {
fake.translateCommandMutex.RLock()
defer fake.translateCommandMutex.RUnlock()
argsForCall := fake.translateCommandArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeTranslator) TranslatePath(arg1 string, arg2 os.FileInfo, arg3 error) error {
fake.translatePathMutex.Lock()
ret, specificReturn := fake.translatePathReturnsOnCall[len(fake.translatePathArgsForCall)]
fake.translatePathArgsForCall = append(fake.translatePathArgsForCall, struct {
arg1 string
arg2 os.FileInfo
arg3 error
}{arg1, arg2, arg3})
fake.recordInvocation("TranslatePath", []interface{}{arg1, arg2, arg3})
fake.translatePathMutex.Unlock()
if fake.TranslatePathStub != nil {
return fake.TranslatePathStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.translatePathReturns
return fakeReturns.result1
}
func (fake *FakeTranslator) TranslatePathCallCount() int {
fake.translatePathMutex.RLock()
defer fake.translatePathMutex.RUnlock()
return len(fake.translatePathArgsForCall)
}
func (fake *FakeTranslator) TranslatePathCalls(stub func(string, os.FileInfo, error) error) {
fake.translatePathMutex.Lock()
defer fake.translatePathMutex.Unlock()
fake.TranslatePathStub = stub
}
func (fake *FakeTranslator) TranslatePathArgsForCall(i int) (string, os.FileInfo, error) {
fake.translatePathMutex.RLock()
defer fake.translatePathMutex.RUnlock()
argsForCall := fake.translatePathArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeTranslator) TranslatePathReturns(result1 error) {
fake.translatePathMutex.Lock()
defer fake.translatePathMutex.Unlock()
fake.TranslatePathStub = nil
fake.translatePathReturns = struct {
result1 error
}{result1}
}
func (fake *FakeTranslator) TranslatePathReturnsOnCall(i int, result1 error) {
fake.translatePathMutex.Lock()
defer fake.translatePathMutex.Unlock()
fake.TranslatePathStub = nil
if fake.translatePathReturnsOnCall == nil {
fake.translatePathReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.translatePathReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeTranslator) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.translateCommandMutex.RLock()
defer fake.translateCommandMutex.RUnlock()
fake.translatePathMutex.RLock()
defer fake.translatePathMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeTranslator) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ uidgid.Translator = new(FakeTranslator)
| apache-2.0 |
Hivedi/ErrorReportAdapter | app/src/test/java/com/hivedi/errorreportadapterexample/ExampleUnitTest.java | 329 | package com.hivedi.errorreportadapterexample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
VHAINNOVATIONS/Maternity-Tracker | Dashboard/va.gov.artemis.commands/Vpr/Data/Allergy.cs | 1567 | // Originally submitted to OSEHRA 2/21/2017 by DSS, Inc.
// Authored by DSS, Inc. 2014-2017
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using VA.Gov.Artemis.Vista.Utility;
namespace VA.Gov.Artemis.Commands.Vpr.Data
{
[Serializable]
public class Allergy : ClinicalItem
{
// TODO: Implement....
// comment
// removed
// severity
[XmlElement("assessment")]
public ValueElement Assessment { get; set; }
[XmlArray("drugIngredients")]
[XmlArrayItem("drugIngredient")]
public List<NameElement> DrugIngredients { get; set; }
[XmlArray("drugClasses")]
[XmlArrayItem("drugClass")]
public List<NameElement> DrugClasses { get; set; }
[XmlElement("entered")]
public VprDateTime Entered { get; set; }
[XmlElement("localCode")]
public ValueElement LocalCode { get; set; }
[XmlElement("mechanism")]
public ValueElement Mechanism { get; set; }
[XmlArray("reactions")]
[XmlArrayItem("reaction")]
public List<CodeElement> Reactions { get; set; }
[XmlElement("source")]
public ValueElement Source { get; set; }
[XmlElement("type")]
public CodeElement AllergyType { get; set; }
[XmlElement("vuid")]
public ValueElement Vuid { get; set; }
[XmlElement("verified")]
public VprDateTime Verified { get; set; }
}
}
| apache-2.0 |
sgudupat/force5 | src/main/java/com/force/five/app/domain/PersistentAuditEvent.java | 1803 | package com.force.five.app.domain;
import java.time.LocalDateTime;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* Persist AuditEvent managed by the Spring Boot actuator
* @see org.springframework.boot.actuate.audit.AuditEvent
*/
@Entity
@Table(name = "jhi_persistent_audit_event")
public class PersistentAuditEvent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "event_id")
private Long id;
@NotNull
@Column(nullable = false)
private String principal;
@Column(name = "event_date")
private LocalDateTime auditEventDate;
@Column(name = "event_type")
private String auditEventType;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
private Map<String, String> data = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public LocalDateTime getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(LocalDateTime auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
}
| apache-2.0 |
Obisoft2017/ObisoftWebCore | src/ObisoftWebCore/Models/ManageViewModels/SetPasswordViewModel.cs | 769 | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ObisoftWebCore.Models.ManageViewModels
{
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| apache-2.0 |
amanharitsh123/zulip | zerver/views/zephyr.py | 2177 | from typing import Any, List, Dict, Optional, Callable, Tuple, Iterable, Sequence, Text
from django.conf import settings
from django.http import HttpResponse, HttpRequest
from django.utils.translation import ugettext as _
from zerver.decorator import authenticated_json_view
from zerver.lib.ccache import make_ccache
from zerver.lib.request import has_request_variables, REQ, JsonableError
from zerver.lib.response import json_success, json_error
from zerver.lib.str_utils import force_str
from zerver.models import UserProfile
import base64
import logging
import subprocess
import ujson
# Hack for mit.edu users whose Kerberos usernames don't match what they zephyr
# as. The key is for Kerberos and the value is for zephyr.
kerberos_alter_egos = {
'golem': 'ctl',
}
@authenticated_json_view
@has_request_variables
def webathena_kerberos_login(request, user_profile,
cred=REQ(default=None)):
# type: (HttpRequest, UserProfile, Text) -> HttpResponse
global kerberos_alter_egos
if cred is None:
return json_error(_("Could not find Kerberos credential"))
if not user_profile.realm.webathena_enabled:
return json_error(_("Webathena login not enabled"))
try:
parsed_cred = ujson.loads(cred)
user = parsed_cred["cname"]["nameString"][0]
if user in kerberos_alter_egos:
user = kerberos_alter_egos[user]
assert(user == user_profile.email.split("@")[0])
ccache = make_ccache(parsed_cred)
except Exception:
return json_error(_("Invalid Kerberos cache"))
# TODO: Send these data via (say) rabbitmq
try:
subprocess.check_call(["ssh", settings.PERSONAL_ZMIRROR_SERVER, "--",
"/home/zulip/zulip/api/integrations/zephyr/process_ccache",
force_str(user),
force_str(user_profile.api_key),
force_str(base64.b64encode(ccache))])
except Exception:
logging.exception("Error updating the user's ccache")
return json_error(_("We were unable to setup mirroring for you"))
return json_success()
| apache-2.0 |
HubSpot/jinjava | src/test/java/com/hubspot/jinjava/lib/filter/TruncateFilterTest.java | 1653 | package com.hubspot.jinjava.lib.filter;
import static org.assertj.core.api.Assertions.assertThat;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TruncateFilterTest {
@Mock
JinjavaInterpreter interpreter;
@InjectMocks
TruncateFilter filter;
@Test
public void itPassesThroughSmallEnoughText() throws Exception {
String s = StringUtils.rightPad("", 255, 'x');
assertThat(filter.filter(s, interpreter)).isEqualTo(s);
}
@Test
public void itTruncatesText() throws Exception {
assertThat(
filter
.filter(StringUtils.rightPad("", 256, 'x') + "y", interpreter, "255", "True")
.toString()
)
.hasSize(258)
.endsWith("x...");
}
@Test
public void itTruncatesToSpecifiedLength() throws Exception {
assertThat(filter.filter("foo bar", interpreter, "5", "True")).isEqualTo("foo b...");
}
@Test
public void itDiscardsLastWordWhenKillwordsFalse() throws Exception {
assertThat(filter.filter("foo bar", interpreter, "5")).isEqualTo("foo ...");
}
@Test
public void itTruncatesWithDifferentEndingIfSpecified() throws Exception {
assertThat(filter.filter("foo bar", interpreter, "5", "True", "!"))
.isEqualTo("foo b!");
}
@Test
public void itTruncatesGivenNegativeLength() throws Exception {
assertThat(filter.filter("foo bar", interpreter, "-1", "True")).isEqualTo("...");
}
}
| apache-2.0 |
oillio/dropwizard-guice | src/test/java/com/hubspot/dropwizard/guice/sample/command/TestConfiguredCommand.java | 1005 | package com.hubspot.dropwizard.guice.sample.command;
import com.hubspot.dropwizard.guice.ConfigData.Config;
import com.hubspot.dropwizard.guice.InjectedConfiguredCommand;
import com.hubspot.dropwizard.guice.Run;
import com.hubspot.dropwizard.guice.sample.HelloWorldConfiguration;
import io.dropwizard.setup.Bootstrap;
import net.sourceforge.argparse4j.inf.Namespace;
public class TestConfiguredCommand extends InjectedConfiguredCommand<HelloWorldConfiguration> {
public static String configName;
public static Bootstrap bootstrap;
public static Namespace namespace;
public TestConfiguredCommand() {
super("SimpleCommand", "A command that does not do much.");
}
@Run
public void run(@Config("defaultName") String name,
Bootstrap bootstrap,
Namespace namespace) {
TestConfiguredCommand.configName = name;
TestConfiguredCommand.bootstrap = bootstrap;
TestConfiguredCommand.namespace = namespace;
}
}
| apache-2.0 |
BannedWolf/tankgame | BattleTank/Source/BattleTank/Tank.cpp | 689 | // Fill out your copyright notice in the Description page of Project Settings.
#include "BattleTank.h"
#include "Tank.h"
// Sets default values
ATank::ATank()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ATank::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ATank::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void ATank::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
| apache-2.0 |
uw-it-aca/django-userservice | userservice/username.py | 596 | # Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.conf import settings
def _get_format():
return getattr(settings, "REMOTE_USER_FORMAT", "eppn")
def expect_uid():
username_format = _get_format()
return username_format is not None and\
(username_format == "uid" or username_format == "uwnetid")
def get_uid(username):
if username is not None and len(username) and expect_uid():
try:
(username, domain) = username.split('@', 1)
except ValueError as ex:
pass
return username
| apache-2.0 |
SpaceTrafficDevelopers/SpaceTraffic | Core/Entities/Base.cs | 2079 | /**
Copyright 2010 FAV ZCU
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 System.Linq;
using System.Text;
namespace SpaceTraffic.Entities
{
/// <summary>
/// Class representing entity of base on planet
/// </summary>
public class Base
{
/// <summary>
/// Identification number
/// </summary>
public int BaseId { get; set; }
/// <summary>
/// Name of the base
/// </summary>
public string BaseName { get; set; }
/// <summary>
/// Planet on which base is
/// </summary>
public string Planet { get; set; }
/// <summary>
/// Simple name of planet
/// </summary>
/// <value>
/// The name of the planet.
/// </value>
public string PlanetName
{
get
{
string[] planetString = this.Planet.Split('\\');
return planetString[1];
}
}
/// <summary>
/// Simple name of starSystem
/// </summary>
/// <value>
/// The name of the planet.
/// </value>
public string StarSystemName
{
get
{
string[] planetString = this.Planet.Split('\\');
return planetString[0];
}
}
/// <summary>
/// Trader which trades on the planet
/// </summary>
public Trader Trader { get; set; }
/// <summary>
/// Collection of spaceships
/// </summary>
public virtual ICollection<SpaceShip> SpaceShips { get; set; }
/// <summary>
/// Colection of factories
/// </summary>
public virtual ICollection<Factory> Factories { get; set; }
}
}
| apache-2.0 |
appccelerate/io | source/Appccelerate.IO/Access/IFileExtension.g.cs | 13538 | //-------------------------------------------------------------------------------
// <copyright file="IFileExtension.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.IO.Access
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using System.Text;
/// <summary>
/// Interface for file access extensions
/// </summary>
[CompilerGenerated]
public interface IFileExtension
{
void BeginGetLastWriteTime(string path);
void EndGetLastWriteTime(DateTime result, string path);
void FailGetLastWriteTime(ref Exception exception, string path);
void BeginGetLastWriteTimeUtc(string path);
void EndGetLastWriteTimeUtc(DateTime result, string path);
void FailGetLastWriteTimeUtc(ref Exception exception, string path);
void BeginMove(string sourceFileName, string destFileName);
void EndMove(string sourceFileName, string destFileName);
void FailMove(ref Exception exception, string sourceFileName, string destFileName);
void BeginOpenRead(string path);
void EndOpenRead(Stream result, string path);
void FailOpenRead(ref Exception exception, string path);
void BeginOpenText(string path);
void EndOpenText(StreamReader result, string path);
void FailOpenText(ref Exception exception, string path);
void BeginOpenWrite(string path);
void EndOpenWrite(FileStream result, string path);
void FailOpenWrite(ref Exception exception, string path);
void BeginReplace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
void EndReplace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
void FailReplace(ref Exception exception, string sourceFileName, string destinationFileName, string destinationBackupFileName);
void BeginReplace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
void EndReplace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
void FailReplace(ref Exception exception, string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
void BeginSetAccessControl(string path, FileSecurity fileSecurity);
void EndSetAccessControl(string path, FileSecurity fileSecurity);
void FailSetAccessControl(ref Exception exception, string path, FileSecurity fileSecurity);
void BeginSetCreationTime(string path, DateTime creationTime);
void EndSetCreationTime(string path, DateTime creationTime);
void FailSetCreationTime(ref Exception exception, string path, DateTime creationTime);
void BeginSetCreationTimeUtc(string path, DateTime creationTimeUtc);
void EndSetCreationTimeUtc(string path, DateTime creationTimeUtc);
void FailSetCreationTimeUtc(ref Exception exception, string path, DateTime creationTimeUtc);
void BeginSetLastAccessTime(string path, DateTime lastAccessTime);
void EndSetLastAccessTime(string path, DateTime lastAccessTime);
void FailSetLastAccessTime(ref Exception exception, string path, DateTime lastAccessTime);
void BeginSetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc);
void EndSetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc);
void FailSetLastAccessTimeUtc(ref Exception exception, string path, DateTime lastAccessTimeUtc);
void BeginSetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
void EndSetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
void FailSetLastWriteTimeUtc(ref Exception exception, string path, DateTime lastWriteTimeUtc);
void BeginDelete(string path);
void EndDelete(string path);
void FailDelete(ref Exception exception, string path);
void BeginCopy(string sourceFileName, string destFileName);
void EndCopy(string sourceFileName, string destFileName);
void FailCopy(ref Exception exception, string sourceFileName, string destFileName);
void BeginCopy(string sourceFileName, string destFileName, bool overwrite);
void EndCopy(string sourceFileName, string destFileName, bool overwrite);
void FailCopy(ref Exception exception, string sourceFileName, string destFileName, bool overwrite);
void BeginCreateText(string path);
void EndCreateText(StreamWriter result, string path);
void FailCreateText(ref Exception exception, string path);
void BeginGetAttributes(string path);
void EndGetAttributes(FileAttributes result, string path);
void FailGetAttributes(ref Exception exception, string path);
void BeginSetLastWriteTime(string path, DateTime lastWriteTime);
void EndSetLastWriteTime(string path, DateTime lastWriteTime);
void FailSetLastWriteTime(ref Exception exception, string path, DateTime lastWriteTime);
void BeginSetAttributes(string path, FileAttributes fileAttributes);
void EndSetAttributes(string path, FileAttributes fileAttributes);
void FailSetAttributes(ref Exception exception, string path, FileAttributes fileAttributes);
void BeginExists(string path);
void EndExists(bool result, string path);
void FailExists(ref Exception exception, string path);
void BeginReadAllBytes(string path);
void EndReadAllBytes(byte[] result, string path);
void FailReadAllBytes(ref Exception exception, string path);
void BeginReadAllLines(string path, Encoding encoding);
void EndReadAllLines(string[] result, string path, Encoding encoding);
void FailReadAllLines(ref Exception exception, string path, Encoding encoding);
void BeginReadAllLines(string path);
void EndReadAllLines(string[] result, string path);
void FailReadAllLines(ref Exception exception, string path);
void BeginReadAllText(string path, Encoding encoding);
void EndReadAllText(string result, string path, Encoding encoding);
void FailReadAllText(ref Exception exception, string path, Encoding encoding);
void BeginReadAllText(string path);
void EndReadAllText(string result, string path);
void FailReadAllText(ref Exception exception, string path);
void BeginReadLines(string path);
void EndReadLines(IEnumerable<string> result, string path);
void FailReadLines(ref Exception exception, string path);
void BeginReadLines(string path, Encoding encoding);
void EndReadLines(IEnumerable<string> result, string path, Encoding encoding);
void FailReadLines(ref Exception exception, string path, Encoding encoding);
void BeginWriteAllLines(string path, IEnumerable<string> contents, Encoding encoding);
void EndWriteAllLines(string path, IEnumerable<string> contents, Encoding encoding);
void FailWriteAllLines(ref Exception exception, string path, IEnumerable<string> contents, Encoding encoding);
void BeginWriteAllLines(string path, IEnumerable<string> contents);
void EndWriteAllLines(string path, IEnumerable<string> contents);
void FailWriteAllLines(ref Exception exception, string path, IEnumerable<string> contents);
void BeginWriteAllText(string path, string contents);
void EndWriteAllText(string path, string contents);
void FailWriteAllText(ref Exception exception, string path, string contents);
void BeginWriteAllText(string path, string contents, Encoding encoding);
void EndWriteAllText(string path, string contents, Encoding encoding);
void FailWriteAllText(ref Exception exception, string path, string contents, Encoding encoding);
void BeginWriteAllBytes(string path, byte[] bytes);
void EndWriteAllBytes(string path, byte[] bytes);
void FailWriteAllBytes(ref Exception exception, string path, byte[] bytes);
void BeginOpen(string path, FileMode mode);
void EndOpen(FileStream result, string path, FileMode mode);
void FailOpen(ref Exception exception, string path, FileMode mode);
void BeginOpen(string path, FileMode mode, FileAccess access);
void EndOpen(FileStream result, string path, FileMode mode, FileAccess access);
void FailOpen(ref Exception exception, string path, FileMode mode, FileAccess access);
void BeginOpen(string path, FileMode mode, FileAccess access, FileShare share);
void EndOpen(FileStream result, string path, FileMode mode, FileAccess access, FileShare share);
void FailOpen(ref Exception exception, string path, FileMode mode, FileAccess access, FileShare share);
void BeginAppendAllLines(string path, IEnumerable<string> contents);
void EndAppendAllLines(string path, IEnumerable<string> contents);
void FailAppendAllLines(ref Exception exception, string path, IEnumerable<string> contents);
void BeginAppendAllLines(string path, IEnumerable<string> contents, Encoding encoding);
void EndAppendAllLines(string path, IEnumerable<string> contents, Encoding encoding);
void FailAppendAllLines(ref Exception exception, string path, IEnumerable<string> contents, Encoding encoding);
void BeginAppendAllText(string path, string contents);
void EndAppendAllText(string path, string contents);
void FailAppendAllText(ref Exception exception, string path, string contents);
void BeginAppendAllText(string path, string contents, Encoding encoding);
void EndAppendAllText(string path, string contents, Encoding encoding);
void FailAppendAllText(ref Exception exception, string path, string contents, Encoding encoding);
void BeginAppendText(string path);
void EndAppendText(StreamWriter result, string path);
void FailAppendText(ref Exception exception, string path);
void BeginCreate(string path);
void EndCreate(FileStream result, string path);
void FailCreate(ref Exception exception, string path);
void BeginCreate(string path, int bufferSize);
void EndCreate(FileStream result, string path, int bufferSize);
void FailCreate(ref Exception exception, string path, int bufferSize);
void BeginCreate(string path, int bufferSize, FileOptions options);
void EndCreate(FileStream result, string path, int bufferSize, FileOptions options);
void FailCreate(ref Exception exception, string path, int bufferSize, FileOptions options);
void BeginCreate(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
void EndCreate(FileStream result, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
void FailCreate(ref Exception exception, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
void BeginDecrypt(string path);
void EndDecrypt(string path);
void FailDecrypt(ref Exception exception, string path);
void BeginEncrypt(string path);
void EndEncrypt(string path);
void FailEncrypt(ref Exception exception, string path);
void BeginGetAccessControl(string path);
void EndGetAccessControl(FileSecurity result, string path);
void FailGetAccessControl(ref Exception exception, string path);
void BeginGetAccessControl(string path, AccessControlSections includeSections);
void EndGetAccessControl(FileSecurity result, string path, AccessControlSections includeSections);
void FailGetAccessControl(ref Exception exception, string path, AccessControlSections includeSections);
void BeginGetCreationTime(string path);
void EndGetCreationTime(DateTime result, string path);
void FailGetCreationTime(ref Exception exception, string path);
void BeginGetCreationTimeUtc(string path);
void EndGetCreationTimeUtc(DateTime result, string path);
void FailGetCreationTimeUtc(ref Exception exception, string path);
void BeginGetLastAccessTime(string path);
void EndGetLastAccessTime(DateTime result, string path);
void FailGetLastAccessTime(ref Exception exception, string path);
void BeginGetLastAccessTimeUtc(string path);
void EndGetLastAccessTimeUtc(DateTime result, string path);
void FailGetLastAccessTimeUtc(ref Exception exception, string path);
}
} | apache-2.0 |
badvision/lawless-legends | Platform/Apple/tools/jace/src/main/java/jace/JaceUIController.java | 16871 | /*
* 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 jace;
import com.sun.glass.ui.Application;
import jace.core.Card;
import jace.core.Computer;
import jace.core.Motherboard;
import jace.core.Utility;
import jace.lawless.LawlessComputer;
import jace.lawless.LawlessHacks;
import jace.library.MediaCache;
import jace.library.MediaConsumer;
import jace.library.MediaConsumerParent;
import jace.library.MediaEntry;
import javafx.animation.FadeTransition;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.binding.NumberBinding;
import javafx.beans.binding.When;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.StringConverter;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author blurry
*/
public class JaceUIController {
@FXML
private URL location;
@FXML
private AnchorPane rootPane;
@FXML
private StackPane stackPane;
@FXML
private HBox notificationBox;
@FXML
private ImageView appleScreen;
@FXML
private BorderPane controlOverlay;
@FXML
private Slider speedSlider;
@FXML
private AnchorPane menuButtonPane;
@FXML
private Button menuButton;
@FXML
private ComboBox musicSelection;
Computer computer;
private final BooleanProperty aspectRatioCorrectionEnabled = new SimpleBooleanProperty(false);
@FXML
void initialize() {
assert rootPane != null : "fx:id=\"rootPane\" was not injected: check your FXML file 'JaceUI.fxml'.";
assert stackPane != null : "fx:id=\"stackPane\" was not injected: check your FXML file 'JaceUI.fxml'.";
assert notificationBox != null : "fx:id=\"notificationBox\" was not injected: check your FXML file 'JaceUI.fxml'.";
assert appleScreen != null : "fx:id=\"appleScreen\" was not injected: check your FXML file 'JaceUI.fxml'.";
speedSlider.setValue(1.0);
controlOverlay.setVisible(false);
menuButtonPane.setVisible(false);
controlOverlay.setFocusTraversable(false);
menuButtonPane.setFocusTraversable(false);
NumberBinding aspectCorrectedWidth = rootPane.heightProperty().multiply(3.0).divide(2.0);
NumberBinding width = new When(
aspectRatioCorrectionEnabled.and(aspectCorrectedWidth.lessThan(rootPane.widthProperty()))
).then(aspectCorrectedWidth).otherwise(rootPane.widthProperty());
appleScreen.fitWidthProperty().bind(width);
appleScreen.fitHeightProperty().bind(rootPane.heightProperty());
appleScreen.setVisible(false);
rootPane.setOnDragEntered(this::processDragEnteredEvent);
rootPane.setOnDragExited(this::processDragExitedEvent);
rootPane.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null)));
rootPane.setOnMouseMoved(this::showMenuButton);
rootPane.setOnMouseExited(this::hideControlOverlay);
menuButton.setOnMouseClicked(this::showControlOverlay);
controlOverlay.setOnMouseClicked(this::hideControlOverlay);
delayTimer.getKeyFrames().add(new KeyFrame(Duration.millis(3000), evt -> {
hideControlOverlay(null);
rootPane.requestFocus();
}));
}
private void showMenuButton(MouseEvent evt) {
if (!evt.isPrimaryButtonDown() && !evt.isSecondaryButtonDown() && !controlOverlay.isVisible()) {
resetMenuButtonTimer();
if (!menuButtonPane.isVisible()) {
menuButtonPane.setVisible(true);
FadeTransition ft = new FadeTransition(Duration.millis(500), menuButtonPane);
ft.setFromValue(0.0);
ft.setToValue(1.0);
ft.play();
}
}
rootPane.requestFocus();
}
Timeline delayTimer = new Timeline();
private void resetMenuButtonTimer() {
delayTimer.playFromStart();
}
private void showControlOverlay(MouseEvent evt) {
if (!evt.isPrimaryButtonDown() && !evt.isSecondaryButtonDown()) {
delayTimer.stop();
menuButtonPane.setVisible(false);
controlOverlay.setVisible(true);
FadeTransition ft = new FadeTransition(Duration.millis(500), controlOverlay);
ft.setFromValue(0.0);
ft.setToValue(1.0);
ft.play();
rootPane.requestFocus();
}
}
private void hideControlOverlay(MouseEvent evt) {
if (evt == null || evt.getSource() != null && (
evt.getSource() == musicSelection ||
(evt.getSource() == rootPane && musicSelection.isFocused())
)) {
return;
}
if (menuButtonPane.isVisible()) {
FadeTransition ft1 = new FadeTransition(Duration.millis(500), menuButtonPane);
ft1.setFromValue(1.0);
ft1.setToValue(0.0);
ft1.setOnFinished(evt1 -> menuButtonPane.setVisible(false));
ft1.play();
}
if (controlOverlay.isVisible()) {
FadeTransition ft2 = new FadeTransition(Duration.millis(500), controlOverlay);
ft2.setFromValue(1.0);
ft2.setToValue(0.0);
ft2.setOnFinished(evt1 -> controlOverlay.setVisible(false));
ft2.play();
}
}
protected double convertSpeedToRatio(Double setting) {
if (setting < 1.0) {
return 0.5;
} else if (setting == 1.0) {
return 1.0;
} else if (setting >= 10) {
return Double.MAX_VALUE;
} else {
double val = Math.pow(2.0, (setting - 1.0) / 1.5);
val = Math.floor(val * 2.0) / 2.0;
if (val > 2.0) {
val = Math.floor(val);
}
return val;
}
}
private void connectControls(Stage primaryStage) {
connectButtons(controlOverlay);
if (computer.getKeyboard() != null) {
EventHandler<KeyEvent> keyboardHandler = computer.getKeyboard().getListener();
primaryStage.setOnShowing(evt -> computer.getKeyboard().resetState());
rootPane.setOnKeyPressed(keyboardHandler);
rootPane.setOnKeyReleased(keyboardHandler);
rootPane.setFocusTraversable(true);
}
speedSlider.setMinorTickCount(0);
speedSlider.setMajorTickUnit(1);
speedSlider.setLabelFormatter(new StringConverter<Double>() {
@Override
public String toString(Double val) {
if (val < 1.0) {
return "Half";
} else if (val >= 10.0) {
return "∞";
}
double v = convertSpeedToRatio(val);
if (v != Math.floor(v)) {
return v + "x";
} else {
return (int) v + "x";
}
}
@Override
public Double fromString(String string) {
return 1.0;
}
});
speedSlider.valueProperty().addListener((val, oldValue, newValue) -> setSpeed(newValue.doubleValue()));
Platform.runLater(() -> {
speedSlider.setValue(Emulator.logic.speedSetting);
// Kind of redundant but make sure speed is properly set as if the user did it
setSpeed(Emulator.logic.speedSetting);
});
musicSelection.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) ->
((LawlessHacks) ((LawlessComputer) computer).activeCheatEngine).changeMusicScore(String.valueOf(newValue))
);
}
private void connectButtons(Node n) {
if (n instanceof Button) {
Button button = (Button) n;
Runnable action = Utility.getNamedInvokableAction(button.getText());
button.setOnMouseClicked(evt -> action.run());
} else if (n instanceof Parent) {
((Parent) n).getChildrenUnmodifiable().forEach(child -> connectButtons(child));
}
}
protected void setSpeed(double speed) {
Emulator.logic.speedSetting = (int) speed;
double speedRatio = convertSpeedToRatio(speed);
if (speedSlider.getValue() != speed) {
Platform.runLater(()->speedSlider.setValue(speed));
}
if (speedRatio >= 100.0) {
Emulator.getComputer().getMotherboard().setMaxSpeed(true);
Motherboard.cpuPerClock = 10;
} else {
if (speedRatio > 25) {
Motherboard.cpuPerClock = 2;
} else {
Motherboard.cpuPerClock = 1;
}
Emulator.getComputer().getMotherboard().setMaxSpeed(false);
Emulator.getComputer().getMotherboard().setSpeedInPercentage((int) (speedRatio * 100));
}
Emulator.getComputer().getMotherboard().reconfigure();
}
public void toggleAspectRatio() {
setAspectRatioEnabled(aspectRatioCorrectionEnabled.not().get());
}
public void setAspectRatioEnabled(boolean enabled) {
aspectRatioCorrectionEnabled.set(enabled);
}
public void connectComputer(Computer computer, Stage primaryStage) {
if (computer == null) {
return;
}
this.computer = computer;
Platform.runLater(() -> {
connectControls(primaryStage);
appleScreen.setImage(computer.getVideo().getFrameBuffer());
appleScreen.setVisible(true);
rootPane.requestFocus();
});
}
private void processDragEnteredEvent(DragEvent evt) {
MediaEntry media = null;
if (evt.getDragboard().hasFiles()) {
media = MediaCache.getMediaFromFile(getDraggedFile(evt.getDragboard().getFiles()));
} else if (evt.getDragboard().hasUrl()) {
media = MediaCache.getMediaFromUrl(evt.getDragboard().getUrl());
} else if (evt.getDragboard().hasString()) {
String path = evt.getDragboard().getString();
try {
URI.create(path);
media = MediaCache.getMediaFromUrl(path);
} catch (IllegalArgumentException ex) {
File f = new File(path);
if (f.exists()) {
media = MediaCache.getMediaFromFile(f);
}
}
}
if (media != null) {
evt.acceptTransferModes(TransferMode.LINK, TransferMode.COPY);
startDragEvent(media);
}
}
private void processDragExitedEvent(DragEvent evt) {
endDragEvent();
}
private File getDraggedFile(List<File> files) {
if (files == null || files.isEmpty()) {
return null;
}
for (File f : files) {
if (f.exists()) {
return f;
}
}
return null;
}
HBox drivePanel;
private void startDragEvent(MediaEntry media) {
List<MediaConsumer> consumers = getMediaConsumers();
drivePanel = new HBox();
consumers.stream()
.filter((consumer) -> (consumer.isAccepted(media, media.files.get(0))))
.forEach((consumer) -> {
Label icon = consumer.getIcon().orElse(null);
if (icon == null) {
return;
}
icon.setTextFill(Color.WHITE);
icon.setPadding(new Insets(2.0));
drivePanel.getChildren().add(icon);
icon.setOnDragOver(event -> {
event.acceptTransferModes(TransferMode.ANY);
event.consume();
});
icon.setOnDragDropped(event -> {
System.out.println("Dropping media on " + icon.getText());
try {
computer.pause();
consumer.insertMedia(media, media.files.get(0));
computer.resume();
event.setDropCompleted(true);
event.consume();
} catch (IOException ex) {
Logger.getLogger(JaceUIController.class.getName()).log(Level.SEVERE, null, ex);
}
endDragEvent();
});
});
stackPane.getChildren().add(drivePanel);
drivePanel.setLayoutX(10);
drivePanel.setLayoutY(10);
}
private void endDragEvent() {
stackPane.getChildren().remove(drivePanel);
drivePanel.getChildren().forEach((n) -> n.setOnDragDropped(null));
}
private List<MediaConsumer> getMediaConsumers() {
List<MediaConsumer> consumers = new ArrayList<>();
consumers.add(Emulator.getComputer().getUpgradeHandler());
if (Emulator.logic.showDrives) {
for (Optional<Card> card : computer.memory.getAllCards()) {
card.filter(c -> c instanceof MediaConsumerParent).ifPresent(parent ->
consumers.addAll(Arrays.asList(((MediaConsumerParent) parent).getConsumers()))
);
}
}
return consumers;
}
Map<Label, Long> iconTTL = new ConcurrentHashMap<>();
void addIndicator(Label icon) {
addIndicator(icon, 250);
}
void addIndicator(Label icon, long TTL) {
if (!iconTTL.containsKey(icon)) {
Application.invokeLater(() -> {
if (!notificationBox.getChildren().contains(icon)) {
notificationBox.getChildren().add(icon);
}
});
}
trackTTL(icon, TTL);
}
void removeIndicator(Label icon) {
Application.invokeLater(() -> {
notificationBox.getChildren().remove(icon);
iconTTL.remove(icon);
});
}
ScheduledExecutorService notificationExecutor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture ttlCleanupTask = null;
private void trackTTL(Label icon, long TTL) {
iconTTL.put(icon, System.currentTimeMillis() + TTL);
if (ttlCleanupTask == null || ttlCleanupTask.isCancelled()) {
ttlCleanupTask = notificationExecutor.scheduleWithFixedDelay(this::processTTL, 1, 100, TimeUnit.MILLISECONDS);
}
}
private void processTTL() {
Long now = System.currentTimeMillis();
iconTTL.keySet().stream()
.filter((icon) -> (iconTTL.get(icon) <= now))
.forEach(this::removeIndicator);
if (iconTTL.isEmpty()) {
ttlCleanupTask.cancel(true);
ttlCleanupTask = null;
}
}
public void addMouseListener(EventHandler<MouseEvent> handler) {
appleScreen.addEventHandler(MouseEvent.ANY, handler);
}
public void removeMouseListener(EventHandler<MouseEvent> handler) {
appleScreen.removeEventHandler(MouseEvent.ANY, handler);
}
Label currentNotification = null;
public void displayNotification(String message) {
Label oldNotification = currentNotification;
Label notification = new Label(message);
currentNotification = notification;
notification.setEffect(new DropShadow(2.0, Color.BLACK));
notification.setTextFill(Color.WHITE);
notification.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 80, 0.7), new CornerRadii(5.0), new Insets(-5.0))));
Application.invokeLater(() -> {
stackPane.getChildren().remove(oldNotification);
stackPane.getChildren().add(notification);
});
notificationExecutor.schedule(
() -> Application.invokeLater(() -> stackPane.getChildren().remove(notification)),
4, TimeUnit.SECONDS);
}
}
| apache-2.0 |
dremio/dremio-oss | sabot/kernel/src/main/java/com/dremio/sabot/op/common/ht2/XXHashByteBuf.java | 2740 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.sabot.op.common.ht2;
import org.apache.arrow.memory.ArrowBuf;
import io.netty.util.internal.PlatformDependent;
public class XXHashByteBuf {
public static int hash(ArrowBuf buf, int bufferOffset, int len, int seed) {
buf.checkBytes(bufferOffset, bufferOffset + len);
return hashAddr(buf.memoryAddress(), bufferOffset, len, seed);
}
public static int hashAddr(long memoryAddress, int bufferOffset, int len, int seed){
long off = memoryAddress + bufferOffset;
return hashAddr(off, len, seed);
}
public static int hashAddr(long off, int len, int seed){
long end = off + len;
int h32;
if (len >= 16) {
long limit = end - 16;
int v1 = seed + -1640531535 + -2048144777;
int v2 = seed + -2048144777;
int v3 = seed + 0;
int v4 = seed - -1640531535;
do {
v1 += PlatformDependent.getInt(off) * -2048144777;
v1 = Integer.rotateLeft(v1, 13);
v1 *= -1640531535;
off += 4;
v2 += PlatformDependent.getInt(off) * -2048144777;
v2 = Integer.rotateLeft(v2, 13);
v2 *= -1640531535;
off += 4;
v3 += PlatformDependent.getInt(off) * -2048144777;
v3 = Integer.rotateLeft(v3, 13);
v3 *= -1640531535;
off += 4;
v4 += PlatformDependent.getInt(off) * -2048144777;
v4 = Integer.rotateLeft(v4, 13);
v4 *= -1640531535;
off += 4;
} while (off <= limit);
h32 = Integer.rotateLeft(v1, 1) + Integer.rotateLeft(v2, 7) + Integer.rotateLeft(v3, 12)
+ Integer.rotateLeft(v4, 18);
} else {
h32 = seed + 374761393;
}
h32 += len;
while (off <= end - 4) {
h32 += PlatformDependent.getInt(off) * -1028477379;
h32 = Integer.rotateLeft(h32, 17) * 668265263;
off += 4;
}
while (off < end) {
h32 += (PlatformDependent.getInt(off) & 0xFF) * 374761393;
h32 = Integer.rotateLeft(h32, 11) * -1640531535;
++off;
}
h32 ^= h32 >>> 15;
h32 *= -2048144777;
h32 ^= h32 >>> 13;
h32 *= -1028477379;
h32 ^= h32 >>> 16;
return h32;
}
}
| apache-2.0 |
mike-tr-adamson/java-driver | driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java | 3895 | /*
* Copyright (C) 2012-2015 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core.querybuilder;
import com.datastax.driver.core.*;
import com.datastax.driver.core.utils.CassandraVersion;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.testng.annotations.Test;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
@CassandraVersion(major = 2.1, minor = 3)
public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
@Override
protected Collection<String> getTableDefinitions() {
return Arrays.asList("CREATE TYPE udt (i int, a inet)",
"CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)");
}
@Test(groups = "short")
public void insertUdtTest() throws Exception {
UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
assertEquals(insert.toString(), "INSERT INTO udtTest (k,t) VALUES (1,{i:2, a:'127.0.0.1'});");
session.execute(insert);
List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
assertEquals(rows.size(), 1);
Row r1 = rows.get(0);
assertEquals("127.0.0.1", r1.getUDTValue("t").getInet("a").getHostAddress());
}
@Test(groups = "short")
public void should_handle_collections_of_UDT() throws Exception {
UserType udtType = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt");
UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost"));
Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest (k,l) VALUES (1,[{i:2, a:'127.0.0.1'}]);");
session.execute(insert);
List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
assertThat(rows.size()).isEqualTo(1);
Row r1 = rows.get(0);
assertThat(r1.getList("l", UDTValue.class).get(0).getInet("a").getHostAddress()).isEqualTo("127.0.0.1");
Map<Integer, UDTValue> map = Maps.newHashMap();
map.put(0, udtValue);
map.put(2, udtValue2);
Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1));
assertThat(updateMap.toString())
.isEqualTo("UPDATE udtTest SET m=m+{0:{i:2, a:'127.0.0.1'},2:{i:3, a:'127.0.0.1'}} WHERE k=1;");
session.execute(updateMap);
rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
r1 = rows.get(0);
assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map);
}
}
| apache-2.0 |
csgordon/SJS | sjsc/src/main/java/com/samsung/sjs/theorysolver/TheorySolver.java | 10026 | /*
* Copyright 2014-2016 Samsung Research America, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samsung.sjs.theorysolver;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* This is a tiny max-theory solver. See
* {@link #solve(Theory, FixingSetFinder, List, List)}
* for extended details.
*/
public class TheorySolver {
/** True to shuffle constraints before sending them to the theory solver */
private static final boolean SHUFFLE = false;
/** True to enable verbose progress messages */
private static final boolean NOISY = true;
private static <T> T timed(Supplier<T> f, String msg) {
if (NOISY) {
System.out.print(msg + "... ");
System.out.flush();
long start = System.currentTimeMillis();
T result = f.get();
long duration = System.currentTimeMillis() - start;
System.out.println(duration + "ms");
return result;
} else {
return f.get();
}
}
static int[] extendClause(int[] clause, int i) {
int[] result = new int[clause.length + 1];
System.arraycopy(clause, 0, result, 0, clause.length);
result[clause.length] = i;
return result;
}
public static <Constraint, Model> void enumerateFixingSets(
FixingSetFinder<Constraint> fixingSetFinder,
Theory<Constraint, Model> theorySolver,
Collection<Constraint> hardConstraints,
Collection<Constraint> softConstraints,
FixingSetListener<Constraint, Model> listener) {
Collection<Constraint> constraints = new ArrayList<>();
Collection<Constraint> core = new ArrayList<>();
Collection<Constraint> fixingSet = new LinkedHashSet<>();
for (;;) {
if (fixingSetFinder.currentFixingSet(fixingSet, listener) == FixingSetListener.Action.STOP) {
return;
}
constraints.addAll(hardConstraints);
softConstraints.stream().filter(c -> !fixingSet.contains(c)).forEach(constraints::add);
Either<Model, Collection<Constraint>> result = theorySolver.check(constraints);
if (result.left != null) {
if (listener.onFixingSet(result.left, fixingSet) == FixingSetListener.Action.STOP) {
return;
}
fixingSetFinder.addCore(constraints.stream()
.filter(softConstraints::contains)
.collect(Collectors.toList()));
} else {
result.right.stream().filter(softConstraints::contains).forEach(core::add);
if (listener.onCore(core) == FixingSetListener.Action.STOP) {
return;
}
assert core.stream().allMatch(c -> !fixingSet.contains(c));
fixingSetFinder.addCore(core);
}
core.clear();
constraints.clear();
fixingSet.clear();
}
}
/**
* Given a fixing set finder, a solver for some particular theory, and some constraints,
* this procedure either finds a model or it finds a minimum set of constraints
* which, if broken, make the system satisfiable (a "fixing set").
*
* <p>A <em>theory</em> is a solver that solves simple conjunctions of constraints.
* The performance of this algorithm highly depends on the ability of the theory to
* produce small unsatisfiable cores.
*
* @param <Constraint> the type of constraint solved by the theory
* @param <Model> the type of model produced by the theory
* @param theorySolver a solver for some theory
* @param fixingSetFinder a strategy for finding a fixing set
* @param hardConstraints the hard constraints which MUST be satisfied
* @param softConstraints the labeled soft constraints from which the fixing set is drawn
* @return A pair (m,l) where l is the fixing set (a minimum set of constraints which had
* to be weakened to satisfy the system), and m is the resulting model after weakening.
* Note that <code>l.isEmpty()</code> means the entire set of constraints is satisfiable.
* @see SatSolver
* @see Theory
*/
public static <Constraint, Model> Pair<Model, Collection<Constraint>> solve(
Theory<Constraint, Model> theorySolver,
FixingSetFinder<Constraint> fixingSetFinder,
List<Constraint> hardConstraints,
List<Constraint> softConstraints) {
FixingSetListener<Constraint, Model> listener = NOISY ?
loggingListener() :
FixingSetListener.dummyListener();
fixingSetFinder.setup(softConstraints);
// These two are complements of each other:
// - fixingSet is the constraints we are going to remove
// - positive is the constraints we are going to keep
// (i.e. all those not in the fixing set)
Collection<Constraint> fixingSet = new ArrayList<>();
Collection<Constraint> positive = new LinkedHashSet<>();
for (;;) {
// Be polite---interruptions mean that someone else wants
// this thread to stop what it's doing.
if (Thread.currentThread().isInterrupted()) {
throw new RuntimeException("thread was interrupted");
}
positive.addAll(hardConstraints);
positive.addAll(softConstraints);
positive.removeAll(fixingSet);
// Check the proposed fixing set against the theory.
Either<Model, Collection<Constraint>> result =
timed(() -> theorySolver.check(positive), "CHECKING THEORY");
if (result.right == null) {
// The proposed fixing set works! We are done!
if (NOISY) System.out.println("VALID MODEL");
listener.onFixingSet(result.left, fixingSet);
return Pair.of(result.left, fixingSet);
} else {
// The proposed fixing set didn't work. We will use the core
// to adjust what fixing set gets returned next.
// Inform the listener
listener.onCore(result.right);
// The fixing set finder shouldn't care about hard constraints
Collection<Constraint> softCore = result.right.stream()
.filter(c -> !hardConstraints.contains(c))
.collect(Collectors.toList());
if (softCore.isEmpty()) {
throw new IllegalStateException("Hard clauses are unsat!");
}
// Push the core to the fixing set finder
fixingSet.clear();
fixingSetFinder.addCore(softCore);
timed(() -> fixingSetFinder.currentFixingSet(fixingSet, listener),
"FINDING FIXING SET");
System.out.println(" --> PROPOSAL SIZE = " + fixingSet.size());
}
}
}
private static <T> Collection<T> without(Collection<T> collection, T element) {
return collection.stream().filter(e -> !element.equals(e)).collect(Collectors.toList());
}
public static <Constraint, Model> Pair<Model, Collection<Constraint>> minimizeFixingSet(
Theory<Constraint, Model> theorySolver,
List<Constraint> hardConstraints,
List<Constraint> softConstraints,
Model model,
Collection<Constraint> fixingSet) {
System.out.println("MINIMIZING FIXING SET [initial size=" + fixingSet.size() + ']');
int iter = 0;
Collection<Constraint> positive = new LinkedHashSet<>();
boolean changed;
do {
++iter;
System.out.println(" --> iteration " + iter + "...");
changed = false;
for (Constraint c : fixingSet) {
Collection<Constraint> candidate = without(fixingSet, c);
positive.addAll(hardConstraints);
positive.addAll(softConstraints);
positive.removeAll(candidate);
Either<Model, Collection<Constraint>> result = theorySolver.check(positive);
if (result.left != null) {
// it's still a fixing set!
changed = true;
fixingSet = candidate;
model = result.left;
break;
}
}
} while (changed);
System.out.println("FINISHED MINIMIZING [final size=" + fixingSet.size() + ']');
return Pair.of(model, fixingSet);
}
private static <Constraint, Model> FixingSetListener<Constraint, Model> loggingListener() {
return new FixingSetListener<Constraint, Model>() {
@Override
public Action onCore(Collection<Constraint> unsatCore) {
System.out.println("INVALID MODEL [core_size=" + unsatCore.size() + ']');
return Action.CONTINUE;
}
@Override
public Action onFixingSet(Model model, Collection<Constraint> fixingSet) {
System.out.println("VALID MODEL");
return Action.CONTINUE;
}
};
}
}
| apache-2.0 |
gregberns/ZipRdlProjectDev410 | src/RdlEngine/Definition/MatrixCellEntry.cs | 2433 | /* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
namespace fyiReporting.RDL
{
///<summary>
/// Runtime data structure representing the group hierarchy
///</summary>
internal class MatrixCellEntry
{
Rows _Data; // Rows matching this cell entry
ReportItem _DisplayItem; // Report item to display in report
double _Value=double.MinValue; // used by Charts to optimize data request
float _XPosition; // position of cell
float _Height; // height of cell
float _Width; // width of cell
MatrixEntry _RowME; // MatrixEntry for the row that made cell entry
MatrixEntry _ColumnME; // MatrixEntry for the column that made cell entry
int _ColSpan; // # of columns spanned
internal MatrixCellEntry(Rows d, ReportItem ri)
{
_Data = d;
_DisplayItem = ri;
_ColSpan = 1;
}
internal Rows Data
{
get { return _Data; }
}
internal int ColSpan
{
get { return _ColSpan;}
set { _ColSpan = value; }
}
internal ReportItem DisplayItem
{
get { return _DisplayItem; }
}
internal float Height
{
get { return _Height; }
set { _Height = value; }
}
internal MatrixEntry ColumnME
{
get { return _ColumnME; }
set { _ColumnME = value; }
}
internal MatrixEntry RowME
{
get { return _RowME; }
set { _RowME = value; }
}
internal double Value
{
get { return _Value; }
set { _Value = value; }
}
internal float Width
{
get { return _Width; }
set { _Width = value; }
}
internal float XPosition
{
get { return _XPosition; }
set { _XPosition = value; }
}
}
}
| apache-2.0 |
mmm2a/GridApp | test/com/morgan/grid/client/common/AllCommonTests.java | 408 | package com.morgan.grid.client.common;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.morgan.grid.client.common.feature.AllFeatureTests;
import com.morgan.grid.client.common.navigation.AllNavigationTests;
@RunWith(Suite.class)
@SuiteClasses({
AllFeatureTests.class,
AllNavigationTests.class
})
public class AllCommonTests {
}
| apache-2.0 |
intelsdi-x/swan | pkg/workloads/specjbb/parser/parse_test.go | 8102 | // Copyright (c) 2017 Intel Corporation
//
// 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 parser
import (
"path/filepath"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestStdoutParser(t *testing.T) {
Convey("Opening non-existing file for high bound injection rate (critical jops determined in tuning phase) should fail",
t, func() {
jops, err := FileWithHBIRRT("/non/existing/file")
Convey("jops should equal 0 and the error should not be nil", func() {
So(jops, ShouldEqual, 0)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "open /non/existing/file: no such file or directory")
})
})
Convey("Opening readable and correct file for high bound injection rate (critical jops determined in tuning phase)",
t, func() {
path, err := filepath.Abs("criticaljops")
So(err, ShouldBeNil)
Convey("should provide meaningful results", func() {
jops, err := FileWithHBIRRT(path)
So(err, ShouldBeNil)
So(jops, ShouldEqual, 2684)
})
})
Convey("Opening readable and correct file for high bound injection rate (critical jops determined in tuning phase) from remote output",
t, func() {
path, err := filepath.Abs("remote_output")
So(err, ShouldBeNil)
Convey("should provide meaningful results", func() {
jops, err := FileWithHBIRRT(path)
So(err, ShouldBeNil)
So(jops, ShouldEqual, 2684)
})
})
Convey("Attempting to read file without measured critical jops", t, func() {
path, err := filepath.Abs("criticaljops_not_measured")
So(err, ShouldBeNil)
Convey("should return 0 value for jops and an error", func() {
jops, err := FileWithHBIRRT(path)
So(jops, ShouldEqual, 0)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Run result not found, cannot determine critical-jops")
})
})
Convey("Opening non-existing file for latencies should fail", t, func() {
results, err := FileWithLatencies("/non/existing/file")
Convey("results should be nil and the error should not be nil", func() {
So(results.Raw, ShouldHaveLength, 0)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "open /non/existing/file: no such file or directory")
})
})
Convey("Opening readable and correct file for latencies", t, func() {
path, err := filepath.Abs("latencies")
So(err, ShouldBeNil)
Convey("should provide meaningful results", func() {
results, err := FileWithLatencies(path)
So(err, ShouldBeNil)
So(results.Raw, ShouldHaveLength, 14)
So(results.Raw[SuccessKey], ShouldEqual, 115276)
So(results.Raw[PartialKey], ShouldEqual, 0)
So(results.Raw[FailedKey], ShouldEqual, 0)
So(results.Raw[SkipFailKey], ShouldEqual, 0)
So(results.Raw[ProbesKey], ShouldEqual, 108937)
So(results.Raw[SamplesKey], ShouldEqual, 133427)
So(results.Raw[MinKey], ShouldEqual, 300)
So(results.Raw[Percentile50Key], ShouldEqual, 3100)
So(results.Raw[Percentile90Key], ShouldEqual, 21000)
So(results.Raw[Percentile95Key], ShouldEqual, 89000)
So(results.Raw[Percentile99Key], ShouldEqual, 517000)
So(results.Raw[MaxKey], ShouldEqual, 640000)
So(results.Raw[QPSKey], ShouldEqual, 4007)
So(results.Raw[IssuedRequestsKey], ShouldEqual, 4007)
})
})
Convey("Attempting to read file without measured latencies", t, func() {
path, err := filepath.Abs("latencies_not_measured")
So(err, ShouldBeNil)
Convey("should return 0 results and an error", func() {
results, err := FileWithLatencies(path)
So(results.Raw, ShouldHaveLength, 0)
So(err, ShouldNotBeNil)
})
})
Convey("Attempting to read file without measured processed requests and issued requests", t, func() {
path, err := filepath.Abs("pr_not_measured")
So(err, ShouldBeNil)
Convey("should return empty results and an error", func() {
results, err := FileWithLatencies(path)
So(results.Raw, ShouldHaveLength, 0)
So(err, ShouldNotBeNil)
})
})
Convey("Attempting to read correct and readable file with many iterations for load", t, func() {
path, err := filepath.Abs("many_iterations")
So(err, ShouldBeNil)
Convey("should return last iteration results and no error", func() {
results, err := FileWithLatencies(path)
So(results.Raw, ShouldHaveLength, 14)
So(err, ShouldBeNil)
So(results.Raw[SuccessKey], ShouldEqual, 114968)
So(results.Raw[PartialKey], ShouldEqual, 0)
So(results.Raw[FailedKey], ShouldEqual, 0)
So(results.Raw[SkipFailKey], ShouldEqual, 0)
So(results.Raw[ProbesKey], ShouldEqual, 110647)
So(results.Raw[SamplesKey], ShouldEqual, 125836)
So(results.Raw[MinKey], ShouldEqual, 300)
So(results.Raw[Percentile50Key], ShouldEqual, 2700)
So(results.Raw[Percentile90Key], ShouldEqual, 6600)
So(results.Raw[Percentile95Key], ShouldEqual, 35000)
So(results.Raw[Percentile99Key], ShouldEqual, 352000)
So(results.Raw[MaxKey], ShouldEqual, 1100000)
So(results.Raw[QPSKey], ShouldEqual, 3999)
So(results.Raw[IssuedRequestsKey], ShouldEqual, 3999)
})
})
Convey("Attempting to read correct and readable file for latencies with output from SPECjbb run remotely", t, func() {
path, err := filepath.Abs("remote_output")
So(err, ShouldBeNil)
Convey("should return correct results and no error", func() {
results, err := FileWithLatencies(path)
So(results.Raw, ShouldHaveLength, 14)
So(err, ShouldBeNil)
So(results.Raw[SuccessKey], ShouldEqual, 14355)
So(results.Raw[PartialKey], ShouldEqual, 0)
So(results.Raw[FailedKey], ShouldEqual, 0)
So(results.Raw[SkipFailKey], ShouldEqual, 0)
So(results.Raw[ProbesKey], ShouldEqual, 13832)
So(results.Raw[SamplesKey], ShouldEqual, 15916)
So(results.Raw[MinKey], ShouldEqual, 1000)
So(results.Raw[Percentile50Key], ShouldEqual, 4000)
So(results.Raw[Percentile90Key], ShouldEqual, 9530)
So(results.Raw[Percentile95Key], ShouldEqual, 40150)
So(results.Raw[Percentile99Key], ShouldEqual, 94000)
So(results.Raw[MaxKey], ShouldEqual, 120000)
So(results.Raw[QPSKey], ShouldEqual, 500)
So(results.Raw[IssuedRequestsKey], ShouldEqual, 500)
})
})
Convey("Opening non-existing file for raw file name should fail", t, func() {
fileName, err := FileWithRawFileName("/non/existing/file")
Convey("file name should be nil and the error should not be nil", func() {
So(fileName, ShouldEqual, "")
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "open /non/existing/file: no such file or directory")
})
})
Convey("Opening readable and correct file for raw file name", t, func() {
path, err := filepath.Abs("raw_file_name")
So(err, ShouldBeNil)
Convey("should provide meaningful results", func() {
fileName, err := FileWithRawFileName(path)
So(err, ShouldBeNil)
So(fileName, ShouldEqual, "/swan/workloads/web_serving/specjbb/specjbb2015-D-20160921-00002.data.gz")
})
})
Convey("Opening readable and correct file for raw file name from remote output", t, func() {
path, err := filepath.Abs("remote_output")
So(err, ShouldBeNil)
Convey("should provide meaningful results", func() {
fileName, err := FileWithRawFileName(path)
So(err, ShouldBeNil)
So(fileName, ShouldEqual, "/swan/workloads/web_serving/specjbb/specjbb2015-D-20160921-00002.data.gz")
})
})
Convey("Attempting to read file without raw file name", t, func() {
path, err := filepath.Abs("raw_file_name_not_given")
So(err, ShouldBeNil)
Convey("should result in an empty name and an error", func() {
fileName, err := FileWithRawFileName(path)
So(fileName, ShouldEqual, "")
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Raw file name not found")
})
})
}
| apache-2.0 |
googleapis/google-cloud-dotnet | apis/Google.Area120.Tables.V1Alpha1/Google.Area120.Tables.V1Alpha1/TablesServiceClient.g.cs | 90414 | // 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Area120.Tables.V1Alpha1
{
/// <summary>Settings for <see cref="TablesServiceClient"/> instances.</summary>
public sealed partial class TablesServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="TablesServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="TablesServiceSettings"/>.</returns>
public static TablesServiceSettings GetDefault() => new TablesServiceSettings();
/// <summary>Constructs a new <see cref="TablesServiceSettings"/> object with default settings.</summary>
public TablesServiceSettings()
{
}
private TablesServiceSettings(TablesServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetTableSettings = existing.GetTableSettings;
ListTablesSettings = existing.ListTablesSettings;
GetWorkspaceSettings = existing.GetWorkspaceSettings;
ListWorkspacesSettings = existing.ListWorkspacesSettings;
GetRowSettings = existing.GetRowSettings;
ListRowsSettings = existing.ListRowsSettings;
CreateRowSettings = existing.CreateRowSettings;
BatchCreateRowsSettings = existing.BatchCreateRowsSettings;
UpdateRowSettings = existing.UpdateRowSettings;
BatchUpdateRowsSettings = existing.BatchUpdateRowsSettings;
DeleteRowSettings = existing.DeleteRowSettings;
BatchDeleteRowsSettings = existing.BatchDeleteRowsSettings;
OnCopy(existing);
}
partial void OnCopy(TablesServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.GetTable</c> and <c>TablesServiceClient.GetTableAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetTableSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.ListTables</c> and <c>TablesServiceClient.ListTablesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListTablesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.GetWorkspace</c> and <c>TablesServiceClient.GetWorkspaceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetWorkspaceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.ListWorkspaces</c> and <c>TablesServiceClient.ListWorkspacesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListWorkspacesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TablesServiceClient.GetRow</c>
/// and <c>TablesServiceClient.GetRowAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetRowSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.ListRows</c> and <c>TablesServiceClient.ListRowsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListRowsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.CreateRow</c> and <c>TablesServiceClient.CreateRowAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateRowSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.BatchCreateRows</c> and <c>TablesServiceClient.BatchCreateRowsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings BatchCreateRowsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.UpdateRow</c> and <c>TablesServiceClient.UpdateRowAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateRowSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.BatchUpdateRows</c> and <c>TablesServiceClient.BatchUpdateRowsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings BatchUpdateRowsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.DeleteRow</c> and <c>TablesServiceClient.DeleteRowAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteRowSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TablesServiceClient.BatchDeleteRows</c> and <c>TablesServiceClient.BatchDeleteRowsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings BatchDeleteRowsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="TablesServiceSettings"/> object.</returns>
public TablesServiceSettings Clone() => new TablesServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="TablesServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class TablesServiceClientBuilder : gaxgrpc::ClientBuilderBase<TablesServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public TablesServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public TablesServiceClientBuilder()
{
UseJwtAccessWithScopes = TablesServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref TablesServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TablesServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override TablesServiceClient Build()
{
TablesServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<TablesServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<TablesServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private TablesServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return TablesServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<TablesServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return TablesServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => TablesServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => TablesServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => TablesServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>TablesService client wrapper, for convenient use.</summary>
/// <remarks>
/// The Tables Service provides an API for reading and updating tables.
/// It defines the following resource model:
///
/// - The API has a collection of [Table][google.area120.tables.v1alpha1.Table]
/// resources, named `tables/*`
///
/// - Each Table has a collection of [Row][google.area120.tables.v1alpha1.Row]
/// resources, named `tables/*/rows/*`
///
/// - The API has a collection of
/// [Workspace][google.area120.tables.v1alpha1.Workspace]
/// resources, named `workspaces/*`.
/// </remarks>
public abstract partial class TablesServiceClient
{
/// <summary>
/// The default endpoint for the TablesService service, which is a host of "area120tables.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "area120tables.googleapis.com:443";
/// <summary>The default TablesService scopes.</summary>
/// <remarks>
/// The default TablesService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/drive</description></item>
/// <item><description>https://www.googleapis.com/auth/drive.file</description></item>
/// <item><description>https://www.googleapis.com/auth/drive.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/spreadsheets</description></item>
/// <item><description>https://www.googleapis.com/auth/spreadsheets.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/tables</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/tables",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="TablesServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TablesServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="TablesServiceClient"/>.</returns>
public static stt::Task<TablesServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new TablesServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="TablesServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TablesServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="TablesServiceClient"/>.</returns>
public static TablesServiceClient Create() => new TablesServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="TablesServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="TablesServiceSettings"/>.</param>
/// <returns>The created <see cref="TablesServiceClient"/>.</returns>
internal static TablesServiceClient Create(grpccore::CallInvoker callInvoker, TablesServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
TablesService.TablesServiceClient grpcClient = new TablesService.TablesServiceClient(callInvoker);
return new TablesServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC TablesService client</summary>
public virtual TablesService.TablesServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Table GetTable(GetTableRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(GetTableRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(GetTableRequest request, st::CancellationToken cancellationToken) =>
GetTableAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Table GetTable(string name, gaxgrpc::CallSettings callSettings = null) =>
GetTable(new GetTableRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetTableAsync(new GetTableRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(string name, st::CancellationToken cancellationToken) =>
GetTableAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Table GetTable(TableName name, gaxgrpc::CallSettings callSettings = null) =>
GetTable(new GetTableRequest
{
TableName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(TableName name, gaxgrpc::CallSettings callSettings = null) =>
GetTableAsync(new GetTableRequest
{
TableName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the table to retrieve.
/// Format: tables/{table}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Table> GetTableAsync(TableName name, st::CancellationToken cancellationToken) =>
GetTableAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists tables for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Table"/> resources.</returns>
public virtual gax::PagedEnumerable<ListTablesResponse, Table> ListTables(ListTablesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists tables for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Table"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListTablesResponse, Table> ListTablesAsync(ListTablesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Workspace GetWorkspace(GetWorkspaceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(GetWorkspaceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(GetWorkspaceRequest request, st::CancellationToken cancellationToken) =>
GetWorkspaceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Workspace GetWorkspace(string name, gaxgrpc::CallSettings callSettings = null) =>
GetWorkspace(new GetWorkspaceRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetWorkspaceAsync(new GetWorkspaceRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(string name, st::CancellationToken cancellationToken) =>
GetWorkspaceAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Workspace GetWorkspace(WorkspaceName name, gaxgrpc::CallSettings callSettings = null) =>
GetWorkspace(new GetWorkspaceRequest
{
WorkspaceName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(WorkspaceName name, gaxgrpc::CallSettings callSettings = null) =>
GetWorkspaceAsync(new GetWorkspaceRequest
{
WorkspaceName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="name">
/// Required. The name of the workspace to retrieve.
/// Format: workspaces/{workspace}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Workspace> GetWorkspaceAsync(WorkspaceName name, st::CancellationToken cancellationToken) =>
GetWorkspaceAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists workspaces for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Workspace"/> resources.</returns>
public virtual gax::PagedEnumerable<ListWorkspacesResponse, Workspace> ListWorkspaces(ListWorkspacesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists workspaces for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Workspace"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListWorkspacesResponse, Workspace> ListWorkspacesAsync(ListWorkspacesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row GetRow(GetRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(GetRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(GetRowRequest request, st::CancellationToken cancellationToken) =>
GetRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row GetRow(string name, gaxgrpc::CallSettings callSettings = null) =>
GetRow(new GetRowRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetRowAsync(new GetRowRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(string name, st::CancellationToken cancellationToken) =>
GetRowAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row GetRow(RowName name, gaxgrpc::CallSettings callSettings = null) =>
GetRow(new GetRowRequest
{
RowName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(RowName name, gaxgrpc::CallSettings callSettings = null) =>
GetRowAsync(new GetRowRequest
{
RowName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="name">
/// Required. The name of the row to retrieve.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> GetRowAsync(RowName name, st::CancellationToken cancellationToken) =>
GetRowAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Row"/> resources.</returns>
public virtual gax::PagedEnumerable<ListRowsResponse, Row> ListRows(ListRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Row"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListRowsResponse, Row> ListRowsAsync(ListRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="parent">
/// Required. The parent table.
/// Format: tables/{table}
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Row"/> resources.</returns>
public virtual gax::PagedEnumerable<ListRowsResponse, Row> ListRows(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRows(new ListRowsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="parent">
/// Required. The parent table.
/// Format: tables/{table}
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Row"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListRowsResponse, Row> ListRowsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRowsAsync(new ListRowsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row CreateRow(CreateRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> CreateRowAsync(CreateRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> CreateRowAsync(CreateRowRequest request, st::CancellationToken cancellationToken) =>
CreateRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="parent">
/// Required. The parent table where this row will be created.
/// Format: tables/{table}
/// </param>
/// <param name="row">
/// Required. The row to create.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row CreateRow(string parent, Row row, gaxgrpc::CallSettings callSettings = null) =>
CreateRow(new CreateRowRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Row = gax::GaxPreconditions.CheckNotNull(row, nameof(row)),
}, callSettings);
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="parent">
/// Required. The parent table where this row will be created.
/// Format: tables/{table}
/// </param>
/// <param name="row">
/// Required. The row to create.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> CreateRowAsync(string parent, Row row, gaxgrpc::CallSettings callSettings = null) =>
CreateRowAsync(new CreateRowRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Row = gax::GaxPreconditions.CheckNotNull(row, nameof(row)),
}, callSettings);
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="parent">
/// Required. The parent table where this row will be created.
/// Format: tables/{table}
/// </param>
/// <param name="row">
/// Required. The row to create.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> CreateRowAsync(string parent, Row row, st::CancellationToken cancellationToken) =>
CreateRowAsync(parent, row, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual BatchCreateRowsResponse BatchCreateRows(BatchCreateRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchCreateRowsResponse> BatchCreateRowsAsync(BatchCreateRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchCreateRowsResponse> BatchCreateRowsAsync(BatchCreateRowsRequest request, st::CancellationToken cancellationToken) =>
BatchCreateRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row UpdateRow(UpdateRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> UpdateRowAsync(UpdateRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> UpdateRowAsync(UpdateRowRequest request, st::CancellationToken cancellationToken) =>
UpdateRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="row">
/// Required. The row to update.
/// </param>
/// <param name="updateMask">
/// The list of fields to update.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Row UpdateRow(Row row, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateRow(new UpdateRowRequest
{
Row = gax::GaxPreconditions.CheckNotNull(row, nameof(row)),
UpdateMask = updateMask,
}, callSettings);
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="row">
/// Required. The row to update.
/// </param>
/// <param name="updateMask">
/// The list of fields to update.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> UpdateRowAsync(Row row, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateRowAsync(new UpdateRowRequest
{
Row = gax::GaxPreconditions.CheckNotNull(row, nameof(row)),
UpdateMask = updateMask,
}, callSettings);
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="row">
/// Required. The row to update.
/// </param>
/// <param name="updateMask">
/// The list of fields to update.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Row> UpdateRowAsync(Row row, wkt::FieldMask updateMask, st::CancellationToken cancellationToken) =>
UpdateRowAsync(row, updateMask, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual BatchUpdateRowsResponse BatchUpdateRows(BatchUpdateRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchUpdateRowsResponse> BatchUpdateRowsAsync(BatchUpdateRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchUpdateRowsResponse> BatchUpdateRowsAsync(BatchUpdateRowsRequest request, st::CancellationToken cancellationToken) =>
BatchUpdateRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteRow(DeleteRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(DeleteRowRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(DeleteRowRequest request, st::CancellationToken cancellationToken) =>
DeleteRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteRow(string name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRow(new DeleteRowRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRowAsync(new DeleteRowRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(string name, st::CancellationToken cancellationToken) =>
DeleteRowAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteRow(RowName name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRow(new DeleteRowRequest
{
RowName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(RowName name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRowAsync(new DeleteRowRequest
{
RowName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="name">
/// Required. The name of the row to delete.
/// Format: tables/{table}/rows/{row}
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteRowAsync(RowName name, st::CancellationToken cancellationToken) =>
DeleteRowAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void BatchDeleteRows(BatchDeleteRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task BatchDeleteRowsAsync(BatchDeleteRowsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task BatchDeleteRowsAsync(BatchDeleteRowsRequest request, st::CancellationToken cancellationToken) =>
BatchDeleteRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>TablesService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The Tables Service provides an API for reading and updating tables.
/// It defines the following resource model:
///
/// - The API has a collection of [Table][google.area120.tables.v1alpha1.Table]
/// resources, named `tables/*`
///
/// - Each Table has a collection of [Row][google.area120.tables.v1alpha1.Row]
/// resources, named `tables/*/rows/*`
///
/// - The API has a collection of
/// [Workspace][google.area120.tables.v1alpha1.Workspace]
/// resources, named `workspaces/*`.
/// </remarks>
public sealed partial class TablesServiceClientImpl : TablesServiceClient
{
private readonly gaxgrpc::ApiCall<GetTableRequest, Table> _callGetTable;
private readonly gaxgrpc::ApiCall<ListTablesRequest, ListTablesResponse> _callListTables;
private readonly gaxgrpc::ApiCall<GetWorkspaceRequest, Workspace> _callGetWorkspace;
private readonly gaxgrpc::ApiCall<ListWorkspacesRequest, ListWorkspacesResponse> _callListWorkspaces;
private readonly gaxgrpc::ApiCall<GetRowRequest, Row> _callGetRow;
private readonly gaxgrpc::ApiCall<ListRowsRequest, ListRowsResponse> _callListRows;
private readonly gaxgrpc::ApiCall<CreateRowRequest, Row> _callCreateRow;
private readonly gaxgrpc::ApiCall<BatchCreateRowsRequest, BatchCreateRowsResponse> _callBatchCreateRows;
private readonly gaxgrpc::ApiCall<UpdateRowRequest, Row> _callUpdateRow;
private readonly gaxgrpc::ApiCall<BatchUpdateRowsRequest, BatchUpdateRowsResponse> _callBatchUpdateRows;
private readonly gaxgrpc::ApiCall<DeleteRowRequest, wkt::Empty> _callDeleteRow;
private readonly gaxgrpc::ApiCall<BatchDeleteRowsRequest, wkt::Empty> _callBatchDeleteRows;
/// <summary>
/// Constructs a client wrapper for the TablesService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TablesServiceSettings"/> used within this client.</param>
public TablesServiceClientImpl(TablesService.TablesServiceClient grpcClient, TablesServiceSettings settings)
{
GrpcClient = grpcClient;
TablesServiceSettings effectiveSettings = settings ?? TablesServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetTable = clientHelper.BuildApiCall<GetTableRequest, Table>(grpcClient.GetTableAsync, grpcClient.GetTable, effectiveSettings.GetTableSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetTable);
Modify_GetTableApiCall(ref _callGetTable);
_callListTables = clientHelper.BuildApiCall<ListTablesRequest, ListTablesResponse>(grpcClient.ListTablesAsync, grpcClient.ListTables, effectiveSettings.ListTablesSettings);
Modify_ApiCall(ref _callListTables);
Modify_ListTablesApiCall(ref _callListTables);
_callGetWorkspace = clientHelper.BuildApiCall<GetWorkspaceRequest, Workspace>(grpcClient.GetWorkspaceAsync, grpcClient.GetWorkspace, effectiveSettings.GetWorkspaceSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetWorkspace);
Modify_GetWorkspaceApiCall(ref _callGetWorkspace);
_callListWorkspaces = clientHelper.BuildApiCall<ListWorkspacesRequest, ListWorkspacesResponse>(grpcClient.ListWorkspacesAsync, grpcClient.ListWorkspaces, effectiveSettings.ListWorkspacesSettings);
Modify_ApiCall(ref _callListWorkspaces);
Modify_ListWorkspacesApiCall(ref _callListWorkspaces);
_callGetRow = clientHelper.BuildApiCall<GetRowRequest, Row>(grpcClient.GetRowAsync, grpcClient.GetRow, effectiveSettings.GetRowSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetRow);
Modify_GetRowApiCall(ref _callGetRow);
_callListRows = clientHelper.BuildApiCall<ListRowsRequest, ListRowsResponse>(grpcClient.ListRowsAsync, grpcClient.ListRows, effectiveSettings.ListRowsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListRows);
Modify_ListRowsApiCall(ref _callListRows);
_callCreateRow = clientHelper.BuildApiCall<CreateRowRequest, Row>(grpcClient.CreateRowAsync, grpcClient.CreateRow, effectiveSettings.CreateRowSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateRow);
Modify_CreateRowApiCall(ref _callCreateRow);
_callBatchCreateRows = clientHelper.BuildApiCall<BatchCreateRowsRequest, BatchCreateRowsResponse>(grpcClient.BatchCreateRowsAsync, grpcClient.BatchCreateRows, effectiveSettings.BatchCreateRowsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callBatchCreateRows);
Modify_BatchCreateRowsApiCall(ref _callBatchCreateRows);
_callUpdateRow = clientHelper.BuildApiCall<UpdateRowRequest, Row>(grpcClient.UpdateRowAsync, grpcClient.UpdateRow, effectiveSettings.UpdateRowSettings).WithGoogleRequestParam("row.name", request => request.Row?.Name);
Modify_ApiCall(ref _callUpdateRow);
Modify_UpdateRowApiCall(ref _callUpdateRow);
_callBatchUpdateRows = clientHelper.BuildApiCall<BatchUpdateRowsRequest, BatchUpdateRowsResponse>(grpcClient.BatchUpdateRowsAsync, grpcClient.BatchUpdateRows, effectiveSettings.BatchUpdateRowsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callBatchUpdateRows);
Modify_BatchUpdateRowsApiCall(ref _callBatchUpdateRows);
_callDeleteRow = clientHelper.BuildApiCall<DeleteRowRequest, wkt::Empty>(grpcClient.DeleteRowAsync, grpcClient.DeleteRow, effectiveSettings.DeleteRowSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteRow);
Modify_DeleteRowApiCall(ref _callDeleteRow);
_callBatchDeleteRows = clientHelper.BuildApiCall<BatchDeleteRowsRequest, wkt::Empty>(grpcClient.BatchDeleteRowsAsync, grpcClient.BatchDeleteRows, effectiveSettings.BatchDeleteRowsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callBatchDeleteRows);
Modify_BatchDeleteRowsApiCall(ref _callBatchDeleteRows);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetTableApiCall(ref gaxgrpc::ApiCall<GetTableRequest, Table> call);
partial void Modify_ListTablesApiCall(ref gaxgrpc::ApiCall<ListTablesRequest, ListTablesResponse> call);
partial void Modify_GetWorkspaceApiCall(ref gaxgrpc::ApiCall<GetWorkspaceRequest, Workspace> call);
partial void Modify_ListWorkspacesApiCall(ref gaxgrpc::ApiCall<ListWorkspacesRequest, ListWorkspacesResponse> call);
partial void Modify_GetRowApiCall(ref gaxgrpc::ApiCall<GetRowRequest, Row> call);
partial void Modify_ListRowsApiCall(ref gaxgrpc::ApiCall<ListRowsRequest, ListRowsResponse> call);
partial void Modify_CreateRowApiCall(ref gaxgrpc::ApiCall<CreateRowRequest, Row> call);
partial void Modify_BatchCreateRowsApiCall(ref gaxgrpc::ApiCall<BatchCreateRowsRequest, BatchCreateRowsResponse> call);
partial void Modify_UpdateRowApiCall(ref gaxgrpc::ApiCall<UpdateRowRequest, Row> call);
partial void Modify_BatchUpdateRowsApiCall(ref gaxgrpc::ApiCall<BatchUpdateRowsRequest, BatchUpdateRowsResponse> call);
partial void Modify_DeleteRowApiCall(ref gaxgrpc::ApiCall<DeleteRowRequest, wkt::Empty> call);
partial void Modify_BatchDeleteRowsApiCall(ref gaxgrpc::ApiCall<BatchDeleteRowsRequest, wkt::Empty> call);
partial void OnConstruction(TablesService.TablesServiceClient grpcClient, TablesServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC TablesService client</summary>
public override TablesService.TablesServiceClient GrpcClient { get; }
partial void Modify_GetTableRequest(ref GetTableRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListTablesRequest(ref ListTablesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetWorkspaceRequest(ref GetWorkspaceRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListWorkspacesRequest(ref ListWorkspacesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetRowRequest(ref GetRowRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListRowsRequest(ref ListRowsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateRowRequest(ref CreateRowRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_BatchCreateRowsRequest(ref BatchCreateRowsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateRowRequest(ref UpdateRowRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_BatchUpdateRowsRequest(ref BatchUpdateRowsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteRowRequest(ref DeleteRowRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_BatchDeleteRowsRequest(ref BatchDeleteRowsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Table GetTable(GetTableRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetTableRequest(ref request, ref callSettings);
return _callGetTable.Sync(request, callSettings);
}
/// <summary>
/// Gets a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Table> GetTableAsync(GetTableRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetTableRequest(ref request, ref callSettings);
return _callGetTable.Async(request, callSettings);
}
/// <summary>
/// Lists tables for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Table"/> resources.</returns>
public override gax::PagedEnumerable<ListTablesResponse, Table> ListTables(ListTablesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListTablesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListTablesRequest, ListTablesResponse, Table>(_callListTables, request, callSettings);
}
/// <summary>
/// Lists tables for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Table"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListTablesResponse, Table> ListTablesAsync(ListTablesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListTablesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListTablesRequest, ListTablesResponse, Table>(_callListTables, request, callSettings);
}
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Workspace GetWorkspace(GetWorkspaceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetWorkspaceRequest(ref request, ref callSettings);
return _callGetWorkspace.Sync(request, callSettings);
}
/// <summary>
/// Gets a workspace. Returns NOT_FOUND if the workspace does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Workspace> GetWorkspaceAsync(GetWorkspaceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetWorkspaceRequest(ref request, ref callSettings);
return _callGetWorkspace.Async(request, callSettings);
}
/// <summary>
/// Lists workspaces for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Workspace"/> resources.</returns>
public override gax::PagedEnumerable<ListWorkspacesResponse, Workspace> ListWorkspaces(ListWorkspacesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListWorkspacesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListWorkspacesRequest, ListWorkspacesResponse, Workspace>(_callListWorkspaces, request, callSettings);
}
/// <summary>
/// Lists workspaces for the user.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Workspace"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListWorkspacesResponse, Workspace> ListWorkspacesAsync(ListWorkspacesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListWorkspacesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListWorkspacesRequest, ListWorkspacesResponse, Workspace>(_callListWorkspaces, request, callSettings);
}
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Row GetRow(GetRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRowRequest(ref request, ref callSettings);
return _callGetRow.Sync(request, callSettings);
}
/// <summary>
/// Gets a row. Returns NOT_FOUND if the row does not exist in the table.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Row> GetRowAsync(GetRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRowRequest(ref request, ref callSettings);
return _callGetRow.Async(request, callSettings);
}
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Row"/> resources.</returns>
public override gax::PagedEnumerable<ListRowsResponse, Row> ListRows(ListRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListRowsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListRowsRequest, ListRowsResponse, Row>(_callListRows, request, callSettings);
}
/// <summary>
/// Lists rows in a table. Returns NOT_FOUND if the table does not exist.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Row"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListRowsResponse, Row> ListRowsAsync(ListRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListRowsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListRowsRequest, ListRowsResponse, Row>(_callListRows, request, callSettings);
}
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Row CreateRow(CreateRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateRowRequest(ref request, ref callSettings);
return _callCreateRow.Sync(request, callSettings);
}
/// <summary>
/// Creates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Row> CreateRowAsync(CreateRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateRowRequest(ref request, ref callSettings);
return _callCreateRow.Async(request, callSettings);
}
/// <summary>
/// Creates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override BatchCreateRowsResponse BatchCreateRows(BatchCreateRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchCreateRowsRequest(ref request, ref callSettings);
return _callBatchCreateRows.Sync(request, callSettings);
}
/// <summary>
/// Creates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<BatchCreateRowsResponse> BatchCreateRowsAsync(BatchCreateRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchCreateRowsRequest(ref request, ref callSettings);
return _callBatchCreateRows.Async(request, callSettings);
}
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Row UpdateRow(UpdateRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateRowRequest(ref request, ref callSettings);
return _callUpdateRow.Sync(request, callSettings);
}
/// <summary>
/// Updates a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Row> UpdateRowAsync(UpdateRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateRowRequest(ref request, ref callSettings);
return _callUpdateRow.Async(request, callSettings);
}
/// <summary>
/// Updates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override BatchUpdateRowsResponse BatchUpdateRows(BatchUpdateRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchUpdateRowsRequest(ref request, ref callSettings);
return _callBatchUpdateRows.Sync(request, callSettings);
}
/// <summary>
/// Updates multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<BatchUpdateRowsResponse> BatchUpdateRowsAsync(BatchUpdateRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchUpdateRowsRequest(ref request, ref callSettings);
return _callBatchUpdateRows.Async(request, callSettings);
}
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void DeleteRow(DeleteRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteRowRequest(ref request, ref callSettings);
_callDeleteRow.Sync(request, callSettings);
}
/// <summary>
/// Deletes a row.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task DeleteRowAsync(DeleteRowRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteRowRequest(ref request, ref callSettings);
return _callDeleteRow.Async(request, callSettings);
}
/// <summary>
/// Deletes multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void BatchDeleteRows(BatchDeleteRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchDeleteRowsRequest(ref request, ref callSettings);
_callBatchDeleteRows.Sync(request, callSettings);
}
/// <summary>
/// Deletes multiple rows.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task BatchDeleteRowsAsync(BatchDeleteRowsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchDeleteRowsRequest(ref request, ref callSettings);
return _callBatchDeleteRows.Async(request, callSettings);
}
}
public partial class ListTablesRequest : gaxgrpc::IPageRequest
{
}
public partial class ListWorkspacesRequest : gaxgrpc::IPageRequest
{
}
public partial class ListRowsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListTablesResponse : gaxgrpc::IPageResponse<Table>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Table> GetEnumerator() => Tables.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class ListWorkspacesResponse : gaxgrpc::IPageResponse<Workspace>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Workspace> GetEnumerator() => Workspaces.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class ListRowsResponse : gaxgrpc::IPageResponse<Row>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Row> GetEnumerator() => Rows.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeClientVpnRoutesResult.java | 7137 | /*
* 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.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceResult;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeClientVpnRoutesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Information about the Client VPN endpoint routes.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ClientVpnRoute> routes;
/**
* <p>
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no more
* results to return.
* </p>
*/
private String nextToken;
/**
* <p>
* Information about the Client VPN endpoint routes.
* </p>
*
* @return Information about the Client VPN endpoint routes.
*/
public java.util.List<ClientVpnRoute> getRoutes() {
if (routes == null) {
routes = new com.amazonaws.internal.SdkInternalList<ClientVpnRoute>();
}
return routes;
}
/**
* <p>
* Information about the Client VPN endpoint routes.
* </p>
*
* @param routes
* Information about the Client VPN endpoint routes.
*/
public void setRoutes(java.util.Collection<ClientVpnRoute> routes) {
if (routes == null) {
this.routes = null;
return;
}
this.routes = new com.amazonaws.internal.SdkInternalList<ClientVpnRoute>(routes);
}
/**
* <p>
* Information about the Client VPN endpoint routes.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setRoutes(java.util.Collection)} or {@link #withRoutes(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param routes
* Information about the Client VPN endpoint routes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeClientVpnRoutesResult withRoutes(ClientVpnRoute... routes) {
if (this.routes == null) {
setRoutes(new com.amazonaws.internal.SdkInternalList<ClientVpnRoute>(routes.length));
}
for (ClientVpnRoute ele : routes) {
this.routes.add(ele);
}
return this;
}
/**
* <p>
* Information about the Client VPN endpoint routes.
* </p>
*
* @param routes
* Information about the Client VPN endpoint routes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeClientVpnRoutesResult withRoutes(java.util.Collection<ClientVpnRoute> routes) {
setRoutes(routes);
return this;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no more
* results to return.
* </p>
*
* @param nextToken
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no
* more results to return.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no more
* results to return.
* </p>
*
* @return The token to use to retrieve the next page of results. This value is <code>null</code> when there are no
* more results to return.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no more
* results to return.
* </p>
*
* @param nextToken
* The token to use to retrieve the next page of results. This value is <code>null</code> when there are no
* more results to return.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeClientVpnRoutesResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRoutes() != null)
sb.append("Routes: ").append(getRoutes()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeClientVpnRoutesResult == false)
return false;
DescribeClientVpnRoutesResult other = (DescribeClientVpnRoutesResult) obj;
if (other.getRoutes() == null ^ this.getRoutes() == null)
return false;
if (other.getRoutes() != null && other.getRoutes().equals(this.getRoutes()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRoutes() == null) ? 0 : getRoutes().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public DescribeClientVpnRoutesResult clone() {
try {
return (DescribeClientVpnRoutesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
SecUSo/EasyVote | vcd_votedevice/src/main/java/de/tud/vcd/votedevice/ampel/StatusSignaling.java | 1381 | /*******************************************************************************
* # Copyright 2015 SecUSo.org / Jurlind Budurushi / Roman Jöris
* #
* # 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.tud.vcd.votedevice.ampel;
public interface StatusSignaling {
/**
* Setzt den Status der Signalisierung auf Rot
*/
public abstract void setRed();
/**
* Setzt den Status der Signalisierung auf Grün
*/
public abstract void setGreen();
/**
* Setzt den Status der Signalisierung auf Orange/Gelb
*/
public abstract void setOrange();
/**
* Setzt den Status der Signalisierung auf den INitialzustand
*/
public abstract void setInit();
//public abstract boolean unlockAllowed();
} | apache-2.0 |
McLeodMoores/starling | projects/analytics/src/main/java/com/opengamma/analytics/financial/provider/calculator/discounting/CashFlowEquivalentCurveSensitivityCalculator.java | 8719 | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.provider.calculator.discounting;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitorAdapter;
import com.opengamma.analytics.financial.interestrate.annuity.derivative.Annuity;
import com.opengamma.analytics.financial.interestrate.annuity.derivative.AnnuityCouponFixed;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponFixed;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIbor;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIborSpread;
import com.opengamma.analytics.financial.interestrate.payments.derivative.Payment;
import com.opengamma.analytics.financial.interestrate.payments.derivative.PaymentFixed;
import com.opengamma.analytics.financial.interestrate.swap.derivative.Swap;
import com.opengamma.analytics.financial.interestrate.swap.derivative.SwapFixedCoupon;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ForwardSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.SimplyCompoundedForwardSensitivity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.DoublesPair;
/**
* Calculator of the cash flow equivalent sensitivity to the curve. The result is a map from Double to {@link MulticurveSensitivity}. The cash flow equivalent
* sensitivity is represented by the double which is the time of the cash flow and the MulticurveSensitivity which is the sensitivity of the cash flow at that
* date.
*/
public class CashFlowEquivalentCurveSensitivityCalculator
extends InstrumentDerivativeVisitorAdapter<MulticurveProviderInterface, Map<Double, MulticurveSensitivity>> {
/**
* The unique instance of the calculator.
*/
private static final CashFlowEquivalentCurveSensitivityCalculator INSTANCE = new CashFlowEquivalentCurveSensitivityCalculator();
/**
* Gets the calculator instance.
*
* @return The calculator.
*/
public static CashFlowEquivalentCurveSensitivityCalculator getInstance() {
return INSTANCE;
}
/**
* Constructor.
*/
CashFlowEquivalentCurveSensitivityCalculator() {
}
@Override
public Map<Double, MulticurveSensitivity> visitFixedPayment(final PaymentFixed payment, final MulticurveProviderInterface multicurves) {
return new HashMap<>();
}
@Override
public Map<Double, MulticurveSensitivity> visitCouponFixed(final CouponFixed coupon, final MulticurveProviderInterface multicurves) {
return new HashMap<>();
}
@Override
public Map<Double, MulticurveSensitivity> visitCouponIbor(final CouponIbor payment, final MulticurveProviderInterface multicurves) {
ArgumentChecker.notNull(payment, "Payment");
ArgumentChecker.notNull(multicurves, "Multicurves provider");
final Currency ccy = payment.getCurrency();
final double fixingStartTime = payment.getFixingPeriodStartTime();
final double fixingEndTime = payment.getFixingPeriodEndTime();
final double paymentTime = payment.getPaymentTime();
final double dfRatio = multicurves.getDiscountFactor(ccy, paymentTime) / multicurves.getDiscountFactor(ccy, fixingStartTime);
final double af = payment.getFixingAccrualFactor();
final double beta = (1.0
+ af * multicurves.getSimplyCompoundForwardRate(payment.getIndex(), fixingStartTime, fixingEndTime, payment.getFixingAccrualFactor())) * dfRatio;
final double betaBar = payment.getNotional() * payment.getPaymentYearFraction() / af;
final double forwardBar = af * dfRatio * betaBar;
final Map<Double, MulticurveSensitivity> result = new HashMap<>();
final Map<String, List<ForwardSensitivity>> resultFwd = new HashMap<>();
final List<ForwardSensitivity> listForward = new ArrayList<>();
listForward.add(new SimplyCompoundedForwardSensitivity(fixingStartTime, fixingEndTime, af, forwardBar));
resultFwd.put(multicurves.getName(payment.getIndex()), listForward);
final Map<String, List<DoublesPair>> resultDsc = new HashMap<>();
final List<DoublesPair> listDisc = new ArrayList<>();
final DoublesPair discStart = DoublesPair.of(fixingStartTime, beta * fixingStartTime * betaBar);
listDisc.add(discStart);
final DoublesPair discPay = DoublesPair.of(paymentTime, -paymentTime * beta * betaBar);
listDisc.add(discPay);
resultDsc.put(multicurves.getName(ccy), listDisc);
result.put(fixingStartTime, MulticurveSensitivity.of(resultDsc, resultFwd));
return result;
}
@Override
public Map<Double, MulticurveSensitivity> visitCouponIborSpread(final CouponIborSpread payment, final MulticurveProviderInterface multicurves) {
ArgumentChecker.notNull(payment, "Payment");
ArgumentChecker.notNull(multicurves, "Multicurves provider");
final Currency ccy = payment.getCurrency();
final double fixingStartTime = payment.getFixingPeriodStartTime();
final double fixingEndTime = payment.getFixingPeriodEndTime();
final double paymentTime = payment.getPaymentTime();
final double dfRatio = multicurves.getDiscountFactor(ccy, paymentTime) / multicurves.getDiscountFactor(ccy, fixingStartTime);
final double af = payment.getFixingAccrualFactor();
final double beta = (1.0
+ af * multicurves.getSimplyCompoundForwardRate(payment.getIndex(), fixingStartTime, fixingEndTime, payment.getFixingAccrualFactor())) * dfRatio;
final double betaBar = payment.getNotional() * payment.getPaymentYearFraction() / af;
final double forwardBar = af * dfRatio * betaBar;
final Map<Double, MulticurveSensitivity> result = new HashMap<>();
final Map<String, List<ForwardSensitivity>> resultFwd = new HashMap<>();
final List<ForwardSensitivity> listForward = new ArrayList<>();
listForward.add(new SimplyCompoundedForwardSensitivity(fixingStartTime, fixingEndTime, af, forwardBar));
resultFwd.put(multicurves.getName(payment.getIndex()), listForward);
final Map<String, List<DoublesPair>> resultDsc = new HashMap<>();
final List<DoublesPair> listDisc = new ArrayList<>();
final DoublesPair discStart = DoublesPair.of(fixingStartTime, beta * fixingStartTime * betaBar);
listDisc.add(discStart);
final DoublesPair discPay = DoublesPair.of(paymentTime, -paymentTime * beta * betaBar);
listDisc.add(discPay);
resultDsc.put(multicurves.getName(ccy), listDisc);
result.put(fixingStartTime, MulticurveSensitivity.of(resultDsc, resultFwd));
return result;
}
@Override
public Map<Double, MulticurveSensitivity> visitGenericAnnuity(final Annuity<? extends Payment> annuity, final MulticurveProviderInterface multicurves) {
ArgumentChecker.notNull(annuity, "Annuity");
ArgumentChecker.notNull(multicurves, "Multicurves provider");
final Map<Double, MulticurveSensitivity> result = new HashMap<>();
for (final Payment p : annuity.getPayments()) {
final Map<Double, MulticurveSensitivity> paymentSensi = p.accept(this, multicurves);
result.putAll(paymentSensi);
// It is suppose that no two coupons have the same cfe sensitivity date.
}
return result;
}
@Override
public Map<Double, MulticurveSensitivity> visitFixedCouponAnnuity(final AnnuityCouponFixed annuity, final MulticurveProviderInterface multicurves) {
return visitGenericAnnuity(annuity, multicurves);
}
@Override
public Map<Double, MulticurveSensitivity> visitSwap(final Swap<?, ?> swap, final MulticurveProviderInterface multicurves) {
ArgumentChecker.notNull(swap, "Swap");
ArgumentChecker.notNull(multicurves, "Multicurves provider");
final Map<Double, MulticurveSensitivity> result = new HashMap<>();
final Map<Double, MulticurveSensitivity> legSensi1 = swap.getFirstLeg().accept(this, multicurves);
result.putAll(legSensi1);
final Map<Double, MulticurveSensitivity> legSensi2 = swap.getSecondLeg().accept(this, multicurves);
result.putAll(legSensi2);
// It is suppose that the two legs have different cfe sensitivity date.
return result;
}
@Override
public Map<Double, MulticurveSensitivity> visitFixedCouponSwap(final SwapFixedCoupon<?> swap, final MulticurveProviderInterface multicurves) {
return visitSwap(swap, multicurves);
}
}
| apache-2.0 |
quarkusio/quarkus | extensions/oidc/runtime/src/main/java/io/quarkus/oidc/TenantResolver.java | 629 | package io.quarkus.oidc;
import io.vertx.ext.web.RoutingContext;
/**
* A tenant resolver is responsible for resolving tenants dynamically so that the proper configuration can be used accordingly.
*/
public interface TenantResolver {
/**
* Returns a tenant identifier given a {@code RoutingContext}, where the identifier will be used to choose the proper
* configuration during runtime.
*
* @param context the routing context
* @return the tenant identifier. If {@code null}, indicates that the default configuration/tenant should be chosen
*/
String resolve(RoutingContext context);
}
| apache-2.0 |
nickolasnikolic/leesh-mobile-app | Resources/struct/model/entities/persons.js | 216 | var persons = new joli.model({
table: 'persons',
columns: {
id: 'INTEGER',
locationID: 'INTEGER',
name: 'TEXT',
description: 'TEXT'
}
}); | apache-2.0 |
balajivenki/dyno | dyno-contrib/src/main/java/com/netflix/dyno/contrib/consul/ConsulHostsSupplier.java | 5797 | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.dyno.contrib.consul;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.health.model.HealthService;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.dyno.connectionpool.Host;
import com.netflix.dyno.connectionpool.HostSupplier;
/**
* Simple class that implements {@link Supplier}<{@link List}<{@link Host}>>. It provides a List<{@link Host}>
* using the {@link DiscoveryManager} which is the consul client.
*
* Note that the class needs the consul application name to discover all instances for that application.
*
* Example of register at consul
*
curl -X PUT http://localhost:8500/v1/agent/service/register -d "{
\"ID\": \"dynomite-8102\",
\"Name\": \"dynomite\",
\"Tags\": [\"datacenter=dc\",\"cloud=openstack\",\"rack=dc-rack\"],
\"Address\": \"127.0.0.2\",
\"Port\": 8102,
\"Check\": {
\"Interval\": \"10s\",
\"HTTP\": \"http://127.0.0.1:22222/ping\"
}}"
*
* @author tiodollar
*/
public class ConsulHostsSupplier implements HostSupplier {
private static final Logger Logger = LoggerFactory.getLogger(ConsulHostsSupplier.class);
// The Dynomite cluster name for discovering nodes
private final String applicationName;
private final ConsulClient discoveryClient;
public ConsulHostsSupplier(String applicationName, ConsulClient discoveryClient) {
this.applicationName = applicationName;
this.discoveryClient = discoveryClient;
}
public static ConsulHostsSupplier newInstance(String applicationName, ConsulHostsSupplier hostsSupplier) {
return new ConsulHostsSupplier(applicationName, hostsSupplier.getDiscoveryClient());
}
@Override
public List<Host> getHosts() {
return getUpdateFromConsul();
}
private List<Host> getUpdateFromConsul() {
if (discoveryClient == null) {
Logger.error("Discovery client cannot be null");
throw new RuntimeException("ConsulHostsSupplier needs a non-null DiscoveryClient");
}
Logger.info("Dyno fetching instance list for app: " + applicationName);
Response<List<HealthService>> services = discoveryClient.getHealthServices(applicationName, false, QueryParams.DEFAULT);
List<HealthService> app = services.getValue();
List<Host> hosts = new ArrayList<Host>();
if (app != null && app.size() < 0) {
return hosts;
}
hosts = Lists.newArrayList(Collections2.transform(app,
new Function<HealthService, Host>() {
@Override
public Host apply(HealthService info) {
String hostName = ConsulHelper.findHost(info);
Map<String, String> metaData = ConsulHelper.getMetadata(info);
Host.Status status = Host.Status.Up;
for (com.ecwid.consul.v1.health.model.Check check : info.getChecks()) {
if (check.getStatus() == Check.CheckStatus.CRITICAL) {
status = Host.Status.Down;
break;
}
}
String rack = null;
try {
if (metaData.containsKey("cloud") && StringUtils.equals(metaData.get("cloud"), "aws")) {
rack = metaData.get("availability-zone");
} else {
rack = metaData.get("rack");
}
} catch (Throwable t) {
Logger.error("Error getting rack for host " + info.getNode(), t);
}
if (rack == null) {
Logger.error("Rack wasn't found for host:" + info.getNode()
+ " there may be issues matching it up to the token map");
}
Host host = new Host(hostName, hostName, info.getService().getPort(), rack,
String.valueOf(metaData.get("datacenter")), status);
return host;
}
}));
Logger.info("Dyno found hosts from consul - num hosts: " + hosts.size());
return hosts;
}
@Override
public String toString() {
return ConsulHostsSupplier.class.getName();
}
public String getApplicationName() {
return applicationName;
}
public ConsulClient getDiscoveryClient() {
return discoveryClient;
}
} | apache-2.0 |
bitsofinfo/hazelcast-docker-swarm-discovery-spi | src/main/java/org/bitsofinfo/hazelcast/discovery/docker/swarm/filter/NameBasedServiceFilter.java | 796 | package org.bitsofinfo.hazelcast.discovery.docker.swarm.filter;
import com.spotify.docker.client.messages.swarm.Service;
public class NameBasedServiceFilter extends AbstractServiceFilter {
private String serviceName;
public NameBasedServiceFilter(String serviceName) {
this.serviceName = serviceName;
}
/**
* @see ServiceFilter#accept(Service)
*/
@Override
public boolean accept(Service service) {
try {
return serviceName.equals(service.spec().name());
} catch (NullPointerException e) {
return false;
}
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return "ServiceNameFilter: \"" + serviceName + "\".equals(service.spec().name())";
}
}
| apache-2.0 |
JoelMarcey/buck | src/com/facebook/buck/jvm/kotlin/KotlinLibraryDescription.java | 4580 | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.kotlin;
import com.facebook.buck.jvm.java.DefaultJavaLibrary;
import com.facebook.buck.jvm.java.HasJavaAbi;
import com.facebook.buck.jvm.java.JavaLibrary;
import com.facebook.buck.jvm.java.JavaLibraryDescription;
import com.facebook.buck.jvm.java.JavaSourceJar;
import com.facebook.buck.jvm.java.MavenUberJar;
import com.facebook.buck.maven.AetherUtil;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
public class KotlinLibraryDescription
implements Description<KotlinLibraryDescription.Arg>, Flavored {
private final KotlinBuckConfig kotlinBuckConfig;
public static final ImmutableSet<Flavor> SUPPORTED_FLAVORS =
ImmutableSet.of(JavaLibrary.SRC_JAR, JavaLibrary.MAVEN_JAR);
public KotlinLibraryDescription(KotlinBuckConfig kotlinBuckConfig) {
this.kotlinBuckConfig = kotlinBuckConfig;
}
@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
return SUPPORTED_FLAVORS.containsAll(flavors);
}
@Override
public Class<Arg> getConstructorArgType() {
return Arg.class;
}
@Override
public BuildRule createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
Arg args)
throws NoSuchBuildTargetException {
BuildTarget target = params.getBuildTarget();
ImmutableSortedSet<Flavor> flavors = target.getFlavors();
BuildRuleParams paramsWithMavenFlavor = null;
if (flavors.contains(JavaLibrary.MAVEN_JAR)) {
paramsWithMavenFlavor = params;
// Maven rules will depend upon their vanilla versions, so the latter have to be constructed
// without the maven flavor to prevent output-path conflict
params = params.withoutFlavor(JavaLibrary.MAVEN_JAR);
}
if (flavors.contains(JavaLibrary.SRC_JAR)) {
args.mavenCoords =
args.mavenCoords.map(
input -> AetherUtil.addClassifier(input, AetherUtil.CLASSIFIER_SOURCES));
if (!flavors.contains(JavaLibrary.MAVEN_JAR)) {
return new JavaSourceJar(params, args.srcs, args.mavenCoords);
} else {
return MavenUberJar.SourceJar.create(
Preconditions.checkNotNull(paramsWithMavenFlavor),
args.srcs,
args.mavenCoords,
args.mavenPomTemplate);
}
}
DefaultKotlinLibraryBuilder defaultKotlinLibraryBuilder =
new DefaultKotlinLibraryBuilder(params, resolver, kotlinBuckConfig).setArgs(args);
// We know that the flavour we're being asked to create is valid, since the check is done when
// creating the action graph from the target graph.
if (HasJavaAbi.isAbiTarget(target)) {
return defaultKotlinLibraryBuilder.buildAbi();
}
DefaultJavaLibrary defaultKotlinLibrary = defaultKotlinLibraryBuilder.build();
if (!flavors.contains(JavaLibrary.MAVEN_JAR)) {
return defaultKotlinLibrary;
} else {
return MavenUberJar.create(
defaultKotlinLibrary,
Preconditions.checkNotNull(paramsWithMavenFlavor),
args.mavenCoords,
args.mavenPomTemplate);
}
}
@SuppressFieldNotInitialized
public static class Arg extends JavaLibraryDescription.Arg {
public ImmutableList<String> extraKotlincArguments = ImmutableList.of();
}
}
| apache-2.0 |
FinishX/coolweather | gradle/gradle-2.8/src/platform-play/org/gradle/play/internal/twirl/VersionedTwirlCompilerAdapter.java | 1317 | /*
* Copyright 2014 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 org.gradle.play.internal.twirl;
import org.gradle.scala.internal.reflect.ScalaMethod;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
public interface VersionedTwirlCompilerAdapter extends Serializable {
String getDependencyNotation();
ScalaMethod getCompileMethod(ClassLoader cl) throws ClassNotFoundException;
Object[] createCompileParameters(ClassLoader cl, File file, File sourceDirectory, File destinationDirectory, boolean javaProject) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException;
Iterable<String> getClassLoaderPackages();
}
| apache-2.0 |
apache/incubator-shardingsphere | sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/sharding/merge/dql/orderby/OrderByStreamMergedResult.java | 3517 | /*
* 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.shardingsphere.sharding.merge.dql.orderby;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.shardingsphere.sql.parser.binder.metadata.schema.SchemaMetaData;
import org.apache.shardingsphere.sql.parser.binder.statement.dml.SelectStatementContext;
import org.apache.shardingsphere.underlying.executor.sql.queryresult.QueryResult;
import org.apache.shardingsphere.underlying.merge.result.impl.stream.StreamMergedResult;
import org.apache.shardingsphere.sql.parser.binder.segment.select.orderby.OrderByItem;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Stream merged result for order by.
*/
public class OrderByStreamMergedResult extends StreamMergedResult {
private final Collection<OrderByItem> orderByItems;
@Getter(AccessLevel.PROTECTED)
private final Queue<OrderByValue> orderByValuesQueue;
@Getter(AccessLevel.PROTECTED)
private boolean isFirstNext;
public OrderByStreamMergedResult(final List<QueryResult> queryResults, final SelectStatementContext selectStatementContext, final SchemaMetaData schemaMetaData) throws SQLException {
this.orderByItems = selectStatementContext.getOrderByContext().getItems();
this.orderByValuesQueue = new PriorityQueue<>(queryResults.size());
orderResultSetsToQueue(queryResults, selectStatementContext, schemaMetaData);
isFirstNext = true;
}
private void orderResultSetsToQueue(final List<QueryResult> queryResults, final SelectStatementContext selectStatementContext, final SchemaMetaData schemaMetaData) throws SQLException {
for (QueryResult each : queryResults) {
OrderByValue orderByValue = new OrderByValue(each, orderByItems, selectStatementContext, schemaMetaData);
if (orderByValue.next()) {
orderByValuesQueue.offer(orderByValue);
}
}
setCurrentQueryResult(orderByValuesQueue.isEmpty() ? queryResults.get(0) : orderByValuesQueue.peek().getQueryResult());
}
@Override
public boolean next() throws SQLException {
if (orderByValuesQueue.isEmpty()) {
return false;
}
if (isFirstNext) {
isFirstNext = false;
return true;
}
OrderByValue firstOrderByValue = orderByValuesQueue.poll();
if (firstOrderByValue.next()) {
orderByValuesQueue.offer(firstOrderByValue);
}
if (orderByValuesQueue.isEmpty()) {
return false;
}
setCurrentQueryResult(orderByValuesQueue.peek().getQueryResult());
return true;
}
}
| apache-2.0 |
aot-pro/aot-sdk-java | src/main/java/aot/util/JsonUtil.java | 2564 | /*
* Copyright (C) 2016 Dmitry Kotlyarov.
* 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.
*/
package aot.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Dmitry Kotlyarov
* @since 1.0
*/
public final class JsonUtil {
public static final String APPLICATION_JSON = "application/json";
private static final JsonFactory factory = new JsonFactory();
private static final ObjectMapper mapper = new ObjectMapper(factory);
private JsonUtil() {
}
public static byte[] toBytes(Object value) {
try {
return mapper.writeValueAsBytes(value);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T fromBytes(byte[] data, Class<T> type) {
try {
return mapper.readValue(data, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void writeBytes(OutputStream output, Object value) {
try {
mapper.writeValue(output, value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T readBytes(InputStream input, Class<T> type) {
try {
return mapper.readValue(input, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String toString(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T fromString(String content, Class<T> type) {
try {
return mapper.readValue(content, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
ctr-lang/ctr | lib/ctr-nodes/target/target-stack-manager.js | 15098 | const _ = require('lodash');
const defclass = require('defclass');
const Immutable = require('immutable');
const throwErr = require('./target-errors.js');
const _M = require('../manager/manager-index.js');
const StackManager = defclass({
constructor: function (target) {
const self = this;
//set list
self.car = Immutable.List();
self.cdr = Immutable.List();
self.media = Immutable.List();
self.override = Immutable.List();
//set refs
self.target = target;
self.appendToIndex = false;
self.attachToOption = false;
self.stackSize = target.get('stack').size;
self.inheritSelector = _M._option.getIn(['inheritSelector']);
//swap keys when we are checking key order
self.elmNotSwap = ['after', 'before', 'first-letter', 'first-line', 'selection',
'backdrop', 'placeholder', 'marker', 'spelling-error', 'grammar-error'];
},
/**
* Wrapper to see if last in statck
* @return {bln} -> Only sith lords deal in absolutes
*/
isLastStack: function () {
const self = this;
return self.cdr.size === (self.stackSize - 1);
},
/**
* Configs media, with one catch. If there is more than one media, as in
* if there is a media within a media we will want to `and` that shit
* together.
* @param {str} curMedia -> current Media
* @param {str} newMedia -> new Media
* @return {str} -> media
*/
configMedia: function (curMedia, newMedia) {
if (!curMedia.length) {
return newMedia;
}
//@test
//join this shit up, inception type media
//need to slice it to remove any prefix like screen
curMedia = curMedia + ' and ' + newMedia.slice(newMedia.indexOf('('));
return curMedia;
},
/**
* AppendTo target Option, this guy is a bit tricky just depepending
* on if we are dealing with a inheritSelector we have to make some
* extra adjustments. But typlicall just appendsTo
* @param {str} cdr -> cdr key
* @param {map} optionMap -> option map
* @return {str} -> cdr key
*/
appendTo: function (cdr, optionMap) {
const self = this;
if (optionMap.has('appendTo')) {
// we only need to append with `&` which is done in the
// get fn when we are inheriting the selector
if (self.appendToIndex === false && self.inheritSelector) {
self.appendToIndex = self.cdr.size;
cdr += optionMap.get('appendTo');
}else {
cdr += optionMap.get('appendTo');
}
}
if (optionMap.get('appendKey')) {
if (self.appendToIndex === false && self.inheritSelector) {
self.appendToIndex = self.cdr.size;
}else {
cdr = '&' + cdr;
}
}
return cdr;
},
/**
* ApplyTo target option, just adds a "safe space" cus you know applyTo
* @param {str} cdr -> cdr key
* @param {map} optionMap -> option map
* @return {str} -> key with applyTo if present
*/
applyTo: function (cdr, optionMap) {
if (optionMap.has('applyTo')) {
cdr = cdr + ' ' + optionMap.get('applyTo');
}
return cdr;
},
/**
* AttachTo target option, the impotant part here is that is will set
* the attachToOption upstairs, to the constructor.
* @param {str} cdr -> cdr key
* @param {map} optionMap -> opt map
* @param {str} id -> instance ref for lookup
* @return {srt} -> cdr key
*/
attachTo: function (cdr, optionMap, id) {
if (optionMap.has('attachTo')) {
//get option
let attachTo = optionMap.get('attachTo');
//check if true, if so assing to root str
attachTo = (attachTo === true || attachTo === 0) ? 'root' : attachTo;
//set in the updstairs constructor scrope for pickup on composer
this.attachToOption = {
id: id,
key: cdr,
index: attachTo
};
}
return cdr;
},
/**
* Calles the target options in the order we want
* @param {str} cdr -> cdr key, empty string
* @param {map} optionMap -> optiion map
* @param {str} id -> instace id ref
* @return {str} -> cdr with options applied if any
*/
configCdr: function (cdr, optionMap, id) {
const self = this;
//list order
cdr = self.appendTo(cdr, optionMap);
cdr = self.applyTo(cdr, optionMap);
cdr = self.attachTo(cdr, optionMap, id);
return cdr;
},
/**
* This dude, deals with any interal `_appendTo`s that come his way.
* The gist behing this is states are set with an internal `_appendTo`
* since we will need to append it to whatever its parent key is
* and this does just that if that makes any sense
* @return {---} -> none, just sets global need be
*/
setInternal: function (dataMap) {
const self = this;
//note: _appendTo if interally comes from state
const append = dataMap.getIn(['option', 'specific', '_appendTo'])
&& self.appendToIndex === false
&& self.inheritSelector
&& dataMap.get('type') !== 'transition';
const appendToIndex = append ? self.cdr.size : false;
if (appendToIndex !== false) {
//set global
self.appendToIndex = appendToIndex;
}
},
/**
* Our config man, who configs all the options from all the lands
* @param {map} dataMap -> data ref to what we are configing
* @param {str} id -> id ref
* @return {obj} -> the configed parts
*/
config: function (dataMap, id) {
const self = this;
//set internal, if any
self.setInternal(dataMap);
//assign
const type = dataMap.get('type');
let car = '';
let cdr = type !== 'media' ? dataMap.get('key') : '';
let media = false;
let override = false;
const optionMap = dataMap.getIn(['option', 'target']);
//only config these two on last stack
if (self.isLastStack()) {
//config car
car = optionMap.has('root') ? optionMap.get('root') : car;
//config override
override = optionMap.has('override') ? optionMap.get('override') : override;
}
//config cdr
cdr = self.configCdr(cdr, optionMap, id);
//config media
if (type === 'media') {
media = self.configMedia(self.media.reduce(function (str, val) {
if (val.key) {
str += val.key;
}
return str;
}, ''), dataMap.get('key'));
}
return {
car,
cdr,
media,
override
};
},
/**
* Sets the data, in da lists. It will first config the data though.
* @param {map} dataMap -> data map ref to be configed and set
*/
set: function (dataMap) {
const self = this;
//get type
const type = dataMap.get('type');
const typeIndex = dataMap.get('index');
const id = dataMap.get('id');
//reassing dataMap from type stack
dataMap = self.target.getIn([type, typeIndex]);
//config keys
const {car, cdr, override, media} = self.config(dataMap, id);
//set in list
self.car = self.car.push({
key: car,
type: type,
id: id
});
self.cdr = self.cdr.push({
key: cdr,
type: type,
id: id
});
self.override = self.override.push({
key: override,
type: type,
id: id
});
self.media = self.media.push({
key: media,
type: type,
id: id
});
},
/**
* This bad boy configes the source order of the cdr list. Its a big hitter.
* Its primary purpose is to check if any `elements` and `states` need
* to be swaped. For example `.class:hover:first-child` needs to be swaped
* to `.class:first-child:hover`. This will also config attachTo target option
* if needed.
* @param {list} cdr -> cdr list
* @return {list} -> cdr list sorted all out
*/
composeCdrOrder: function (cdr) {
const self = this;
//config attachTo if needed
if (self.attachToOption) {
//get vals
let {id, index} = self.attachToOption;
//check to see if the same as appendToIndex
let equalsAppendIndex = false;
if (_.isNumber(self.appendToIndex)) {
equalsAppendIndex = cdr.get(self.appendToIndex).id === id;
}
/**
* wrapper funk to get index
* @param {str} id -> id we are looking for
* @return {num} -> index number
*/
const getCurIndex = function (_id) {
return cdr.findIndex(function (val) {
return val.id === _id;
});
};
/**
* wrapper funk to get index reffrance used in sort
* @param {num} indexNum -> index num we are looking for
* @return {obj} -> index
*/
const getIndexRef = function (indexNum) {
const indexRef = cdr.get(indexNum);
//make sure its not a trans, cant attachTo
return indexRef.type !== 'transition'
? indexRef
//pick before or affter that is the question
: cdr.get(indexNum - 1);
};
//assing index reff in not root, can be an index or key
let indexRef;
if (index !== 'root') {
if (index === 'prv' || index === 'previous') {
//get current index
const curIndex = getCurIndex(id);
//assing ref, we use two here, since we are assume the
//user is in a state which is index, so we have to lookup
//outside of the state to the next component
indexRef = getIndexRef(curIndex - 2);
}else {
const indexNum = Number.parseInt(index);
//num ref
if (!_.isNaN(indexNum) && _.isNumber(indexNum)) {
// assing ref
indexRef = getIndexRef(indexNum);
}else {
//if user used a string, literally
indexRef = cdr.find(function (val) {
//probs need to cycle to this to make sure its an exsact match
const reg = new RegExp(index + '(?!.{1})');
if (val.type !== 'transition' && reg.test(val.key)) {
return val;
}
});
}
}
}else {
indexRef = {
id: 'root'
};
}
//assing key
if (indexRef) {
index = indexRef.id;
// sort to new order
cdr = cdr.sort(function (valA, valB) {
if (valA.id === id) {
//foward
if (index === 'root') {
return -1;
}else if (index === valB.id) {
return 0;
}
return -1;
}else if (valB.id === id) {
//backward
if (index === 'root') {
return 1;
}else if (index === valA.id) {
return 0;
}
return 1;
}
return 0;
});
//reassing the appendTo index
if (equalsAppendIndex) {
self.appendToIndex = cdr.findIndex(function (val) {
return val.id === id;
});
}
}else {
//throw error attachTo Key not found
const keyOptions = cdr.map(function (val, i) {
const key = i === 0 ? 'root' : val.key;
return ('[Key ' + i + ']: ' + key);
}).toJS();
throwErr('attachTo', {
key: index,
keyOptions: keyOptions
});
}
}
//reduce to seperate non vals
return cdr.reduce(function (map, val, index) {
if (val.key.length) {
return map.update('val', function (list) {
return list.push({
val: val,
index: index
});
});
}
return map.update('non', function (list) {
return list.push({
val: val,
index: index
});
});
}, Immutable.Map({
val: Immutable.List(),
non: Immutable.List()
}))
//sort val values
.update('val', function (list) {
return list.sort(function (valA, valB) {
//checks to see if element is next to state to see if we
//need to change the sorce order
if (valB.val.type === 'element' && valA.val.type === 'state') {
const cleanKey = valB.val.key.replace(/:/g, '');
if (!_.includes(self.elmNotSwap, cleanKey)) {
//swap indexes
const valAdex = valA.index;
const valBdex = valB.index;
valA.index = valBdex;
valB.index = valAdex;
return 1;
}
}else if (valA.val.type === 'element' && valB.val.type === 'state') {
const cleanKey = valA.val.key.replace(/:/g, '');
if (_.includes(self.elmNotSwap, cleanKey)) {
//swap indexes
const valAdex = valA.index;
const valBdex = valB.index;
valA.index = valBdex;
valB.index = valAdex;
return -1;
}
}
return 0;
});
})
//re-compose
.reduce(function (list, valList) {
return valList.reduce(function (_list, val) {
return _list.set(val.index, val.val);
}, list);
}, Immutable.List());
},
/**
* This will compose and get the key for out output. This pretty damn important
* for two reasons, first this is the key output, but secondly, this is how
* we merge like data. Since all the data is complied before its applied. And
* as you prbly assumed all the data is stored via a immutable map you can check
* index-manager if some more insight or confusion, it depends.
* @return {obj} -> key
*/
get: function () {
const self = this;
//compose cdr
const composedCdr = self.composeCdrOrder(self.cdr);
//compose the family
const selectorList = composedCdr.reduce(function (map, val, index) {
//override
const override = self.override.get(index).key;
if (override) {
return map.set('override', override);
}
//media
const media = self.media.get(index).key;
if (media) {
map = map.set('media', media);
}
//car
const car = self.car.get(index).key;
if (car.length) {
map = map.set('car', car);
}
//cdr
let cdr = val.key;
//no reson to map if val empty
if (cdr.length && val.type !== 'media') {
map = map.update('cdr', function (str) {
//appendTo reffrence
if (self.appendToIndex === index && !str.includes('&')) {
str = '&' + str;
}else if (str.includes('&') && cdr.startsWith('&')) {
//remove '&' which occurs on multi level comp chains appnedKey
cdr = cdr.slice(1);
}
str += cdr;
return str;
});
}
return map;
}, Immutable.Map({
cdr: '',
car: '',
media: false,
override: false
}));
//grab results out of map
const res = {
override: selectorList.get('override'),
selectorCar: selectorList.get('car'),
selectorCdr: selectorList.get('cdr'),
selectorMedia: selectorList.get('media')
};
return res;
}
});
module.exports = StackManager;
| apache-2.0 |
fbaligand/lognavigator | src/main/java/org/lognavigator/util/UriUtil.java | 557 | package org.lognavigator.util;
import static org.lognavigator.util.Constants.URL_ENCODING;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.UnsupportedCharsetException;
/**
* Utility functions for URI processing
*/
public class UriUtil {
/**
* URI encode and return the parameter
*/
public static String encode(String param) {
try {
return URLEncoder.encode(param, URL_ENCODING);
}
catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(URL_ENCODING);
}
}
}
| apache-2.0 |
meat4every1/Smoosh | smoosh/Assets/scripts/MoveListNet.cs | 5595 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class MoveListNet : ScriptableObject
{
ChallengerConNet p1;
public Action<int> jab;
public Action<int> grab;
public Action<int> fweak;
public Action<int> uweak;
public Action<int> dweak;
public Action<int> fstrong;
public Action<int> ustrong;
public Action<int> dstrong;
public Action<int> nspec;
public Action<int> fspec;
public Action<int> uspec;
public Action<int> dspec;
public Action<int> nair;
public Action<int> fair;
public Action<int> bair;
public Action<int> uair;
public Action<int> dair;
public Action<int> dash;
public Action<int> resUpdate;
public int numResources;
public MoveListNet(ChallengerConNet player, string character)
{
p1 = player;
switch (character)
{
case "TMan":
jab = TMANjab;
grab = TMANgrab;
fweak = TMANfweak;
uweak = TMANuweak;
dweak = TMANdweak;
fstrong = TMANfstrong;
ustrong = TMANustrong;
dstrong = TMANdstrong;
nair = TMANnair;
fair = TMANfair;
bair = TMANbair;
uair = TMANuair;
dair = TMANdair;
nspec = TMANnspec;
fspec = TMANfspec;
uspec = TMANuspec;
dspec = TMANdspec;
numResources = 2;
resUpdate = TMANresUpdate;
break;
}
}
// TMAN //////////////////////////////////////////////////////////////
public void TMANfweak(int na)
{
blank();
}
public void TMANuweak(int na)
{
blank();
}
public void TMANdweak(int na)
{
blank();
}
public void TMANfstrong(int na)
{
blank();
}
public void TMANustrong(int na)
{
blank();
}
public void TMANdstrong(int na)
{
blank();
}
public void TMANnair(int na)
{
blank();
}
public void TMANfair(int na)
{
p1.state = "attacking";
p1.lag = 45;
p1.CmdDeQ(9, .3f, 25, Vector3.right * p1.currentDir*.5f+Vector3.up*.5f, true, Vector3.down*.05f+Vector3.right*p1.currentDir*.05f, -p1.currentDir*.1f,
p1.thisPlayer, Vector3.up, 10, 0, false, 0, 150, 10);
//int activeOn, float size, int duration, Vector3 location, bool tethered, Vector3 direction, float rotation,
//int playerNum, Vector3 angle, int dmg, int sdmg, bool grab, int priority, float bkb, float skb)
}
public void TMANbair(int na)
{
blank();
}
public void TMANuair(int na)
{
blank();
}
public void TMANdair(int na)
{
blank();
}
public void TMANnspec(int na)
{
if (p1.resource[1] > 0)
{
p1.resource[1]--;
p1.state = "attacking";
p1.lag = 7;
p1.bbDeQ();
BlankBoxNet bb = p1.currentBB;
bb.duration = 4;
bb.act = delegate (int n)
{
bb.duration--;
if (bb.duration == 1)
{
//
p1.transform.position += Vector3.right * ((p1.mouseX - p1.screenPos.x) / (float)Math.Sqrt((p1.mouseX - p1.screenPos.x) * (p1.mouseX - p1.screenPos.x) + (p1.mouseY - p1.screenPos.y) * (p1.mouseY - p1.screenPos.y)));
p1.transform.position += Vector3.up * ((p1.mouseY - p1.screenPos.y) / (float)Math.Sqrt((p1.mouseX - p1.screenPos.x) * (p1.mouseX - p1.screenPos.x) + (p1.mouseY - p1.screenPos.y) * (p1.mouseY - p1.screenPos.y)));
}
if (bb.duration == 0)
{
p1.bbEnQ(bb);
bb.act = bb.blank;
}
};
}
}
public void TMANfspec(int na)
{
blank();
}
public void TMANuspec(int na)
{
blank();
}
public void TMANdspec(int na)
{
p1.state = "attacking";
p1.lag = 10;
p1.CmdDeQ(15, .5f, 200, Vector3.right * p1.currentDir, false, Vector3.zero, 0,
0, Vector3.up, 10, 0, false, 0, 150, 10);
//bool active, int activeOn, float size, int duration, Vector3 location, bool tethered, Vector3 direction, float rotation
//int playerNum, float angle, int dmg, int sdmg, bool grab, int priority, float bkb, float skb
}
public void TMANjab(int na)
{
p1.state = "attacking";
p1.lag = 60;
p1.CmdDeQ(15, .2f, 55, Vector3.right * p1.currentDir, true, Vector3.zero, 0,
p1.thisPlayer, Vector3.up, 5, 5, false, 0, 50, 10);
//bool active, int activeOn, float size, int duration, Vector3 location, bool tethered, Vector3 direction, float rotation
//int playerNum, float angle, int dmg, int sdmg, bool grab, int priority, float bkb, float skb
}
public void TMANgrab(int na)
{
blank();
}
public void TMANresUpdate(int na)
{
//Debug.Log("update");
if (p1.resource[0] < 120)
{
p1.resource[0]++;
}
else
{
if (p1.resource[1] < 2)
{
p1.resource[1]++;
p1.resource[0] = 0;
}
else
{
p1.resource[0] = 0;
}
}
}
public void blank() { }
}
| apache-2.0 |
scribble/scribble.github.io | src/main/jbake/assets/docs/scribble/modules/core/src/main/java/org/scribble/del/local/LRecursionDel.java | 4342 | package org.scribble.del.local;
import org.scribble.ast.AstFactoryImpl;
import org.scribble.ast.Recursion;
import org.scribble.ast.ScribNode;
import org.scribble.ast.local.LProtocolBlock;
import org.scribble.ast.local.LRecursion;
import org.scribble.ast.name.simple.RecVarNode;
import org.scribble.del.RecursionDel;
import org.scribble.main.ScribbleException;
import org.scribble.sesstype.name.RecVar;
import org.scribble.visit.ProtocolDefInliner;
import org.scribble.visit.context.EGraphBuilder;
import org.scribble.visit.context.ProjectedChoiceSubjectFixer;
import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker;
import org.scribble.visit.context.env.UnguardedChoiceDoEnv;
import org.scribble.visit.env.InlineProtocolEnv;
import org.scribble.visit.wf.ReachabilityChecker;
import org.scribble.visit.wf.env.ReachabilityEnv;
public class LRecursionDel extends RecursionDel implements LCompoundInteractionNodeDel
{
@Override
public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException
{
Recursion<?> rec = (Recursion<?>) visited;
UnguardedChoiceDoEnv merged = checker.popEnv().mergeContext((UnguardedChoiceDoEnv) rec.block.del().env());
checker.pushEnv(merged);
return (Recursion<?>) super.leaveUnguardedChoiceDoProjectionCheck(parent, child, checker, rec);
}
@Override
public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException
{
LRecursion lr = (LRecursion) visited;
//RecVarNode recvar = lr.recvar.clone();
RecVarNode recvar = (RecVarNode) ((InlineProtocolEnv) lr.recvar.del().env()).getTranslation();
LProtocolBlock block = (LProtocolBlock) ((InlineProtocolEnv) lr.block.del().env()).getTranslation();
LRecursion inlined = AstFactoryImpl.FACTORY.LRecursion(lr.getSource(), recvar, block);
inl.pushEnv(inl.popEnv().setTranslation(inlined));
return (LRecursion) super.leaveProtocolInlining(parent, child, inl, lr);
}
@Override
public LRecursion leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException
{
LRecursion lr = (LRecursion) visited;
ReachabilityEnv env = checker.popEnv().mergeContext((ReachabilityEnv) lr.block.del().env());
env = env.removeContinueLabel(lr.recvar.toName());
checker.pushEnv(env);
return (LRecursion) LCompoundInteractionNodeDel.super.leaveReachabilityCheck(parent, child, checker, visited); // records the current checker Env to the current del; also pops and merges that env into the parent env*/
}
@Override
public void enterEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph)
{
super.enterEGraphBuilding(parent, child, graph);
LRecursion lr = (LRecursion) child;
RecVar rv = lr.recvar.toName();
// Update existing state, not replace it -- cf. LDoDel
/*if (graph.builder.isUnguardedInChoice()) // Actually, not needed since unfoldings are enough to make graph building work (and this makes combined unguarded choice-rec and continue protocols work)
{
// Using "previous" entry for this rec lab works because unguarded recs already unfolded (including nested recvar shadowing -- if unguarded choice-rec, it will be unfolded and rec entry recorded for guarded unfolding)
graph.builder.pushRecursionEntry(rv, graph.builder.getRecursionEntry(rv));
}
else*/
{
graph.util.addEntryLabel(rv);
graph.util.pushRecursionEntry(rv, graph.util.getEntry());
}
}
@Override
public LRecursion leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) throws ScribbleException
{
LRecursion lr = (LRecursion) visited;
RecVar rv = lr.recvar.toName();
graph.util.popRecursionEntry(rv);
return (LRecursion) super.leaveEGraphBuilding(parent, child, graph, lr);
}
@Override
public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer)
{
fixer.pushRec(((LRecursion) child).recvar.toName());
}
@Override
public ScribNode leaveProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer, ScribNode visited)
{
fixer.popRec(((LRecursion) child).recvar.toName());
return visited;
}
}
| apache-2.0 |
dannywxh/mypy | MyPys/common.py | 3687 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, re, time, sys
import hashlib, bencode
import requests
from bs4 import BeautifulSoup
reload(sys)
#print sys.getdefaultencoding()
#sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
def parse_tor(file):
bt_path = {}
bt_file = open(file, 'rb')
bt_info = bencode.bdecode(bt_file.read()).get('info')
bt_info_hash_hex = hashlib.sha1(bencode.bencode(bt_info)).hexdigest()
bt_file_size = bt_info.get('length')
bt_file_name = bt_info.get('name')
bt_path[bt_file_name]=bt_file_size
print bt_path
bt_file.close()
#提取无码的格式,如 082516-001
def format_rule1(s):
pattern="\d{6}-\d{3}|\d{6}-\d{2}|\d{6}_\d{3}|\d{6}_\d{2}"
rs=re.findall(pattern, s);
if len(rs)>=1:
return rs[0]
else:
return ""
def format_rule2(s):
rs=''
#匹配开头是数字,判断是非wm编号
wm=re.findall(r'^\d+',s)
if len(wm)==1: #是wm
rs=s[0:10]
return rs
# 如:mide-267FHD_ok_0001.mp4
#查找所有的非数字,['mide-', 'FHD_ok_', '.mp']
#第一个元素就是"mide-"
alpha_list=re.findall(r'\D+', s)
if len(alpha_list)>0:
rs+=alpha_list[0]
#查找所有的数字,['267', '0001', '4']
#第一个元素就是"267"
num_list=re.findall(r'\d+', s)
if len(num_list)>0:
rs+=num_list[0]
if rs=='':
rs=s
rs=rs.replace("-","")
rs=rs.replace(" ","")
rs=rs.replace("_","")
rs=rs.lower()
return rs
#for test
def format_torrent(path):
for x in os.listdir(path):
print format_rule2(x)
def walkpath(path):
#files= [(dirpath,filenames) for dirpath,dirname,filenames in os.walk(path)]
files= []
for dirpath,dirname,filenames in os.walk(path.decode('utf-8')):
for filename in filenames:
files.append((filename,dirpath))
return files
def walkfile(path):
files=[x for x in os.listdir(path) if all([os.path.splitext(x)[1]=='.txt', not os.path.isdir(path+"\\"+x)])]
# txtfile=[f for f in files if os.path.splitext(f)[1]=='.txt']
store=[]
for txtfile in files:
for line in open(path+"/"+txtfile):
p,f=os.path.split(line)
store.append((f.replace("\n",""),txtfile))
return store
#����list�ԱȺ��Ĺ��ܣ������ܵ���
def comparelist(src,des):
#src: ["file"]
#des:[("file","path")]
from collections import defaultdict
dic=defaultdict(list)
for x in src:
for a,b in des:
#print x,a,b
if format_rule2(x)==format_rule2(a):
dic[x].append(os.path.join(b,a))
return dic
def download(url):
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, compress',
'Accept-Language': 'en-us;q=0.5,en;q=0.3',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
print "download from "+url+"\n"
try:
response = requests.get(url=url,headers=headers,timeout=5) # 最基本的GET请求
return response
except Exception,e:
print e
#print "status_code",response.status_code
| apache-2.0 |
mrtamm/rocket-path | src/main/java/ws/rocket/path/annotation/TreeNode.java | 3324 | // @formatter:off
/*
* Copyright 2012 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.
*/
// @formatter:on
package ws.rocket.path.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.enterprise.util.Nonbinding;
/**
* Annotation used on {@link ws.rocket.path.TreeNode} values (classes) for describing the node to be constructed where
* the annotated value object will belong to. Since the node value object is known (instance of the annotated class),
* this annotation describes the key (reference to a key object) and the possible child nodes (references to their value
* objects).
* <p>
* For both node key and child node values it is possible to use either reference by bean name or reference by type.
* When key attributes are omitted, the tree node key will be <code>null</code>. When children attributes are omitted,
* the constructed tree node will not have any children.
*
* @see ws.rocket.path.TreeNode
* @author Martti Tamm
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(TYPE)
public @interface TreeNode {
/**
* Specifies the node key as a string. This value is used when the value of this attribute is not empty.
*
* @return The node key as a string.
*/
@Nonbinding
String key() default "";
/**
* Reference to node key object by bean type. This value is used when {@link #key()} is empty and
* <code>keyType != Object.class</code>. When CDI cannot resolve the type to exactly one bean, tree construction will
* fail.
*
* @return The CDI bean type for the node key object.
*/
@Nonbinding
Class<?> keyType() default Object.class;
/**
* Reference to node key object by CDI bean name. This value is used when {@link #key()} is empty,
* <code>{@link #keyType()} == Object.class</code>, and the value of this attribute is not empty.
*
* @return The CDI bean name for the node key object.
*/
@Nonbinding
String keyName() default "";
/**
* Reference to the values of child-tree-nodes by CDI bean names. This value is used when <code>childTypes</code> is
* empty.
*
* @return An array of CDI bean names of value objects for constructing the child-tree-nodes.
*/
@Nonbinding
String[] childNames() default {};
/**
* Reference to the values of child-tree-nodes by CDI bean types. This value is used when not empty.
*
* @return An array of CDI bean types of value objects for constructing the child-tree-nodes.
*/
@Nonbinding
Class<?>[] childTypes() default {};
}
| apache-2.0 |
xiangzhuyuan/spring-security-oauth | spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/error/OAuth2ExceptionRenderer.java | 1210 | /*
* Copyright 2006-2011 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 org.springframework.security.oauth2.provider.error;
import org.springframework.http.HttpEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.context.request.ServletWebRequest;
/**
* Strategy for rendering a {@link OAuth2Exception} in cases where they cannot be rendered by the Spring dispatcher
* servlet (i.e. usually in a filter chain).
*
* @author Dave Syer
*/
public interface OAuth2ExceptionRenderer {
void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception;
}
| apache-2.0 |
lvht/phpcd.vim | php/Matcher/FuzzyMatcher.php | 473 | <?php
namespace PHPCD\Matcher;
class FuzzyMatcher implements Matcher
{
public function match($pattern, $subject)
{
if (!$pattern) {
return true;
}
$chars = str_split($pattern);
$parts = ['/.*'];
foreach ($chars as $char) {
$parts[] = $char;
$parts[] = '.*';
}
$parts[] = '/i';
$pattern = implode($parts);
return preg_match($pattern, $subject);
}
}
| apache-2.0 |
angegar/CDI-WebApplication | KarateIsere.DataAccess/IdentityModels.cs | 2229 | using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using KarateIsere.DataAccess;
using KarateContext = KarateIsere.DataAccess;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace KarateIsere.Models {
// Vous pouvez ajouter des données de profil pour l'utilisateur en ajoutant plus de propriétés à votre classe ApplicationUser ; consultez http://go.microsoft.com/fwlink/?LinkID=317594 pour en savoir davantage.
public partial class ApplicationUser : IdentityUser {
public ApplicationUser () {
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync ( UserManager<ApplicationUser> manager ) {
// Notez qu'authenticationType doit correspondre à l'élément défini dans CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync( this, DefaultAuthenticationTypes.ApplicationCookie );
// Ajouter les revendications personnalisées de l’utilisateur ici
return userIdentity;
}
public virtual Club Club {
get;
set;
}
//[ForeignKey( "Club" )]
public virtual string NumAffiliation {
get;
set;
}
}
//public class ApplicationDbContext : KarateIsere<ApplicationUser> {
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext ()
: base( "KarateIsere", throwIfV1Schema: false ) {
Configuration.LazyLoadingEnabled=true;
Configuration.ProxyCreationEnabled=true;
Configuration.AutoDetectChangesEnabled = true;
}
public static ApplicationDbContext Create () {
return new ApplicationDbContext();
}
public virtual DbSet<Club> Clubs {
get;
set;
}
protected override void OnModelCreating ( DbModelBuilder modelBuilder ) {
base.OnModelCreating( modelBuilder );
}
}
} | apache-2.0 |
librallu/cohorte-herald | python/herald/transports/http/servlet.py | 12509 | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Herald HTTP transport servlet
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.3
:status: Alpha
..
Copyright 2014 isandlaTech
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.
"""
# Module version
__version_info__ = (0, 0, 3)
__version__ = ".".join(str(x) for x in __version_info__)
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
# Herald
from . import ACCESS_ID, SERVICE_HTTP_DIRECTORY, SERVICE_HTTP_RECEIVER, \
FACTORY_SERVLET, CONTENT_TYPE_JSON
from . import beans
import herald.beans
import herald.transports.peer_contact as peer_contact
import herald.utils as utils
import herald.transports.http
# Pelix
from pelix.ipopo.decorators import ComponentFactory, Requires, Provides, \
Property, Validate, Invalidate, RequiresBest
from pelix.utilities import to_bytes, to_unicode
import pelix.http
import pelix.misc.jabsorb as jabsorb
# Standard library
import json
import logging
import threading
import time
import uuid
# ------------------------------------------------------------------------------
_logger = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
def _make_json_result(code, message="", results=None):
"""
An utility method to prepare a JSON result string, usable by the
SignalReceiver
:param code: A HTTP Code
:param message: An associated message
"""
return code, json.dumps({'code': code,
'message': message,
'results': results})
@ComponentFactory(FACTORY_SERVLET)
@RequiresBest('_probe', herald.SERVICE_PROBE)
@Requires('_core', herald.SERVICE_HERALD_INTERNAL)
@Requires('_directory', herald.SERVICE_DIRECTORY)
@Requires('_http_directory', SERVICE_HTTP_DIRECTORY)
@Provides(pelix.http.HTTP_SERVLET)
@Provides(SERVICE_HTTP_RECEIVER, '_controller')
@Property('_servlet_path', pelix.http.HTTP_SERVLET_PATH, '/herald')
class HeraldServlet(object):
"""
HTTP reception servlet
"""
def __init__(self):
"""
Sets up the servlet
"""
# Herald services
self._core = None
self._directory = None
self._probe = None
# Peer contact handling
self.__contact = None
# Herald HTTP directory
self._http_directory = None
# Service controller (set once bound)
self._controller = False
self._can_provide = False
self.__lock = threading.Lock()
# Local information
self._host = None
self._port = None
self._servlet_path = None
@staticmethod
def __load_dump(message, description):
"""
Loads and updates the remote peer dump with its HTTP access
:param message: A message containing a remote peer description
:param description: The parsed remote peer description
:return: The peer dump map
"""
if message.access == ACCESS_ID:
# Forge the access to the HTTP server using extra information
extra = message.extra
description['accesses'][ACCESS_ID] = \
beans.HTTPAccess(extra['host'], extra['port'],
extra['path']).dump()
return description
@Validate
def validate(self, _):
"""
Component validated
"""
# Normalize the servlet path
if not self._servlet_path.startswith('/'):
self._servlet_path = '/{0}'.format(self._servlet_path)
# Prepare the peer contact handler
self.__contact = peer_contact.PeerContact(
self._directory, self.__load_dump, __name__ + ".contact")
@Invalidate
def invalidate(self, _):
"""
Component invalidated
"""
# Clean up internal storage
self.__contact.clear()
self.__contact = None
def get_access_info(self):
"""
Retrieves the (host, port) tuple to access this signal receiver.
WARNING: The host might (often) be "localhost"
:return: An (host, port, path) tuple
"""
return self._host, self._port, self._servlet_path
def __set_controller(self):
"""
Sets the service controller to True if possible
"""
with self.__lock:
self._controller = self._can_provide
def bound_to(self, path, parameters):
"""
Servlet bound to a HTTP service
:param path: The path to access the servlet
:param parameters: The server & servlet parameters
"""
if self._host is None and path == self._servlet_path:
# Update our access information
self._host = parameters[pelix.http.PARAM_ADDRESS]
self._port = int(parameters[pelix.http.PARAM_PORT])
# Tell the directory we're ready
access = beans.HTTPAccess(self._host, self._port, path)
self._directory.get_local_peer().set_access(ACCESS_ID, access)
with self.__lock:
# Register our service: use a different thread to let the
# HTTP service register this servlet
self._can_provide = True
threading.Thread(target=self.__set_controller,
name="Herald-HTTP-Servlet-Bound").start()
return True
else:
return False
def unbound_from(self, path, _):
"""
Servlet unbound from a HTTP service
:param path: The path to access the servlet
:param _: The server & servlet parameters
"""
if path == self._servlet_path:
with self.__lock:
# Lock next provide
self._can_provide = False
# Unregister our service
self._controller = False
# Update the directory
self._directory.get_local_peer().unset_access(ACCESS_ID)
# Clear our access information
self._host = None
self._port = None
def do_GET(self, _, response):
"""
Handles a GET request: sends the description of the local peer
:param _: The HTTP request bean
:param response: The HTTP response handler
"""
# pylint: disable=C0103
peer_dump = self._directory.get_local_peer().dump()
jabsorb_content = jabsorb.to_jabsorb(peer_dump)
content = json.dumps(jabsorb_content, default=utils.json_converter)
response.send_content(200, content, CONTENT_TYPE_JSON)
def do_POST(self, request, response):
"""
Handles a POST request, i.e. the reception of a message
:param request: The HTTP request bean
:param response: The HTTP response handler
"""
# pylint: disable=C0103
# Default code and content
code = 200
content = ""
# Extract headers
"""
content_type = request.get_header('content-type')
subject = request.get_header('herald-subject')
uid = request.get_header('herald-uid')
reply_to = request.get_header('herald-reply-to')
timestamp = request.get_header('herald-timestamp')
sender_uid = request.get_header('herald-sender-uid')
"""
content_type = request.get_header('content-type')
subject = None
uid = None
reply_to = None
timestamp = None
sender_uid = None
raw_content = to_unicode(request.read_data())
# print('#'*20)
# print(raw_content)
# print('#'*20)
#
# Client information
host = utils.normalize_ip(request.get_client_address()[0])
message = None
if content_type != CONTENT_TYPE_JSON:
# Raw message
uid = str(uuid.uuid4())
subject = herald.SUBJECT_RAW
#msg_content = raw_content
msg_content = raw_content
port = -1
extra = {'host': host, 'raw': True}
# construct a new Message bean
message = herald.beans.MessageReceived(uid, subject, msg_content,
None, None,
ACCESS_ID, None, extra)
else:
# Herald message
try:
received_msg = utils.from_json(raw_content)
except Exception as ex:
_logger.exception("DoPOST ERROR:: %s", ex)
msg_content = received_msg.content
subject = received_msg.subject
uid = received_msg.uid
reply_to = received_msg.reply_to
timestamp = received_msg.timestamp
sender_uid = received_msg.sender
if not uid or not subject:
# Raw message
uid = str(uuid.uuid4())
subject = herald.SUBJECT_RAW
#msg_content = raw_content
msg_content = raw_content
port = -1
extra = {'host': host, 'raw': True}
# construct a new Message bean
message = herald.beans.MessageReceived(uid, subject, msg_content,
None, None,
ACCESS_ID, None, extra)
else:
# Store sender information
try:
port = int(received_msg.get_header(herald.transports.http.MESSAGE_HEADER_PORT))
except (KeyError, ValueError, TypeError):
port = 80
path = None
if herald.transports.http.MESSAGE_HEADER_PATH in received_msg.headers:
path = received_msg.get_header(herald.transports.http.MESSAGE_HEADER_PATH)
extra = {'host': host, 'port': port,
'path': path,
'parent_uid': uid}
try:
# Check the sender UID port
# (not perfect, but can avoid spoofing)
if not self._http_directory.check_access(
sender_uid, host, port):
# Port doesn't match: invalid UID
sender_uid = "<invalid>"
except ValueError:
# Unknown peer UID: keep it as is
pass
# Prepare the bean
received_msg.add_header(herald.MESSAGE_HEADER_SENDER_UID, sender_uid)
received_msg.set_access(ACCESS_ID)
received_msg.set_extra(extra)
message = received_msg
# Log before giving message to Herald
self._probe.store(
herald.PROBE_CHANNEL_MSG_RECV,
{"uid": message.uid, "timestamp": time.time(),
"transport": ACCESS_ID, "subject": message.subject,
"source": sender_uid, "repliesTo": reply_to or "",
"transportSource": "[{0}]:{1}".format(host, port)})
if subject.startswith(peer_contact.SUBJECT_DISCOVERY_PREFIX):
# Handle discovery message
self.__contact.herald_message(self._core, message)
else:
# All other messages are given to Herald Core
self._core.handle_message(message)
# Convert content (Python 3)
if content:
content = jabsorb.to_jabsorb(content)
content = to_bytes(content)
# Send response
response.send_content(code, content, CONTENT_TYPE_JSON)
| apache-2.0 |
mirsaeedi/CqrsSample | Kaftar/Kaftar.Core/CQRS/CommandStack/Commands/CRUDCommands/DeleteCqrsCommand.cs | 252 | using Kaftar.Core.Data.Models;
namespace Kaftar.Core.CQRS.CommandStack.Commands.CRUDCommands
{
public class DeleteCqrsCommand<TEntity>:CqrsCommand
where TEntity : Entity
{
public TEntity Entity { get; set; }
}
} | apache-2.0 |
tianfengjingjing/YOFC_Stage1_RightOracle | src/com/yofc/odn/login/dao/LoginDao.java | 221 | package com.yofc.odn.login.dao;
import com.yofc.odn.common.model.Staff;
import com.yofc.odn.login.vo.UserVO;
public interface LoginDao {
public Staff getUser(UserVO user);
public boolean updatePsw(Staff staff);
}
| apache-2.0 |
fabric8io/kubernetes | pkg/kubelet/config/etcd.go | 3035 | /*
Copyright 2014 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.
*/
// Reads the pod configuration from etcd using the Kubernetes etcd schema.
package config
import (
"errors"
"fmt"
"path"
"time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
_ "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta1"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
"github.com/golang/glog"
)
func EtcdKeyForHost(hostname string) string {
return path.Join("/", "registry", "hosts", hostname, "kubelet")
}
type SourceEtcd struct {
key string
helper tools.EtcdHelper
updates chan<- interface{}
}
// NewSourceEtcd creates a config source that watches and pulls from a key in etcd
func NewSourceEtcd(key string, client tools.EtcdClient, updates chan<- interface{}) *SourceEtcd {
helper := tools.EtcdHelper{
client,
runtime.DefaultCodec,
runtime.DefaultResourceVersioner,
}
source := &SourceEtcd{
key: key,
helper: helper,
updates: updates,
}
glog.Infof("Watching etcd for %s", key)
go util.Forever(source.run, time.Second)
return source
}
func (s *SourceEtcd) run() {
watching, err := s.helper.Watch(s.key, 0)
if err != nil {
glog.Errorf("Failed to initialize etcd watch: %v", err)
return
}
for {
select {
case event, ok := <-watching.ResultChan():
if !ok {
return
}
pods, err := eventToPods(event)
if err != nil {
glog.Errorf("Failed to parse result from etcd watch: %v", err)
continue
}
glog.Infof("Received state from etcd watch: %+v", pods)
s.updates <- kubelet.PodUpdate{pods, kubelet.SET}
}
}
}
// eventToPods takes a watch.Event object, and turns it into a structured list of pods.
// It returns a list of containers, or an error if one occurs.
func eventToPods(ev watch.Event) ([]kubelet.Pod, error) {
pods := []kubelet.Pod{}
manifests, ok := ev.Object.(*api.ContainerManifestList)
if !ok {
return pods, errors.New("unable to parse response as ContainerManifestList")
}
for i, manifest := range manifests.Items {
name := manifest.ID
if name == "" {
name = fmt.Sprintf("%d", i+1)
}
pods = append(pods, kubelet.Pod{
Name: name,
Manifest: manifest})
}
return pods, nil
}
func makeContainerKey(machine string) string {
return "/registry/hosts/" + machine + "/kubelet"
}
| apache-2.0 |
matiwinnetou/play-soy-view | app/com/github/mati1979/play/soyplugin/ajax/auth/AuthManager.java | 345 | package com.github.mati1979.play.soyplugin.ajax.auth;
/**
* Created with IntelliJ IDEA.
* User: mati
* Date: 12/10/2013
* Time: 23:38
*
* AuthManager is an interface, which is responsible for controlling which templates are allowed to be compiled
* to JavaScript
*/
public interface AuthManager {
boolean isAllowed(String url);
}
| apache-2.0 |
AdrianKluge/Invite-Key-Grabber | Invite-Key-Grabber-Python2.py | 938 | # Python 2.7 - Invite Key Grabber for the OnePlusTwo
# It's not guranteed that you will get an invite, it's only a
# random invite generator.
# Copyright Adrian Kluge, 2015
import webbrowser, random, string, time
loop = 0
while loop == 0:
def id_generator(size=4, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size)) # sets the random letters and numbers
block1 = id_generator()
block2 = id_generator()
block3 = id_generator()
block4 = id_generator() # make the random stuff and put it into a variable
print block1 +"-"+ block2 +"-"+ block3 +"-"+ block4 # print the code
webbrowser.open_new_tab("http://invites.oneplus.net/claim/"+ block1 +"-"+ block2 +"-"+ block3 +"-"+ block4)
time.sleep(1) # if you want to spam the whole browser, you can deactivate it with a "#" before this line
# open the browser with specific code
| apache-2.0 |
walterfan/snippets | html/jquery/development-bundle/ui/minified/jquery.ui.effect-shake.min.js | 914 | /*! jQuery UI - v1.10.4 - 2014-01-26
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","height","width"],o=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",l=e.distance||20,h=e.times||3,c=2*h+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,a),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+l,g[d]=(p?"+=":"-=")+2*l,m[d]=(p?"-=":"+=")+2*l,n.animate(f,u,e.easing),s=1;h>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}})(jQuery); | apache-2.0 |
LQJJ/demo | 126-go-common-master/app/admin/main/spy/dao/dao.go | 1705 | package dao
import (
"context"
"fmt"
"time"
"go-common/app/admin/main/spy/conf"
account "go-common/app/service/main/account/rpc/client"
spy "go-common/app/service/main/spy/rpc/client"
"go-common/library/cache/memcache"
"go-common/library/database/sql"
)
// Dao struct user of Dao.
type Dao struct {
c *conf.Config
// db
db *sql.DB
getUserInfoStmt []*sql.Stmt
eventStmt *sql.Stmt
factorAllStmt *sql.Stmt
allGroupStmt *sql.Stmt
// cache
mcUser *memcache.Pool
mcUserExpire int32
// rpc
spyRPC *spy.Service
accRPC *account.Service3
}
// New create a instance of Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// conf
c: c,
// db
db: sql.NewMySQL(c.DB.Spy),
// mc
mcUser: memcache.NewPool(c.Memcache.User),
mcUserExpire: int32(time.Duration(c.Memcache.UserExpire) / time.Second),
// rpc
spyRPC: spy.New(c.SpyRPC),
accRPC: account.New3(c.AccountRPC),
}
if conf.Conf.Property.UserInfoShard <= 0 {
panic("conf.Conf.Property.UserInfoShard <= 0")
}
if conf.Conf.Property.HistoryShard <= 0 {
panic("conf.Conf.Property.HistoryShard <= 0")
}
d.getUserInfoStmt = make([]*sql.Stmt, conf.Conf.Property.UserInfoShard)
for i := int64(0); i < conf.Conf.Property.UserInfoShard; i++ {
d.getUserInfoStmt[i] = d.db.Prepared(fmt.Sprintf(_getUserInfoSQL, i))
}
d.eventStmt = d.db.Prepared(_eventSQL)
d.factorAllStmt = d.db.Prepared(_factorAllSQL)
d.allGroupStmt = d.db.Prepared(_allGroupSQL)
return
}
// Ping check connection of db , mc.
func (d *Dao) Ping(c context.Context) (err error) {
return d.db.Ping(c)
}
// Close close connection of db , mc.
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
}
| apache-2.0 |
antalpeti/Test | src/testpackage2/C.java | 262 | package testpackage2;
public class C extends B {
public C() {
}
@Override
void play() {
super.play();
System.out.println("Play from C.");
}
public static void main(String[] args) {
C c = new C();
c.play();
}
}
| apache-2.0 |
softwaremill/janusz-backend | src/main/java/com/softwaremill/janusz_backend/fourth_question/FourthQuestionRepository.java | 745 | package com.softwaremill.janusz_backend.fourth_question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.Optional;
@Repository
interface FourthQuestionRepository extends JpaRepository<Question, Long> {
long countByAskedDateIsNull();
Optional<Question> findByAskedDate(LocalDate askedDate);
Optional<Question> findFirstByAskedDateIsNullOrderByAddedTimeAsc();
@Modifying
@Query("update Question q set q.askedDate = ?1 where q.uuid = ?2")
void setAskedByUUID(LocalDate askedDate, String uuid);
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-dms/src/main/java/com/amazonaws/services/databasemigrationservice/model/AddTagsToResourceRequest.java | 7574 | /*
* Copyright 2014-2019 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.databasemigrationservice.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Associates a set of tags with an AWS DMS resource.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/AddTagsToResource" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AddTagsToResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon Resource
* Name (ARN).
* </p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
* </p>
*/
private String resourceArn;
/**
* <p>
* One or more tags to be assigned to the resource.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon Resource
* Name (ARN).
* </p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
* </p>
*
* @param resourceArn
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon
* Resource Name (ARN).</p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
*/
public void setResourceArn(String resourceArn) {
this.resourceArn = resourceArn;
}
/**
* <p>
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon Resource
* Name (ARN).
* </p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
* </p>
*
* @return Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon
* Resource Name (ARN).</p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
*/
public String getResourceArn() {
return this.resourceArn;
}
/**
* <p>
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon Resource
* Name (ARN).
* </p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
* </p>
*
* @param resourceArn
* Identifies the AWS DMS resource to which tags should be added. The value for this parameter is an Amazon
* Resource Name (ARN).</p>
* <p>
* For AWS DMS, you can tag a replication instance, an endpoint, or a replication task.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AddTagsToResourceRequest withResourceArn(String resourceArn) {
setResourceArn(resourceArn);
return this;
}
/**
* <p>
* One or more tags to be assigned to the resource.
* </p>
*
* @return One or more tags to be assigned to the resource.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* One or more tags to be assigned to the resource.
* </p>
*
* @param tags
* One or more tags to be assigned to the resource.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* One or more tags to be assigned to the resource.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* One or more tags to be assigned to the resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AddTagsToResourceRequest withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* One or more tags to be assigned to the resource.
* </p>
*
* @param tags
* One or more tags to be assigned to the resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AddTagsToResourceRequest withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResourceArn() != null)
sb.append("ResourceArn: ").append(getResourceArn()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AddTagsToResourceRequest == false)
return false;
AddTagsToResourceRequest other = (AddTagsToResourceRequest) obj;
if (other.getResourceArn() == null ^ this.getResourceArn() == null)
return false;
if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public AddTagsToResourceRequest clone() {
return (AddTagsToResourceRequest) super.clone();
}
}
| apache-2.0 |
camilesing/zstack | header/src/main/java/org/zstack/header/storage/snapshot/APIDeleteVolumeSnapshotMsg.java | 2964 | package org.zstack.header.storage.snapshot;
import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIDeleteMessage;
import org.zstack.header.message.APIEvent;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.notification.ApiNotification;
import org.zstack.header.rest.APINoSee;
import org.zstack.header.rest.RestRequest;
/**
* @api delete a volume snapshot from primary storage and all its copies from backup stroage
* @category volume snapshot
* @cli
* @httpMsg {
* "org.zstack.header.storage.snapshot.APIDeleteVolumeSnapshotMsg": {
* "uuid": "a4efe4e48c424d009cffe2faae018c70",
* "deleteMode": "Permissive",
* "session": {
* "uuid": "d7d1fb6650d64b20b2b050b0eb06448b"
* }
* }
* }
* @msg {
* "org.zstack.header.storage.snapshot.APIDeleteVolumeSnapshotMsg": {
* "uuid": "a4efe4e48c424d009cffe2faae018c70",
* "deleteMode": "Permissive",
* "session": {
* "uuid": "d7d1fb6650d64b20b2b050b0eb06448b"
* },
* "timeout": 1800000,
* "id": "eae63912be604948a2fc19fe1ff907a6",
* "serviceId": "api.portal"
* }
* }
* @result see :ref:`APIDeleteVolumeSnapshotEvent`
* @since 0.1.0
*/
@Action(category = VolumeSnapshotConstant.ACTION_CATEGORY)
@RestRequest(
path = "/volume-snapshots/{uuid}",
method = HttpMethod.DELETE,
responseClass = APIDeleteVolumeSnapshotEvent.class
)
public class APIDeleteVolumeSnapshotMsg extends APIDeleteMessage implements VolumeSnapshotMessage {
/**
* @desc volume snapshot uuid
*/
@APIParam(checkAccount = true, operationTarget = true)
private String uuid;
/**
* @ignore
*/
@APINoSee
private String volumeUuid;
/**
* @ignore
*/
@APINoSee
private String treeUuid;
@Override
public String getTreeUuid() {
return treeUuid;
}
@Override
public void setTreeUuid(String treeUuid) {
this.treeUuid = treeUuid;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String getSnapshotUuid() {
return uuid;
}
@Override
public String getVolumeUuid() {
return volumeUuid;
}
public void setVolumeUuid(String volumeUuid) {
this.volumeUuid = volumeUuid;
}
public static APIDeleteVolumeSnapshotMsg __example__() {
APIDeleteVolumeSnapshotMsg msg = new APIDeleteVolumeSnapshotMsg();
msg.setUuid(uuid());
return msg;
}
public ApiNotification __notification__() {
APIMessage that = this;
return new ApiNotification() {
@Override
public void after(APIEvent evt) {
ntfy("Deleted").resource(uuid, VolumeSnapshotVO.class.getSimpleName())
.messageAndEvent(that, evt).done();
}
};
}
}
| apache-2.0 |
lihongjie/spring-tutorial | spring-core-tutorials/Spring-AOP-Examples-master/src/main/java/com/examples/jdk/Test.java | 518 | package com.examples.jdk;
import java.lang.reflect.Proxy;
/**
* Created by lihongjie on 7/4/17.
* JDK动态代理
*
*
*/
public class Test {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
ProxyUtils proxyUtils = new ProxyUtils(userService);
UserService proxyObject = (UserService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),UserServiceImpl.class.getInterfaces(), proxyUtils);
proxyObject.add();
}
}
| apache-2.0 |
Warglaive/TechModuleSeptember2017 | Methods.DebuggingandLab/03. Printing Triangle/03. Printing Triangle.cs | 724 | using System;
namespace _03.Printing_Triangle
{
class Program
{
static void Main()
{
var n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
PrintLine(1, i);
}
for (int i = 0; i < n; i++)
{
PrintLine(1, n - i);
}
for (int i = n - 1; i >= 0; i--)
{
PrintLine(1, i);
}
}
private static void PrintLine(int start, int end)
{
for (int i = start; i <= end; i++)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
}
} | apache-2.0 |
opis/validation | src/Formatter.php | 2259 | <?php
/* ===========================================================================
* Copyright 2018 Zindex Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================================ */
namespace Opis\Validation;
class Formatter
{
/** @var string */
protected $escape;
/** @var string */
protected $plain;
/**
* Placeholder constructor.
* @param string $plain
* @param string $escape
*/
public function __construct(string $plain = '%', string $escape = '@')
{
$this->plain = $plain;
$this->escape = $escape;
}
/**
* @param string $text
* @param array $placeholders
*
* @return string
*/
public function format(string $text, array $placeholders = []): string
{
if (!$placeholders) {
return $text;
}
return strtr(strtr($text, $this->getPlainArgs($placeholders)), $this->getEscapedArgs($placeholders));
}
/**
* @param array $placeholders
* @return array
*/
protected function getPlainArgs(array $placeholders): array
{
$args = [];
$plain = $this->plain;
foreach ($placeholders as $key => $value) {
$args[$plain . $key] = $value;
}
return $args;
}
/**
* @param array $placeholders
* @return array
*/
protected function getEscapedArgs(array $placeholders): array
{
$args = [];
$escape = $this->escape;
foreach ($placeholders as $key => $value) {
$args[$escape . $key] = is_string($value) ? htmlspecialchars($value, ENT_QUOTES, 'UTF-8') : $value;
}
return $args;
}
} | apache-2.0 |
mldbai/mldb | testing/mldb_js_plugin_requestexc.js | 604 | // This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
// test plugin for MLDB
function handleStatus()
{
// Hello this is a comment
plugin.log("handling status");
return { "message": "A-OK" };
}
function handleRequest(relpath, verb, resource, params, payload, contentType, contentLength,
headers)
{
plugin.log("handling request " + verb + " " + relpath);
throw "Exception in handleRequest thrown on purpose for testing";
}
plugin.setStatusHandler(handleStatus);
plugin.setRequestHandler(handleRequest);
plugin.log("Hello, world");
| apache-2.0 |
thecartercenter/elmo | db/migrate/20130523135556_add_new_translation_fields.rb | 450 | class AddNewTranslationFields < ActiveRecord::Migration[4.2]
def change
add_column :questions, :name, :text
add_column :questions, :hint, :text
add_column :questions, :name_translations, :text
add_column :questions, :hint_translations, :text
add_column :options, :name, :string
add_column :options, :hint, :text
add_column :options, :name_translations, :text
add_column :options, :hint_translations, :text
end
end
| apache-2.0 |
cedral/aws-sdk-cpp | aws-cpp-sdk-email/source/model/TestRenderTemplateResult.cpp | 2152 | /*
* Copyright 2010-2017 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.
*/
#include <aws/email/model/TestRenderTemplateResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::SES::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
TestRenderTemplateResult::TestRenderTemplateResult()
{
}
TestRenderTemplateResult::TestRenderTemplateResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
TestRenderTemplateResult& TestRenderTemplateResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "TestRenderTemplateResult"))
{
resultNode = rootNode.FirstChild("TestRenderTemplateResult");
}
if(!resultNode.IsNull())
{
XmlNode renderedTemplateNode = resultNode.FirstChild("RenderedTemplate");
if(!renderedTemplateNode.IsNull())
{
m_renderedTemplate = Aws::Utils::Xml::DecodeEscapedXmlText(renderedTemplateNode.GetText());
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::SES::Model::TestRenderTemplateResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| apache-2.0 |
joel-costigliola/assertj-core | src/test/java/org/assertj/core/internal/LongArraysBaseTest.java | 2346 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2020 the original author or authors.
*/
package org.assertj.core.internal;
import static org.assertj.core.test.LongArrays.arrayOf;
import static org.mockito.Mockito.spy;
import java.util.Comparator;
import org.assertj.core.util.AbsValueComparator;
import org.junit.jupiter.api.BeforeEach;
/**
* Base class for testing <code>{@link LongArrays}</code>, set up an instance with {@link StandardComparisonStrategy} and another
* with {@link ComparatorBasedComparisonStrategy}.
* <p>
* Is in <code>org.assertj.core.internal</code> package to be able to set {@link LongArrays#failures} appropriately.
*
* @author Joel Costigliola
*/
public class LongArraysBaseTest {
/**
* is initialized with {@link #initActualArray()} with default value = {6, 8, 10}
*/
protected long[] actual;
protected Failures failures;
protected LongArrays arrays;
protected ComparatorBasedComparisonStrategy absValueComparisonStrategy;
protected LongArrays arraysWithCustomComparisonStrategy;
private AbsValueComparator<Long> absValueComparator = new AbsValueComparator<>();
@BeforeEach
public void setUp() {
failures = spy(new Failures());
arrays = new LongArrays();
arrays.failures = failures;
absValueComparisonStrategy = new ComparatorBasedComparisonStrategy(comparatorForCustomComparisonStrategy());
arraysWithCustomComparisonStrategy = new LongArrays(absValueComparisonStrategy);
arraysWithCustomComparisonStrategy.failures = failures;
initActualArray();
}
protected void initActualArray() {
actual = arrayOf(6L, 8L, 10L);
}
protected Comparator<?> comparatorForCustomComparisonStrategy() {
return absValueComparator;
}
protected void setArrays(Arrays internalArrays) {
arrays.setArrays(internalArrays);
}
} | apache-2.0 |
KIZI/EasyMiner-EasyMinerCenter | docker/db.php | 703 | <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$databasePrefix = $argv[1];
$database = $databasePrefix . '000';
$mysqli = new mysqli("easyminer-mysql", "root", "root");
$mysqli->query('DROP DATABASE IF EXISTS '.$database);
$mysqli->query('GRANT ALL PRIVILEGES ON *.* TO "'.$database.'"@"%" IDENTIFIED BY "'.$database.'" WITH GRANT OPTION');
$mysqli->query('CREATE DATABASE '.$database);
$mysqli->query("GRANT ALL PRIVILEGES ON ".$database.".* TO '".$database."'@'%' IDENTIFIED BY '".$database."' WITH GRANT OPTION");
$mysqli->select_db($database);
$sql = file_get_contents('/var/www/html/easyminercenter/app/InstallModule/data/mysql.sql');
$mysqli->multi_query($sql);
$mysqli->close(); | apache-2.0 |
andrewdbate/jautomata | jautomata-core/src/main/java/rationals/converters/analyzers/Lexer.java | 2818 | /*
* (C) Copyright 2005 Arnaud Bailly (arnaud.oqube@gmail.com),
* Yves Roos (yroos@lifl.fr) and others.
*
* 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 rationals.converters.analyzers;
import rationals.converters.ConverterException;
/**
* Interface lifting lexical analysis.
* This interface allows customization of parsing of RE, in particular to
* override the definition of what is a labeL.
* Instances of Lexer are used by instances of Parser to retrieve tokens.
*
* @version $Id: Lexer.java 2 2006-08-24 14:41:48Z oqube $
* @see DefaultLexer
* @see Parser
*/
public interface Lexer<L> {
public static final int LABEL = 0;
public static final int INT = 1;
public static final int EPSILON = 2;
public static final int EMPTY = 3;
public static final int ITERATION = 4;
public static final int UNION = 5;
public static final int STAR = 6;
public static final int OPEN = 7;
public static final int CLOSE = 8;
public static final int END = 9;
public static final int UNKNOWN = 10;
// AB
public static final int SHUFFLE = 11;
public static final int MIX = 12;
public static final int OBRACE = 13;
public static final int CBRACE = 14;
/**
* Read more data from the underying input.
*
* @throws ConverterException if some characters cannot be converted
*/
public abstract void read() throws ConverterException;
/**
* Return the current line number in the underlying character
* stream.
* Line separation is platform dependent.
*
* @return number of current line, starting from 1
*/
public abstract int lineNumber();
/**
* Return the image of current token.
* This method is used by Parser to create atomic Automaton objects
* so any Object can be used.
*
* @return an Object which is a label for a transition.
*/
public abstract L label();
/**
* Return the value of a number.
*
* @return value of a number.
*/
public abstract int value();
/**
* Returns the current token value.
* This value must be one of the constants defined in interface Lexer.
*
* @return a constant denoting the kind of token.
*/
public abstract int current();
} | apache-2.0 |
ragnor-rs/visum | demo/src/main/java/io/reist/sandbox/app/model/remote/RetrofitService.java | 1525 | /*
* Copyright (C) 2017 Renat Sarymsakov.
*
* 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 io.reist.sandbox.app.model.remote;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import io.reist.sandbox.app.model.SandboxService;
import rx.functions.Action1;
/**
* Created by Reist on 11/2/15.
*/
public abstract class RetrofitService<T> implements SandboxService<T> {
protected final SandboxApi sandboxApi;
private final List<Action1<T>> listeners = new CopyOnWriteArrayList<>();
public RetrofitService(SandboxApi sandboxApi) {
this.sandboxApi = sandboxApi;
}
protected final void notifyDataChanged(T entity) {
for (Action1<T> listener : listeners) {
listener.call(entity);
}
}
@Override
public void addListener(Action1<T> dataListener) {
listeners.add(dataListener);
}
@Override
public void removeListener(Action1<T> dataListener) {
listeners.remove(dataListener);
}
}
| apache-2.0 |
marti584/Project-DJ-Cast | tests/jasmine/server/integration/methods/User_unsubscribe_spec.js | 2419 | // describe('User unsubscribe method', function() {
// /*
// * Set up some fake user credentials and spies to simulate logging in
// */
// beforeEach(function() {
// this.fakeUser = {
// _id: '12345',
// username: 'Fakey'
// };
// this.userSpy = spyOn(Meteor, 'user').and.returnValue(this.fakeUser);
// this.userIdSpy = spyOn(Meteor, 'userId').and.returnValue(this.fakeUser._id);
// });
// it('throws if we are NOT logged in', function() {
// // Call through to the original Meteor.user() implementation
// // This will return 'null' because we're obviously not logged in
// this.userSpy.and.callThrough();
// let channel = new Channel({
// title: 'Logged out',
// query: 'Should throw'
// });
// channel.save();
// try {
// Meteor.call('/users/unsubscribe', channel);
// fail('method should throw if we are not logged in');
// } catch(e) {
// expect(e.error).toBe('unauthorized');
// }
// channel.remove();
// });
// it('throws if the given channel does not exist', function() {
// let channel = new Channel({
// title: 'Logged out',
// query: 'Should throw'
// });
// Do not save it!
// try {
// Meteor.call('/users/unsubscribe', channel);
// fail('method should throw if the channel does not exists');
// } catch(e) {
// expect(e.error).toBe('channel-not-found');
// }
// });
// it('calls the unsubscribe from method', function() {
// let subscribeToSpy = jasmine.createSpy('subscribeTo');
// let unsubscribeFromSpy = jasmine.createSpy('unsubscribeFrom');
// let meSpy = spyOn(User, 'me').and.returnValue({
// subscribeTo: subscribeToSpy,
// unsubscribeFrom: unsubscribeFromSpy
// });
// let channel = new Channel({
// title: 'Logged out',
// query: 'Should throw'
// });
// channel.save();
// // Make sure we are first subscribed to the channel
// Meteor.call('/users/subscribe', channel);
// Meteor.call('/users/unsubscribe', channel);
// // Here we'll just check that we are correctly calling the model method.
// // We are already testing that method works in a different test.
// expect(subscribeToSpy).toHaveBeenCalledWith(channel);
// expect(unsubscribeFromSpy).toHaveBeenCalledWith(channel);
// channel.remove();
// });
// });
| apache-2.0 |
voislavj/fwmvc | app/models/page_model.php | 411 | <?php
class PageModel extends Model {
public $table = 'pages';
public $order = 'position';
public $validate = array(
'title' => array(
'rule' => '/.+/',
'message' => 'Polje `Naslov` je obavezno.'
)
);
public static function menu() {
return self::build()
->where(array('menu'=>1))
->query();
}
} | apache-2.0 |
googleapis/google-api-ruby-client | generated/google-apis-serviceusage_v1beta1/lib/google/apis/serviceusage_v1beta1.rb | 1825 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/serviceusage_v1beta1/service.rb'
require 'google/apis/serviceusage_v1beta1/classes.rb'
require 'google/apis/serviceusage_v1beta1/representations.rb'
require 'google/apis/serviceusage_v1beta1/gem_version.rb'
module Google
module Apis
# Service Usage API
#
# Enables services that service consumers want to use on Google Cloud Platform,
# lists the available or enabled services, or disables services that service
# consumers no longer use.
#
# @see https://cloud.google.com/service-usage/
module ServiceusageV1beta1
# Version of the Service Usage API this client connects to.
# This is NOT the gem version.
VERSION = 'V1beta1'
# See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
# View your data across Google Cloud services and see the email address of your Google Account
AUTH_CLOUD_PLATFORM_READ_ONLY = 'https://www.googleapis.com/auth/cloud-platform.read-only'
# Manage your Google API service configuration
AUTH_SERVICE_MANAGEMENT = 'https://www.googleapis.com/auth/service.management'
end
end
end
| apache-2.0 |
kamalmarhubi/bazel | src/test/java/com/google/devtools/build/lib/events/ReporterStreamTest.java | 2183 | // Copyright 2014 The Bazel 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.
package com.google.devtools.build.lib.events;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.PrintWriter;
@RunWith(JUnit4.class)
public class ReporterStreamTest {
private Reporter reporter;
private StringBuilder out;
private EventHandler outAppender;
@Before
public void setUp() throws Exception {
reporter = new Reporter();
out = new StringBuilder();
outAppender = new EventHandler() {
@Override
public void handle(Event event) {
out.append("[" + event.getKind() + ": " + event.getMessage() + "]\n");
}
};
}
@Test
public void reporterStream() throws Exception {
assertThat(out.toString()).isEmpty();
reporter.addHandler(outAppender);
try (
PrintWriter warnWriter =
new PrintWriter(new ReporterStream(reporter, EventKind.WARNING), true);
PrintWriter infoWriter =
new PrintWriter(new ReporterStream(reporter, EventKind.INFO), true)
) {
infoWriter.println("some info");
warnWriter.println("a warning");
}
reporter.getOutErr().printOutLn("some output");
reporter.getOutErr().printErrLn("an error");
MoreAsserts.assertEqualsUnifyingLineEnds(
"[INFO: some info\n]\n"
+ "[WARNING: a warning\n]\n"
+ "[STDOUT: some output\n]\n"
+ "[STDERR: an error\n]\n",
out.toString());
}
}
| apache-2.0 |
devisnik/RxJava | rxjava-core/src/perf/java/rx/schedulers/TestRecursionMemoryUsage.java | 3466 | /**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.schedulers;
import rx.Observable;
import rx.Observable.OnSubscribeFunc;
import rx.Observer;
import rx.Scheduler;
import rx.Scheduler.Inner;
import rx.Subscription;
import rx.functions.Action1;
/**
* Used for manual testing of memory leaks with recursive schedulers.
*
*/
public class TestRecursionMemoryUsage {
public static void main(String args[]) {
usingFunc2(Schedulers.newThread());
usingAction0(Schedulers.newThread());
usingFunc2(Schedulers.currentThread());
usingAction0(Schedulers.currentThread());
usingFunc2(Schedulers.computation());
usingAction0(Schedulers.computation());
System.exit(0);
}
protected static void usingFunc2(final Scheduler scheduler) {
System.out.println("************ usingFunc2: " + scheduler);
Observable.create(new OnSubscribeFunc<Long>() {
@Override
public Subscription onSubscribe(final Observer<? super Long> o) {
return scheduler.schedule(new Action1<Inner>() {
long i = 0;
@Override
public void call(Inner inner) {
i++;
if (i % 500000 == 0) {
System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory());
o.onNext(i);
}
if (i == 100000000L) {
o.onCompleted();
return;
}
inner.schedule(this);
}
});
}
}).toBlockingObservable().last();
}
protected static void usingAction0(final Scheduler scheduler) {
System.out.println("************ usingAction0: " + scheduler);
Observable.create(new OnSubscribeFunc<Long>() {
@Override
public Subscription onSubscribe(final Observer<? super Long> o) {
return scheduler.schedule(new Action1<Inner>() {
private long i = 0;
@Override
public void call(Inner inner) {
i++;
if (i % 500000 == 0) {
System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory());
o.onNext(i);
}
if (i == 100000000L) {
o.onCompleted();
return;
}
inner.schedule(this);
}
});
}
}).toBlockingObservable().last();
}
}
| apache-2.0 |
TapTrack/BasicNfc-Command-Family | commandfamily-basicnfc/src/main/java/com/taptrack/tcmptappy2/commandfamilies/basicnfc/responses/TagWrittenResponse.java | 1538 | package com.taptrack.tcmptappy2.commandfamilies.basicnfc.responses;
import com.taptrack.tcmptappy.tappy.constants.TagTypes;
import com.taptrack.tcmptappy2.MalformedPayloadException;;
import com.taptrack.tcmptappy2.commandfamilies.basicnfc.AbstractBasicNfcMessage;
import java.util.Arrays;
/**
* A tag has been written by the Tappy
*/
public class TagWrittenResponse extends AbstractBasicNfcMessage {
public static final byte COMMAND_CODE = 0x05;
byte[] tagCode;
byte tagType;
public TagWrittenResponse() {
tagCode = new byte[7];
tagType = TagTypes.TAG_UNKNOWN;
}
public TagWrittenResponse(byte[] tagCode, byte tagType) {
this.tagCode = tagCode;
this.tagType = tagType;
}
@Override
public void parsePayload(byte[] payload) throws MalformedPayloadException {
tagType = payload[0];
tagCode = Arrays.copyOfRange(payload, 1, payload.length);
}
public byte[] getTagCode() {
return tagCode;
}
public void setTagCode(byte[] tagCode) {
this.tagCode = tagCode;
}
public byte getTagType() {
return tagType;
}
public void setTagType(byte tagType) {
this.tagType = tagType;
}
@Override
public byte[] getPayload() {
byte[] payload = new byte[tagCode.length+1];
payload[0] = tagType;
System.arraycopy(tagCode,0,payload,1, tagCode.length);
return payload;
}
@Override
public byte getCommandCode() {
return COMMAND_CODE;
}
}
| apache-2.0 |
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/main/credential_plugins/plugin.py | 1657 | import os
import tempfile
from collections import namedtuple
from requests.exceptions import HTTPError
CredentialPlugin = namedtuple('CredentialPlugin', ['name', 'inputs', 'backend'])
def raise_for_status(resp):
resp.raise_for_status()
if resp.status_code >= 300:
exc = HTTPError()
setattr(exc, 'response', resp)
raise exc
class CertFiles():
"""
A context manager used for writing a certificate and (optional) key
to $TMPDIR, and cleaning up afterwards.
This is particularly useful as a shared resource for credential plugins
that want to pull cert/key data out of the database and persist it
temporarily to the file system so that it can loaded into the openssl
certificate chain (generally, for HTTPS requests plugins make via the
Python requests library)
with CertFiles(cert_data, key_data) as cert:
# cert is string representing a path to the cert or pemfile
# temporarily written to disk
requests.post(..., cert=cert)
"""
certfile = None
def __init__(self, cert, key=None):
self.cert = cert
self.key = key
def __enter__(self):
if not self.cert:
return None
self.certfile = tempfile.NamedTemporaryFile('wb', delete=False)
self.certfile.write(self.cert.encode())
if self.key:
self.certfile.write(b'\n')
self.certfile.write(self.key.encode())
self.certfile.flush()
return str(self.certfile.name)
def __exit__(self, *args):
if self.certfile and os.path.exists(self.certfile.name):
os.remove(self.certfile.name)
| apache-2.0 |
DanGrew/Nuts | nuts/src/uk/dangrew/nuts/progress/custom/ProgressChangedListener.java | 1900 | package uk.dangrew.nuts.progress.custom;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.BiConsumer;
public class ProgressChangedListener< DateT, ValueT > {
private final Set< BiConsumer< DateT, ValueT > > whenAdded;
private final Set< BiConsumer< DateT, ValueT > > whenUpdated;
private final Set< BiConsumer< DateT, ValueT > > whenRemoved;
public ProgressChangedListener() {
this.whenAdded = new LinkedHashSet<>();
this.whenUpdated = new LinkedHashSet<>();
this.whenRemoved = new LinkedHashSet<>();
}//End Constructor
public void progressAdded( DateT timestamp, ValueT value ){
whenAdded.forEach( c -> c.accept( timestamp, value ) );
}//End Method
public void progressRemoved( DateT timestamp, ValueT value ){
whenRemoved.forEach( c -> c.accept( timestamp, value ) );
}//End Method
public void progressUpdated( DateT timestamp, ValueT value ){
whenUpdated.forEach( c -> c.accept( timestamp, value ) );
}//End Method
public void whenProgressAdded( BiConsumer< DateT, ValueT > consumer ) {
this.whenAdded.add( consumer );
}//End Method
public void whenProgressRemoved( BiConsumer< DateT, ValueT > consumer ) {
this.whenRemoved.add( consumer );
}//End Method
public void whenProgressUpdated( BiConsumer< DateT, ValueT > consumer ) {
this.whenUpdated.add( consumer );
}//End Method
public void removeWhenProgressAdded( BiConsumer< DateT, ValueT > consumer ) {
this.whenAdded.remove( consumer );
}//End Method
public void removeWhenProgressUpdated( BiConsumer< DateT, ValueT > consumer ) {
this.whenUpdated.remove( consumer );
}//End Method
public void removeWhenProgressRemoved( BiConsumer< DateT, ValueT > consumer ) {
this.whenRemoved.remove( consumer );
}//End Method
}//End Interface
| apache-2.0 |
arnohaase/cass-driver | src/main/scala/com/ajjpj/cassdriver/connection/api/CassTimestamp.scala | 316 | package com.ajjpj.cassdriver.connection.api
import java.time.Instant
class CassTimestamp(val l: Long) extends AnyVal {
}
object CassTimestamp {
def forInstant(i: Instant) = new CassTimestamp(i.toEpochMilli * 1000 + (i.getNano / 1000) % 1000)
def forMillis(millis: Long) = new CassTimestamp(millis * 1000)
}
| apache-2.0 |
flibbertigibbet/hibernate-validator-android | engine/src/main/java/org/hibernate/validator/internal/util/classhierarchy/ClassHierarchyHelper.java | 4699 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.hibernate.validator.internal.util.classhierarchy;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.hibernate.validator.internal.util.Contracts;
import static org.hibernate.validator.internal.util.CollectionHelper.newArrayList;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
/**
* Helper class for dealing with inheritance hierarchies of given types which
* allows to selectively retrieve elements from such hierarchies, e.g. all
* super-classes, all implemented interfaces etc.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class ClassHierarchyHelper {
/**
* Gets the elements of the hierarchy of the given class which match the
* given filters. Classes are added by starting with the class itself and
* its implemented interfaces. Then its super class and interfaces are added
* and so on.
*
* @param clazz the class for which to retrieve the hierarchy
* @param filters filters applying for the search
*
* @return List of hierarchy classes. Will only contain those types matching
* the given filters. The list contains the given class itself, if
* it is no proxy class.
*/
public static <T> List<Class<? super T>> getHierarchy(Class<T> clazz, Filter... filters) {
Contracts.assertNotNull( clazz );
List<Class<? super T>> classes = newArrayList();
List<Filter> allFilters = newArrayList();
allFilters.addAll( Arrays.asList( filters ) );
allFilters.add( Filters.excludeProxies() );
getHierarchy( clazz, classes, allFilters );
return classes;
}
/**
* Retrieves all superclasses and interfaces recursively.
*
* @param clazz the class to start the search with
* @param classes list of classes to which to add all found super types matching
* the given filters
* @param filters filters applying for the search
*/
private static <T> void getHierarchy(Class<? super T> clazz, List<Class<? super T>> classes, Iterable<Filter> filters) {
for ( Class<? super T> current = clazz; current != null; current = current.getSuperclass() ) {
if ( classes.contains( current ) ) {
return;
}
if ( acceptedByAllFilters( current, filters ) ) {
classes.add( current );
}
for ( Class<?> currentInterface : current.getInterfaces() ) {
//safe since interfaces are super-types
@SuppressWarnings("unchecked")
Class<? super T> currentInterfaceCasted = (Class<? super T>) currentInterface;
getHierarchy( currentInterfaceCasted, classes, filters );
}
}
}
private static boolean acceptedByAllFilters(Class<?> clazz, Iterable<Filter> filters) {
for ( Filter classFilter : filters ) {
if ( !classFilter.accepts( clazz ) ) {
return false;
}
}
return true;
}
/**
* Gets all interfaces (and recursively their super-interfaces) which the
* given class directly implements. Interfaces implemented by super-classes
* are not contained.
*
* @param clazz the class for which to retrieve the implemented interfaces
*
* @return Set of all interfaces implemented by the class represented by
* this hierarchy. The empty list is returned if it does not
* implement any interfaces.
*/
public static <T> Set<Class<? super T>> getDirectlyImplementedInterfaces(Class<T> clazz) {
Contracts.assertNotNull( clazz );
Set<Class<? super T>> classes = newHashSet();
getImplementedInterfaces( clazz, classes );
return classes;
}
private static <T> void getImplementedInterfaces(Class<? super T> clazz, Set<Class<? super T>> classes) {
for ( Class<?> currentInterface : clazz.getInterfaces() ) {
@SuppressWarnings("unchecked") //safe since interfaces are super-types
Class<? super T> currentInterfaceCasted = (Class<? super T>) currentInterface;
classes.add( currentInterfaceCasted );
getImplementedInterfaces( currentInterfaceCasted, classes );
}
}
}
| apache-2.0 |
sequenceiq/cloudbreak | autoscale/src/main/java/com/sequenceiq/periscope/monitor/MetricMonitor.java | 900 | package com.sequenceiq.periscope.monitor;
import java.util.Collections;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.sequenceiq.periscope.domain.Cluster;
import com.sequenceiq.periscope.monitor.evaluator.EvaluatorContext;
import com.sequenceiq.periscope.monitor.evaluator.MetricEvaluator;
@Component
public class MetricMonitor extends AbstractMonitor implements Monitor {
@Override
public String getIdentifier() {
return "metric-monitor";
}
@Override
public String getTriggerExpression() {
return MonitorUpdateRate.METRIC_UPDATE_RATE_CRON;
}
@Override
public Class getEvaluatorType() {
return MetricEvaluator.class;
}
@Override
public Map<String, Object> getContext(Cluster cluster) {
return Collections.singletonMap(EvaluatorContext.CLUSTER_ID.name(), cluster.getId());
}
}
| apache-2.0 |
xifanoo/coolweather | app/src/main/java/com/sw/coolweather/ui/activity/SplashActivity.java | 377 | package com.sw.coolweather.ui.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.sw.coolweather.R;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
}
| apache-2.0 |
sncap/scouter | scouter.client/src/scouter/client/xlog/views/XLogProfilePageView.java | 28379 | /*
* Copyright 2015 LG CNS.
*
* 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 scouter.client.xlog.views;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import scouter.client.Activator;
import scouter.client.Images;
import scouter.client.model.TextProxy;
import scouter.client.util.ExUtil;
import scouter.client.util.ImageUtil;
import scouter.client.util.MyKeyAdapter;
import scouter.client.util.StepWrapper;
import scouter.client.util.UIUtil;
import scouter.client.util.UIUtil.XLogViewWithTable;
import scouter.client.xlog.SaveProfileJob;
import scouter.client.xlog.XLogUtil;
import scouter.lang.pack.XLogPack;
import scouter.lang.step.ApiCallStep;
import scouter.lang.step.ApiCallSum;
import scouter.lang.step.MessageStep;
import scouter.lang.step.MethodStep;
import scouter.lang.step.MethodSum;
import scouter.lang.step.SqlStep;
import scouter.lang.step.SqlSum;
import scouter.lang.step.Step;
import scouter.lang.step.StepEnum;
import scouter.lang.step.StepSingle;
import scouter.lang.step.StepSummary;
import scouter.util.CastUtil;
import scouter.util.DateUtil;
import scouter.util.Hexa32;
import scouter.util.StringUtil;
public class XLogProfilePageView extends ViewPart implements XLogViewWithTable {
public static final String ID = XLogProfilePageView.class.getName();
private StyledText header, text;
Button prevBtn, nextBtn, endBtn, startBtn, summaryBtn;
Text targetPage;
Label totalPage, totalProfile;
@SuppressWarnings("unused")
private IMemento memento;
IToolBarManager man;
Action spaceNarrow, spaceWide;
int pageNum = 0;
int rowPerPage = 30;
SashForm sashForm;
Action showSearchAreaBtn;
Composite mainComposite;
String[] titles = {"Page", "Profile"};
Text searchText;
Table searchResultTable;
Label searchLbl;
ProgressBar searchProg;
Button searchBtn, stopBtn;
Text searchFromTxt, searchToTxt;
Text maxCountTxt;
MyKeyAdapter adapter;
private final int SORT_WITH_COUNT = 100;
private final int SORT_WITH_SUM = 200;
private final int SORT_WITH_AVG = 300;
private int CURRENT_SORT_CRITERIA = SORT_WITH_COUNT;
Button sortCountBtn, sortSumBtn, sortAvgBtn;
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
this.memento = memento;
}
public void createPartControl(Composite parent) {
adapter = new MyKeyAdapter(parent.getShell(), "SelectedLog.txt");
man = getViewSite().getActionBars().getToolBarManager();
sashForm = new SashForm(parent, SWT.HORIZONTAL);
sashForm.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
sashForm.SASH_WIDTH = 1;
mainComposite = new Composite(sashForm, SWT.NONE);
mainComposite.setLayout(new GridLayout(1, true));
header = new StyledText(mainComposite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP );
GridData bodyData = new GridData(GridData.FILL, GridData.FILL, true, false);
bodyData.heightHint = 100;
header.setLayoutData(bodyData);
header.setText("");
header.setFont(new Font(null, "Courier New", 10, SWT.NORMAL));
header.setBackgroundImage(Activator.getImage("icons/grid.jpg"));
Composite centerComp = new Composite(mainComposite, SWT.NONE);
bodyData = new GridData(GridData.FILL, GridData.FILL, true, false);
bodyData.heightHint = 55;
centerComp.setLayoutData(bodyData);
centerComp.setLayout(UIUtil.formLayout(5, 5));
summaryBtn = new Button(centerComp, SWT.TOGGLE);
summaryBtn.setText("Summary");
summaryBtn.setLayoutData(UIUtil.formData(null, -1, null, -1, 100, 0, null, -1));
summaryBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if(b.getSelection()){
getSummary();
}else{
pageNum = 0;
setProfile();
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
endBtn = new Button(centerComp, SWT.NONE);
endBtn.setImage(Images.toend);
endBtn.setText("");
endBtn.setLayoutData(UIUtil.formData(null, -1, null, -1, summaryBtn, 0, null, -1, 40));
endBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
pageNum = total - 1;
targetPage.setText(""+(pageNum + 1));
setProfile();
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
nextBtn = new Button(centerComp, SWT.NONE);
nextBtn.setImage(Images.tonext);
nextBtn.setText("Next");
nextBtn.setLayoutData(UIUtil.formData(null, -1, null, -1, endBtn, 0, null, -1, 80));
nextBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
pageNum++;
targetPage.setText(""+(pageNum + 1));
setProfile();
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
prevBtn = new Button(centerComp, SWT.NONE);
prevBtn.setImage(Images.toprev);
prevBtn.setText("Before");
prevBtn.setLayoutData(UIUtil.formData(null, -1, null, -1, nextBtn, 0, null, -1, 80));
prevBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
pageNum--;
targetPage.setText(""+(pageNum + 1));
setProfile();
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
startBtn = new Button(centerComp, SWT.NONE);
startBtn.setImage(Images.tostart);
startBtn.setText("");
startBtn.setLayoutData(UIUtil.formData(null, -1, null, -1, prevBtn, 0, null, -1, 40));
startBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
pageNum = 0;
targetPage.setText(""+(pageNum + 1));
setProfile();
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
totalPage = new Label(centerComp, SWT.NONE);
totalPage.setLayoutData(UIUtil.formData(null, -1, 0, 3, startBtn, 0, null, -1, 60));
totalProfile = new Label(centerComp, SWT.NONE);
totalProfile.setLayoutData(UIUtil.formData(0, 0, 0, 3, null, -1, null, -1, 100));
targetPage = new Text(centerComp, SWT.BORDER | SWT.RIGHT);
targetPage.setLayoutData(UIUtil.formData(null, -1, null, -1, totalPage, 0, null, -1, 60));
targetPage.addListener(SWT.Traverse, new Listener() {
public void handleEvent(Event event) {
if (event.detail == SWT.TRAVERSE_RETURN) {
pageNum = CastUtil.cint(targetPage.getText()) - 1;
if(pageNum > total){
pageNum = total - 1;
}
targetPage.setText(""+(pageNum + 1));
setProfile();
}
}
});
targetPage.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
Text text = (Text)e.getSource();
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isFloat = true;
try {
Float.parseFloat(newS);
} catch (NumberFormatException ex) {
isFloat = false;
}
if(!isFloat)
e.doit = false;
}
});
sortCountBtn = new Button(centerComp, SWT.NONE);
sortCountBtn.setText("Count");
sortCountBtn.setLayoutData(UIUtil.formData(0, 2, totalProfile, 8, null, -1, null, -1, 70));
sortCountBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
CURRENT_SORT_CRITERIA = SORT_WITH_COUNT;
getSummary();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
sortSumBtn = new Button(centerComp, SWT.NONE);
sortSumBtn.setText("Sum");
sortSumBtn.setLayoutData(UIUtil.formData(sortCountBtn, 20, totalProfile, 8, null, -1, null, -1, 70));
sortSumBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
CURRENT_SORT_CRITERIA = SORT_WITH_SUM;
getSummary();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
sortAvgBtn = new Button(centerComp, SWT.NONE);
sortAvgBtn.setText("Avg");
sortAvgBtn.setLayoutData(UIUtil.formData(sortSumBtn, 20, totalProfile, 8, null, -1, null, -1, 70));
sortAvgBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
CURRENT_SORT_CRITERIA = SORT_WITH_AVG;
getSummary();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
text = new StyledText(mainComposite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
bodyData = new GridData(GridData.FILL, GridData.FILL, true, true);
text.setLayoutData(bodyData);
text.setText("");
text.setFont(new Font(null, "Courier New", 10, SWT.NORMAL));
text.setBackgroundImage(Activator.getImage("icons/grid.jpg"));
text.addKeyListener(adapter);
text.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL) {
if (e.keyCode == 'f') {
showSearchAreaBtn.setChecked(true);
sashForm.setMaximizedControl(null);
searchText.setFocus();
}
}
}
});
// RIGHT
Composite searchComposite = new Composite(sashForm, SWT.NONE);
GridLayout searchLayout = new GridLayout(2, true);
searchComposite.setLayout(searchLayout);
Composite searchArea = new Composite(searchComposite, SWT.NONE);
searchArea.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
searchArea.setLayout(UIUtil.formLayout(1, 1));
Label pageLbl = new Label(searchArea, SWT.NONE);
pageLbl.setText("Page:");
pageLbl.setLayoutData(UIUtil.formData(0, 2, 0, 2, null, -1, null, -1, 70));
searchFromTxt = new Text(searchArea, SWT.BORDER | SWT.RIGHT);
searchFromTxt.setLayoutData(UIUtil.formData(pageLbl, 2, 0, 0, null, -1, null, -1, 45));
Label fromToLbl = new Label(searchArea, SWT.NONE);
fromToLbl.setText("~");
fromToLbl.setLayoutData(UIUtil.formData(searchFromTxt, 2, 0, 2, null, -1, null, -1));
searchToTxt = new Text(searchArea, SWT.BORDER | SWT.RIGHT);
searchToTxt.setLayoutData(UIUtil.formData(fromToLbl, 2, 0, 0, 100, -5, null, -1));
Label maxLbl = new Label(searchArea, SWT.NONE);
maxLbl.setText("Max Count:");
maxLbl.setLayoutData(UIUtil.formData(0, 2, searchToTxt, 5, null, -1, null, -1, 70));
maxCountTxt = new Text(searchArea, SWT.BORDER | SWT.RIGHT);
maxCountTxt.setLayoutData(UIUtil.formData(maxLbl, 2, searchToTxt, 3, 100, -5, null, -1));
stopBtn = new Button(searchArea, SWT.NONE);
// stopBtn.setImage(Images.stop);
stopBtn.setText("Stop");
stopBtn.setLayoutData(UIUtil.formData(null, -1, maxCountTxt, 5, 100, -5, null, -1));
stopBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
breakSearch = true;
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
searchBtn = new Button(searchArea, SWT.NONE);
searchBtn.setText("search");
searchBtn.setLayoutData(UIUtil.formData(null, -1, maxCountTxt, 5, stopBtn, -5, null, -1));
searchBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
searchWithNewText();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
searchText = new Text(searchArea, SWT.BORDER);
searchText.setLayoutData(UIUtil.formData(0, 2, maxCountTxt, 7, searchBtn, -5, null, -1));
searchText.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if(e.character == SWT.CR){
searchWithNewText();
}
}
public void keyPressed(KeyEvent e) {
}
});
Composite labelComp = new Composite(searchComposite, SWT.NONE);
labelComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
labelComp.setLayout(UIUtil.formLayout(0, 0));
searchLbl = new Label(labelComp, SWT.NONE | SWT.RIGHT);
searchLbl.setLayoutData(UIUtil.formData(0, 2, 0, 2, 100, -5, null, -1));
searchProg = new ProgressBar(labelComp, SWT.SMOOTH/* SWT.HORIZONTAL | SWT.INDETERMINATE*/);
searchProg.setVisible(false);
searchProg.setLayoutData(UIUtil.formData(0, 2, 0, 0, 100, -5, null, -1, -1, 10));
Composite tableComp = new Composite(searchComposite, SWT.NONE);
tableComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
searchResultTable = new Table(tableComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
searchResultTable.setHeaderVisible(true);
TableColumn column0 = UIUtil.create(searchResultTable, SWT.RIGHT, titles[0], 6, 0, false, 100, this);
TableColumn column1 = UIUtil.create(searchResultTable, SWT.NONE, titles[1], 6, 1, false, 100, this);
for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
searchResultTable.getColumn(loopIndex).pack();
}
TableColumnLayout layout = new TableColumnLayout();
tableComp.setLayout( layout );
layout.setColumnData( column0, new ColumnWeightData( 15 ) );
layout.setColumnData( column1, new ColumnWeightData( 85 ) );
searchResultTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TableItem selectItem = (TableItem)event.item;
searchLineIndex = CastUtil.cint(selectItem.getData());
int select = CastUtil.cint(selectItem.getText(0)) - 1;
if(pageNum != select){
pageNum = select;
if(pageNum > total){
pageNum = total - 1;
}
targetPage.setText(""+(pageNum + 1));
}
setProfile();
}
});
showSearchAreaBtn = new Action("Search Text", IAction.AS_CHECK_BOX){
public void run(){
if(showSearchAreaBtn.isChecked()){
sashForm.setMaximizedControl(null);
searchText.setFocus();
}else{
sashForm.setMaximizedControl(mainComposite);
}
}
};
showSearchAreaBtn.setImageDescriptor(ImageUtil.getImageDescriptor(Images.SEARCH));
man.add(showSearchAreaBtn);
sashForm.setWeights(new int[]{3, 1});
// sashForm.setMaximizedControl(mainComposite);
// sjkim request.
sashForm.setMaximizedControl(null);
showSearchAreaBtn.setChecked(true);
searchText.setFocus();
}
private int searchLineIndex = -1;
int index;
String m = "";
int prog = 0;
String searchTxt;
boolean breakSearch = false;
int maxCount = 0;
private void searchWithNewText(){
searchTxt = searchText.getText();
searchCnt = 0;
if(CastUtil.cint(searchFromTxt.getText()) < 1){
searchFromTxt.setText("1");
}
if(CastUtil.cint(searchToTxt.getText()) > total){
searchToTxt.setText(""+total);
}
int startProfile = CastUtil.cint(searchFromTxt.getText()) * rowPerPage - rowPerPage;
int endProfile = CastUtil.cint(searchToTxt.getText()) * rowPerPage;
if(endProfile > profiles.length){
endProfile = profiles.length;
}
maxCount = CastUtil.cint(maxCountTxt.getText());
clearTable();
searchWithText(startProfile, endProfile);
}
private void clearTable(){
searchResultTable.removeAll();
}
int searchCnt = 0;
private void searchWithText(final int startProfile, final int endProfile){
prog = 0;
breakSearch = false;
searchText.setText(searchTxt);
setSearchWidgets(true);
ExUtil.asyncRun(new Runnable() {
public void run() {
for (int i = startProfile; i < endProfile && !breakSearch; i++) {
Step step;
if(profiles[i].step instanceof StepSingle){
step = (StepSingle) profiles[i].step;
index = ((StepSingle)step).index;
}else{
step = (StepSummary) profiles[i].step;
index = profiles[i].sSummaryIdx;
}
m = "";
switch (step.getStepType()) {
case StepEnum.METHOD:
m = TextProxy.method.getText(((MethodStep)step).hash);
if (m == null){
m = Hexa32.toString32(((MethodStep)step).hash);
}
break;
case StepEnum.METHOD_SUM:
m = TextProxy.method.getText(((MethodSum)step).hash);
if (m == null){
m = Hexa32.toString32(((MethodSum)step).hash);
}
break;
case StepEnum.SQL:
case StepEnum.SQL2:
SqlStep sql = (SqlStep) step;
m = TextProxy.sql.getText(sql.hash);
if (m == null){
m = Hexa32.toString32(sql.hash);
}
if (StringUtil.isEmpty(sql.param) == false) {
m += " [" + sql.param + "]";
}
if (sql.error != 0) {
m += TextProxy.error.getText(sql.error);
}
break;
case StepEnum.SQL_SUM:
SqlSum sqlsum = (SqlSum) step;
m = TextProxy.sql.getText(sqlsum.hash);
if (m == null){
m = Hexa32.toString32(sqlsum.hash);
}
if (StringUtil.isEmpty(sqlsum.param) == false) {
m += " [" + sqlsum.param + "]";
}
if (sqlsum.error != 0) {
m += TextProxy.error.getText(sqlsum.error);
}
break;
case StepEnum.MESSAGE:
m = ((MessageStep) step).message;
break;
case StepEnum.APICALL:
ApiCallStep apicall = (ApiCallStep) step;
m = TextProxy.apicall.getText(apicall.hash);
if (m == null)
m = Hexa32.toString32(apicall.hash);
if (apicall.error != 0) {
m += TextProxy.error.getText(apicall.error);
}
break;
case StepEnum.APICALL_SUM:
ApiCallSum apicallsum = (ApiCallSum) step;
m = TextProxy.apicall.getText(apicallsum.hash);
if (m == null)
m = Hexa32.toString32(apicallsum.hash);
if (apicallsum.error != 0) {
m += TextProxy.error.getText(apicallsum.error);
}
break;
}
if(m.indexOf(searchTxt) != -1){
searchResultTable.getDisplay().syncExec(new Runnable() {
public void run() {
if (searchResultTable.isDisposed())
return;
TableItem item = new TableItem(searchResultTable, SWT.NULL);
item.setText(0, "" + ((index / rowPerPage) + 1));
item.setText(1, m);
item.setData(index);
searchCnt++;
}
});
}
prog = i - startProfile;
searchResultTable.getDisplay().syncExec(new Runnable() {
public void run() {
searchProg.setSelection((prog * 100 / (endProfile - startProfile)));
}
});
if(searchCnt >= maxCount){
breakSearch = true;
}
}
searchResultTable.getDisplay().syncExec(new Runnable() {
public void run() {
setSearchWidgets(false);
}
});
}
});
}
private void setSearchWidgets(boolean searchDoing){
if(searchDoing){
searchText.setEnabled(false);
searchLbl.setVisible(false);
searchProg.setVisible(true);
searchBtn.setEnabled(false);
}else{
searchText.setEnabled(true);
searchText.setFocus();
searchText.selectAll();
searchLbl.setVisible(true);
searchLbl.setText("Count : "+searchCnt);
searchProg.setVisible(false);
searchBtn.setEnabled(true);
}
}
private void setWidgets(boolean enabled){
prevBtn.setEnabled(enabled);
nextBtn.setEnabled(enabled);
endBtn.setEnabled(enabled);
startBtn.setEnabled(enabled);
targetPage.setEnabled(enabled);
sortCountBtn.setEnabled(!enabled);
sortSumBtn.setEnabled(!enabled);
sortAvgBtn.setEnabled(!enabled);
}
protected void getSummary() {
setWidgets(false);
HashMap<String, ProfileSummary> summary = new HashMap<String, ProfileSummary>();
Color red = text.getDisplay().getSystemColor(SWT.COLOR_RED);
Color dgreen = text.getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
for(int inx = 0 ; inx < profiles.length ; inx++){
StepSingle step = (StepSingle)profiles[inx].step;
switch (step.getStepType()) {
case StepEnum.METHOD:
putSummary(summary, (MethodStep)step);
break;
case StepEnum.SQL:
case StepEnum.SQL2:
putSummary(summary, (SqlStep)step);
break;
case StepEnum.MESSAGE:
putSummary(summary, (MessageStep)step);
break;
case StepEnum.APICALL:
putSummary(summary, (ApiCallStep)step);
break;
}
}
ValueComparator bvc = new ValueComparator(summary);
TreeMap<String, ProfileSummary> sorted_map = new TreeMap<String, ProfileSummary>(bvc);
sorted_map.putAll(summary);
StringBuffer sb = new StringBuffer();
java.util.List<StyleRange> sr = new ArrayList<StyleRange>();
int length = 0;
sb.append("------------------------------------------------------------------------------------------\n");
sb.append(" Count Sum Avg Contents\n");
sb.append("------------------------------------------------------------------------------------------\n");
Iterator<String> itr = sorted_map.keySet().iterator();
while (itr.hasNext()) {
String key = itr.next();
ProfileSummary value = summary.get(key);
sb.append(String.format("%10d", value.callCnt));
sb.append(" ");
sb.append(String.format("%10d", value.sumResTime));
sb.append(" ");
sb.append(String.format("%10d", value.avgResTime));
sb.append(" ");
length = sb.length();
sb.append(value.name);
switch(value.type){
case TYPE_MESSAGE:
sr.add(style(length, sb.length() - length, dgreen, SWT.NORMAL));
break;
case TYPE_SQL:
sr.add(style(length, sb.length() - length, red, SWT.NORMAL));
break;
case TYPE_APICALL:
sr.add(style(length, sb.length() - length, red, SWT.NORMAL));
break;
default:
break;
}
sb.append("\n");
}
sb.append("------------------------------------------------------------------------------------------\n");
text.setText(sb.toString());
text.setStyleRanges(sr.toArray(new StyleRange[sr.size()]));
}
private final int TYPE_MESSAGE = 102;
private final int TYPE_SQL = 103;
private final int TYPE_METHOD = 104;
private final int TYPE_APICALL = 105;
private void putSummary(HashMap<String, ProfileSummary> summary, ApiCallStep step) {
String m = TextProxy.apicall.getText(step.hash);
if (m == null)
m = Hexa32.toString32(step.hash);
ProfileSummary ps = summary.get(m);
if(ps == null){
summary.put(m, new ProfileSummary(m, 1, step.elapsed, step.elapsed, TYPE_APICALL));
}else{
ps.addResTime(step.elapsed);
summary.put(m, ps);
}
}
private void putSummary(HashMap<String, ProfileSummary> summary, MessageStep step) {
String m = step.message;
ProfileSummary ps = summary.get(m);
if(ps == null){
summary.put(m, new ProfileSummary(m, 1, 0, 0, TYPE_MESSAGE));
}else{
ps.addResTime(0);
summary.put(m, ps);
}
}
private void putSummary(HashMap<String, ProfileSummary> summary, SqlStep step) {
String m = TextProxy.sql.getText(step.hash);
if (m == null)
m = Hexa32.toString32(step.hash);
ProfileSummary ps = summary.get(m);
if(ps == null){
summary.put(m, new ProfileSummary(m, 1, step.elapsed, step.elapsed, TYPE_SQL));
}else{
ps.addResTime(step.elapsed);
summary.put(m, ps);
}
}
private void putSummary(HashMap<String, ProfileSummary> summary, MethodStep step) {
String m = TextProxy.method.getText(step.hash);
if (m == null)
m = Hexa32.toString32(step.hash);
ProfileSummary ps = summary.get(m);
if(ps == null){
summary.put(m, new ProfileSummary(m, 1, step.elapsed, step.elapsed, TYPE_METHOD));
}else{
ps.addResTime(step.elapsed);
summary.put(m, ps);
}
}
XLogPack p;
StepWrapper[] profiles;
int total;
private int serverId;
private boolean isSummary;
public void setInput(File xLogDir, int serverId, boolean isSummary){
this.serverId = serverId;
this.isSummary = isSummary;
p = SaveProfileJob.getTranxData(xLogDir, header, serverId);
profiles = SaveProfileJob.getProfileData(p, xLogDir, isSummary);
if (profiles == null || profiles.length < 1) {
return;
}
String date = DateUtil.yyyymmdd(p.endTime);
Step[] steps = new Step[profiles.length];
for(int inx = 0 ; inx < profiles.length ; inx++){
steps[inx] = profiles[inx].step;
}
XLogUtil.loadStepText(serverId, date, steps);
totalProfile.setText("Profile:"+(((StepWrapper)profiles[profiles.length - 1]).getLastIndex() + 1));
total = (profiles.length / rowPerPage) + 1;
if(profiles.length % rowPerPage == 0){
total = total - 1;
}
totalPage.setText("/"+total);
targetPage.setText(""+(pageNum + 1));
searchToTxt.setText((total > 300)? "300":""+total);
searchFromTxt.setText("1");
maxCountTxt.setText("10000");
if(isSummary){
summaryBtn.setEnabled(false);
}
adapter.setFileName(TextProxy.object.getLoadText(date, p.objHash, serverId) + "_ " + Hexa32.toString32(p.txid)+".txt");
setProfile();
}
public void setProfile(){
setWidgets(true);
text.setText("");
int lastIdx = ((StepWrapper)profiles[profiles.length - 1]).getLastIndex();
int length = Integer.toString(lastIdx).length();
SaveProfileJob.setProfileData(p, profiles, text, pageNum, rowPerPage, prevBtn, nextBtn, startBtn, endBtn, length, serverId, searchLineIndex, isSummary);
}
public void setFocus() {
}
@Override
public void dispose() {
super.dispose();
}
public class ProfileSummary{
String name;
int callCnt;
int sumResTime;
int avgResTime;
int type;
public ProfileSummary(String name, int callCnt, int sumResTime,
int avgResTime, int type) {
super();
this.name = name;
this.callCnt = callCnt;
this.sumResTime = sumResTime;
this.avgResTime = avgResTime;
this.type = type;
}
public void addResTime(int resTime){
callCnt += 1;
sumResTime += resTime;
avgResTime = (int) Math.ceil(sumResTime / (double)callCnt );
}
public int getSortValue(int type){
if(type == SORT_WITH_COUNT){
return callCnt;
}else if(type == SORT_WITH_SUM){
return sumResTime;
}else if(type == SORT_WITH_AVG){
return avgResTime;
}else{
return callCnt;
}
}
}
class ValueComparator implements Comparator<String> {
Map<String, ProfileSummary> base;
public ValueComparator(Map<String, ProfileSummary> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a).getSortValue(CURRENT_SORT_CRITERIA) >= base.get(b).getSortValue(CURRENT_SORT_CRITERIA)) {
return -1;
} else {
return 1;
}
}
}
private StyleRange style(int start, int length, Color c, int f) {
StyleRange t = new StyleRange();
t.start = start;
t.length = length;
t.foreground = c;
t.fontStyle = f;
return t;
}
public void setTableItem(TableItem t) {
// TODO Auto-generated method stub
}
public void setChanges() {
// TODO Auto-generated method stub
}
} | apache-2.0 |
xuanaiwu/wechatcms | src/com/dayuan/interceptor/AuthInterceptor.java | 2747 | package com.dayuan.interceptor;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.dayuan.action.BaseAction;
import com.dayuan.annotation.Auth;
import com.dayuan.bean.SysUser;
import com.dayuan.utils.HtmlUtil;
import com.dayuan.utils.SessionUtils;
/**
* 权限拦截器
* @author xuanaiwu
*
*/
public class AuthInterceptor extends HandlerInterceptorAdapter {
private final static Logger log= Logger.getLogger(AuthInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HandlerMethod method = (HandlerMethod)handler;
Auth auth = method.getMethod().getAnnotation(Auth.class);
////验证登陆超时问题 auth = null,默认验证
if( auth == null || auth.verifyLogin()){
String baseUri = request.getContextPath();
String path = request.getServletPath();
SysUser user =SessionUtils.getUser(request);
if(user == null){
if(path.endsWith(".shtml")){
response.setStatus(response.SC_GATEWAY_TIMEOUT);
response.sendRedirect(baseUri+"/login.shtml");
return false;
}else{
response.setStatus(response.SC_GATEWAY_TIMEOUT);
Map<String, Object> result = new HashMap<String, Object>();
result.put(BaseAction.SUCCESS, false);
result.put(BaseAction.LOGOUT_FLAG, true);//登录标记 true 退出
result.put(BaseAction.MSG, "登录超时.");
HtmlUtil.writerJson(response, result);
return false;
}
}
}
//验证URL权限
if( auth == null || auth.verifyURL()){
//判断是否超级管理员
if(!SessionUtils.isAdmin(request)){
String menuUrl = StringUtils.remove( request.getRequestURI(),request.getContextPath());
if(!SessionUtils.isAccessUrl(request, StringUtils.trim(menuUrl))){
//日志记录
String userMail = SessionUtils.getUser(request).getEmail();
String msg ="URL权限验证不通过:[url="+menuUrl+"][email ="+ userMail+"]" ;
log.error(msg);
response.setStatus(response.SC_FORBIDDEN);
Map<String, Object> result = new HashMap<String, Object>();
result.put(BaseAction.SUCCESS, false);
result.put(BaseAction.MSG, "没有权限访问,请联系管理员.");
HtmlUtil.writerJson(response, result);
return false;
}
}
}
return super.preHandle(request, response, handler);
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/coa/businessobject/IndirectCostRecoveryExclusionAccount.java | 5824 | /*
* Copyright 2006 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.kfs.coa.businessobject;
import java.util.LinkedHashMap;
import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
/**
*
*/
public class IndirectCostRecoveryExclusionAccount extends PersistableBusinessObjectBase implements MutableInactivatable {
private String chartOfAccountsCode;
private String accountNumber;
private String financialObjectChartOfAccountCode;
private String financialObjectCode;
private Chart chart;
private Account account;
private Chart financialObjectChartOfAccount;
private ObjectCode objectCodeCurrent;
private boolean active;
public IndirectCostRecoveryExclusionAccount() {
super();
}
/**
* Gets the chartOfAccountsCode attribute.
*
* @return Returns the chartOfAccountsCode
*/
public String getChartOfAccountsCode() {
return chartOfAccountsCode;
}
/**
* Sets the chartOfAccountsCode attribute.
*
* @param chartOfAccountsCode The chartOfAccountsCode to set.
*/
public void setChartOfAccountsCode(String chartOfAccountsCode) {
this.chartOfAccountsCode = chartOfAccountsCode;
}
/**
* Gets the accountNumber attribute.
*
* @return Returns the accountNumber
*/
public String getAccountNumber() {
return accountNumber;
}
/**
* Sets the accountNumber attribute.
*
* @param accountNumber The accountNumber to set.
*/
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
/**
* Gets the financialObjectChartOfAccountCode attribute.
*
* @return Returns the financialObjectChartOfAccountCode
*/
public String getFinancialObjectChartOfAccountCode() {
return financialObjectChartOfAccountCode;
}
/**
* Sets the financialObjectChartOfAccountCode attribute.
*
* @param financialObjectChartOfAccountCode The financialObjectChartOfAccountCode to set.
*/
public void setFinancialObjectChartOfAccountCode(String financialObjectChartOfAccountCode) {
this.financialObjectChartOfAccountCode = financialObjectChartOfAccountCode;
}
/**
* Gets the financialObjectCode attribute.
*
* @return Returns the financialObjectCode
*/
public String getFinancialObjectCode() {
return financialObjectCode;
}
/**
* Sets the financialObjectCode attribute.
*
* @param financialObjectCode The financialObjectCode to set.
*/
public void setFinancialObjectCode(String financialObjectCode) {
this.financialObjectCode = financialObjectCode;
}
/**
* Gets the chart attribute.
*
* @return Returns the chart
*/
public Chart getChart() {
return chart;
}
/**
* Sets the chart attribute.
*
* @param chart The chart to set.
* @deprecated
*/
public void setChart(Chart chart) {
this.chart = chart;
}
/**
* Gets the account attribute.
*
* @return Returns the account
*/
public Account getAccount() {
return account;
}
/**
* Sets the account attribute.
*
* @param account The account to set.
* @deprecated
*/
public void setAccount(Account account) {
this.account = account;
}
/**
* Gets the financialObjectChartOfAccount attribute.
*
* @return Returns the financialObjectChartOfAccount
*/
public Chart getFinancialObjectChartOfAccount() {
return financialObjectChartOfAccount;
}
/**
* Sets the financialObjectChartOfAccount attribute.
*
* @param financialObjectChartOfAccount The financialObjectChartOfAccount to set.
* @deprecated
*/
public void setFinancialObjectChartOfAccount(Chart financialObjectChartOfAccount) {
this.financialObjectChartOfAccount = financialObjectChartOfAccount;
}
/**
* @return Returns the objectCode.
*/
public ObjectCode getObjectCodeCurrent() {
return objectCodeCurrent;
}
/**
* @param objectCode The objectCode to set.
* @deprecated
*/
public void setObjectCodeCurrent(ObjectCode objectCodeCurrent) {
this.objectCodeCurrent = objectCodeCurrent;
}
/**
* @return Returns whether the objectCode is active.
*/
public boolean isActive() {
return active;
}
/**
* @param active Set if the record is active.
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap m = new LinkedHashMap();
m.put("chartOfAccountsCode", this.chartOfAccountsCode);
m.put("accountNumber", this.accountNumber);
m.put("financialObjectChartOfAccountCode", this.financialObjectChartOfAccountCode);
m.put("financialObjectCode", this.financialObjectCode);
return m;
}
}
| apache-2.0 |
yongjiu/android-database-orm | android-database-orm-example/src/main/java/android/database/orm/example/MainActivity.java | 352 | package android.database.orm.example;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by yongjiu on 15/5/1.
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
} | apache-2.0 |
mandarjog/mixer | cmd/client/util_test.go | 5020 | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"reflect"
"testing"
"time"
ptypes "github.com/gogo/protobuf/types"
mixerpb "istio.io/api/mixer/v1"
)
func TestAttributeHandling(t *testing.T) {
type testCase struct {
rootArgs rootArgs
attrs mixerpb.Attributes
result bool
}
ts, _ := ptypes.TimestampProto(time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC))
d := ptypes.DurationProto(time.Duration(42) * time.Second)
cases := []testCase{
{
rootArgs: rootArgs{
stringAttributes: "a=X,b=Y,ccc=XYZ,d=X Z,e=X",
int64Attributes: "f=1,g=2,hhh=345",
doubleAttributes: "i=1,j=2,kkk=345.678",
boolAttributes: "l=true,m=false,nnn=true",
timestampAttributes: "o=2006-01-02T15:04:05Z",
durationAttributes: "p=42s",
bytesAttributes: "q=1,r=34:56",
attributes: "s=XYZ,t=2,u=3.0,v=true,w=2006-01-02T15:04:05Z,x=98:76,y=42s",
},
attrs: mixerpb.Attributes{
Dictionary: map[int32]string{
0: "a", 1: "b", 2: "ccc", 3: "d", 4: "e", 5: "f", 6: "g",
7: "hhh", 8: "i", 9: "j", 10: "kkk", 11: "l", 12: "m", 13: "nnn", 14: "o",
15: "p", 16: "q", 17: "r", 18: "s", 19: "t", 20: "u", 21: "v", 22: "w", 23: "x", 24: "y"},
StringAttributes: map[int32]string{0: "X", 1: "Y", 2: "XYZ", 3: "X Z", 4: "X", 18: "XYZ"},
Int64Attributes: map[int32]int64{5: 1, 6: 2, 7: 345, 19: 2},
DoubleAttributes: map[int32]float64{8: 1, 9: 2, 10: 345.678, 20: 3.0},
BoolAttributes: map[int32]bool{11: true, 12: false, 13: true, 21: true},
TimestampAttributes: map[int32]*ptypes.Timestamp{14: ts, 22: ts},
DurationAttributes: map[int32]*ptypes.Duration{15: d, 24: d},
BytesAttributes: map[int32][]uint8{16: {1}, 17: {0x34, 0x56}, 23: {0x98, 0x76}},
},
result: true,
},
{rootArgs: rootArgs{stringAttributes: "a,b=Y,ccc=XYZ,d=X Z,e=X"}},
{rootArgs: rootArgs{stringAttributes: "=,b=Y,ccc=XYZ,d=X Z,e=X"}},
{rootArgs: rootArgs{stringAttributes: "=X,b=Y,ccc=XYZ,d=X Z,e=X"}},
{rootArgs: rootArgs{int64Attributes: "f,g=2,hhh=345"}},
{rootArgs: rootArgs{int64Attributes: "f=,g=2,hhh=345"}},
{rootArgs: rootArgs{int64Attributes: "=,g=2,hhh=345"}},
{rootArgs: rootArgs{int64Attributes: "=1,g=2,hhh=345"}},
{rootArgs: rootArgs{int64Attributes: "f=XY,g=2,hhh=345"}},
{rootArgs: rootArgs{doubleAttributes: "i,j=2,kkk=345.678"}},
{rootArgs: rootArgs{doubleAttributes: "i=,j=2,kkk=345.678"}},
{rootArgs: rootArgs{doubleAttributes: "=,j=2,kkk=345.678"}},
{rootArgs: rootArgs{doubleAttributes: "=1,j=2,kkk=345.678"}},
{rootArgs: rootArgs{doubleAttributes: "i=XY,j=2,kkk=345.678"}},
{rootArgs: rootArgs{boolAttributes: "l,m=false,nnn=true"}},
{rootArgs: rootArgs{boolAttributes: "l=,m=false,nnn=true"}},
{rootArgs: rootArgs{boolAttributes: "=,m=false,nnn=true"}},
{rootArgs: rootArgs{boolAttributes: "=true,m=false,nnn=true"}},
{rootArgs: rootArgs{boolAttributes: "l=EURT,m=false,nnn=true"}},
{rootArgs: rootArgs{timestampAttributes: "o"}},
{rootArgs: rootArgs{timestampAttributes: "o="}},
{rootArgs: rootArgs{timestampAttributes: "="}},
{rootArgs: rootArgs{timestampAttributes: "=2006-01-02T15:04:05Z"}},
{rootArgs: rootArgs{timestampAttributes: "o=XYZ"}},
{rootArgs: rootArgs{durationAttributes: "x"}},
{rootArgs: rootArgs{durationAttributes: "x="}},
{rootArgs: rootArgs{durationAttributes: "="}},
{rootArgs: rootArgs{durationAttributes: "=1.2"}},
{rootArgs: rootArgs{durationAttributes: "x=XYZ"}},
{rootArgs: rootArgs{bytesAttributes: "p,q=34:56"}},
{rootArgs: rootArgs{bytesAttributes: "p=,q=34:56"}},
{rootArgs: rootArgs{bytesAttributes: "=,q=34:56"}},
{rootArgs: rootArgs{bytesAttributes: "=1,q=34:56"}},
{rootArgs: rootArgs{bytesAttributes: "p=XY,q=34:56"}},
{rootArgs: rootArgs{bytesAttributes: "p=123,q=34:56"}},
}
for i, c := range cases {
if a, err := parseAttributes(&c.rootArgs); err == nil {
if !c.result {
t.Errorf("Expected failure for test case %v, got success", i)
}
// technically, this is enforcing the dictionary mappings, which is not guaranteed by the
// API contract, but that's OK...
if !reflect.DeepEqual(a, &c.attrs) {
t.Errorf("Mismatched results for test %v\nGot:\n%#v\nExpected\n%#v\n", i, a, c.attrs)
}
} else {
if c.result {
t.Errorf("Expected success for test case %v, got failure %v", i, err)
}
if a != nil {
t.Errorf("Expecting nil attributes, got some instead for test case %v", i)
}
}
}
}
| apache-2.0 |
fire-eggs/YAGP | SharpGEDParse/SharpGEDWriter/Tests/IndiOrder.cs | 2056 | using NUnit.Framework;
using System.Diagnostics.CodeAnalysis;
using System.Text;
// Sub-records of INDI have been fixed to an order which is similar to that of PAF, AncQuest
namespace SharpGEDWriter.Tests
{
[ExcludeFromCodeCoverage]
[TestFixture]
class IndiOrder : GedWriteTest
{
private string[] validOrder =
{
"0 @I1@ INDI",
"1 NAME Fred",
"2 GIVN Fred",
"1 SEX M",
"1 FAMS @F1@",
"1 FAMC @F2@",
"1 _UID 9876543210", // Note: not valid value
"1 NOTE @N1@",
"1 CHAN",
"2 DATE 2 DEC 2017"
};
private string MakeInput(int start=1)
{
// Take the valid order set and output in a different sequence
// Done by shifting, works only with single-line sub-records
StringBuilder inp = new StringBuilder();
inp.Append(validOrder[0]);
inp.Append("\n");
for (int i = start; i < validOrder.Length; i++)
{
inp.Append(validOrder[i]);
inp.Append("\n");
}
for (int i = 1; i < start; i++)
{
inp.Append(validOrder[i]);
inp.Append("\n");
}
return inp.ToString();
}
[Test]
public void Baseline()
{
// Using original valid order, what goes in must come out
var str = MakeInput();
var res = ParseAndWrite(str);
Assert.AreEqual(str, res);
}
[Test]
public void Variants()
{
// exercise rotated variants - works only with one line sub-records
var valid = MakeInput(); // valid order
for (int i = 2; i < 7; i++) // NOTE: makes assumptions about input
{
var str = MakeInput(i);
var res = ParseAndWrite(str);
Assert.AreEqual(valid, res, "Shift "+i);
}
}
}
}
| apache-2.0 |
ricreade/gmgamemgr | ModelTests/DataConnTest.cs | 909 | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GMGameManager;
using Model.Data;
namespace ModelTests
{
[TestClass]
public class DataConnTest
{
[TestMethod]
public void DataConnectionTest()
{
String conn = GMGameManager.Properties.Settings.Default.ConnString;
try
{
SqlDataIntegration integration = new SqlDataIntegration(conn);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
try
{
SqlDataIntegration integration = new SqlDataIntegration();
integration.SetConnectionString(conn);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
}
}
| apache-2.0 |
AndyNortrup/TweetHarvest | init.go | 299 | package tweetharvest
import (
"net/http"
"github.com/gorilla/mux"
)
func init() {
th := &MapBuilder{}
proc := &Reducer{}
consume := &FeedProducer{}
plex := mux.NewRouter()
plex.Handle("/map", th)
plex.Handle("/reduce", proc)
plex.Handle("/consume", consume)
http.Handle("/", plex)
}
| apache-2.0 |
daboyuka/PIQUE | tools/build-index.cpp | 12959 | /*
* Copyright 2015 David A. Boyuka II
*
* 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.
*/
/*
* build-meta.cpp
*
* Created on: May 20, 2014
* Author: David A. Boyuka II
*/
extern "C" {
#include <getopt.h>
#ifndef _Bool
#define _Bool bool
#endif
#include <pique/util/myopts.h>
}
#include <cstdint>
#include <cstring>
#include <cassert>
#include <typeindex>
#include <iostream>
#include <fstream>
#include <boost/none.hpp>
#include <boost/optional.hpp>
#include <boost/algorithm/string/split.hpp>
#include <pique/data/dataset.hpp>
#include <pique/io/database.hpp>
#include <pique/indexing/binned-index.hpp>
#include <pique/indexing/index-builder.hpp>
#include <pique/region/region-encoding.hpp>
#include <pique/region/ii/ii.hpp>
#include <pique/region/ii/ii-encode.hpp>
#include <pique/setops/ii/ii-setops.hpp>
#include <pique/region/cii/cii.hpp>
#include <pique/region/cii/cii-encode.hpp>
#include <pique/setops/cii/cii-setops.hpp>
#include <pique/region/cblq/cblq.hpp>
#include <pique/region/cblq/cblq-encode.hpp>
#include <pique/setops/cblq/cblq-setops.hpp>
#include <pique/region/wah/wah.hpp>
#include <pique/region/wah/wah-encode.hpp>
#include <pique/setops/wah/wah-setops.hpp>
#include <pique/io/index-io.hpp>
#include <pique/io/posix/posix-index-io.hpp>
struct cmd_args_t {
char *dataset_meta_filename_str{nullptr};
char *index_filename_str{nullptr};
char *index_rep_str{nullptr};
char *index_enc_str{nullptr};
char *binning_type_str{nullptr};
char *binning_param_str{nullptr};
bool cblq_dense_suff{false};
};
struct cmd_config_t {
std::string dataset_meta_filename;
std::string index_filename;
RegionEncoding::Type index_rep;
boost::shared_ptr< IndexEncoding > index_enc;
AbstractBinningSpecification::BinningSpecificationType binning_type;
std::string binning_param;
bool cblq_dense_suff;
};
template< typename BinningSpecificationT >
struct BinningSpecBuilder { static boost::shared_ptr< BinningSpecificationT > build(const cmd_config_t &conf); };
template< typename ValueTypeT >
struct BinningSpecBuilder< SigbitsBinningSpecification< ValueTypeT > > {
static boost::shared_ptr< SigbitsBinningSpecification< ValueTypeT > > build(const cmd_config_t &conf) {
const int sigbits = strtol(conf.binning_param.c_str(), NULL, 0);
assert(sigbits);
std::cerr << "Using SIGBITS binning with " << sigbits << " significant bits" << std::endl;
return boost::make_shared< SigbitsBinningSpecification< ValueTypeT > >(sigbits);
}
};
template< typename ValueTypeT >
struct BinningSpecBuilder< PrecisionBinningSpecification< ValueTypeT > > {
static boost::shared_ptr< PrecisionBinningSpecification< ValueTypeT > > build(const cmd_config_t &conf) {
const int digits = strtol(conf.binning_param.c_str(), NULL, 0);
assert(digits);
std::cerr << "Using PRECISION binning with " << digits << " digits" << std::endl;
return boost::make_shared< PrecisionBinningSpecification< ValueTypeT > >(digits);
}
};
template< typename ValueTypeT >
struct BinningSpecBuilder< ExplicitBinsBinningSpecification< ValueTypeT > > {
static boost::shared_ptr< ExplicitBinsBinningSpecification< ValueTypeT > > build(const cmd_config_t &conf) {
using binning_datatype_t = typename ExplicitBinsBinningSpecification< ValueTypeT >::QKeyType;
std::fstream fin(conf.binning_param);
assert(fin.good());
binning_datatype_t bin_bound;
std::vector< binning_datatype_t > bin_bounds;
while (!fin.eof()) {
assert(!fin.bad());
fin >> bin_bound;
bin_bounds.push_back(bin_bound);
}
fin.close();
std::cerr << "Using EXPLICIT binning with " << bin_bounds.size() << " bin boundaries read from file " << conf.binning_param << std::endl;
return boost::make_shared< ExplicitBinsBinningSpecification< ValueTypeT > >(bin_bounds);
}
};
template<typename datatype_t, typename BinningSpecificationT, typename boost::disable_if_c< BinningSpecificationT::is_valid_instantiation, int >::type ignore = 0 >
static boost::shared_ptr< BinnedIndex > build_index(const cmd_config_t &conf, boost::shared_ptr< Dataset > dataset) {
abort();
}
template<typename datatype_t, typename BinningSpecificationT, typename boost::enable_if_c< BinningSpecificationT::is_valid_instantiation, int >::type ignore = 0 >
static boost::shared_ptr< BinnedIndex > build_index(const cmd_config_t &conf, boost::shared_ptr< Dataset > dataset) {
boost::shared_ptr< BinningSpecificationT > binning_spec = BinningSpecBuilder< BinningSpecificationT >::build(conf);
switch (conf.index_rep) {
case RegionEncoding::Type::II:
return IndexBuilder< datatype_t, IIRegionEncoder, BinningSpecificationT >(IIRegionEncoderConfig(), binning_spec).build_index(*dataset);
case RegionEncoding::Type::CII:
return IndexBuilder< datatype_t, CIIRegionEncoder, BinningSpecificationT >(CIIRegionEncoderConfig(), binning_spec).build_index(*dataset);
case RegionEncoding::Type::WAH:
return IndexBuilder< datatype_t, WAHRegionEncoder, BinningSpecificationT >(WAHRegionEncoderConfig(), binning_spec).build_index(*dataset);
case RegionEncoding::Type::CBLQ_2D:
return IndexBuilder< datatype_t, CBLQRegionEncoder<2>, BinningSpecificationT >(CBLQRegionEncoderConfig(conf.cblq_dense_suff), binning_spec).build_index(*dataset);
case RegionEncoding::Type::CBLQ_3D:
return IndexBuilder< datatype_t, CBLQRegionEncoder<3>, BinningSpecificationT >(CBLQRegionEncoderConfig(conf.cblq_dense_suff), binning_spec).build_index(*dataset);
case RegionEncoding::Type::CBLQ_4D:
return IndexBuilder< datatype_t, CBLQRegionEncoder<4>, BinningSpecificationT >(CBLQRegionEncoderConfig(conf.cblq_dense_suff), binning_spec).build_index(*dataset);
default:
std::cerr << "Unsupported index representation " << (int)conf.index_rep << std::endl;
abort();
}
return nullptr;
}
template<typename datatype_t>
boost::shared_ptr< BinnedIndex > build_index(const cmd_config_t &conf, boost::shared_ptr< Dataset > dataset) {
using BinningSpecificationType = AbstractBinningSpecification::BinningSpecificationType;
switch (conf.binning_type) {
case BinningSpecificationType::SIGBITS:
return build_index<datatype_t, SigbitsBinningSpecification< datatype_t > >(conf, dataset);
case BinningSpecificationType::EXPLICIT_BINS:
return build_index<datatype_t, ExplicitBinsBinningSpecification< datatype_t > >(conf, dataset);
case BinningSpecificationType::PRECISION:
return build_index<datatype_t, PrecisionBinningSpecification< datatype_t > >(conf, dataset);
default:
std::cerr << "Unsupported binning method " << (int)conf.binning_type << std::endl;
abort();
}
return nullptr;
}
struct BuildIndexDatatypeHelper {
template<typename datatype_t>
boost::shared_ptr< BinnedIndex > operator()(const cmd_config_t &conf, boost::shared_ptr< Dataset > dataset) {
return build_index<datatype_t>(conf, dataset);
}
};
static boost::shared_ptr< BinnedIndex > build_index(const cmd_config_t &conf, boost::shared_ptr< Dataset > dataset) {
boost::shared_ptr< BinnedIndex > index =
Datatypes::DatatypeIDToCTypeDispatch::template dispatchMatching< boost::shared_ptr< BinnedIndex > >(
dataset->get_datatype(),
BuildIndexDatatypeHelper(),
nullptr,
conf, dataset
);
if (!index) {
std::cerr << "Unsupported dataset datatype " << (int)dataset->get_datatype() << std::endl;
abort();
}
return index;
}
static boost::shared_ptr< BinnedIndex > encode_index(const cmd_config_t &conf, boost::shared_ptr< BinnedIndex > flat_index) {
PreferenceListSetOperations setops;
setops.push_back(boost::make_shared< IISetOperations >(IISetOperationsConfig()));
setops.push_back(boost::make_shared< CIISetOperations >(CIISetOperationsConfig(true)));
setops.push_back(boost::make_shared< CBLQSetOperationsFast<2> >(CBLQSetOperationsConfig(true)));
setops.push_back(boost::make_shared< CBLQSetOperationsFast<3> >(CBLQSetOperationsConfig(true)));
setops.push_back(boost::make_shared< CBLQSetOperationsFast<4> >(CBLQSetOperationsConfig(true)));
setops.push_back(boost::make_shared< WAHSetOperations >(WAHSetOperationsConfig(true)));
return IndexEncoding::get_encoded_index(conf.index_enc, flat_index, setops);
}
static boost::shared_ptr< IndexIO > open_index_io(const cmd_config_t &conf) {
return boost::make_shared< POSIXIndexIO >();
}
static void produce_index_file(const cmd_config_t &conf) {
using EncType = IndexEncoding::Type;
std::cout << "[1] Loading dataset based on metafile \"" << conf.dataset_meta_filename << "\"" << std::endl;
DataVariable dv("thevar", conf.dataset_meta_filename, boost::none);
boost::shared_ptr< Dataset > dataset = dv.open_dataset();
assert(dataset /* Need successful dataset load */);
std::cout << "[2] Building index..." << std::endl;
boost::shared_ptr< BinnedIndex > flat_index = build_index(conf, dataset);
std::cout << " Index statistics:" << std::endl;
flat_index->dump_summary();
boost::shared_ptr< BinnedIndex > final_index;
if (conf.index_enc->get_type() == EncType::EQUALITY) {
final_index = flat_index;
} else {
std::cout << "[2.5] Encoding index..." << std::endl;
final_index = encode_index(conf, flat_index);
std::cout << " Encoded index statistics:" << std::endl;
final_index->dump_summary();
}
std::cout << "[3] Opening index file \"" << conf.index_filename << "\" for writing..." << std::endl;
boost::shared_ptr< IndexIO > indexio = open_index_io(conf);
indexio->open(conf.index_filename, IndexOpenMode::WRITE);
std::cout << "[4] Writing index to disk..." << std::endl;
boost::shared_ptr< IndexPartitionIO > partio = indexio->append_partition();
partio->write_index(*final_index);
std::cout << "[5] Finalizing index..." << std::endl;
partio->close();
indexio->close();
std::cout << "[6] Done!" << std::endl;
}
static void validate_and_fully_parse_args(cmd_config_t &conf, cmd_args_t &args) {
using EncType = IndexEncoding::Type;
using BinningType = AbstractBinningSpecification::BinningSpecificationType;
conf.dataset_meta_filename = args.dataset_meta_filename_str;
conf.index_filename = args.index_filename_str;
const boost::optional< RegionEncoding::Type > reptype = RegionEncoding::get_region_representation_type_by_name(args.index_rep_str);
assert(reptype /* Need valid index representation type */);
conf.index_rep = *reptype;
std::string enctype = args.index_enc_str;
if (enctype == "flat")
conf.index_enc = IndexEncoding::get_instance(EncType::EQUALITY);
else if (enctype == "range")
conf.index_enc = IndexEncoding::get_instance(EncType::RANGE);
else if (enctype == "interval")
conf.index_enc = IndexEncoding::get_instance(EncType::INTERVAL);
else if (enctype == "hier")
conf.index_enc = IndexEncoding::get_instance(EncType::HIERARCHICAL);
else if (enctype == "binarycomp")
conf.index_enc = IndexEncoding::get_instance(EncType::BINARY_COMPONENT);
else
abort();
std::string binningtype = args.binning_type_str;
if (binningtype == "sigbits")
conf.binning_type = BinningType::SIGBITS;
else if (binningtype == "explicit")
conf.binning_type = BinningType::EXPLICIT_BINS;
else if (binningtype == "precision")
conf.binning_type = BinningType::PRECISION;
else
abort();
conf.binning_param = std::string(args.binning_param_str);
conf.cblq_dense_suff = args.cblq_dense_suff;
}
static myoption addopt(const char *flagname, int hasarg, OPTION_VALUE_TYPE type, void *output, void *fixedval = NULL) {
myoption opt;
opt.flagname = flagname;
opt.hasarg = hasarg;
opt.type = type;
opt.output = output;
opt.fixedval = fixedval;
return opt;
}
int main(int argc, char **argv) {
cmd_args_t args;
cmd_config_t conf;
bool TRUEVAL = true; //, FALSEVAL = false;
myoption opts[] = {
addopt("metafile", required_argument, OPTION_TYPE_STRING, &args.dataset_meta_filename_str),
addopt("indexfile", required_argument, OPTION_TYPE_STRING, &args.index_filename_str),
addopt("indexrep", required_argument, OPTION_TYPE_STRING, &args.index_rep_str),
addopt("indexenc", required_argument, OPTION_TYPE_STRING, &args.index_enc_str),
addopt("binningtype", required_argument, OPTION_TYPE_STRING, &args.binning_type_str),
addopt("binningparam", required_argument, OPTION_TYPE_STRING, &args.binning_param_str),
addopt("cblq_dense_suff", optional_argument, OPTION_TYPE_BOOLEAN, &args.cblq_dense_suff, &TRUEVAL),
addopt(NULL, required_argument, OPTION_TYPE_BOOLEAN, NULL),
};
parse_args(&argc, &argv, opts);
validate_and_fully_parse_args(conf, args);
produce_index_file(conf);
}
| apache-2.0 |
CloudSlang/score | worker/worker-manager/score-worker-manager-impl/src/main/java/io/cloudslang/worker/management/services/WorkerRecoveryManagerImpl.java | 3717 | /*
* Copyright © 2014-2017 EntIT Software LLC, a Micro Focus company (L.P.)
*
* 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 io.cloudslang.worker.management.services;
import io.cloudslang.engine.node.services.WorkerNodeService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* Date: 6/11/13
*
*/
public class WorkerRecoveryManagerImpl implements WorkerRecoveryManager {
protected static final Logger logger = LogManager.getLogger(WorkerRecoveryManagerImpl.class);
private static final int EXIT_STATUS = 75;
@Autowired
private List<WorkerRecoveryListener> listeners;
@Autowired
private WorkerNodeService workerNodeService;
@Autowired
private RetryTemplate retryTemplate;
@Autowired
private SynchronizationManager syncManager;
@Autowired
protected WorkerVersionService workerVersionService;
private volatile boolean inRecovery; //must be volatile since it is read/written in several threads
private volatile String wrv; //must be volatile since it is read/written in several threads
public void doRecovery(){
try {
boolean toRestart = Boolean.getBoolean("cloudslang.worker.restart.on.recovery");
//If we are configured to restart on recovery - do shutdown
if(toRestart){
logger.warn("Worker is configured to restart on recovery and since internal recovery is needed the process is exiting...");
System.exit(EXIT_STATUS);
}
synchronized (this){
//If already in recovery - then return and do nothing
if(inRecovery){
return;
}
inRecovery = true;
}
syncManager.startRecovery();
logger.warn("Worker internal recovery started");
for (WorkerRecoveryListener listener : listeners){
try {
listener.doRecovery();
} catch (Exception ex) {
logger.error("Failed on worker internal recovery", ex);
}
}
if (logger.isDebugEnabled()) logger.debug("Listeners recovery is done");
retryTemplate.retry(RetryTemplate.INFINITELY, 30*1000L, new RetryTemplate.RetryCallback() {
@Override
public void tryOnce() {
if(logger.isDebugEnabled()) logger.debug("sending worker UP");
String newWrv = workerNodeService.up(System.getProperty("worker.uuid"), workerVersionService.getWorkerVersion(), workerVersionService.getWorkerVersionId());
setWRV(newWrv);
if(logger.isDebugEnabled()) logger.debug("the worker is UP");
}
});
inRecovery = false;
logger.warn("Worker recovery is done");
} finally {
syncManager.finishRecovery();
}
}
public boolean isInRecovery() {
return inRecovery;
}
public String getWRV() {
return wrv;
}
public void setWRV(String newWrv) {
wrv = newWrv;
}
}
| apache-2.0 |
Owldream/Ginseng | include/ginseng/3rd-party/boost/process/detail/posix/async_pipe.hpp | 11299 | // Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROCESS_DETAIL_POSIX_ASYNC_PIPE_HPP_
#define BOOST_PROCESS_DETAIL_POSIX_ASYNC_PIPE_HPP_
#include <boost/process/detail/posix/basic_pipe.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <system_error>
#include <string>
#include <utility>
namespace boost { namespace process { namespace detail { namespace posix {
class async_pipe
{
::boost::asio::posix::stream_descriptor _source;
::boost::asio::posix::stream_descriptor _sink ;
public:
typedef int native_handle_type;
typedef ::boost::asio::posix::stream_descriptor handle_type;
inline async_pipe(boost::asio::io_context & ios) : async_pipe(ios, ios) {}
inline async_pipe(boost::asio::io_context & ios_source,
boost::asio::io_context & ios_sink) : _source(ios_source), _sink(ios_sink)
{
int fds[2];
if (::pipe(fds) == -1)
boost::process::detail::throw_last_error("pipe(2) failed");
_source.assign(fds[0]);
_sink .assign(fds[1]);
};
inline async_pipe(boost::asio::io_context & ios, const std::string & name)
: async_pipe(ios, ios, name) {}
inline async_pipe(boost::asio::io_context & ios_source,
boost::asio::io_context & io_sink, const std::string & name);
inline async_pipe(const async_pipe& lhs);
async_pipe(async_pipe&& lhs) : _source(std::move(lhs._source)), _sink(std::move(lhs._sink))
{
lhs._source.assign (-1);
lhs._sink .assign (-1);
}
template<class CharT, class Traits = std::char_traits<CharT>>
explicit async_pipe(::boost::asio::io_context & ios_source,
::boost::asio::io_context & ios_sink,
const basic_pipe<CharT, Traits> & p)
: _source(ios_source, p.native_source()), _sink(ios_sink, p.native_sink())
{
}
template<class CharT, class Traits = std::char_traits<CharT>>
explicit async_pipe(boost::asio::io_context & ios, const basic_pipe<CharT, Traits> & p)
: async_pipe(ios, ios, p)
{
}
template<class CharT, class Traits = std::char_traits<CharT>>
inline async_pipe& operator=(const basic_pipe<CharT, Traits>& p);
inline async_pipe& operator=(const async_pipe& rhs);
inline async_pipe& operator=(async_pipe&& lhs);
~async_pipe()
{
if (_sink .native_handle() != -1)
::close(_sink.native_handle());
if (_source.native_handle() != -1)
::close(_source.native_handle());
}
template<class CharT, class Traits = std::char_traits<CharT>>
inline explicit operator basic_pipe<CharT, Traits>() const;
void cancel()
{
if (_sink.is_open())
_sink.cancel();
if (_source.is_open())
_source.cancel();
}
void close()
{
if (_sink.is_open())
_sink.close();
if (_source.is_open())
_source.close();
}
void close(boost::system::error_code & ec)
{
if (_sink.is_open())
_sink.close(ec);
if (_source.is_open())
_source.close(ec);
}
bool is_open() const
{
return _sink.is_open() || _source.is_open();
}
void async_close()
{
if (_sink.is_open())
_sink.get_io_context(). post([this]{_sink.close();});
if (_source.is_open())
_source.get_io_context().post([this]{_source.close();});
}
template<typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence & buffers)
{
return _source.read_some(buffers);
}
template<typename MutableBufferSequence>
std::size_t write_some(const MutableBufferSequence & buffers)
{
return _sink.write_some(buffers);
}
native_handle_type native_source() const {return const_cast<boost::asio::posix::stream_descriptor&>(_source).native_handle();}
native_handle_type native_sink () const {return const_cast<boost::asio::posix::stream_descriptor&>(_sink ).native_handle();}
template<typename MutableBufferSequence,
typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
ReadHandler, void(boost::system::error_code, std::size_t))
async_read_some(
const MutableBufferSequence & buffers,
ReadHandler &&handler)
{
_source.async_read_some(buffers, std::forward<ReadHandler>(handler));
}
template<typename ConstBufferSequence,
typename WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
WriteHandler, void(boost::system::error_code, std::size_t))
async_write_some(
const ConstBufferSequence & buffers,
WriteHandler&& handler)
{
_sink.async_write_some(buffers, std::forward<WriteHandler>(handler));
}
const handle_type & sink () const & {return _sink;}
const handle_type & source() const & {return _source;}
handle_type && sink() && { return std::move(_sink); }
handle_type && source()&& { return std::move(_source); }
handle_type source(::boost::asio::io_context& ios) &&
{
::boost::asio::posix::stream_descriptor stolen(ios, _source.release());
return stolen;
}
handle_type sink (::boost::asio::io_context& ios) &&
{
::boost::asio::posix::stream_descriptor stolen(ios, _sink.release());
return stolen;
}
handle_type source(::boost::asio::io_context& ios) const &
{
auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native_handle();
return ::boost::asio::posix::stream_descriptor(ios, ::dup(source_in));
}
handle_type sink (::boost::asio::io_context& ios) const &
{
auto sink_in = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native_handle();
return ::boost::asio::posix::stream_descriptor(ios, ::dup(sink_in));
}
};
async_pipe::async_pipe(boost::asio::io_context & ios_source,
boost::asio::io_context & ios_sink,
const std::string & name) : _source(ios_source), _sink(ios_sink)
{
auto fifo = mkfifo(name.c_str(), 0666 );
if (fifo != 0)
boost::process::detail::throw_last_error("mkfifo() failed");
int read_fd = open(name.c_str(), O_RDWR);
if (read_fd == -1)
boost::process::detail::throw_last_error();
int write_fd = dup(read_fd);
if (write_fd == -1)
boost::process::detail::throw_last_error();
_source.assign(read_fd);
_sink .assign(write_fd);
}
async_pipe::async_pipe(const async_pipe & p) :
_source(const_cast<async_pipe&>(p)._source.get_io_context()),
_sink( const_cast<async_pipe&>(p)._sink.get_io_context())
{
//cannot get the handle from a const object.
auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native_handle();
auto sink_in = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native_handle();
if (source_in == -1)
_source.assign(-1);
else
{
_source.assign(::dup(source_in));
if (_source.native_handle()== -1)
::boost::process::detail::throw_last_error("dup()");
}
if (sink_in == -1)
_sink.assign(-1);
else
{
_sink.assign(::dup(sink_in));
if (_sink.native_handle() == -1)
::boost::process::detail::throw_last_error("dup()");
}
}
async_pipe& async_pipe::operator=(const async_pipe & p)
{
int source;
int sink;
//cannot get the handle from a const object.
auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native_handle();
auto sink_in = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native_handle();
if (source_in == -1)
source = -1;
else
{
source = ::dup(source_in);
if (source == -1)
::boost::process::detail::throw_last_error("dup()");
}
if (sink_in == -1)
sink = -1;
else
{
sink = ::dup(sink_in);
if (sink == -1)
::boost::process::detail::throw_last_error("dup()");
}
_source.assign(source);
_sink. assign(sink);
return *this;
}
async_pipe& async_pipe::operator=(async_pipe && lhs)
{
std::swap(_source, lhs._source);
std::swap(_sink, lhs._sink);
return *this;
}
template<class CharT, class Traits>
async_pipe::operator basic_pipe<CharT, Traits>() const
{
int source;
int sink;
//cannot get the handle from a const object.
auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native_handle();
auto sink_in = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native_handle();
if (source_in == -1)
source = -1;
else
{
source = ::dup(source_in);
if (source == -1)
::boost::process::detail::throw_last_error("dup()");
}
if (sink_in == -1)
sink = -1;
else
{
sink = ::dup(sink_in);
if (sink == -1)
::boost::process::detail::throw_last_error("dup()");
}
return basic_pipe<CharT, Traits>{source, sink};
}
inline bool operator==(const async_pipe & lhs, const async_pipe & rhs)
{
return compare_handles(lhs.native_source(), rhs.native_source()) &&
compare_handles(lhs.native_sink(), rhs.native_sink());
}
inline bool operator!=(const async_pipe & lhs, const async_pipe & rhs)
{
return !compare_handles(lhs.native_source(), rhs.native_source()) ||
!compare_handles(lhs.native_sink(), rhs.native_sink());
}
template<class Char, class Traits>
inline bool operator==(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
return compare_handles(lhs.native_source(), rhs.native_source()) &&
compare_handles(lhs.native_sink(), rhs.native_sink());
}
template<class Char, class Traits>
inline bool operator!=(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
return !compare_handles(lhs.native_source(), rhs.native_source()) ||
!compare_handles(lhs.native_sink(), rhs.native_sink());
}
template<class Char, class Traits>
inline bool operator==(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
return compare_handles(lhs.native_source(), rhs.native_source()) &&
compare_handles(lhs.native_sink(), rhs.native_sink());
}
template<class Char, class Traits>
inline bool operator!=(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
return !compare_handles(lhs.native_source(), rhs.native_source()) ||
!compare_handles(lhs.native_sink(), rhs.native_sink());
}
}}}}
#endif /* INCLUDE_BOOST_PIPE_DETAIL_WINDOWS_ASYNC_PIPE_HPP_ */
| apache-2.0 |
spektrumprojekt/spektrum | intelligence/src/main/java/de/spektrumprojekt/i/learner/Learner.java | 6992 | /*
* 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 de.spektrumprojekt.i.learner;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.spektrumprojekt.commons.chain.CommandChain;
import de.spektrumprojekt.commons.chain.ProxyCommand;
import de.spektrumprojekt.communication.CommunicationMessage;
import de.spektrumprojekt.communication.MessageHandler;
import de.spektrumprojekt.configuration.ConfigurationDescriptable;
import de.spektrumprojekt.datamodel.message.Message;
import de.spektrumprojekt.i.informationextraction.InformationExtractionCommand;
import de.spektrumprojekt.i.learner.chain.LoadRelatedObservationsCommand;
import de.spektrumprojekt.i.learner.chain.StoreObservationCommand;
import de.spektrumprojekt.i.learner.chain.UserModelLearnerCommand;
import de.spektrumprojekt.i.learner.time.TimeBinnedUserModelEntryIntegrationStrategy;
import de.spektrumprojekt.i.ranker.MessageFeatureContext;
import de.spektrumprojekt.i.ranker.Ranker;
import de.spektrumprojekt.i.ranker.RankerConfiguration;
import de.spektrumprojekt.i.ranker.RankerConfigurationFlag;
import de.spektrumprojekt.i.ranker.UserModelConfiguration;
import de.spektrumprojekt.i.timebased.TermCounterCommand;
import de.spektrumprojekt.persistence.Persistence;
/**
*
* @author Communote GmbH - <a href="http://www.communote.de/">http://www.communote.com/</a>
*
*/
public class Learner implements MessageHandler<LearningMessage>, ConfigurationDescriptable {
private final CommandChain<LearnerMessageContext> learnerChain;
private final Persistence persistence;
private final static Logger LOGGER = LoggerFactory.getLogger(Ranker.class);
/**
* TODO use a LearnerConfiguration
*
* @param persistence
* the persistence
* @param userModelEntryIntegrationStrategy
* the strategy to integrate the user model
*/
public Learner(Persistence persistence, RankerConfiguration configuration,
InformationExtractionCommand<MessageFeatureContext> ieChain) {
if (persistence == null) {
throw new IllegalArgumentException("persistence cannot be null!");
}
if (configuration == null) {
throw new IllegalArgumentException("configuration cannot be null!");
}
if (configuration.getUserModelTypes() == null
|| configuration.getUserModelTypes().size() == 0) {
throw new IllegalArgumentException(
"configuration.getUserModelTypes() cannot be null or empty !");
}
this.persistence = persistence;
this.learnerChain = new CommandChain<LearnerMessageContext>();
if (!configuration.hasFlag(RankerConfigurationFlag.NO_INFORMATION_EXTRACTION)) {
this.learnerChain
.addCommand(new ProxyCommand<MessageFeatureContext, LearnerMessageContext>(
ieChain));
}
this.learnerChain.addCommand(new LoadRelatedObservationsCommand(this.persistence));
for (String userModelType : configuration.getUserModelTypes().keySet()) {
UserModelEntryIntegrationStrategy userModelEntryIntegrationStrategy;
UserModelConfiguration userModelConfiguration = configuration.getUserModelTypes().get(
userModelType);
switch (userModelConfiguration.getUserModelEntryIntegrationStrategy()) {
case PLAIN:
userModelEntryIntegrationStrategy = new UserModelEntryIntegrationPlainStrategy();
break;
default:
userModelEntryIntegrationStrategy = new TimeBinnedUserModelEntryIntegrationStrategy(
userModelConfiguration.getStartTime(), userModelConfiguration.getBinSize(),
userModelConfiguration.getPrecision(),
userModelConfiguration.isCalculateLater());
}
this.learnerChain.addCommand(new UserModelLearnerCommand(this.persistence,
userModelType, userModelEntryIntegrationStrategy));
}
this.learnerChain.addCommand(new StoreObservationCommand(this.persistence));
if (configuration.getShortTermMemoryConfiguration() != null
&& configuration.getShortTermMemoryConfiguration()
.getEnergyCalculationConfiguration() != null) {
this.learnerChain.addCommand(new TermCounterCommand(configuration, this.persistence));
}
}
/**
* {@inheritDoc}
*/
@Override
public void deliverMessage(LearningMessage learningMessage) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Message message = this.persistence.getMessageByGlobalId(learningMessage.getObservation()
.getMessageGlobalId());
if (message == null) {
throw new IllegalStateException("Message for globalId="
+ learningMessage.getObservation().getMessageGlobalId()
+ " not found in persistence.");
}
LearnerMessageContext context = new LearnerMessageContext(persistence,
learningMessage.getObservation(), message, learningMessage.getMessageRelation());
this.learnerChain.process(context);
stopWatch.stop();
LOGGER.trace("Learner processed message {} in {} ms", context.getMessage().getGlobalId(),
stopWatch.getTime());
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigurationDescription() {
return this.getClass().getSimpleName() + " learnerChain: "
+ this.learnerChain.getConfigurationDescription();
}
/**
* {@inheritDoc}
*/
@Override
public Class<LearningMessage> getMessageClass() {
return LearningMessage.class;
}
/**
* {@inheritDoc}
*/
@Override
public boolean supports(CommunicationMessage message) {
return message instanceof LearningMessage;
}
}
| apache-2.0 |
3emad/koding-hackathon | client/lib/tos_samples.js | 123 | var Tos = require('tos');
var listTos = [
new Tos('Facebook'),
new Tos('Adparlor')
];
module.exports = listTos; | apache-2.0 |