repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
rombie/contrail-test
scripts/webui/__init__.py
<filename>scripts/webui/__init__.py "Contrail Webui Selenium Tests"
leozz37/makani
avionics/firmware/identity/carrier_hardware.c
/* * Copyright 2020 Makani Technologies 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. */ #include "avionics/firmware/identity/carrier_hardware.h" #include <stdint.h> #include "avionics/firmware/cpu/adc.h" #include "avionics/firmware/identity/identity_types.h" #include "common/macros.h" #define CARRIER_ADC_MODULE 1 #define CARRIER_ADC_CHANNEL_0 4 #define CARRIER_ADC_CHANNEL_1 5 #define CARRIER_ADC_CHANNEL_2 6 #define CARRIER_ADC_CHANNEL_3 7 CarrierHardwareType g_carrier_hardware_type = kCarrierHardwareTypeUnknown; static CarrierHardwareType ReadCarrierHardwareType(void) { int16_t adc_result[ADC_CHANNELS]; AdcInit(CARRIER_ADC_MODULE); AdcTriggerGroup1(CARRIER_ADC_MODULE, 1 << CARRIER_ADC_CHANNEL_0 | 1 << CARRIER_ADC_CHANNEL_1 | 1 << CARRIER_ADC_CHANNEL_2 | 1 << CARRIER_ADC_CHANNEL_3); while (!AdcReadGroup1(CARRIER_ADC_MODULE, ARRAYSIZE(adc_result), adc_result)) {} CarrierHardwareType type = (adc_result[CARRIER_ADC_CHANNEL_0] > ADC_LOGIC_LOW ? 1 << 0 : 0) | (adc_result[CARRIER_ADC_CHANNEL_1] > ADC_LOGIC_LOW ? 1 << 1 : 0) | (adc_result[CARRIER_ADC_CHANNEL_2] > ADC_LOGIC_LOW ? 1 << 2 : 0) | (adc_result[CARRIER_ADC_CHANNEL_3] > ADC_LOGIC_LOW ? 1 << 3 : 0); return type; } CarrierHardwareType GetCarrierHardwareType(void) { if (g_carrier_hardware_type == kCarrierHardwareTypeUnknown) { g_carrier_hardware_type = ReadCarrierHardwareType(); } return g_carrier_hardware_type; }
MajidJ/DonationApp
client/src/components/Settings/Settings.js
<reponame>MajidJ/DonationApp<gh_stars>0 import React, { Component } from 'react'; import API from '../../utils/API'; import Input from '../Input'; import { Redirect } from 'react-router-dom'; import {Elements, StripeProvider} from 'react-stripe-elements'; import StripeCheckout from 'react-stripe-checkout'; import ButtonPrimary from '../Buttons/ButtonPrimary' class Settings extends Component { state = { firstName: '', lastName: '', email: '', password: '', confirmPassword: '', message: false, messageContent: '', userId: '' }; componentDidMount = () => { this.setState({ userId: this.props.userInfo.userId, firstName: this.props.userInfo.firstName, lastName: this.props.userInfo.lastName, email: this.props.userInfo.email }); } handleFirstNameInput = e => { this.setState({firstName: e.target.value}); } handleLastNameInput = e => { this.setState({lastName: e.target.value}); } handleEmailInput = e => { this.setState({email: e.target.value}); } handlePasswordInput = e => { this.setState({password: e.target.value}); } handlePasswordConfirmInput = e => { this.setState({confirmPassword: e.target.value}); } updateUserInfo = event => { event.preventDefault(); this.setState({ message: false, messageContent: '' }); if (!this.state.firstName) { this.setState({ message: true, messageContent: 'Please enter your first name.' }); } else if (!this.state.lastName) { this.setState({ message: true, messageContent: 'Please enter your last name.' }); } else if (!this.state.email) { this.setState({ message: true, messageContent: 'Please enter your email.' }); } else { API.updateUserInfo(this.state.userId, this.state.firstName, this.state.lastName, this.state.email).then(res => { if (res.status === 200) { this.setState({ message: true, messageContent: 'User information updated.' }); this.props.updateUser({ firstName: res.data.firstName, lastName: res.data.lastName, email: res.data.email }); } else { this.setState({ message: true, messageContent: 'something went wrong' }); } }).catch(err => { this.setState({ message: true, messageContent: err }); console.log('Something went wrong: '); console.log(err); }); } } updateUserPassword = event => { event.preventDefault(); this.setState({ message: false, messageContent: '' }); if (!this.state.password) { this.setState({ message: true, messageContent: 'Please enter a password.' }); } else if (this.state.password.indexOf('$') !== -1) { this.setState({ message: true, messageContent: 'Passwords cannot contain a $ symbol.' }); } else if (this.state.password !== this.state.confirmPassword) { this.setState({ message: true, messageContent: 'Please re-enter a matching password.' }); } else { API.updateUserPassword(this.state.userId, this.state.password).then(res => { if (res.status === 200) { this.setState({ message: true, messageContent: 'Password updated.' }); } else { this.setState({ message: true, messageContent: 'Something went wrong.' }); } }).catch(err => { this.setState({ message: true, messageContent: 'Something went wrong.' }); console.log('Something went wrong: '); console.log(err); }); } } onToken = token => { API.updateUserPaymentInfo(this.state.userId, this.state.email, token.id).then(res => { if (res.status === 200) { this.setState({ message: true, messageContent: 'Payment information updated.' }); } else { this.setState({ message: true, messageContent: 'Something went wrong.' }); } }).catch(err => { this.setState({ message: true, messageContent: 'Something went wrong.' }); console.log('Something went wrong: '); console.log(err); }); } deletePaymentInfo = () => { API.deleteUserPaymentInfo(this.state.userId).then(res => { if (res.status === 200) { this.setState({ message: true, messageContent: 'Payment information deleted.' }); this.props.updateUser({ hasCustomerAccount: false, hasSubscription: false }); } else { this.setState({ message: true, messageContent: 'Something went wrong.' }); } }).catch(err => { this.setState({ message: true, messageContent: 'Something went wrong.' }); console.log('Something went wrong: '); console.log(err); }); } render() { if (!this.props.userInfo.loggedIn) { return <Redirect to={{ pathname: '/' }} /> } else { return ( <div> <h4>User Information:</h4> <form> <Input title="First Name" name="First Name" type="text" value={this.state.firstName} handleInput={this.handleFirstNameInput} /> <Input title="Last Name" name="Last Name" type="text" value={this.state.lastName} handleInput={this.handleLastNameInput} /> <Input title="Email" name="Email" type="text" value={this.state.email} handleInput={this.handleEmailInput} /> <ButtonPrimary handleClick={this.updateUserInfo}>Update</ButtonPrimary> </form> <br/><br/> <h4>Update Password:</h4> <form> <Input title="New Password" name="New Password" type="password" value={this.state.password} handleInput={this.handlePasswordInput} /> <Input title="Confirm Password" name="Confirm Password" type="password" value={this.state.confirmPassword} handleInput={this.handlePasswordConfirmInput} /> <ButtonPrimary handleClick={this.updateUserPassword}>Update</ButtonPrimary> </form> <br/><br/> <h4>Update Payment Information:</h4> {/*replace apiKey with your public key*/} <StripeProvider apiKey="<KEY>"> <Elements> <StripeCheckout email={this.state.email} label ="Update Payment Information" token={this.onToken} //replace stripeKey with your public key stripeKey={'<KEY>'} allowRememberMe = {false} > <ButtonPrimary>Update Info</ButtonPrimary> </StripeCheckout> </Elements> </StripeProvider> <br/><br/> <ButtonPrimary handleClick={this.deletePaymentInfo}> Delete My Payment Information </ButtonPrimary> {this.state.message ? ( <p>{this.state.messageContent}</p> ) : ( <div></div> )} </div> ) } } } export default Settings;
noelhunt/PadsPi
pads/host/sf.c
#include <pads.h> #include <stdarg.h> #define SF_HASH 823 struct SF_CELL { SF_CELL *link; char buf[1]; }; static int Calls, Strings, Worst, Bytes; char *sf(const char *fmt, ...){ if( !fmt ){ static char report[128]; sprintf( report, "strings=%d calls=%d worst=%d bytes=%d", Strings, Calls, Worst, Bytes ); return report; } va_list ap; va_start(ap, fmt); char *r = vf( fmt, ap ); va_end(ap); return r; } char *vf(const char *fmt, va_list va){ char x[1024], *p; unsigned long len, h, i; struct SF_CELL *s; static SF_CELL *Table[SF_HASH]; char *StrDup(const char*); ++Calls; vsprintf( x, fmt, va ); h = 0; for( len = 0, p = x; *p; ) h += (*p++) << (++len%4); h %= SF_HASH; for( s=Table[h],i=1; s; s=s->link,++i ) if(!strcmp(x,s->buf)) return s->buf; ++Strings; if( i>Worst ) Worst = (int)i; len = (len+4+sizeof(SF_CELL*)) / 4 * 4; /* vax */ s = (SF_CELL*) new char [len]; if( !s ) return StrDup("sf(): out of memory"); Bytes += (int)len; s->link = Table[h]; Table[h] = s; strcpy( s->buf, x ); return s->buf; }
achilex/MgDev
Oem/dbxml/dbxml/test/cpp/xmlUnit/XmlUnitRunner.cpp
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // #include "XmlUnit.hpp" using namespace DbXml; using namespace std; // // Add test cases and suites here. Comment heavily to describe // what tests are intended to achieve. // void addTestCases(XmlUnitSuite &suite) { } // // main program to drive suite // int main(int argc, char **argv) { try { // put it in a suite XmlUnitSuite suite("XmlUnitRunner"); addTestCases(suite); suite.run(); suite.report(); } catch (XmlUnitException &xue) { std::cerr << "exception: " << xue.getMessage() << std::endl; } }
bradchesney79/illacceptanything
linux/drivers/staging/vt6656/card.h
/* * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * File: card.h * * Purpose: Provide functions to setup NIC operation mode * * Author: <NAME> * * Date: May 21, 1996 * */ #ifndef __CARD_H__ #define __CARD_H__ #include "device.h" /* init card type */ #define CB_MAX_CHANNEL_24G 14 #define CB_MAX_CHANNEL_5G 42 /* add channel9(5045MHz), 41==>42 */ #define CB_MAX_CHANNEL (CB_MAX_CHANNEL_24G + CB_MAX_CHANNEL_5G) struct vnt_private; void vnt_set_channel(struct vnt_private *, u32); void vnt_set_rspinf(struct vnt_private *, u8); void vnt_update_ifs(struct vnt_private *); void vnt_update_top_rates(struct vnt_private *); int vnt_ofdm_min_rate(struct vnt_private *); void vnt_adjust_tsf(struct vnt_private *, u8, u64, u64); bool vnt_get_current_tsf(struct vnt_private *, u64 *); bool vnt_clear_current_tsf(struct vnt_private *); void vnt_reset_next_tbtt(struct vnt_private *, u16); void vnt_update_next_tbtt(struct vnt_private *, u64, u16); u64 vnt_get_next_tbtt(u64, u16); u64 vnt_get_tsf_offset(u8 byRxRate, u64 qwTSF1, u64 qwTSF2); int vnt_radio_power_off(struct vnt_private *); int vnt_radio_power_on(struct vnt_private *); u8 vnt_get_pkt_type(struct vnt_private *); void vnt_set_bss_mode(struct vnt_private *); #endif /* __CARD_H__ */
woshiwpa/MFPAndroLib
MFPAnLib/src/main/coresrc/com/cyzapps/Jsma/SMErrProcessor.java
// MFP project, SMErrProcessor.java : Designed and developed by <NAME> in 2021 package com.cyzapps.Jsma; import java.io.Serializable; public class SMErrProcessor { /* Definition of error types. Note that the errors here are only for 1. AbstractExpr construction 2. AbstractExpr simplification & merging 3. pattern recognition 4. indefinite integration/derivative If it is a calculation error triggered by dataclass, it should be a JCALC error. */ public static enum ERRORTYPES { /* No error */ NO_ERROR_STATE, /* Invalid AbstractExpr */ ERROR_INVALID_ABSTRACTEXPR, /* Invalid Result */ ERROR_INVALID_RESULT, /* Unknown variable undeclared */ ERROR_UNKNOWN_VARIABLE_UNDECLARED, /* Unknown variable redeclared */ ERROR_UNKNOWN_VARIABLE_REDECLARED, /* Variable value not known */ ERROR_VARIABLE_VALUE_NOT_KNOWN, /* Function in Abstract expression should return a value */ ERROR_FUNCTION_IN_AEXPR_SHOULD_RETURN_A_VALUE, /* Not a constant abstract expression type */ ERROR_NOT_CONSTANT_ABSTRACTEXPR, /* Incorrect abstract expression type */ ERROR_INCORRECT_ABSTRACTEXPR_TYPE, /* Cannot merge two abstract expressions */ ERROR_CANNOT_MERGE_TWO_ABSTRACTEXPRS, /* Operator should have at least two operands */ ERROR_OPERATOR_SHOULD_HAVE_AT_LEAST_TWO_OPERANDS, /* Can only assign to a variable */ ERROR_CAN_ONLY_ASSIGN_TO_A_VARIABLE, /* Pseudo-constant cannot be evaluated */ ERROR_PSEUDO_CONST_CANNOT_BE_EVALUATED, /* Invalid operator */ ERROR_INVALID_OPERATOR, /* Cannot calculate dimension */ ERROR_CANNOT_CALCULATE_DIMENSION, /* Number of variables not match */ ERROR_NUMBER_OF_VARIABLES_NOT_MATCH, /* Invalid abstract expr pattern */ ERROR_INVALID_ABSTRACTEXPRPATTERN, /* Invalid variable or pseudoconst dimension */ ERROR_INVALID_VARIABLE_OR_PSEUDOCONST_DIMENSION, /* Invalid pattern variable order */ ERROR_INVALID_PATTERN_VARIABLE_ORDER, /* Invalid pattern unknown unit */ ERROR_INVALID_PATTERN_UNKNOWN_UNIT, /* Redefined variable or pseudoconst */ ERROR_REDEFINED_VARIABLE_OR_PSEUDOCONST, /* Variable cannot be solved */ ERROR_VARIABLE_CANNOT_BE_SOLVED, /* Unsupported simple pattern */ ERROR_UNSUPPORTED_SIMPLE_PATTERN, /* Invalid simple pattern */ ERROR_INVALID_SIMPLE_PATTERN, /* Unrecognized pattern */ ERROR_UNRECOGNIZED_PATTERN, /* Cannot fit restrict */ ERROR_CANNOT_FIT_RESTRICT, /* Invalid integration */ ERROR_INVALID_INTEGRATION, /* Invalid integration type */ ERROR_INVALID_INTEGRATION_TYPE, /* Unsupported integration type */ ERROR_UNSUPPORTED_INTEGRATION_TYPE, /* Invalid integration range */ ERROR_INVALID_INTEGRATION_RANGE, /* Cannot solve calculation */ ERROR_CANNOT_SOLVE_CALCULATION, } /* Definition of the error structure. */ public static class StructError implements Serializable { private static final long serialVersionUID = 1L; public ERRORTYPES m_enumErrorType; public String m_strUserDefMsg; public String getErrorType() { String strErrorType = "NO_EXCEPTION"; switch(m_enumErrorType) /* Find the corresponding error type. */ { case ERROR_INVALID_ABSTRACTEXPR: strErrorType = "INVALID_ABSTRACT_EXPR_TYPE_EXCEPTION"; break; case ERROR_INVALID_RESULT: strErrorType = "INVALID_RESULT"; break; case ERROR_UNKNOWN_VARIABLE_UNDECLARED: strErrorType = "UNKNOWN_VARIABLE_UNDECLARED"; break; case ERROR_UNKNOWN_VARIABLE_REDECLARED: strErrorType = "UNKNOWN_VARIABLE_REDECLARED"; break; case ERROR_VARIABLE_VALUE_NOT_KNOWN: strErrorType = "VARIABLE_VALUE_NOT_KNOWN"; break; case ERROR_FUNCTION_IN_AEXPR_SHOULD_RETURN_A_VALUE: strErrorType = "FUNCTION_IN_AEXPR_SHOULD_RETURN_A_VALUE"; break; case ERROR_NOT_CONSTANT_ABSTRACTEXPR: strErrorType = "NOT_CONSTANT_ABSTRACTEXPR"; break; case ERROR_INCORRECT_ABSTRACTEXPR_TYPE: strErrorType = "INCORRECT_ABSTRACTEXPR_TYPE"; break; case ERROR_CANNOT_MERGE_TWO_ABSTRACTEXPRS: strErrorType = "CANNOT_MERGE_TWO_ABSTRACTEXPRS"; break; case ERROR_OPERATOR_SHOULD_HAVE_AT_LEAST_TWO_OPERANDS: strErrorType = "OPERATOR_SHOULD_HAVE_AT_LEAST_TWO_OPERANDS"; break; case ERROR_CAN_ONLY_ASSIGN_TO_A_VARIABLE: strErrorType = "CAN_ONLY_ASSIGN_TO_A_VARIABLE"; break; case ERROR_PSEUDO_CONST_CANNOT_BE_EVALUATED: strErrorType = "PSEUDO_CONST_CANNOT_BE_EVALUATED"; break; case ERROR_INVALID_OPERATOR: strErrorType = "INVALID_OPERATOR"; break; case ERROR_CANNOT_CALCULATE_DIMENSION: strErrorType = "CANNOT_CALCULATE_DIMENSION"; break; case ERROR_NUMBER_OF_VARIABLES_NOT_MATCH: strErrorType = "NUMBER_OF_VARIABLES_NOT_MATCH"; break; case ERROR_INVALID_ABSTRACTEXPRPATTERN: strErrorType = "INVALID_ABSTRACTEXPRPATTERN"; break; case ERROR_INVALID_VARIABLE_OR_PSEUDOCONST_DIMENSION: strErrorType = "INVALID_VARIABLE_OR_PSEUDOCONST_DIMENSION"; break; case ERROR_INVALID_PATTERN_VARIABLE_ORDER: strErrorType = "INVALID_PATTERN_VARIABLE_ORDER"; break; case ERROR_INVALID_PATTERN_UNKNOWN_UNIT: strErrorType = "INVALID_PATTERN_UNKNOWN_UNIT"; break; case ERROR_REDEFINED_VARIABLE_OR_PSEUDOCONST: strErrorType = "REDEFINED_VARIABLE_OR_PSEUDOCONST"; break; case ERROR_VARIABLE_CANNOT_BE_SOLVED: strErrorType = "VARIABLE_CANNOT_BE_SOLVED"; break; case ERROR_UNSUPPORTED_SIMPLE_PATTERN: strErrorType = "UNSUPPORTED_SIMPLE_PATTERN"; break; case ERROR_INVALID_SIMPLE_PATTERN: strErrorType = "INVALID_SIMPLE_PATTERN"; break; case ERROR_UNRECOGNIZED_PATTERN: strErrorType = "UNRECOGNIZED_PATTERN"; break; case ERROR_CANNOT_FIT_RESTRICT: strErrorType = "CANNOT_FIT_RESTRICT"; break; case ERROR_INVALID_INTEGRATION: strErrorType = "INVALID_INTEGRATION"; break; case ERROR_INVALID_INTEGRATION_TYPE: strErrorType = "INVALID_INTEGRATION_TYPE"; break; case ERROR_UNSUPPORTED_INTEGRATION_TYPE: strErrorType = "UNSUPPORTED_INTEGRATION_TYPE"; break; case ERROR_INVALID_INTEGRATION_RANGE: strErrorType = "INVALID_INTEGRATION_RANGE"; break; case ERROR_CANNOT_SOLVE_CALCULATION: strErrorType = "CANNOT_SOLVE_CALCULATION"; break; default: ; /*NO_ERROR_STATE returns "NO_EXCEPTION"*/ } return strErrorType; } public String getErrorInfo() { /* Handle error. */ String strErrorMsg = ""; /* The string to save error information. */ switch(m_enumErrorType) /* Find the corresponding error type. */ { case ERROR_INVALID_ABSTRACTEXPR: strErrorMsg = "Invalid abstract expression type!"; break; case ERROR_INVALID_RESULT: strErrorMsg = "Invalid result!"; break; case ERROR_UNKNOWN_VARIABLE_UNDECLARED: strErrorMsg = "Unknown_variable undeclared!"; break; case ERROR_UNKNOWN_VARIABLE_REDECLARED: strErrorMsg = "Unknown_variable redeclared!"; break; case ERROR_VARIABLE_VALUE_NOT_KNOWN: strErrorMsg = "Variable value not known!"; break; case ERROR_FUNCTION_IN_AEXPR_SHOULD_RETURN_A_VALUE: strErrorMsg = "Function in abstract expression should return a value!"; break; case ERROR_NOT_CONSTANT_ABSTRACTEXPR: strErrorMsg = "Not a constant abstract expression type!"; break; case ERROR_INCORRECT_ABSTRACTEXPR_TYPE: strErrorMsg = "Incorrect abstract expression type!"; break; case ERROR_CANNOT_MERGE_TWO_ABSTRACTEXPRS: strErrorMsg = "Cannot merge two abstract expressions!"; break; case ERROR_OPERATOR_SHOULD_HAVE_AT_LEAST_TWO_OPERANDS: strErrorMsg = "Operator should have at least two operands!"; break; case ERROR_CAN_ONLY_ASSIGN_TO_A_VARIABLE: strErrorMsg = "Can only assign to a variable!"; break; case ERROR_PSEUDO_CONST_CANNOT_BE_EVALUATED: strErrorMsg = "Pseudo-constant cannot be evaluated!"; break; case ERROR_INVALID_OPERATOR: strErrorMsg = "Invalid operator!"; break; case ERROR_CANNOT_CALCULATE_DIMENSION: strErrorMsg = "Cannot calculate dimension!"; break; case ERROR_NUMBER_OF_VARIABLES_NOT_MATCH: strErrorMsg = "Number of variables not match!"; break; case ERROR_INVALID_ABSTRACTEXPRPATTERN: strErrorMsg = "Invalid abstract expression type!"; break; case ERROR_INVALID_VARIABLE_OR_PSEUDOCONST_DIMENSION: strErrorMsg = "Invalid variable or pseudoconst dimension!"; break; case ERROR_INVALID_PATTERN_VARIABLE_ORDER: strErrorMsg = "Invalid pattern variable order!"; break; case ERROR_INVALID_PATTERN_UNKNOWN_UNIT: strErrorMsg = "Invalid pattern unknown unit!"; break; case ERROR_REDEFINED_VARIABLE_OR_PSEUDOCONST: strErrorMsg = "Redefined variable or pseudo constant!"; break; case ERROR_VARIABLE_CANNOT_BE_SOLVED: strErrorMsg = "Variable cannot be solved!"; break; case ERROR_UNSUPPORTED_SIMPLE_PATTERN: strErrorMsg = "Unsupported simple pattern!"; break; case ERROR_INVALID_SIMPLE_PATTERN: strErrorMsg = "Invalid simple pattern!"; break; case ERROR_UNRECOGNIZED_PATTERN: strErrorMsg = "Unrecognized pattern!"; break; case ERROR_CANNOT_FIT_RESTRICT: strErrorMsg = "Cannot fit restrict!"; break; case ERROR_INVALID_INTEGRATION: strErrorMsg = "Invalid integration!"; break; case ERROR_INVALID_INTEGRATION_TYPE: strErrorMsg = "Invalid integration type!"; break; case ERROR_UNSUPPORTED_INTEGRATION_TYPE: strErrorMsg = "Unsupported integration type!"; break; case ERROR_INVALID_INTEGRATION_RANGE: strErrorMsg = "Invalid integration range!"; break; case ERROR_CANNOT_SOLVE_CALCULATION: strErrorMsg = "Cannot solve calculation!"; break; default: ; /*NO_ERROR_STATE returns null*/ }; return strErrorMsg; } } public static class JSmartMathErrException extends Exception { private static final long serialVersionUID = 1L; public StructError m_se = new StructError(); public String m_strBlockName = null; public Exception m_exceptionLowerLevel = null; public JSmartMathErrException() { m_se.m_enumErrorType = ERRORTYPES.NO_ERROR_STATE; m_se.m_strUserDefMsg = ""; m_strBlockName = ""; m_exceptionLowerLevel = null; } public JSmartMathErrException(ERRORTYPES e) { m_se.m_enumErrorType = e; m_se.m_strUserDefMsg = ""; m_strBlockName = null; m_exceptionLowerLevel = null; } public JSmartMathErrException(ERRORTYPES e, String strBlockName, Exception exceptionLowerLevel) { m_se.m_enumErrorType = e; m_se.m_strUserDefMsg =""; m_strBlockName = strBlockName; m_exceptionLowerLevel = exceptionLowerLevel; } public JSmartMathErrException(ERRORTYPES e, String strUserDefMsg) { m_se.m_enumErrorType = e; m_se.m_strUserDefMsg = strUserDefMsg; m_strBlockName = null; m_exceptionLowerLevel = null; } public JSmartMathErrException(ERRORTYPES e, String strUserDefMsg, String strBlockName, Exception exceptionLowerLevel) { m_se.m_enumErrorType = e; m_se.m_strUserDefMsg = strUserDefMsg; m_strBlockName = strBlockName; m_exceptionLowerLevel = exceptionLowerLevel; } public JSmartMathErrException(StructError se) { m_se.m_enumErrorType = se.m_enumErrorType; m_se.m_strUserDefMsg = se.m_strUserDefMsg; m_strBlockName = ""; m_exceptionLowerLevel = null; } public JSmartMathErrException(StructError se, String strBlockName, Exception exceptionLowerLevel) { m_se.m_enumErrorType = se.m_enumErrorType; m_se.m_strUserDefMsg = se.m_strUserDefMsg; m_strBlockName = strBlockName; m_exceptionLowerLevel = exceptionLowerLevel; } @Override public String getMessage() { return m_se.getErrorInfo(); } @Override public String getLocalizedMessage() { return m_se.getErrorInfo(); } } }
SumOfUs/api-services
lib/dynamodb/eventTypeChecker.js
<filename>lib/dynamodb/eventTypeChecker.js export const CANCEL_PAYMENT_EVENT = 'PAYMENT_SERVICE:SUBSCRIPTION:DELETE'; export const UPDATE_MEMBER_EVENT = 'MEMBERS_SERVICE:MEMBER:UPDATE'; export const SUBJECT_ACCESS_REQUEST_EVENT = 'MEMBERS_SERVICE:MEMBER:SUBJECT_ACCESS_REQUEST'; export function updateMemberEvent(eventName, record = {}): boolean { return eventName === 'INSERT' && record.eventType === UPDATE_MEMBER_EVENT; } export function cancelPaymentEvent(eventName, record = {}): boolean { return eventName === 'INSERT' && record.eventType === CANCEL_PAYMENT_EVENT; } export function subjectAccessRequestEvent(eventName, record = {}): boolean { return ( (eventName === 'INSERT' || 'UPDATE') && record.eventType === SUBJECT_ACCESS_REQUEST_EVENT ); }
lateef/yaegar-books-rest-service
src/integration-test/java/com/yaegar/yaegarbooksrestservice/steps/SpringBootIntegrationTest.java
package com.yaegar.yaegarbooksrestservice.steps; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SpringBootIntegrationTest { @LocalServerPort int port; }
willFederer/taichi
src/renderer/mlt.cpp
/******************************************************************************* Taichi - Physically based Computer Graphics Library Copyright (c) 2016 <NAME> <<EMAIL>> All rights reserved. Use of this source code is governed by the MIT license as written in the LICENSE file. *******************************************************************************/ #include <taichi/math/discrete_sampler.h> #include "bidirectional_renderer.h" #include "markov_chain.h" TC_NAMESPACE_BEGIN class PSSMLTMarkovChain : public MarkovChain { public: real resolution_x, resolution_y; PSSMLTMarkovChain() : PSSMLTMarkovChain(0, 0) {} PSSMLTMarkovChain(real resolution_x, real resolution_y) : resolution_x(resolution_x), resolution_y(resolution_y) { } PSSMLTMarkovChain large_step() const { PSSMLTMarkovChain result(resolution_x, resolution_y); return result; } PSSMLTMarkovChain mutate() const { PSSMLTMarkovChain result(*this); // Screen coordinates real delta_pixel = 2.0f / (resolution_x + resolution_y); result.get_state(2); result.states[0] = perturb(result.states[0], delta_pixel, 0.1f); result.states[1] = perturb(result.states[1], delta_pixel, 0.1f); // Events for (int i = 2; i < (int)result.states.size(); i++) result.states[i] = perturb(result.states[i], 1.0f / 1024.0f, 1.0f / 64.0f); return result; } protected: inline static real perturb(const real value, const real s1, const real s2) { real result; real r = rand(); if (r < 0.5f) { r = r * 2.0f; result = value + s2 * exp(-log(s2 / s1) * r); } else { r = (r - 0.5f) * 2.0f; result = value - s2 * exp(-log(s2 / s1) * r); } result -= floor(result); return result; } }; class PSSMLTRenderer : public BidirectionalRenderer { private: struct MCMCState { PSSMLTMarkovChain chain; PathContribution pc; real sc; MCMCState() {} MCMCState(const PSSMLTMarkovChain &chain, const PathContribution &pc, real sc) : chain(chain), pc(pc), sc(sc) { } }; MCMCState current_state; bool first_stage_done = false; // Normalizer real b; protected: real large_step_prob; public: virtual void initialize(const Config &config) override { BidirectionalRenderer::initialize(config); large_step_prob = config.get("large_step_prob", 0.3f); } real estimate_b() { real sum = 0; int n_samples = width * height; for (int k = 0; k < n_samples; k++) { auto state_sequence = RandomStateSequence(sampler, k); Path eye_path = trace_eye_path(state_sequence); Path light_path = trace_light_path(state_sequence); PathContribution pc = connect(eye_path, light_path); sum += scalar_contribution_function(pc); } return sum / n_samples; } real scalar_contribution_function(const PathContribution &pc) { real ret = 0.0f; for (auto &contribution : pc.contributions) { ret = max(ret, scalar_contribution_function(contribution)); } return ret; } real scalar_contribution_function(const Contribution &contribution) { return max_component(contribution.c); // TODO: change to luminance } virtual PathContribution get_path_contribution(MarkovChain &mc) { auto state_sequence = MCStateSequence(mc); Path eye_path = trace_eye_path(state_sequence); Path light_path = trace_light_path(state_sequence); return connect(eye_path, light_path); } virtual void render_stage() override { if (!first_stage_done) { b = estimate_b(); P(b); current_state.chain = PSSMLTMarkovChain((real)width, (real)height); current_state.pc = get_path_contribution(current_state.chain); current_state.sc = scalar_contribution_function(current_state.pc); first_stage_done = true; } MCMCState new_state; for (int k = 0; k < width * height / stage_frequency; k++) { real is_large_step; if (rand() <= large_step_prob) { new_state.chain = current_state.chain.large_step(); is_large_step = 1.0; } else { new_state.chain = current_state.chain.mutate(); is_large_step = 0.0; } new_state.pc = get_path_contribution(new_state.chain); new_state.sc = scalar_contribution_function(new_state.pc); double a = 1.0; if (current_state.sc > 0.0) { a = clamp(new_state.sc / current_state.sc, 0.0f, 1.0f); } // accumulate samples with mean value substitution and MIS if (new_state.sc > 0.0) { write_path_contribution(new_state.pc, real((a + is_large_step) / (new_state.sc / b + large_step_prob))); } if (current_state.sc > 0.0) { write_path_contribution(current_state.pc, real((1.0 - a) / (current_state.sc / b + large_step_prob))); } // conditionally accept the chain if (rand() <= a) { current_state = new_state; } sample_count += 1; } } }; class MMLTRenderer : public PSSMLTRenderer { protected: class MMLTMarkovChain : public PSSMLTMarkovChain { private: real technique_state; public: MMLTMarkovChain() : MMLTMarkovChain(0, 0) {} MMLTMarkovChain(int resolution_x, int resolution_y) : PSSMLTMarkovChain((real)resolution_x, (real)resolution_y) { technique_state = rand(); } MMLTMarkovChain large_step() const { return MMLTMarkovChain((int)resolution_x, (int)resolution_y); } MMLTMarkovChain mutate() const { MMLTMarkovChain result(*this); // Pixel location real delta_pixel = 2.0f / (resolution_x + resolution_y); result.get_state(2); result.states[0] = perturb(result.states[0], delta_pixel, 0.1f); result.states[1] = perturb(result.states[1], delta_pixel, 0.1f); result.technique_state = perturb(result.technique_state, 1.0 / 1024.0f, 1.0 / 64.0f); // Events for (int i = 2; i < (int)result.states.size(); i++) result.states[i] = perturb(result.states[i], 1.0f / 1024.0f, 1.0f / 64.0f); return result; } real get_technique_state() { return technique_state; } }; struct MCMCState { MMLTMarkovChain chain; PathContribution pc; real sc, weight; MCMCState() { weight = 1.0f; } MCMCState(const MMLTMarkovChain &chain, const PathContribution &pc, real sc) : chain(chain), pc(pc), sc(sc) { weight = 1.0f; } }; std::vector<MCMCState> current_states; bool first_stage_done = false; DiscreteSampler path_length_sampler; std::vector<real> normalizers; public: virtual void initialize(const Config &config) override { PSSMLTRenderer::initialize(config); current_states.resize(max_path_length + 1); normalizers.resize(max_path_length + 1); } void estimate_normalizers() { real sum = 0; int n_samples = width * height; std::vector<real> intensities(max_path_length + 1, 0.0f); std::vector<long long> samples(max_path_length + 1, 0LL); for (int k = 0; k < n_samples; k++) { auto state_sequence = RandomStateSequence(sampler, k); Path eye_path = trace_eye_path(state_sequence); Path light_path = trace_light_path(state_sequence); PathContribution pc = connect(eye_path, light_path); for (auto &contribution : pc.contributions) { intensities[contribution.path_length] += scalar_contribution_function(contribution); samples[contribution.path_length] += 1; } } for (int k = min_path_length; k <= max_path_length; k++) { normalizers[k] = intensities[k] / n_samples / (k + 1); } } PathContribution get_path_contribution(MMLTMarkovChain &mc, int path_length) { auto state_sequence = MCStateSequence(mc); Path eye_path = trace_eye_path(state_sequence); Path light_path = trace_light_path(state_sequence); int t = std::min(path_length, (int)floor(mc.get_technique_state() * (path_length + 1))) + 1, s = path_length - t + 1; assert_info(0 <= t && t <= path_length + 1, "Invalid eye path length: " + std::to_string(t) + " state: " + std::to_string(mc.get_technique_state())); return connect(eye_path, light_path, t, s); } void initialize_path_length_sampler() { estimate_normalizers(); for (int i = min_path_length; i <= max_path_length; i++) { if (normalizers[i] == 0.0f) { // No path of such length continue; } while (true) { current_states[i].chain = MMLTMarkovChain(width, height); current_states[i].pc = get_path_contribution(current_states[i].chain, i); current_states[i].sc = scalar_contribution_function(current_states[i].pc); if (current_states[i].sc > 0) { break; } } } path_length_sampler.initialize(normalizers); } virtual void render_stage() override { if (!first_stage_done) { initialize_path_length_sampler(); first_stage_done = true; } MCMCState new_state; for (int k = 0; k < width * height / stage_frequency; k++) { real path_length_pdf; int path_length = path_length_sampler.sample(rand(), path_length_pdf); real is_large_step; MCMCState &current_state = current_states[path_length]; if (rand() < large_step_prob) { new_state.chain = current_state.chain.large_step(); is_large_step = 1.0; } else { new_state.chain = current_state.chain.mutate(); is_large_step = 0.0; } new_state.pc = get_path_contribution(new_state.chain, path_length); new_state.sc = scalar_contribution_function(new_state.pc); real a = 1.0; if (current_state.sc > 0.0) { a = clamp(new_state.sc / current_state.sc, 0.0f, 1.0f); } real factor = (path_length + 1) / path_length_pdf; // accumulate samples with mean value substitution and MIS if (new_state.sc > 0.0) { write_path_contribution(new_state.pc, factor * (a + is_large_step) / (new_state.sc / normalizers[path_length] + large_step_prob)); } if (current_state.sc > 0.0) { write_path_contribution(current_state.pc, factor * real(1.0 - a) / real((current_state.sc / normalizers[path_length] + large_step_prob))); } // conditionally accept the chain if (rand() <= a) { current_state = new_state; } sample_count += 1; } } }; TC_IMPLEMENTATION(Renderer, PSSMLTRenderer, "pssmlt"); class DWMMLTRenderer : public MMLTRenderer { public: void initialize(Config &config) { MMLTRenderer::initialize(config); large_step_prob = 0.0f; } virtual void render_stage() override { if (!first_stage_done) { initialize_path_length_sampler(); first_stage_done = true; } MCMCState new_state; for (int k = 0; k < width * height / stage_frequency; k++) { real path_length_pdf; int path_length = path_length_sampler.sample(rand(), path_length_pdf); MCMCState &current_state = current_states[path_length]; //P(current_state.weight); new_state.chain = current_state.chain.mutate(); new_state.pc = get_path_contribution(new_state.chain, path_length); new_state.sc = scalar_contribution_function(new_state.pc); bool accepted = false; real theta = 0.1f, r, a; if (current_state.sc > 0) { r = current_state.weight * new_state.sc / current_state.sc; a = r / (r + theta); if (rand() < r) { accepted = true; } } else { a = 0; } if (accepted) { current_state = new_state; current_state.weight = r / a; } else { current_state.weight = current_state.weight / (1 - a); } real factor = (path_length + 1) / path_length_pdf; if (current_state.sc > 0.0) { write_path_contribution(current_state.pc, current_state.weight * factor / (current_state.sc / normalizers[path_length])); } sample_count += 1; } } }; TC_IMPLEMENTATION(Renderer, MMLTRenderer, "mmlt"); TC_NAMESPACE_END
552301/mini-platform
modules/mini-auth/src/main/java/com/github/hiling/auth/service/AccountService.java
<reponame>552301/mini-platform package com.github.hiling.auth.service; import com.github.hiling.auth.model.Account; public interface AccountService { Account login(String username, String password); }
stsdev0487/splash
src/FloatingHelper/FloatingHelper.driver.js
import { closablePopoverDriverFactory } from './ClosablePopover/ClosablePopover.driver'; import { dataHooks } from './constants'; import { floatingHelperContentDriverFactory } from './FloatingHelperContent/FloatingHelperContent.driver'; const floatingHelperDriverFactory = ({ wrapper, element, eventTrigger }) => { const closablePopoverDriver = closablePopoverDriverFactory({ wrapper, element, eventTrigger, }); const popoverContent = () => closablePopoverDriver.getContentElement(); const innerContent = () => popoverContent().querySelector(`[data-hook='${dataHooks.innerContent}']`); const closeButton = () => popoverContent().querySelector(`[data-hook='${dataHooks.closeButton}']`); const contentWrapper = () => popoverContent().querySelector(`[data-hook='${dataHooks.contentWrapper}']`); return { ...closablePopoverDriver, /** check whether the helper has a close button */ hasCloseButton: () => !!closeButton(), /** click the close button */ clickCloseButton: () => eventTrigger.click(closeButton()), /** Get the driver for the helper's content */ getHelperContentDriver: () => floatingHelperContentDriverFactory({ wrapper, element: innerContent(), eventTrigger, }), /** Get width of content's root element */ getWidth: () => window.getComputedStyle(contentWrapper()).width, }; }; export default floatingHelperDriverFactory;
shiguangyin/Discover
app/src/main/java/com/masker/discover/utils/CloseUtils.java
<filename>app/src/main/java/com/masker/discover/utils/CloseUtils.java<gh_stars>1-10 package com.masker.discover.utils; import java.io.Closeable; import java.io.IOException; /** * Author: masker * Date: 2017/8/17 * Description: */ public class CloseUtils { public static void close(Closeable closeable){ if(closeable != null){ try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } }
ajitkhaparde/trex-core
src/dpdk/lib/librte_fib/trie_avx512.h
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2020 Intel Corporation */ #ifndef _TRIE_AVX512_H_ #define _TRIE_AVX512_H_ void rte_trie_vec_lookup_bulk_2b(void *p, uint8_t ips[][RTE_FIB6_IPV6_ADDR_SIZE], uint64_t *next_hops, const unsigned int n); void rte_trie_vec_lookup_bulk_4b(void *p, uint8_t ips[][RTE_FIB6_IPV6_ADDR_SIZE], uint64_t *next_hops, const unsigned int n); void rte_trie_vec_lookup_bulk_8b(void *p, uint8_t ips[][RTE_FIB6_IPV6_ADDR_SIZE], uint64_t *next_hops, const unsigned int n); #endif /* _TRIE_AVX512_H_ */
linusnorton/ccd-data-store-api
src/main/java/uk/gov/hmcts/ccd/domain/service/aggregated/AuthorisedGetCaseTypesOperation.java
package uk.gov.hmcts.ccd.domain.service.aggregated; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import uk.gov.hmcts.ccd.data.user.CachedUserRepository; import uk.gov.hmcts.ccd.data.user.UserRepository; import uk.gov.hmcts.ccd.domain.model.definition.AccessControlList; import uk.gov.hmcts.ccd.domain.model.definition.CaseTypeDefinition; import uk.gov.hmcts.ccd.domain.service.common.AccessControlService; import uk.gov.hmcts.ccd.endpoint.exceptions.ValidationException; /** * Authorised {@link GetCaseTypesOperation}. * * @deprecated until {@link DefaultGetCaseTypesOperation} is deprecated */ @Deprecated @SuppressWarnings("squid:S1133") @Service @Qualifier(AuthorisedGetCaseTypesOperation.QUALIFIER) public class AuthorisedGetCaseTypesOperation implements GetCaseTypesOperation { public static final String QUALIFIER = "authorised"; private final AccessControlService accessControlService; private final UserRepository userRepository; private final GetCaseTypesOperation getCaseTypesOperation; @Autowired public AuthorisedGetCaseTypesOperation(final AccessControlService accessControlService, @Qualifier(CachedUserRepository.QUALIFIER) final UserRepository userRepository, @Qualifier(DefaultGetCaseTypesOperation.QUALIFIER) final GetCaseTypesOperation getCaseTypesOperation) { this.accessControlService = accessControlService; this.userRepository = userRepository; this.getCaseTypesOperation = getCaseTypesOperation; } @Override public List<CaseTypeDefinition> execute(String jurisdictionId, Predicate<AccessControlList> access) { final Set<String> userRoles = getUserRoles(); return getCaseTypesOperation.execute(jurisdictionId, access).stream() .map(caseType -> verifyAccess(caseType, userRoles, access)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } private Set<String> getUserRoles() { Set<String> userRoles = userRepository.getUserRoles(); if (userRoles == null) { throw new ValidationException("Cannot find user roles for the user"); } return userRoles; } private Optional<CaseTypeDefinition> verifyAccess(CaseTypeDefinition caseTypeDefinition, Set<String> userRoles, Predicate<AccessControlList> access) { if (caseTypeDefinition == null || CollectionUtils.isEmpty(userRoles)) { return Optional.empty(); } if (!accessControlService.canAccessCaseTypeWithCriteria(caseTypeDefinition, userRoles, access)) { return Optional.empty(); } caseTypeDefinition.setStates(accessControlService.filterCaseStatesByAccess(caseTypeDefinition.getStates(), userRoles, access)); caseTypeDefinition.setEvents(accessControlService.filterCaseEventsByAccess(caseTypeDefinition.getEvents(), userRoles, access)); caseTypeDefinition.setCaseFieldDefinitions(accessControlService.filterCaseFieldsByAccess( caseTypeDefinition.getCaseFieldDefinitions(), userRoles, access)); return Optional.of(caseTypeDefinition); } }
SpinlockLabs/raptor
kernel/arch/x86/devices/pcnet/pcnet.h
#pragma once void pcnet_driver_setup(void);
AlekNS/yahe
internal/auth/app/auth_interfaces.go
package app //go:generate mockgen -source=auth_interfaces.go -package=app -destination=auth_interfaces_mocks.go import "github.com/alekns/yahe/pkg/subscribs" type ( // // Domain services // // UserRepositoryService . UserRepositoryService interface { GetByLogin(tenantID TenantID, login string) (*User, error) GetByIDs(tenantID TenantID, userID UserID) (*User, error) Save(user *User) (*User, error) } // JwtRepositoryService . JwtRepositoryService interface { GetAll(tenantID TenantID, userID UserID) ([]Jwt, error) GetByIDs(tenantID TenantID, userID UserID, tokenID JwtID) (*Jwt, error) Save(token *Jwt) (*Jwt, error) RemoveAll(tenantID TenantID, userID UserID) error Remove(token *Jwt) error } // PasswordService . PasswordService interface { Create(salt []byte, password string) ([]byte, error) Verify(salt []byte, srcPassword string, hashedPassword []byte) (bool, error) } // JwtService . JwtService interface { SignAndEncode(attrs JwtAttrs) (string, error) VerifyAndDecode(tokenString string) (JwtAttrs, error) } // // Events // // DomainEvents . DomainEvents interface { UserCreated() subscribs.EventHandler UserStatusChanged() subscribs.EventHandler UserResetPassword() subscribs.EventHandler UserPasswordChanged() subscribs.EventHandler } // // Applications // // UserApp . UserApp interface { Create(tenantID TenantID, user *User) (*User, error) GetUserBy(tenantID TenantID, login string, password string) (*User, error) ChangePassword(tenantID TenantID, userID UserID, oldPassword, newPassword string) (*User, error) ResetPassword(tenantID TenantID, userID UserID, newPassword string) (*User, error) } // JwtApp . JwtApp interface { GetAllByUserID(tenantID TenantID, userID UserID) ([]JwtEncoded, error) Create(tenantID TenantID, login, password string, request *JwtAppCreateRequest) (JwtEncoded, error) Validate(tenantID TenantID, token JwtEncoded) (*JwtDecoded, error) Invalidate(tenantID TenantID, token JwtEncoded) error InvalidateAllTokens(tenantID TenantID, userID UserID) error } // AuthorizeApp . //AuthorizeApp interface { // //} )
simonadi/AlgoTipBot
algotip_bot/clients.py
<reponame>simonadi/AlgoTipBot<filename>algotip_bot/clients.py """ File containing all clients to communicate with services Redis: database running locally algod: SDK to interact with the Algorand blockchain Reddit: API wrapper to communicate with reddit """ import os import praw from algosdk.v2client import algod from redis import Redis from rich.console import Console ######################### Initialize Redis connection ######################### # Get the Redis DB password from the environment variables and initialize the client REDIS_PW = os.environ.get("REDIS_PW") redis = Redis(password=REDIS_PW, decode_responses=True) # decode_responses is used to automatically # convert bytes to strings and vice-versa ######################### Initialize Algod connection ######################### # Get API key from the environment variables and initialize the client ALGOD_TOKEN = os.environ.get("ALGOD_TOKEN") NETWORK = os.environ.get("NETWORK") algod_address = f"https://{NETWORK}-algorand.api.purestake.io/ps2" headers = { "x-api-key": ALGOD_TOKEN } algod = algod.AlgodClient(ALGOD_TOKEN, algod_address, headers) ######################### Initialize Reddit connection ######################### CLIENT_SECRET = os.environ.get("CLIENT_SECRET") CLIENT_ID = os.environ.get("CLIENT_ID") PASSWORD = os.environ.get("PASSWORD") USERNAME = os.environ.get("USERNAME") USER_AGENT = os.environ.get("USER_AGENT") # Fetches information from the praw.ini file reddit = praw.Reddit( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, password=PASSWORD, username=USERNAME, user_agent=USER_AGENT ) ######################### Initialize Rich console ######################### console = Console()
FroobWorld/NabSuite
src/main/java/com/froobworld/nabsuite/data/identity/PlayerIdentity.java
<filename>src/main/java/com/froobworld/nabsuite/data/identity/PlayerIdentity.java package com.froobworld.nabsuite.data.identity; import com.froobworld.nabsuite.data.SchemaEntries; import com.froobworld.nabsuite.data.SimpleDataSchema; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class PlayerIdentity { private static final SimpleDataSchema<PlayerIdentity> SCHEMA = new SimpleDataSchema.Builder<PlayerIdentity>() .addField("uuid", SchemaEntries.uuidEntry(p -> p.uuid, (p, u) -> p.uuid = u)) .addField("last-name", SchemaEntries.stringEntry(p -> p.lastName, (p, s) -> p.lastName = s)) .addField("previous-names", SchemaEntries.stringListEntry(p -> p.previousNames, (p, l) -> p.previousNames = l)) .build(); private UUID uuid; private String lastName; private List<String> previousNames; private PlayerIdentity() {} public PlayerIdentity(UUID uuid, String lastName, List<String> previousNames) { this.uuid = uuid; this.lastName = lastName; this.previousNames = previousNames; } public UUID getUuid() { return uuid; } public String getLastName() { return lastName; } public List<String> getPreviousNames() { return new ArrayList<>(previousNames); } public CompletableFuture<NameHistory> getFullNameHistory() { return NameHistory.fromUuid(uuid); } public Player asPlayer() { return Bukkit.getPlayer(uuid); } public OfflinePlayer asOfflinePlayer() { return Bukkit.getOfflinePlayer(uuid); } void setLastName(String lastName) { this.lastName = lastName; } void addPreviousName(String previousName) { previousNames.add(previousName); } public Component displayName() { Player onlinePlayer = asPlayer(); return onlinePlayer != null ? onlinePlayer.displayName() : Component.text(getLastName()); } public String toJsonString() { try { return SCHEMA.toJsonString(this); } catch (IOException e) { e.printStackTrace(); } return null; } public static PlayerIdentity fromJsonString(String jsonString) { PlayerIdentity playerIdentity = new PlayerIdentity(); try { SCHEMA.populateFromJsonString(playerIdentity, jsonString); return playerIdentity; } catch (IOException e) { e.printStackTrace(); } return null; } }
ilyukevich/university-schedule
apps/schedule/admin.py
from django.contrib import admin from .models import Lessons, Schedule class LessonsAdmin(admin.ModelAdmin): """***""" list_display = ('auditory', 'lesson_name', 'day', 'time', 'created', 'updated',) list_display_links = ('lesson_name',) ordering = ('-created',) #fieldsets = () # class LessonsInline(admin.TabularInline): # model = Lessons # #extra = 1 class ScheduleAdmin(admin.ModelAdmin): """***""" list_display = ('schedule_name', 'student', 'faculty', 'departament', 'studygroups', 'day', 'available', 'created', 'updated',) list_display_links = ('schedule_name',) ordering = ('-created',) #fieldsets = () #inlines = [LessonsInline] admin.site.register(Lessons, LessonsAdmin) admin.site.register(Schedule, ScheduleAdmin)
dyuri/vizzu-lib
src/data/table/datatable.h
#ifndef DATATABLE_H #define DATATABLE_H #include <map> #include <string> #include <span> #include "table.h" #include "columninfo.h" namespace Vizzu { namespace Data { enum class SortType : uint8_t { AsSeen, Natural }; class DataCube; class TextTable; class DataTable : public Table<double> { public: typedef Table<double> Base; struct DataIndex { ColumnIndex value; ColumnInfo::Type type; DataIndex(ColumnIndex value, ColumnInfo::Type type) : value(value), type(type) {} DataIndex() : value((size_t)-1), type(ColumnInfo::Type::Continous) {} bool isInvalid() const { return value == (size_t)-1; } }; DataTable(); explicit DataTable(const TextTable &table); const ColumnInfo &getInfo(ColumnIndex index) const; DataIndex getIndex(ColumnIndex index) const; ColumnIndex getColumn(const std::string &name) const; DataIndex getIndex(const std::string &name) const; DataIndex addColumn(const std::string &name, const std::span<double> &values); DataIndex addColumn(const std::string &name, const std::span<std::string> &values); DataIndex addColumn(const std::string &name, const std::span<const char*> &values); void pushRow(const std::span<const char*> &cells); void pushRow(const TableRow<std::string> &textRow); private: typedef std::vector<ColumnInfo> Infos; SortType discreteSorting; std::map<std::string, ColumnIndex> indexByName; Infos infos; void processHeader(const TextTable &table); void fillData(const TextTable &table); void sortDiscretes(); template <typename T> DataIndex addTypedColumn(const std::string &name, const std::span<T> &values); }; class CellWrapper { public: CellWrapper(const double &value, const ColumnInfo &info) : value(value), info(info) { } explicit operator std::string() const { return info.toString(value); } const double &operator*() const { return value; } double operator[](const std::string &val) const { return info.discreteValueIndexes().at(val); } const char *discreteValue() const { return info.toDiscreteString(value); } const ColumnInfo &getInfo() const { return info; } private: const double &value; const ColumnInfo &info; }; class RowWrapper { public: RowWrapper(const DataTable &table, const DataTable::Row &row) : table(table), row(row) {} CellWrapper operator[](const std::string &columnName) const { auto colIndex = table.getColumn(columnName); return this->operator[](colIndex); } CellWrapper operator[](ColumnIndex colIndex) const { const auto &info = table.getInfo(colIndex); return CellWrapper(row[colIndex], info); } size_t size() const { return row.size(); } private: const DataTable &table; const DataTable::Row &row; }; } } #endif
SiberiaDante/SDAndroidLib
utilsample/src/main/java/com/siberiadante/utilsample/activity/practice/mvp/LoginModel.java
<gh_stars>100-1000 package com.siberiadante.utilsample.activity.practice.mvp; import com.siberiadante.utilsample.basemvp.BaseModel; import io.reactivex.Observable; /** * create date: 2018/11/13 */ public interface LoginModel extends BaseModel { Observable<LoginBean> doLogin(); }
OluSure/Hacktoberfest2021-1
Knapsack.py
n=int(input("Enter the number of items:\n")) weight,value=[],[] for i in range(n): print("Enter weight and value for item %d"%(i+1)) weight.append(int(input())) value.append(int(input())) ratio=[] for i in range(n): ratio.append(value[i]//weight[i]) cap=int(input("Enter the maximum capacity:\n")) w,v=0,0 while w<=cap: m=max(ratio) i=ratio.index(m) if w+weight[i]<=cap: print("Adding 100 percent of the item %d to the knapsack "%(i+1)) w+=weight[i] v+=value[i] cap-=weight[i] else: f1=cap/weight[i] f1=f1*100.0 print("Adding",f1,"percent of the item %d to the knapsack " %(i+1)) v+=(f1/100.0*value[i]) v=round(v,2) break ratio[i]=-1 print("The maximum value is: %.2f"%v)
TomWeaver18/dexter
feature_tests/commands/perfect/expect_step_kind/func/test.cpp
<reponame>TomWeaver18/dexter<filename>feature_tests/commands/perfect/expect_step_kind/func/test.cpp // Purpose: // Check that \DexExpectStepKind correctly counts 'FUNC' steps for a // trivial test. Expect one 'FUNC' per call to a function which is defined // in one of the source files in the test directory. // // REQUIRES: linux, clang, lldb // // RUN: dexter.py test --fail-lt 1.0 -w \ // RUN: --builder clang --debugger lldb --cflags "-O0 -g" -- %S \ // RUN: | FileCheck %s // CHECK: func: int func(int i) { return i; } int main() { func(0); func(1); return 0; } // main, func, func // DexExpectStepKind('FUNC', 3)
iAnatoly/gobench
web/ui/gobench-ui/src/components/kit/widgets/General/21/index.js
<filename>web/ui/gobench-ui/src/components/kit/widgets/General/21/index.js<gh_stars>10-100 import React from 'react' const General21 = () => { return ( <div className="card border-0 bg-success text-white"> <div className="card-body"> <div className="d-flex flex-wrap align-items-center"> <i className="fe fe-server font-size-50 mr-3" /> <div> <div className="font-size-21 font-weight-bold">Databases</div> <div className="font-size-15">Total: 78,155</div> </div> </div> </div> </div> ) } export default General21
pasmuss/cmssw
DQM/SiStripCommissioningSources/interface/CalibrationTask.h
#ifndef DQM_SiStripCommissioningSources_CalibrationTask_h #define DQM_SiStripCommissioningSources_CalibrationTask_h #include "DQM/SiStripCommissioningSources/interface/CommissioningTask.h" #include <string> /** @class CalibrationTask */ class CalibrationTask : public CommissioningTask { public: CalibrationTask( DQMStore*, const FedChannelConnection&, const sistrip::RunType&, const char* filename, uint32_t run, const edm::EventSetup& setup ); virtual ~CalibrationTask(); private: virtual void book(); virtual void fill( const SiStripEventSummary&, const edm::DetSet<SiStripRawDigi>& ); virtual void update(); void checkAndSave(const uint16_t&); void directory( std::stringstream&, uint32_t run_number = 0 ); sistrip::RunType runType_; std::vector<HistoSet> calib_; uint16_t nBins_; uint16_t lastCalChan_; std::string filename_; std::vector<uint16_t> ped; uint32_t run_; MonitorElement* calchanElement_; }; #endif // DQM_SiStripCommissioningSources_CalibrationTask_h
spatialcurrent/coconut
src/components/loader/index.js
<reponame>spatialcurrent/coconut import Loader from './loader.container'; export default Loader;
JiangJibo/pinpoint
web/src/main/java/com/navercorp/pinpoint/web/util/UserInfoEncoder.java
<filename>web/src/main/java/com/navercorp/pinpoint/web/util/UserInfoEncoder.java package com.navercorp.pinpoint.web.util; import com.navercorp.pinpoint.web.vo.User; import java.util.List; public interface UserInfoEncoder { User encodeUserInfo(User user); List<User> encodeUserInfoList(List<User> userList); }
arista-netdevops-community/runAM
setup.py
import pathlib from setuptools import setup, find_packages # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() setup( name="runAM-evpn", version="0.1.5", description="runAM Python modules to build EVPN network", long_description=README, long_description_content_type="text/markdown", url='https://github.com/arista-netdevops-community/runAM', author='<NAME>', license="BSD", classifiers=[ "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Development Status :: 3 - Alpha", "Operating System :: POSIX :: Linux", ], packages=find_packages(), include_package_data=True, install_requires=[ "argcomplete==1.12.1", "glom==20.11.0", "jq==1.1.1", "PyYAML==5.3.1", ], entry_points = { "console_scripts": ['runAM = runAM.cli:interpreter'] }, )
riyadth/2019-DeepSpace
src/main/java/com/spartronics4915/frc2019/auto/actions/DiagnoseDropouts.java
package com.spartronics4915.frc2019.auto.actions; import java.nio.file.Paths; import com.spartronics4915.frc2019.Constants; import com.spartronics4915.frc2019.subsystems.Drive; import com.spartronics4915.lib.util.DriveSignal; import com.spartronics4915.lib.util.ReflectingCSVWriter; import com.spartronics4915.lib.util.Units; import edu.wpi.first.wpilibj.Timer; public class DiagnoseDropouts implements Action { private final DriveSignal kPercentDemand = new DriveSignal(0.5, 0.5); private final double kRunTime = 10.0; // Seconds private final Drive mDrive = Drive.getInstance(); private final Timer mTimer = new Timer(); private final ReflectingCSVWriter<VelocityTimeDataPoint> mCSVWriter; public DiagnoseDropouts() { mCSVWriter = new ReflectingCSVWriter<>(Paths.get(System.getProperty("user.home"), "DROPOUT_DATAs.csv").toString(), VelocityTimeDataPoint.class); mTimer.start(); mTimer.reset(); } @Override public boolean isFinished() { return mTimer.hasPeriodPassed(kRunTime); } @Override public void update() { mDrive.setOpenLoop(kPercentDemand); mCSVWriter.add(new VelocityTimeDataPoint(mDrive.getLeftVelocityTicksPer100ms())); } @Override public void done() { mCSVWriter.flush(); } @Override public void start() { } public class VelocityTimeDataPoint { public final double velocity; // rps public final double time; // seconds since RoboRIO boot /** * @param velocity in ticks/100ms */ public VelocityTimeDataPoint(double velocity) { this.velocity = Units.rads_per_sec_to_rpm(velocity / Constants.kDriveEncoderPPR * (2 * Math.PI) * 10); this.time = Timer.getFPGATimestamp(); } } }
vierbergenlars/plugin-updates-gradle-plugin
src/integTest/java/be/vbgn/gradle/pluginupdates/integration/SubprojectsTest.java
<filename>src/integTest/java/be/vbgn/gradle/pluginupdates/integration/SubprojectsTest.java package be.vbgn.gradle.pluginupdates.integration; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import be.vbgn.gradle.pluginupdates.AbstractIntegrationTest; import be.vbgn.gradle.pluginupdates.version.Version; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Paths; import org.gradle.testkit.runner.BuildResult; import org.junit.Test; public class SubprojectsTest extends AbstractIntegrationTest { @Test public void subprojects() throws IOException, URISyntaxException { BuildResult buildResult = buildProject(Paths.get(getClass().getResource("subprojects").toURI()), "clean"); assertOutputContainsOneOf(buildResult, "Plugin is outdated in project ':subproject': org.gradle:gradle-hello-world-plugin:[0.1 -> 0.2]", "Plugin is outdated in project ':subproject': id 'org.gradle.hello-world' version '[0.1 -> 0.2]'"); } /** * https://github.com/vierbergenlars/plugin-updates-gradle-plugin/issues/3 */ @Test public void warnOnceAboutUnsupportedSettings() throws IOException, URISyntaxException { // Gradle versions < 4.4 do not have the required api to read settings configuration assumeTrue("Gradle version is at most 4.3", Version.parse(gradleVersion).compareTo(Version.parse("4.4")) < 0); BuildResult buildResult = buildProject(Paths.get(getClass().getResource("subprojects").toURI()), "clean"); String[] lines = buildResult.getOutput().split("\n"); boolean foundWarning = false; for (String line : lines) { if (line.contains( "Plugin update configuration in settings.gradle can not be fetched and will be ignored.")) { assertFalse("The warning message can only be present once.", foundWarning); foundWarning = true; } } assertTrue("The warning message must be present once.", foundWarning); } }
kjleitz/LOSE
app/models/alignment.rb
<reponame>kjleitz/LOSE<gh_stars>0 class Alignment < ApplicationRecord end
geronimo-iia/restexpress
restexpress-common/src/main/java/org/restexpress/serialization/jackson/JacksonLocaleSerializer.java
<gh_stars>1-10 /** * 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.restexpress.serialization.jackson; import java.io.IOException; import java.util.Locale; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; /** * {@link JacksonLocaleSerializer} implements a serializer for {@link Locale} * class. Use underlying method {@link Locale#toString()}. * * Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC". * * @author <a href="mailto:<EMAIL>" ><NAME></a> */ public class JacksonLocaleSerializer extends StdSerializer<Locale> { /** * Build a new instance of JacksonLocaleSerializer.java. */ public JacksonLocaleSerializer() { super(Locale.class); } @Override public void serialize(final Locale locale, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeString(locale.toString()); } }
Fassial/cs61bl
lab12/ExceptionsPuzzle.java
public class ExceptionsPuzzle { public static void checkIfZero(int x) throws Exception { if (x == 0) { throw new Exception("x was zero!"); } System.out.println(x); // PRINT STATEMENT } public static int mystery(int x) { int counter = 0; try { while (true) { x = x / 2; checkIfZero(x); counter += 1; System.out.println("counter is " + counter); // PRINT STATEMENT } } catch (Exception e) { return counter; } } public static void main(String[] args) { System.out.println("mystery of 1 is " + mystery(1)); System.out.println("mystery of 6 is " + mystery(6)); } }
ismartinezrizo/Bluuweb-Curso-de-Javascript
PARTE 11 ASYN AWAIT PROMESAS Fetch API/callback.js
// ----------------- // Función Callback // ----------------- // Una función de callback es una función que se pasa a otra función como un argumento, que luego se invoca dentro de la función externa para completar algún tipo de rutina o acción. // UNA FUNCION NORMAL function saludar() { alert(`Hola ${nombre}`); } // UNA FUNCION NORMAL QUE QUE RECIBE COMO PARAMETRO OTRA FUNCION function pedirNombre(callback) { let nombrePrompt = prompt('Ingrese su nombre por favor: '); // MANDAMOS A LLAMAR A LA FUNCION QUE LE PASAMOS Y LE PASAMOS EL VALOR callback(nombrePrompt); } // MANDAMOS A LLAMAR A LA FUNCION Y LE PASAMOS UNA FUNCION pedirNombre(saludar);
jackypan1989/js-bundler-comparison
complex/esbuild/lib/191.js
<gh_stars>1-10 (() => { // src/191.js var __default = example = 0; })();
randolphwong/mcsema
boost/libs/multi_array/example/basic1.cpp
<reponame>randolphwong/mcsema // Copyright 2002 The Trustees of Indiana University. // Use, modification and distribution is subject to 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) // Boost.MultiArray Library // Authors: <NAME> // <NAME> // <NAME> // See http://www.boost.org/libs/multi_array for documentation. #include <cassert> #include "boost/multi_array.hpp" #include "boost/cstdlib.hpp" int main () { // Create a 3D array that is 3 x 4 x 2 typedef boost::multi_array<double, 3> array; array A(boost::extents[3][4][2]); // Assign a value to an element in the array A[0][0][0] = 3.14; assert(A[0][0][0] == 3.14); return boost::exit_success; }
viewdy/phantomjs
src/qt/qtbase/src/corelib/io/qwinoverlappedionotifier.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwinoverlappedionotifier_p.h" #include <qdebug.h> #include <qmutex.h> #include <qpointer.h> #include <qqueue.h> #include <qset.h> #include <qthread.h> #include <qt_windows.h> #include <private/qobject_p.h> QT_BEGIN_NAMESPACE /*! \class QWinOverlappedIoNotifier \inmodule QtCore \brief The QWinOverlappedIoNotifier class provides support for overlapped I/O notifications on Windows. \since 5.0 \internal The QWinOverlappedIoNotifier class makes it possible to use efficient overlapped (asynchronous) I/O notifications on Windows by using an I/O completion port. Once you have obtained a file handle, you can use setHandle() to get notifications for I/O operations. Whenever an I/O operation completes, the notified() signal is emitted which will pass the number of transferred bytes, the operation's error code and a pointer to the operation's OVERLAPPED object to the receiver. Every handle that supports overlapped I/O can be used by QWinOverlappedIoNotifier. That includes file handles, TCP sockets and named pipes. Note that you must not use ReadFileEx() and WriteFileEx() together with QWinOverlappedIoNotifier. They are not supported as they use a different I/O notification mechanism. The hEvent member in the OVERLAPPED structure passed to ReadFile() or WriteFile() is ignored and can be used for other purposes. \warning This class is only available on Windows. */ struct IOResult { IOResult(DWORD n = 0, DWORD e = 0, OVERLAPPED *p = 0) : numberOfBytes(n), errorCode(e), overlapped(p) {} DWORD numberOfBytes; DWORD errorCode; OVERLAPPED *overlapped; }; class QWinIoCompletionPort; class QWinOverlappedIoNotifierPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QWinOverlappedIoNotifier) public: QWinOverlappedIoNotifierPrivate() : hHandle(INVALID_HANDLE_VALUE) { } void notify(DWORD numberOfBytes, DWORD errorCode, OVERLAPPED *overlapped); OVERLAPPED *_q_notified(); static QWinIoCompletionPort *iocp; static HANDLE iocpInstanceLock; static unsigned int iocpInstanceRefCount; HANDLE hHandle; HANDLE hSemaphore; HANDLE hResultsMutex; QQueue<IOResult> results; }; QWinIoCompletionPort *QWinOverlappedIoNotifierPrivate::iocp = 0; HANDLE QWinOverlappedIoNotifierPrivate::iocpInstanceLock = CreateMutex(NULL, FALSE, NULL); unsigned int QWinOverlappedIoNotifierPrivate::iocpInstanceRefCount = 0; class QWinIoCompletionPort : protected QThread { public: QWinIoCompletionPort() : finishThreadKey(reinterpret_cast<ULONG_PTR>(this)), drainQueueKey(reinterpret_cast<ULONG_PTR>(this + 1)), hPort(INVALID_HANDLE_VALUE) { setObjectName(QLatin1String("I/O completion port thread")); HANDLE hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if (!hIOCP) { qErrnoWarning("CreateIoCompletionPort failed."); return; } hPort = hIOCP; hQueueDrainedEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!hQueueDrainedEvent) { qErrnoWarning("CreateEvent failed."); return; } } ~QWinIoCompletionPort() { PostQueuedCompletionStatus(hPort, 0, finishThreadKey, NULL); QThread::wait(); CloseHandle(hPort); CloseHandle(hQueueDrainedEvent); } void registerNotifier(QWinOverlappedIoNotifierPrivate *notifier) { const HANDLE hHandle = notifier->hHandle; HANDLE hIOCP = CreateIoCompletionPort(hHandle, hPort, reinterpret_cast<ULONG_PTR>(notifier), 0); if (!hIOCP) { qErrnoWarning("Can't associate file handle %x with I/O completion port.", hHandle); return; } mutex.lock(); notifiers += notifier; mutex.unlock(); if (!QThread::isRunning()) QThread::start(); } void unregisterNotifier(QWinOverlappedIoNotifierPrivate *notifier) { mutex.lock(); notifiers.remove(notifier); mutex.unlock(); } void drainQueue() { QMutexLocker locker(&drainQueueMutex); ResetEvent(hQueueDrainedEvent); PostQueuedCompletionStatus(hPort, 0, drainQueueKey, NULL); WaitForSingleObject(hQueueDrainedEvent, INFINITE); } using QThread::isRunning; protected: void run() { DWORD dwBytesRead; ULONG_PTR pulCompletionKey; OVERLAPPED *overlapped; DWORD msecs = INFINITE; forever { BOOL success = GetQueuedCompletionStatus(hPort, &dwBytesRead, &pulCompletionKey, &overlapped, msecs); DWORD errorCode = success ? ERROR_SUCCESS : GetLastError(); if (!success && !overlapped) { if (!msecs) { // Time out in drain mode. The completion status queue is empty. msecs = INFINITE; SetEvent(hQueueDrainedEvent); continue; } qErrnoWarning(errorCode, "GetQueuedCompletionStatus failed."); return; } if (pulCompletionKey == finishThreadKey) return; if (pulCompletionKey == drainQueueKey) { // Enter drain mode. Q_ASSERT(msecs == INFINITE); msecs = 0; continue; } QWinOverlappedIoNotifierPrivate *notifier = reinterpret_cast<QWinOverlappedIoNotifierPrivate *>(pulCompletionKey); mutex.lock(); if (notifiers.contains(notifier)) notifier->notify(dwBytesRead, errorCode, overlapped); mutex.unlock(); } } private: const ULONG_PTR finishThreadKey; const ULONG_PTR drainQueueKey; HANDLE hPort; QSet<QWinOverlappedIoNotifierPrivate *> notifiers; QMutex mutex; QMutex drainQueueMutex; HANDLE hQueueDrainedEvent; }; QWinOverlappedIoNotifier::QWinOverlappedIoNotifier(QObject *parent) : QObject(*new QWinOverlappedIoNotifierPrivate, parent) { Q_D(QWinOverlappedIoNotifier); WaitForSingleObject(d->iocpInstanceLock, INFINITE); if (!d->iocp) d->iocp = new QWinIoCompletionPort; d->iocpInstanceRefCount++; ReleaseMutex(d->iocpInstanceLock); d->hSemaphore = CreateSemaphore(NULL, 0, 255, NULL); d->hResultsMutex = CreateMutex(NULL, FALSE, NULL); connect(this, SIGNAL(_q_notify()), this, SLOT(_q_notified()), Qt::QueuedConnection); } QWinOverlappedIoNotifier::~QWinOverlappedIoNotifier() { Q_D(QWinOverlappedIoNotifier); setEnabled(false); CloseHandle(d->hResultsMutex); CloseHandle(d->hSemaphore); WaitForSingleObject(d->iocpInstanceLock, INFINITE); if (!--d->iocpInstanceRefCount) { delete d->iocp; d->iocp = 0; } ReleaseMutex(d->iocpInstanceLock); } void QWinOverlappedIoNotifier::setHandle(Qt::HANDLE h) { Q_D(QWinOverlappedIoNotifier); d->hHandle = h; } Qt::HANDLE QWinOverlappedIoNotifier::handle() const { Q_D(const QWinOverlappedIoNotifier); return d->hHandle; } void QWinOverlappedIoNotifier::setEnabled(bool enabled) { Q_D(QWinOverlappedIoNotifier); if (enabled) d->iocp->registerNotifier(d); else d->iocp->unregisterNotifier(d); } /*! * Wait synchronously for the notified signal. * * The function returns true if the notified signal was emitted for * the I/O operation that corresponds to the OVERLAPPED object. */ bool QWinOverlappedIoNotifier::waitForNotified(int msecs, OVERLAPPED *overlapped) { Q_D(QWinOverlappedIoNotifier); if (!d->iocp->isRunning()) { qWarning("Called QWinOverlappedIoNotifier::waitForNotified on inactive notifier."); return false; } forever { if (msecs == 0) d->iocp->drainQueue(); DWORD result = WaitForSingleObject(d->hSemaphore, msecs == -1 ? INFINITE : DWORD(msecs)); if (result == WAIT_OBJECT_0) { ReleaseSemaphore(d->hSemaphore, 1, NULL); if (d->_q_notified() == overlapped) return true; continue; } else if (result == WAIT_TIMEOUT) { return false; } } qErrnoWarning("QWinOverlappedIoNotifier::waitForNotified: WaitForSingleObject failed."); return false; } /*! * Note: This function runs in the I/O completion port thread. */ void QWinOverlappedIoNotifierPrivate::notify(DWORD numberOfBytes, DWORD errorCode, OVERLAPPED *overlapped) { Q_Q(QWinOverlappedIoNotifier); WaitForSingleObject(hResultsMutex, INFINITE); results.enqueue(IOResult(numberOfBytes, errorCode, overlapped)); ReleaseMutex(hResultsMutex); ReleaseSemaphore(hSemaphore, 1, NULL); emit q->_q_notify(); } OVERLAPPED *QWinOverlappedIoNotifierPrivate::_q_notified() { Q_Q(QWinOverlappedIoNotifier); if (WaitForSingleObject(hSemaphore, 0) == WAIT_OBJECT_0) { WaitForSingleObject(hResultsMutex, INFINITE); IOResult ioresult = results.dequeue(); ReleaseMutex(hResultsMutex); emit q->notified(ioresult.numberOfBytes, ioresult.errorCode, ioresult.overlapped); return ioresult.overlapped; } return 0; } QT_END_NAMESPACE #include "moc_qwinoverlappedionotifier_p.cpp"
giraffe-tree/boom-java
src/main/java/me/giraffetree/java/boomjava/alg/sort/practice/second/MergeSort.java
<reponame>giraffe-tree/boom-java package me.giraffetree.java.boomjava.alg.sort.practice.second; import java.util.Arrays; /** * 10:31 ~ 10:50 * * @author GiraffeTree * @date 2020/1/21 */ public class MergeSort { public static void main(String[] args) { int[] a = {8, 9, 7, 0, 2}; System.out.println(Arrays.toString(a)); int[] aux = new int[a.length]; sort(a, aux, 0, a.length - 1); System.out.println(Arrays.toString(a)); } private static void sort(int[] a, int[] aux, int lo, int hi) { if (lo >= hi) { return; } // 防止溢出 int mid = (lo + hi) >>> 1; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } private static void merge(int[] a, int[] aux, int lo, int mid, int hi) { System.arraycopy(a, lo, aux, lo, hi - lo + 1); int i = lo, j = mid + 1; int cur = lo; while (cur <= hi) { if (i > mid) { System.arraycopy(aux, j, a, cur, hi - j + 1); break; } if (j > hi) { System.arraycopy(aux, i, a, cur, mid - i + 1); break; } // 到这步, 至少还有两个元素未 merge, 故而不会出现溢出的情况 if (aux[i] <= aux[j]) { a[cur++] = aux[i++]; // continue; } // continue 不加时, 测试了 10000 次没有出现 cur 溢出的情况.... if (aux[i] > aux[j]) { a[cur++] = aux[j++]; } } } }
uktrade/data-hub-frontend
src/apps/events/controllers/events.js
const renderEventsView = async (req, res, next) => { try { const { user } = req.session const currentAdviserId = user.id const props = { title: 'Events', heading: 'Events', currentAdviserId, } return res.render('events/views/events', { props }) } catch (error) { next(error) } } module.exports = { renderEventsView, }
1and1/Troilus
troilus-core-java7/src/main/java/net/oneandone/troilus/Tablename.java
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.troilus; import com.datastax.driver.core.Session; import com.google.common.base.Objects; /** * Tablename */ public class Tablename { private String keyspacename; private String tablename; /** * @param session the session * @param tablename the tablename * @return hte tablename object */ static Tablename newTablename(Session session, String tablename) { String keyspacename = session.getLoggedKeyspace(); if (keyspacename == null) { throw new IllegalStateException("no keyspace assigned"); } return newTablename(keyspacename, tablename); } /** * @param tablename the tablename * @param keyspacename the keyspacename * @return hte tablename object */ static Tablename newTablename(String keyspacename, String tablename) { return new Tablename(keyspacename, tablename); } private Tablename(String keyspacename, String tablename) { this.keyspacename = keyspacename; this.tablename = tablename; } /** * @return the keyspaceanme or null */ String getKeyspacename() { return keyspacename; } /** * @return the tablename */ public String getTablename() { return tablename; } @Override public boolean equals(Object other) { return (other instanceof Tablename) && Objects.equal(((Tablename) other).keyspacename, this.keyspacename) && Objects.equal(((Tablename) other).tablename, this.tablename); } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { return (keyspacename == null) ? tablename : keyspacename + "." + tablename; } }
Ron423c/chromium
chrome/android/junit/src/org/chromium/chrome/browser/safe_browsing/SafeBrowsingReferringAppBridgeTest.java
<reponame>Ron423c/chromium<gh_stars>0 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.safe_browsing; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Browser; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.robolectric.util.ReflectionHelpers; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.app.ChromeActivity; import org.chromium.chrome.browser.safe_browsing.SafeBrowsingReferringAppBridge.ReferringAppInfo; import org.chromium.chrome.browser.safe_browsing.SafeBrowsingReferringAppBridge.ReferringAppInfo.ReferringAppSource; import org.chromium.ui.base.WindowAndroid; import java.lang.ref.WeakReference; /** * Unit tests for SafeBrowsingReferringAppBridge. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SafeBrowsingReferringAppBridgeTest { @Mock private WindowAndroid mWindowAndroid; @Mock private ChromeActivity mActivity; private WeakReference<Activity> mActivityRef; @Before public void setUp() { MockitoAnnotations.initMocks(this); mActivityRef = new WeakReference<>(mActivity); when(mWindowAndroid.getActivity()).thenReturn(mActivityRef); } @Test public void testFromKnownAppId() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtra(Browser.EXTRA_APPLICATION_ID, IntentHandler.PACKAGE_GSA); when(mActivity.getIntent()).thenReturn(intent); ReferringAppInfo info = SafeBrowsingReferringAppBridge.getReferringAppInfo(mWindowAndroid); Assert.assertEquals(ReferringAppSource.KNOWN_APP_ID, info.getSource()); Assert.assertEquals("google.search.app", info.getName()); } @Test public void testFromUnknownAppId() { String packageName = "uncommon.app.name"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtra(Browser.EXTRA_APPLICATION_ID, packageName); when(mActivity.getIntent()).thenReturn(intent); ReferringAppInfo info = SafeBrowsingReferringAppBridge.getReferringAppInfo(mWindowAndroid); Assert.assertEquals(ReferringAppSource.UNKNOWN_APP_ID, info.getSource()); Assert.assertEquals(packageName, info.getName()); } @Test @Config(sdk = Build.VERSION_CODES.N_MR1) public void testFromActivityReferrerHighVersion() { String appReferrer = "android-app://app.name/"; setAppReferrerIntent(appReferrer); ReferringAppInfo info = SafeBrowsingReferringAppBridge.getReferringAppInfo(mWindowAndroid); Assert.assertEquals(ReferringAppSource.ACTIVITY_REFERRER, info.getSource()); Assert.assertEquals(appReferrer, info.getName()); } @Test public void testFromActivityReferrerLowVersion() { // @Config(..., sdk = Build.VERSION_CODES.LOLLIPOP) doesn't work. See crbug.com/944476. ReflectionHelpers.setStaticField( Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.LOLLIPOP); String appReferrer = "android-app://app.name/"; setAppReferrerIntent(appReferrer); ReferringAppInfo info = SafeBrowsingReferringAppBridge.getReferringAppInfo(mWindowAndroid); // The getReferrer API is not available if the version code is too low. Assert.assertEquals(ReferringAppSource.REFERRING_APP_SOURCE_UNSPECIFIED, info.getSource()); Assert.assertEquals("", info.getName()); } private void setAppReferrerIntent(String appReferrer) { Uri appReferrerUri = Uri.parse(appReferrer); Bundle extras = new Bundle(); extras.putParcelable(Intent.EXTRA_REFERRER, appReferrerUri); Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtras(extras); when(mActivity.getIntent()).thenReturn(intent); when(mActivity.getReferrer()).thenReturn(appReferrerUri); } }
jachiang/CryptPeerChat
peerNode2/node_modules/libp2p-websocket-star/test/discovery.spec.js
/* eslint-env mocha */ 'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const expect = chai.expect chai.use(dirtyChai) const multiaddr = require('multiaddr') const each = require('async/each') const WebSocketStar = require('../src') describe('peer discovery', () => { let listeners = [] let ws1 const ma1 = multiaddr('/ip4/127.0.0.1/tcp/15001/ws/p2p-websocket-star/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3A') let ws2 const ma2 = multiaddr('/ip4/127.0.0.1/tcp/15003/ws/p2p-websocket-star/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3B') it('listen on the first', (done) => { ws1 = new WebSocketStar({ allowJoinWithDisabledChallenge: true }) const listener = ws1.createListener((/* conn */) => {}) listeners.push(listener) listener.listen(ma1, (err) => { expect(err).to.not.exist() done() }) }) it('listen on the second, discover the first', (done) => { ws2 = new WebSocketStar({ allowJoinWithDisabledChallenge: true }) ws1.discovery.once('peer', (peerInfo) => { expect(peerInfo.multiaddrs.has(ma2)).to.equal(true) done() }) const listener = ws2.createListener((/* conn */) => {}) listeners.push(listener) listener.listen(ma2, (err) => { expect(err).to.not.exist() }) }).timeout(5000) after(done => each(listeners, (l, next) => l.close(next), done)) })
yorikvanhavre/ifcplusplus
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcRegularTimeSeries.cpp
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcDataOriginEnum.h" #include "ifcpp/IFC4/include/IfcDateTime.h" #include "ifcpp/IFC4/include/IfcExternalReferenceRelationship.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcRegularTimeSeries.h" #include "ifcpp/IFC4/include/IfcText.h" #include "ifcpp/IFC4/include/IfcTimeMeasure.h" #include "ifcpp/IFC4/include/IfcTimeSeriesDataTypeEnum.h" #include "ifcpp/IFC4/include/IfcTimeSeriesValue.h" #include "ifcpp/IFC4/include/IfcUnit.h" // ENTITY IfcRegularTimeSeries IfcRegularTimeSeries::IfcRegularTimeSeries() {} IfcRegularTimeSeries::IfcRegularTimeSeries( int id ) { m_entity_id = id; } IfcRegularTimeSeries::~IfcRegularTimeSeries() {} shared_ptr<BuildingObject> IfcRegularTimeSeries::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcRegularTimeSeries> copy_self( new IfcRegularTimeSeries() ); if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_StartTime ) { copy_self->m_StartTime = dynamic_pointer_cast<IfcDateTime>( m_StartTime->getDeepCopy(options) ); } if( m_EndTime ) { copy_self->m_EndTime = dynamic_pointer_cast<IfcDateTime>( m_EndTime->getDeepCopy(options) ); } if( m_TimeSeriesDataType ) { copy_self->m_TimeSeriesDataType = dynamic_pointer_cast<IfcTimeSeriesDataTypeEnum>( m_TimeSeriesDataType->getDeepCopy(options) ); } if( m_DataOrigin ) { copy_self->m_DataOrigin = dynamic_pointer_cast<IfcDataOriginEnum>( m_DataOrigin->getDeepCopy(options) ); } if( m_UserDefinedDataOrigin ) { copy_self->m_UserDefinedDataOrigin = dynamic_pointer_cast<IfcLabel>( m_UserDefinedDataOrigin->getDeepCopy(options) ); } if( m_Unit ) { copy_self->m_Unit = dynamic_pointer_cast<IfcUnit>( m_Unit->getDeepCopy(options) ); } if( m_TimeStep ) { copy_self->m_TimeStep = dynamic_pointer_cast<IfcTimeMeasure>( m_TimeStep->getDeepCopy(options) ); } for( size_t ii=0; ii<m_Values.size(); ++ii ) { auto item_ii = m_Values[ii]; if( item_ii ) { copy_self->m_Values.push_back( dynamic_pointer_cast<IfcTimeSeriesValue>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcRegularTimeSeries::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCREGULARTIMESERIES" << "("; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_StartTime ) { m_StartTime->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_EndTime ) { m_EndTime->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_TimeSeriesDataType ) { m_TimeSeriesDataType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_DataOrigin ) { m_DataOrigin->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_UserDefinedDataOrigin ) { m_UserDefinedDataOrigin->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Unit ) { m_Unit->getStepParameter( stream, true ); } else { stream << "$" ; } stream << ","; if( m_TimeStep ) { m_TimeStep->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeEntityList( stream, m_Values ); stream << ");"; } void IfcRegularTimeSeries::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcRegularTimeSeries::toString() const { return L"IfcRegularTimeSeries"; } void IfcRegularTimeSeries::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 10 ){ std::stringstream err; err << "Wrong parameter count for entity IfcRegularTimeSeries, expecting 10, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_Name = IfcLabel::createObjectFromSTEP( args[0], map ); m_Description = IfcText::createObjectFromSTEP( args[1], map ); m_StartTime = IfcDateTime::createObjectFromSTEP( args[2], map ); m_EndTime = IfcDateTime::createObjectFromSTEP( args[3], map ); m_TimeSeriesDataType = IfcTimeSeriesDataTypeEnum::createObjectFromSTEP( args[4], map ); m_DataOrigin = IfcDataOriginEnum::createObjectFromSTEP( args[5], map ); m_UserDefinedDataOrigin = IfcLabel::createObjectFromSTEP( args[6], map ); m_Unit = IfcUnit::createObjectFromSTEP( args[7], map ); m_TimeStep = IfcTimeMeasure::createObjectFromSTEP( args[8], map ); readEntityReferenceList( args[9], m_Values, map ); } void IfcRegularTimeSeries::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) { IfcTimeSeries::getAttributes( vec_attributes ); vec_attributes.push_back( std::make_pair( "TimeStep", m_TimeStep ) ); if( m_Values.size() > 0 ) { shared_ptr<AttributeObjectVector> Values_vec_object( new AttributeObjectVector() ); std::copy( m_Values.begin(), m_Values.end(), std::back_inserter( Values_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "Values", Values_vec_object ) ); } } void IfcRegularTimeSeries::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) { IfcTimeSeries::getAttributesInverse( vec_attributes_inverse ); } void IfcRegularTimeSeries::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcTimeSeries::setInverseCounterparts( ptr_self_entity ); } void IfcRegularTimeSeries::unlinkFromInverseCounterparts() { IfcTimeSeries::unlinkFromInverseCounterparts(); }
mariecpereira/Extracao-de-Caracteristicas-Corpo-Caloso
deliver/ia369/iainterpollin.py
<reponame>mariecpereira/Extracao-de-Caracteristicas-Corpo-Caloso # -*- encoding: utf-8 -*- # Module iainterpollin def iainterpollin(f, pts): # f - one, two or three dimention array # pts - array of points to interpolate: # throws IndexError if there are indices out of range in pts from iainterpollin import iainterpollin1D, iainterpollin2D, iainterpollin3D import numpy as np f = f.astype(float) if f.ndim == 1: return iainterpollin1D(f, np.ravel(pts)) if f.ndim == 2: return iainterpollin2D(f, pts) if f.ndim == 3: return iainterpollin3D(f, pts) def iainterpollin1D(f, pts): # f - one dimention array # pts - array of points to interpolate: # throws IndexError if there are indices out of range in pts import numpy as np # integer indices ipts = np.floor(pts).astype(int) # fractional indices fpts = pts - ipts # workaround for the case some index equals the last valid index fpts[ipts>=f.shape[0]-1] += 1 ipts[ipts>=f.shape[0]-1] -= 1 I = ipts.copy() Ix = ipts.copy()+1 a = f[I] b = f[Ix] - a return a + b*fpts def iainterpollin2D(f, pts): # f - bi-dimentional image # pts - array (2xN) of points to interpolate: # throws IndexError if there are indices out of range in pts # let's consider x the first and y the second dimention import numpy as np # integer indices ipts = np.floor(pts).astype(int) # fractional indices fpts = pts - ipts # workaround for the case some index equals the last valid index in the respective dimension fpts[0][ipts[0]>=f.shape[0]-1] += 1 ipts[0][ipts[0]>=f.shape[0]-1] -= 1 fpts[1][ipts[1]>=f.shape[1]-1] += 1 ipts[1][ipts[1]>=f.shape[1]-1] -= 1 I = ipts.copy() Ix = ipts.copy() Ix[0] += 1 Iy = ipts.copy() Iy[1] += 1 Ixy = Ix.copy() Ixy[1] += 1 a = f[I[0], I[1]] b = f[Ix[0], Ix[1]] - a c = f[Iy[0], Iy[1]] - a e = f[Ixy[0], Ixy[1]] - a - b - c return a + b*fpts[0] + c*fpts[1] + e*fpts[0]*fpts[1] def iainterpollin3D(ff, pts): # ff - tri dimentional image # pts - array (3xN) of points to interpolate: # throws IndexError if there are indices out of range in pts # let's consider x the first dimension, y the second and z the third import numpy as np # integer indices ipts = np.floor(pts).astype(int) # fractional indices fpts = pts - ipts # workaround for the case some index equals the last valid index in the respective dimension fpts[0][ipts[0]>=ff.shape[0]-1] += 1 ipts[0][ipts[0]>=ff.shape[0]-1] -= 1 fpts[1][ipts[1]>=ff.shape[1]-1] += 1 ipts[1][ipts[1]>=ff.shape[1]-1] -= 1 fpts[2][ipts[2]>=ff.shape[2]-1] += 1 ipts[2][ipts[2]>=ff.shape[2]-1] -= 1 I = ipts.copy() Ix = ipts.copy() Ix[0] += 1 Iy = ipts.copy() Iy[1] += 1 Iz = ipts.copy() Iz[2] += 1 Ixy = Ix.copy() Ixy[1] += 1 Ixz = Ix.copy() Ixz[2] += 1 Iyz = Iy.copy() Iyz[2] += 1 Ixyz = Ixy.copy() Ixyz[2] += 1 a = ff[I[0], I[1], I[2]] b = ff[Ix[0], Ix[1], Ix[2]] - a c = ff[Iy[0], Iy[1], Iy[2]] - a d = ff[Iz[0], Iz[1], Iz[2]] - a e = ff[Ixy[0], Ixy[1], Ixy[2]] - a - b - c f = ff[Ixz[0], Ixz[1], Ixz[2]] - a - b - d g = ff[Iyz[0], Iyz[1], Iyz[2]] - a - c - d h = ff[Ixyz[0], Ixyz[1], Ixyz[2]] - a - b - c - d - e - f - g return a + b*fpts[0] + c*fpts[1] + d*fpts[2] + e*fpts[0]*fpts[1] + f*fpts[0]*fpts[2] + g*fpts[1]*fpts[2] + h*fpts[0]*fpts[1]*fpts[2]
intbizth/balltoro-mobile
app/controllers/nologin/index.js
<gh_stars>0 var loaded = false; var args = {}; var openedWindow = false; var slider = { initialize : function() { var height = parseInt(Ti.Platform.displayCaps.platformHeight - 160); if (Alloy.Globals.isIos7Plus) { height = height - 20; } $.contentTop.height = height; $.slider.height = height; }, addView : function(view) { if ($.slider.views.length >= 10) { return; } $.slider.addView(view); $.slider.showPagingControl = !($.slider.views.length == 1); }, removeView : function(view) { $.slider.removeView(view); $.slider.showPagingControl = !($.slider.views.length == 1); }, removeAllView : function() { if ($.slider.views.length <= 1) { return; } var views = $.slider.views.reverse(); for (var i in views) { if (views[i].toString() !== '[object sliderMain]') { $.slider.removeView(views[i]); } } $.slider.showPagingControl = !($.slider.views.length == 1); }, test : function() { var random = _.random(1, 100); for (var i = 1; i <= random; i++) { var view = Ti.UI.createView({ id : 'slideView' + i, backgroundColor : Vendor.Tinycolor.random().toHexString() }); var color = Vendor.Tinycolor(view.backgroundColor); color = color.spin(Vendor.Chance.integer({ min : -360, max : 360 })).toString(); var label = Ti.UI.createLabel({ text : i, color : color, font : { fontSize : 60 } }); view.add(label); slider.addView(view); Ti.API.info('slider addView:', i); } Ti.API.info('slider total:', $.slider.views.length); _.delay(function() { var random = _.random(0, 1); if (random === 0) { var random = _.random(1, 100); for (var i = 1; i <= random; i++) { if ($.slider.views.length > 0) { var views = _.shuffle($.slider.views); if (views[0].toString() !== '[object sliderMain]') { slider.removeView(views[0]); Ti.API.info('slider removeView:', views[0].toString()); } } } } else if (random === 1) { slider.removeAllView(); Ti.API.info('slider removeAllView'); } Ti.API.info('slider total:', $.slider.views.length); _.delay(function() { slider.test(); }, 2000); }, 6000); }, }; function loadEvent() { $.registerButton.addEventListener('click', function(e) { if (openedWindow) { return; } openedWindow = true; $.navigation.openWindow($.registerWindow.getView()); $.registerWindow.getView().addEventListener('close', function(e) { openedWindow = false; }); }); $.signinButton.addEventListener('click', function(e) { if (openedWindow) { return; } openedWindow = true; $.navigation.openWindow($.signinWindow.getView()); $.signinWindow.getView().addEventListener('close', function(e) { openedWindow = false; }); }); $.signinWithFacebookButton.addEventListener('click', function(e) { Ti.API.error('Alloy.Facebook.loggedIn', typeof Alloy.Facebook.loggedIn, Alloy.Facebook.loggedIn); if (!Alloy.Facebook.loggedIn) { Alloy.Facebook.authorize(); } else { Alloy.Facebook.logout(); } }); }; function unLoadEvent() { $.registerButton.removeEventListener('click', function(e) { }); $.signinButton.removeEventListener('click', function(e) { }); $.signinWithFacebookButton.removeEventListener('click', function(e) { }); }; function initialize() { Alloy.Facebook.permissions = ['publish_stream', 'read_stream']; Alloy.Facebook.addEventListener('login', function(e) { if (e.success) { alert('login from uid: ' + e.uid + ', name: ' + JSON.parse(e.data).name); } else if (e.cancelled) { // user cancelled alert('cancelled'); } else { alert(e.error); } }); Alloy.Facebook.addEventListener('logout', function(e) { alert('Logged out'); }); $.main.addEventListener('open', function() { load(); Alloy.Globals.nologin.stackWindows.push($.main); }); $.main.addEventListener('close', function() { unLoad(); Alloy.Globals.nologin.stackWindows.pop(); }); $.logoImage.width = Ti.Platform.displayCaps.platformWidth * 0.40; $.logoImage.height = $.logoImage.width; // >> button // > register button $.registerLabel.act = function() { this.opacity = this.opacityAct; }; $.registerLabel.inact = function() { this.opacity = this.opacityInAct; }; $.registerButton.addEventListener('touchstart', function() { $.registerLabel.act(); }); $.registerButton.addEventListener('touchmove', function() { this.fireEvent('touchstart'); }); $.registerButton.addEventListener('touchend', function() { $.registerLabel.inact(); }); $.registerButton.addEventListener('touchcancel', function() { this.fireEvent('touchend'); }); // < register button // > signin button $.signinLabel.act = function() { this.opacity = this.opacityAct; }; $.signinLabel.inact = function() { this.opacity = this.opacityInAct; }; $.signinButton.addEventListener('touchstart', function() { $.signinLabel.act(); }); $.signinButton.addEventListener('touchmove', function() { this.fireEvent('touchstart'); }); $.signinButton.addEventListener('touchend', function() { $.signinLabel.inact(); }); $.signinButton.addEventListener('touchcancel', function() { this.fireEvent('touchend'); }); // < signin button // > signin with facebook button $.signinWithFacebookSubButton.act = function() { this.opacity = this.opacityAct; }; $.signinWithFacebookSubButton.inact = function() { this.opacity = this.opacityInAct; }; $.signinWithFacebookButton.addEventListener('touchstart', function() { $.signinWithFacebookSubButton.act(); }); $.signinWithFacebookButton.addEventListener('touchmove', function() { this.fireEvent('touchstart'); }); $.signinWithFacebookButton.addEventListener('touchend', function() { $.signinWithFacebookSubButton.inact(); }); $.signinWithFacebookButton.addEventListener('touchcancel', function() { this.fireEvent('touchend'); }); // < signin with facebook button // << button slider.initialize(); // slider.test(); }; function load() { loaded = true; openedWindow = false; loadEvent(); Ti.API.debug($.main.name + ':load'); }; function unLoad() { loaded = false; openedWindow = false; unLoadEvent(); Ti.API.debug($.main.name + ':unLoad'); }; exports.getLoad = function() { return loaded; }; exports.load = function() { load(); }; exports.unLoad = function() { unLoad(); }; exports.setArgs = function(value) { args = value; }; initialize();
yummic/CodeBase
java/Foo-with-springboot/src/main/java/fun/clclcl/yummic/codebase/leetcode/LeetCode1023.java
package fun.clclcl.yummic.codebase.leetcode; import java.util.ArrayList; import java.util.List; public class LeetCode1023 { public List<Boolean> camelMatch(String[] queries, String pattern) { List<Boolean> result = new ArrayList<>(); for (String query : queries) { boolean match = match(query, pattern); result.add(match); } return result; } private boolean match(String query, String pattern) { int i = 0, j =0; while (i < query.length() && j < pattern.length()) { char q = query.charAt(i); char p = pattern.charAt(j); if (!isUpperLetter(q)) { if (p == q){ i++; j++; continue; } else { i++; continue; } } else { if (q == p) { i++; j++; continue; } else { break;// not match. } } } if (i == query.length() -1 && j == pattern.length() -1) { return true; } else if (j == pattern.length()){ while (i < query.length()) { if (isUpperLetter(query.charAt(i))) { return false; } i++; } return true; } return false; } private boolean isUpperLetter(char charAt) { return charAt >= 'A' && charAt <= 'Z'; } }
stackprobe/Spica01
charlotte/tools/DateTimeUnit.java
package charlotte.tools; import java.util.List; /** * sec == second of A.D. * second == second of minute * day == day of month * dayOfAD == day of A.D. * */ public class DateTimeUnit { private int _y; private int _m; private int _d; private int _h; private int _i; private int _s; public static DateTimeUnit fromDayOfAD(int dayOfAD) { return fromSec(dayOfAD * 86400L); } public static DateTimeUnit fromDate(int date) { return fromDateTime(date * 1000000L); } public static DateTimeUnit now() { return fromDateTime(DateTimeToSec.Now.getDateTime()); } public static DateTimeUnit fromSec(long sec) { return fromDateTime(DateTimeToSec.Allow11To13Dig.toDateTime(sec)); } public static DateTimeUnit fromDateTime(long dateTime) { int s =(int)(dateTime % 100L); dateTime /= 100L; int i =(int)(dateTime % 100L); dateTime /= 100L; int h =(int)(dateTime % 100L); dateTime /= 100L; int d =(int)(dateTime % 100L); dateTime /= 100L; int m =(int)(dateTime % 100L); int y =(int)(dateTime / 100L); return new DateTimeUnit(y, m, d, h, i, s); } public DateTimeUnit(int y, int m, int d, int h, int i, int s) { _y = y; _m = m; _d = d; _h = h; _i = i; _s = s; } public int getYear() { return _y; } public DateTimeUnit changeYear(int y) { return new DateTimeUnit(y, _m, _d, _h, _i, _s); } public int getMonth() { return _m; } public DateTimeUnit changeMonth(int m) { return new DateTimeUnit(_y, m, _d, _h, _i, _s); } public int getDay() { return _d; } public DateTimeUnit changeDay(int d) { return new DateTimeUnit(_y, _m, d, _h, _i, _s); } public int getHour() { return _h; } public DateTimeUnit changeHour(int h) { return new DateTimeUnit(_y, _m, _d, h, _i, _s); } public int getMinute() { return _i; } public DateTimeUnit changeMinute(int i) { return new DateTimeUnit(_y, _m, _d, _h, i, _s); } public int getSecond() { return _s; } public DateTimeUnit changeSecond(int s) { return new DateTimeUnit(_y, _m, _d, _h, _i, s); } public long getDateTime() { return _y * 10000000000L + _m * 100000000L + _d * 1000000L + _h * 10000L + _i * 100L + _s; } public long getSec() { return DateTimeToSec.Allow11To13Dig.toSec(getDateTime()); } public int getDate() { return (int)(getDateTime() / 1000000L); } public int getDayOfAD() { return (int)(getSec() / 86400L); } public int getWeekdayIndex() { return getDayOfAD() % 7; } private static final String J_WEEK = "月火水木金土日"; // orig: private static final String J_WEEK = "\u6708\u706b\u6c34\u6728\u91d1\u571f\u65e5"; public String getWeekday() { return new String(new char[] { J_WEEK.charAt(getWeekdayIndex()) }); } @Override public String toString() { return toString("Y/M/D (W) h:m:s"); } public String toString(String format) { String ret = format; ret = ret.replace("Y", String.format("%04d", _y)); ret = ret.replace("M", String.format("%02d", _m)); ret = ret.replace("D", String.format("%02d", _d)); ret = ret.replace("h", String.format("%02d", _h)); ret = ret.replace("m", String.format("%02d", _i)); ret = ret.replace("s", String.format("%02d", _s)); ret = ret.replace("W", getWeekday()); return ret; } public static DateTimeUnit fromString(String str) { List<String> tokens = StringTools.tokenize(str, StringTools.DECIMAL, true, true); if(tokens.size() == 1) { String token = tokens.get(0); if(token.length() == 8) { return fromDate(Integer.parseInt(token)); } if(token.length() == 14) { return fromDateTime(Long.parseLong(token)); } } else if(tokens.size() == 3) { int y = Integer.parseInt(tokens.get(0)); int m = Integer.parseInt(tokens.get(1)); int d = Integer.parseInt(tokens.get(2)); return new DateTimeUnit(y, m, d, 0, 0, 0); } else if(tokens.size() == 6 || tokens.size() == 7) { // ? oracle '2015-02-10 00:00:00.0' int y = Integer.parseInt(tokens.get(0)); int m = Integer.parseInt(tokens.get(1)); int d = Integer.parseInt(tokens.get(2)); int h = Integer.parseInt(tokens.get(3)); int i = Integer.parseInt(tokens.get(4)); int s = Integer.parseInt(tokens.get(5)); return new DateTimeUnit(y, m, d, h, i, s); } throw new IllegalArgumentException(str); } }
dainst/cilantro
workers/default/repository/tasks.py
import os import shutil import glob from utils.celery_client import celery_app from workers.base_task import BaseTask, ObjectTask from utils.repository import generate_repository_path from utils.job_db import JobDb from utils import cilantro_info_file repository_dir = os.environ['REPOSITORY_DIR'] archive_dir = os.environ['ARCHIVE_DIR'] working_dir = os.environ['WORKING_DIR'] staging_dir = os.environ['STAGING_DIR'] filename_extension_mapping = { 'pdf': ['**/*.pdf', '**/*.PDF'], 'tif': ['**/*.tif', '**/*.tiff', '**/*.TIF', '**/*.TIFF'], 'txt': ['**/*.txt', '**/*.TXT'] } class CreateObjectTask(ObjectTask): """ Create a Cilantro-Object, the metadatas and the data files in it. Preconditions: -files in staging Creates: -An Object in the working dir """ name = "create_object" def process_object(self, obj): oid = self._generate_object_id() self.job_db.set_job_object_id(self.parent_job_id, oid) staging_directory = os.path.join( staging_dir, self.params['user'], self.params['path'] ) cilantro_info_file.write_processing_started(staging_directory, self.parent_job_id) self._initialize_object(obj, self.params, oid) return {'object_id': oid} def _generate_object_id(self): part_a = self.get_param('id') part_b = self.job_db.get_next_unique_object_id_suffix() return f"{part_a}_{part_b}" def _initialize_object(self, obj, params, oid): obj.id = oid obj.metadata = params['metadata'] self._initialize_files(obj, params['path'], params['user'], params['initial_representation']) obj.write() def _initialize_files(self, obj, path, user, init_rep): files_grabbed = [] for files in filename_extension_mapping[init_rep]: files_grabbed.extend(glob.glob( os.path.join(staging_dir, user, path, files), recursive=True )) if len(files_grabbed) < 1: raise Exception(f'no valid job files found in {path}') for file_name in files_grabbed: obj.add_file(init_rep, file_name) CreateObjectTask = celery_app.register_task(CreateObjectTask()) class CreateComplexObjectTask(ObjectTask): name = "create_complex_object" def process_object(self, obj): oid = self._generate_object_id() self.job_db.set_job_object_id(self.parent_job_id, oid) object_staging_path = os.path.join( staging_dir, self.params['user'], self.params['path'] ) cilantro_info_file.write_processing_started(object_staging_path, self.parent_job_id) self._initialize_object(obj, self.params, oid) return {'object_id': oid} def _initialize_object(self, obj, params, oid): obj.id = oid obj.metadata = params['metadata'] self._initialize_files(obj, params['path'], params['user'], params['copy_instructions']) obj.write() def _initialize_files(self, obj, path, user, copy_instructions): self.log.error("Copying files") self.log.error(copy_instructions) for source_dir, (target_dir, pattern) in copy_instructions.items(): glob_path = os.path.join(staging_dir, user, path, source_dir, pattern) files_grabbed = glob.glob(glob_path) if len(files_grabbed) == 0: raise Exception((f"no valid file found in {glob_path}.")) for file_name in files_grabbed: obj.add_file(target_dir, file_name) def _generate_object_id(self): part_a = self.get_param('id') part_b = self.job_db.get_next_unique_object_id_suffix() return f"{part_a}_{part_b}" CreateComplexObjectTask = celery_app.register_task(CreateComplexObjectTask()) def _get_work_path(params): abs_path = os.path.join(working_dir, params['work_path']) if not os.path.exists(abs_path): os.mkdir(abs_path) return abs_path class PublishToRepositoryTask(BaseTask): """ Copy the given dir-trees from work dir to the repository. TaskParams: Preconditions: Creates: -a copy of the work dir in the repository. """ name = "publish_to_repository" def execute_task(self): work_path = self.get_work_path() repository_path = os.path.join(repository_dir, generate_repository_path( self.get_result('object_id'))) shutil.rmtree(repository_path, ignore_errors=True) shutil.copytree(os.path.join(work_path, 'data', 'pdf'), os.path.join(repository_path, 'data', 'pdf')) shutil.copytree(os.path.join(work_path, 'data', 'jpg'), os.path.join(repository_path, 'data', 'jpg')) shutil.copy(os.path.join(work_path, 'meta.json'), repository_path) shutil.copy(os.path.join(work_path, 'mets.xml'), repository_path) PublishToRepositoryTask = celery_app.register_task(PublishToRepositoryTask()) class PublishToArchiveTask(BaseTask): """Copy the given dir-trees from work dir to the archive.""" name = "publish_to_archive" def execute_task(self): work_path = self.get_work_path() archive_path = os.path.join(archive_dir, generate_repository_path( self.get_result('object_id'))) shutil.rmtree(archive_path, ignore_errors=True) shutil.copytree(work_path, archive_path) PublishToArchiveTask = celery_app.register_task(PublishToArchiveTask())
thunder-/paprika
paprika/repositories/ProcessActionPropertyRepository.py
from paprika.repositories.Repository import Repository from paprika.connectors.Helper import Helper from datetime import datetime from datetime import timedelta class ProcessActionPropertyRepository(Repository): def __init__(self, connector): Repository.__init__(self, connector) def insert(self, process_action_property): connection = self.get_connection() cursor = connection.cursor() params = dict() params['pan_id'] = process_action_property['pan_id'] params['name'] = process_action_property['name'] params['value'] = process_action_property['value'] statement = "insert into processes_actions_properties(pan_id, name, value) values (:pan_id, :name, :value)" statement, parameters = self.statement(statement, params) cursor.execute(statement, parameters) process_action_property['id'] = cursor.lastrowid connection.commit() return process_action_property def update(self, process_action_property): connection = self.get_connection() cursor = connection.cursor() params = dict() params['value'] = process_action_property['value'] params['pan_id'] = process_action_property['pan_id'] params['name'] = process_action_property['name'] statement = "update processes_actions_properties set value = :value where pan_id = :pan_id and name = :name" statement, parameters = self.statement(statement, params) cursor.execute(statement, parameters) connection.commit() def get_property(self, process_action, name, default_value=None): connection = self.get_connection() cursor = connection.cursor() params = dict() params['pan_id'] = process_action['id'] params['name'] = name statement = "select value from processes_actions_properties where pan_id = :pan_id and name = :name" statement, parameters = self.statement(statement, params) cursor.execute(statement, parameters) result = Helper.cursor_to_json(cursor) # if the default_value holds a value, than return this values if no value is found. if len(result) == 0: if default_value: return default_value return None return result[0]['value'] def set_property(self, process_action, name, value): params = dict() params['pan_id'] = process_action['id'] params['name'] = name params['value'] = value if self.get_property(process_action, name): self.update(params) else: self.insert(params) def clean(self, days): connection = self.get_connection() cursor = connection.cursor() statement = "delete from processes_actions_properties where created_at <:created_at" now = datetime.now() window = now - timedelta(days=int(days)) created_at = window.strftime('%Y-%m-%d %H:%M:%S') param = dict() param['created_at'] = created_at statement, parameters = self.statement(statement, param) cursor.execute(statement, parameters) count = cursor.rowcount cursor.close() connection.commit() return count
cham11ng/lets-express-api
src/validators/postValidator.js
import Joi from 'joi'; import validate from '../utils/validate'; import * as postService from '../services/postService'; const SCHEMA = { title: Joi.string() .label('Title') .max(120) .required(), body: Joi.string() .label('Body') .required(), userId: Joi.number() .integer() .label('User') .required(), tags: Joi.array() .items(Joi.number()) .label('User') .required() }; const EDIT_SCHEMA = { title: Joi.string() .label('Title') .max(120) .required(), body: Joi.string() .label('Body') .required(), tags: Joi.array() .items(Joi.number()) .label('User') .required() }; /** * Validate create/update post request. * * @param {object} request * @param {object} response * @param {function} next * @return {Promise} */ export function postValidator(request, response, next) { return validate(request.body, SCHEMA) .then(() => next()) .catch(err => next(err)); } /** * Validate create/update post request. * * @param {object} request * @param {object} response * @param {function} next * @return {Promise} */ export function editValidator(request, response, next) { return validate(request.body, EDIT_SCHEMA) .then(() => next()) .catch(err => next(err)); } /** * Validate posts existence. * * @param {object} request * @param {object} response * @param {function} next * @return {Promise} */ export function findPost(request, response, next) { return postService .getPost(request.params.id) .then(() => next()) .catch(err => next(err)); }
lobotmcj/johann
johann/celeryconfig.py
<reponame>lobotmcj/johann # Copyright (c) 2019-present, The Johann Authors. All Rights Reserved. # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE file. See the AUTHORS file for names of contributors. from johann.shared.config import JohannConfig config = JohannConfig.get_config() broker_url = config.REDIS_URL result_backend = config.REDIS_URL task_track_started = True
SBI-/rtc-git-connector-service
test/src/test/java/org/jazzcommunity/GitConnectorService/ccm/oslc/mapping/IssueMapperTest.java
<gh_stars>1-10 package org.jazzcommunity.GitConnectorService.ccm.oslc.mapping; import ch.sbi.minigit.type.gitlab.issue.Issue; import com.google.gson.Gson; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import org.apache.commons.lang3.builder.EqualsBuilder; import org.jazzcommunity.GitConnectorService.olsc.type.issue.DctermsContributor; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmAssignee; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmAssignee_; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmAuthor; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmClosedBy; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmLinks; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmMilestone; import org.jazzcommunity.GitConnectorService.olsc.type.issue.GitCmTimeStats; import org.jazzcommunity.GitConnectorService.olsc.type.issue.OslcIssue; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.format.DateTimeFormatter; public class IssueMapperTest { private OslcIssue oslcIssue; @Test public void checkDcTermsContributorIsAuthor() { ArrayList<Object> types = new ArrayList<>(); types.add("http://xmlns.com/foaf/0.1/Person"); DctermsContributor expected = new DctermsContributor(); expected.setRdfType(types); expected.setFoafName("User 2"); expected.setRdfAbout("https://git.lab/user.2"); Assert.assertEquals(expected.getFoafName(), oslcIssue.getDctermsContributor().getFoafName()); Assert.assertEquals(expected.getRdfAbout(), oslcIssue.getDctermsContributor().getRdfAbout()); } @Test public void checkAssigneeMapping() { GitCmAssignee expected = new GitCmAssignee(); expected.setId(115); expected.setName("User 1 user1"); expected.setUsername("user.1"); expected.setState("active"); expected.setAvatarUrl("https://repo.git.com/uploads/-/system/user/avatar/115/avatar.png"); expected.setWebUrl("https://git.lab/user.1"); GitCmAssignee assignee = oslcIssue.getGitCmAssignee(); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, assignee)); } @Test public void checkAssigneesMapping() { GitCmAssignee_ expected = new GitCmAssignee_(); expected.setId(115); expected.setName("User 1 user1"); expected.setUsername("user.1"); expected.setState("active"); expected.setAvatarUrl("https://repo.git.com/uploads/-/system/user/avatar/115/avatar.png"); expected.setWebUrl("https://git.lab/user.1"); // in gitlab ce, assignees is always a collection of at most one user, // which is why this test currently only checks for a single assignee. Assert.assertNotNull(oslcIssue.getGitCmAssignees()); Assert.assertFalse(oslcIssue.getGitCmAssignees().isEmpty()); Assert.assertNotNull(oslcIssue.getGitCmAssignees().get(0)); GitCmAssignee_ assignee = oslcIssue.getGitCmAssignees().get(0); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, assignee)); } @Test public void checkMilestoneMapping() { GitCmMilestone expected = new GitCmMilestone(); expected.setId(5607); expected.setIid(1); expected.setProjectId(13027); expected.setTitle("Unit testing milestone"); expected.setDescription("This is a milestone for unit testing."); expected.setState("active"); expected.setCreatedAt("2018-06-05T16:19:05.023+02:00"); expected.setUpdatedAt("2018-06-05T16:19:05.023+02:00"); expected.setDueDate("2019-06-01"); expected.setStartDate("2018-06-01"); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, oslcIssue.getGitCmMilestone())); } @Test public void checkAuthorMapping() { GitCmAuthor expected = new GitCmAuthor(); expected.setId(150); expected.setName("User 2"); expected.setUsername("user.2"); expected.setState("active"); expected.setAvatarUrl(null); expected.setWebUrl("https://git.lab/user.2"); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, oslcIssue.getGitCmAuthor())); } @Test public void checkCmTimeStats() { Assert.assertEquals(Integer.valueOf(0), oslcIssue.getRtcCmEstimate()); Assert.assertEquals(Integer.valueOf(3600 * 1000), oslcIssue.getRtcCmTimeSpent()); } @Test public void checkGitLabTimeStats() { GitCmTimeStats expected = new GitCmTimeStats(); expected.setTimeEstimate(0); expected.setTotalTimeSpent(3600); expected.setHumanTimeEstimate(null); expected.setHumanTotalTimeSpent("1h"); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, oslcIssue.getGitCmTimeStats())); } @Test public void checkDueDateIsUtc() { ZonedDateTime expected = ZonedDateTime.parse("2018-09-29T00:00:00Z", DateTimeFormatter.ISO_OFFSET_DATE_TIME); Assert.assertEquals(expected.toString(), oslcIssue.getRtcCmDue()); } @Test public void checkLinks() { GitCmLinks expected = new GitCmLinks(); expected.setSelf("https://git.lab/api/v4/projects/13027/issues/9"); expected.setNotes("https://git.lab/api/v4/projects/13027/issues/9/notes"); expected.setAwardEmoji("https://git.lab/api/v4/projects/13027/issues/9/award_emoji"); expected.setProject("https://git.lab/api/v4/projects/13027"); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, oslcIssue.getGitCmLinks())); } @Test public void checkPrefixes() { Assert.assertNotNull(oslcIssue.getPrefixes().getGitCm()); Assert.assertNotNull(oslcIssue.getPrefixes().getRtcCm()); Assert.assertNotNull(oslcIssue.getPrefixes().getRdf()); Assert.assertNotNull(oslcIssue.getPrefixes().getDcterms()); Assert.assertNotNull(oslcIssue.getPrefixes().getOslc()); Assert.assertNotNull(oslcIssue.getPrefixes().getOslcCm()); } @Test public void checkSubscribed() { Assert.assertTrue(oslcIssue.getGitCmSubscribed()); } @Test public void checkWebUrl() { Assert.assertEquals( "https://git.lab/user.1/unit-test-project/issues/9", oslcIssue.getGitCmWebUrl()); } @Test public void checkConfidential() { Assert.assertFalse(oslcIssue.getGitCmConfidential()); } @Test public void checkVoteStats() { Assert.assertEquals(new Integer(0), oslcIssue.getGitCmUpvotes()); Assert.assertEquals(new Integer(0), oslcIssue.getGitCmDownvotes()); } @Test public void checkUserNotesCount() { Assert.assertEquals(new Integer(6), oslcIssue.getGitCmUserNotesCount()); } @Test public void checkClosedAt() { Assert.assertEquals("2018-06-08T15:28:20.376+02:00", oslcIssue.getGitCmClosedAt()); } @Test public void checkClosedBy() { Assert.assertTrue(oslcIssue.getOslcCmClosed()); Assert.assertNotNull(oslcIssue.getGitCmClosedBy()); GitCmClosedBy expected = new GitCmClosedBy(); expected.setId(150); expected.setName("User 2"); expected.setUsername("user.2"); expected.setState("active"); expected.setAvatarUrl(null); expected.setWebUrl("https://git.lab/user.2"); Assert.assertTrue(EqualsBuilder.reflectionEquals(expected, oslcIssue.getGitCmClosedBy())); } @Test public void checkProjectId() { Assert.assertEquals(new Integer(13027), oslcIssue.getGitCmProjectId()); } @Test public void checkShortTitle() { Assert.assertEquals("Issue 9", oslcIssue.getOslcShortTitle()); } @Test public void checkGitCmIds() { Assert.assertEquals(new Integer(81560), oslcIssue.getGitCmId()); Assert.assertEquals(new Integer(9), oslcIssue.getGitCmIid()); } @Test public void checkDcTermsIdentifier() { Assert.assertEquals("81560", oslcIssue.getDctermsIdentifier()); } @Test public void checkShortIdMapping() { Assert.assertEquals("9", oslcIssue.getOslcShortId()); } @Test public void checkStateMapping() { Assert.assertEquals("opened", oslcIssue.getOslcCmStatus()); Assert.assertEquals("opened", oslcIssue.getGitCmState()); } @Test public void checkCmClosedMapsToClosedAt() { Assert.assertNotNull(oslcIssue.getGitCmClosedAt()); Assert.assertTrue(oslcIssue.getOslcCmClosed()); } @Test public void checkUtcDateTimeMapping() { ZonedDateTime created = ZonedDateTime.parse( "2018-03-13T15:24:48.339+01:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME); ZonedDateTime modified = ZonedDateTime.parse( "2018-06-04T15:28:20.376+02:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME); ZonedDateTime closed = ZonedDateTime.parse( "2018-06-08T15:28:20.376+02:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME); Assert.assertEquals(created.toString(), oslcIssue.getDctermsCreated()); Assert.assertEquals(created.toString(), oslcIssue.getGitCmCreatedAt()); Assert.assertEquals(modified.toString(), oslcIssue.getDctermsModified()); Assert.assertEquals(modified.toString(), oslcIssue.getGitCmUpdatedAt()); Assert.assertEquals(closed.toString(), oslcIssue.getGitCmClosedAt()); } @Test public void checkAboutIsUrl() { Assert.assertEquals("http://link-to-myself.ch", oslcIssue.getRdfAbout()); } @Test public void checkLabelsAreMapped() { String[] strings = {"Label1", "Label2"}; Assert.assertArrayEquals(strings, oslcIssue.getGitCmLabels().toArray()); } @Test public void checkSubjectIsCommaSeparatedString() { Assert.assertEquals("Label1, Label2", oslcIssue.getDctermsSubject()); } @Test public void checkDescriptionIsMapped() { Assert.assertEquals( "This issue is used in rtc-git-connector-service unit tests", oslcIssue.getDctermsDescription()); Assert.assertEquals( "This issue is used in rtc-git-connector-service unit tests", oslcIssue.getGitCmDescription()); } @Test public void checkTypeIsIssue() { Assert.assertEquals("Issue", oslcIssue.getDctermsType()); } @Test public void checkTitlesAreMapped() { Assert.assertEquals("Unit Test Issue", oslcIssue.getGitCmTitle()); Assert.assertEquals("Unit Test Issue", oslcIssue.getDctermsTitle()); } @Before public void makeIssue() throws IOException { String json = "{\n" + " \"id\": 81560,\n" + " \"iid\": 9,\n" + " \"project_id\": 13027,\n" + " \"title\": \"Unit Test Issue\",\n" + " \"description\": \"This issue is used in rtc-git-connector-service unit tests\",\n" + " \"state\": \"opened\",\n" + " \"created_at\": \"2018-03-13T15:24:48.339+01:00\",\n" + " \"updated_at\": \"2018-06-04T15:28:20.376+02:00\",\n" + " \"closed_at\": \"2018-06-08T15:28:20.376+02:00\",\n" + " \"closed_by\": {\n" + " \"id\": 150,\n" + " \"name\": \"User 2\",\n" + " \"username\": \"user.2\",\n" + " \"state\": \"active\",\n" + " \"avatar_url\": null,\n" + " \"web_url\": \"https://git.lab/user.2\"\n" + " },\n" + " \"labels\": [\n" + " \"Label1\",\n" + " \"Label2\"\n" + " ],\n" + " \"milestone\": {\n" + " \"id\": 5607,\n" + " \"iid\": 1,\n" + " \"project_id\": 13027,\n" + " \"title\": \"Unit testing milestone\",\n" + " \"description\": \"This is a milestone for unit testing.\",\n" + " \"state\": \"active\",\n" + " \"created_at\": \"2018-06-05T16:19:05.023+02:00\",\n" + " \"updated_at\": \"2018-06-05T16:19:05.023+02:00\",\n" + " \"due_date\": \"2019-06-01\",\n" + " \"start_date\": \"2018-06-01\"\n" + " },\n" + " \"assignees\": [\n" + " {\n" + " \"id\": 115,\n" + " \"name\": \"User 1 user1\",\n" + " \"username\": \"user.1\",\n" + " \"state\": \"active\",\n" + " \"avatar_url\": \"https://repo.git.com/uploads/-/system/user/avatar/115/avatar.png\",\n" + " \"web_url\": \"https://git.lab/user.1\"\n" + " }\n" + " ],\n" + " \"author\": {\n" + " \"id\": 150,\n" + " \"name\": \"User 2\",\n" + " \"username\": \"user.2\",\n" + " \"state\": \"active\",\n" + " \"avatar_url\": null,\n" + " \"web_url\": \"https://git.lab/user.2\"\n" + " },\n" + " \"assignee\": {\n" + " \"id\": 115,\n" + " \"name\": \"User 1 user1\",\n" + " \"username\": \"user.1\",\n" + " \"state\": \"active\",\n" + " \"avatar_url\": \"https://repo.git.com/uploads/-/system/user/avatar/115/avatar.png\",\n" + " \"web_url\": \"https://git.lab/user.1\"\n" + " },\n" + " \"user_notes_count\": 6,\n" + " \"upvotes\": 0,\n" + " \"downvotes\": 0,\n" + " \"due_date\": \"2018-09-29\",\n" + " \"confidential\": false,\n" + " \"discussion_locked\": null,\n" + " \"web_url\": \"https://git.lab/user.1/unit-test-project/issues/9\",\n" + " \"time_stats\": {\n" + " \"time_estimate\": 0,\n" + " \"total_time_spent\": 3600,\n" + " \"human_time_estimate\": null,\n" + " \"human_total_time_spent\": \"1h\"\n" + " },\n" + " \"_links\": {\n" + " \"self\": \"https://git.lab/api/v4/projects/13027/issues/9\",\n" + " \"notes\": \"https://git.lab/api/v4/projects/13027/issues/9/notes\",\n" + " \"award_emoji\": \"https://git.lab/api/v4/projects/13027/issues/9/award_emoji\",\n" + " \"project\": \"https://git.lab/api/v4/projects/13027\"\n" + " },\n" + " \"subscribed\": true\n" + "}\n"; Issue issue = new Gson().fromJson(json, Issue.class); this.oslcIssue = IssueMapper.map( issue, new URL("http://link-to-myself.ch"), "https://localhost:7443/jazz/web/"); } }
freman/genesysapi
client/external_contacts/post_externalcontacts_bulk_contacts_update_responses.go
<gh_stars>0 // Code generated by go-swagger; DO NOT EDIT. package external_contacts // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/freman/genesysapi/models" ) // PostExternalcontactsBulkContactsUpdateReader is a Reader for the PostExternalcontactsBulkContactsUpdate structure. type PostExternalcontactsBulkContactsUpdateReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *PostExternalcontactsBulkContactsUpdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPostExternalcontactsBulkContactsUpdateOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPostExternalcontactsBulkContactsUpdateBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 401: result := NewPostExternalcontactsBulkContactsUpdateUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 403: result := NewPostExternalcontactsBulkContactsUpdateForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewPostExternalcontactsBulkContactsUpdateNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 408: result := NewPostExternalcontactsBulkContactsUpdateRequestTimeout() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 413: result := NewPostExternalcontactsBulkContactsUpdateRequestEntityTooLarge() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 415: result := NewPostExternalcontactsBulkContactsUpdateUnsupportedMediaType() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 422: result := NewPostExternalcontactsBulkContactsUpdateUnprocessableEntity() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 429: result := NewPostExternalcontactsBulkContactsUpdateTooManyRequests() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewPostExternalcontactsBulkContactsUpdateInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 503: result := NewPostExternalcontactsBulkContactsUpdateServiceUnavailable() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 504: result := NewPostExternalcontactsBulkContactsUpdateGatewayTimeout() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) } } // NewPostExternalcontactsBulkContactsUpdateOK creates a PostExternalcontactsBulkContactsUpdateOK with default headers values func NewPostExternalcontactsBulkContactsUpdateOK() *PostExternalcontactsBulkContactsUpdateOK { return &PostExternalcontactsBulkContactsUpdateOK{} } /*PostExternalcontactsBulkContactsUpdateOK handles this case with default header values. successful operation */ type PostExternalcontactsBulkContactsUpdateOK struct { Payload *models.BulkContactsResponse } func (o *PostExternalcontactsBulkContactsUpdateOK) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateOK %+v", 200, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateOK) GetPayload() *models.BulkContactsResponse { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.BulkContactsResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateBadRequest creates a PostExternalcontactsBulkContactsUpdateBadRequest with default headers values func NewPostExternalcontactsBulkContactsUpdateBadRequest() *PostExternalcontactsBulkContactsUpdateBadRequest { return &PostExternalcontactsBulkContactsUpdateBadRequest{} } /*PostExternalcontactsBulkContactsUpdateBadRequest handles this case with default header values. The request could not be understood by the server due to malformed syntax. */ type PostExternalcontactsBulkContactsUpdateBadRequest struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateBadRequest) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateBadRequest %+v", 400, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateBadRequest) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateUnauthorized creates a PostExternalcontactsBulkContactsUpdateUnauthorized with default headers values func NewPostExternalcontactsBulkContactsUpdateUnauthorized() *PostExternalcontactsBulkContactsUpdateUnauthorized { return &PostExternalcontactsBulkContactsUpdateUnauthorized{} } /*PostExternalcontactsBulkContactsUpdateUnauthorized handles this case with default header values. No authentication bearer token specified in authorization header. */ type PostExternalcontactsBulkContactsUpdateUnauthorized struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateUnauthorized) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateUnauthorized %+v", 401, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateUnauthorized) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateForbidden creates a PostExternalcontactsBulkContactsUpdateForbidden with default headers values func NewPostExternalcontactsBulkContactsUpdateForbidden() *PostExternalcontactsBulkContactsUpdateForbidden { return &PostExternalcontactsBulkContactsUpdateForbidden{} } /*PostExternalcontactsBulkContactsUpdateForbidden handles this case with default header values. You are not authorized to perform the requested action. */ type PostExternalcontactsBulkContactsUpdateForbidden struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateForbidden) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateForbidden %+v", 403, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateForbidden) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateNotFound creates a PostExternalcontactsBulkContactsUpdateNotFound with default headers values func NewPostExternalcontactsBulkContactsUpdateNotFound() *PostExternalcontactsBulkContactsUpdateNotFound { return &PostExternalcontactsBulkContactsUpdateNotFound{} } /*PostExternalcontactsBulkContactsUpdateNotFound handles this case with default header values. The requested resource was not found. */ type PostExternalcontactsBulkContactsUpdateNotFound struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateNotFound) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateNotFound %+v", 404, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateNotFound) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateRequestTimeout creates a PostExternalcontactsBulkContactsUpdateRequestTimeout with default headers values func NewPostExternalcontactsBulkContactsUpdateRequestTimeout() *PostExternalcontactsBulkContactsUpdateRequestTimeout { return &PostExternalcontactsBulkContactsUpdateRequestTimeout{} } /*PostExternalcontactsBulkContactsUpdateRequestTimeout handles this case with default header values. The client did not produce a request within the server timeout limit. This can be caused by a slow network connection and/or large payloads. */ type PostExternalcontactsBulkContactsUpdateRequestTimeout struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateRequestTimeout) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateRequestTimeout %+v", 408, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateRequestTimeout) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateRequestTimeout) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateRequestEntityTooLarge creates a PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge with default headers values func NewPostExternalcontactsBulkContactsUpdateRequestEntityTooLarge() *PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge { return &PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge{} } /*PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge handles this case with default header values. The request is over the size limit. Content-Length: %s */ type PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateRequestEntityTooLarge %+v", 413, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateRequestEntityTooLarge) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateUnsupportedMediaType creates a PostExternalcontactsBulkContactsUpdateUnsupportedMediaType with default headers values func NewPostExternalcontactsBulkContactsUpdateUnsupportedMediaType() *PostExternalcontactsBulkContactsUpdateUnsupportedMediaType { return &PostExternalcontactsBulkContactsUpdateUnsupportedMediaType{} } /*PostExternalcontactsBulkContactsUpdateUnsupportedMediaType handles this case with default header values. Unsupported Media Type - Unsupported or incorrect media type, such as an incorrect Content-Type value in the header. */ type PostExternalcontactsBulkContactsUpdateUnsupportedMediaType struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateUnsupportedMediaType) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateUnsupportedMediaType %+v", 415, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateUnsupportedMediaType) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateUnsupportedMediaType) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateUnprocessableEntity creates a PostExternalcontactsBulkContactsUpdateUnprocessableEntity with default headers values func NewPostExternalcontactsBulkContactsUpdateUnprocessableEntity() *PostExternalcontactsBulkContactsUpdateUnprocessableEntity { return &PostExternalcontactsBulkContactsUpdateUnprocessableEntity{} } /*PostExternalcontactsBulkContactsUpdateUnprocessableEntity handles this case with default header values. PostExternalcontactsBulkContactsUpdateUnprocessableEntity post externalcontacts bulk contacts update unprocessable entity */ type PostExternalcontactsBulkContactsUpdateUnprocessableEntity struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateUnprocessableEntity) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateUnprocessableEntity %+v", 422, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateUnprocessableEntity) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateTooManyRequests creates a PostExternalcontactsBulkContactsUpdateTooManyRequests with default headers values func NewPostExternalcontactsBulkContactsUpdateTooManyRequests() *PostExternalcontactsBulkContactsUpdateTooManyRequests { return &PostExternalcontactsBulkContactsUpdateTooManyRequests{} } /*PostExternalcontactsBulkContactsUpdateTooManyRequests handles this case with default header values. Rate limit exceeded the maximum. Retry the request in [%s] seconds */ type PostExternalcontactsBulkContactsUpdateTooManyRequests struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateTooManyRequests) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateTooManyRequests %+v", 429, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateTooManyRequests) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateTooManyRequests) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateInternalServerError creates a PostExternalcontactsBulkContactsUpdateInternalServerError with default headers values func NewPostExternalcontactsBulkContactsUpdateInternalServerError() *PostExternalcontactsBulkContactsUpdateInternalServerError { return &PostExternalcontactsBulkContactsUpdateInternalServerError{} } /*PostExternalcontactsBulkContactsUpdateInternalServerError handles this case with default header values. The server encountered an unexpected condition which prevented it from fulfilling the request. */ type PostExternalcontactsBulkContactsUpdateInternalServerError struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateInternalServerError) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateInternalServerError %+v", 500, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateInternalServerError) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateServiceUnavailable creates a PostExternalcontactsBulkContactsUpdateServiceUnavailable with default headers values func NewPostExternalcontactsBulkContactsUpdateServiceUnavailable() *PostExternalcontactsBulkContactsUpdateServiceUnavailable { return &PostExternalcontactsBulkContactsUpdateServiceUnavailable{} } /*PostExternalcontactsBulkContactsUpdateServiceUnavailable handles this case with default header values. Service Unavailable - The server is currently unavailable (because it is overloaded or down for maintenance). */ type PostExternalcontactsBulkContactsUpdateServiceUnavailable struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateServiceUnavailable) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateServiceUnavailable %+v", 503, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateServiceUnavailable) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewPostExternalcontactsBulkContactsUpdateGatewayTimeout creates a PostExternalcontactsBulkContactsUpdateGatewayTimeout with default headers values func NewPostExternalcontactsBulkContactsUpdateGatewayTimeout() *PostExternalcontactsBulkContactsUpdateGatewayTimeout { return &PostExternalcontactsBulkContactsUpdateGatewayTimeout{} } /*PostExternalcontactsBulkContactsUpdateGatewayTimeout handles this case with default header values. The request timed out. */ type PostExternalcontactsBulkContactsUpdateGatewayTimeout struct { Payload *models.ErrorBody } func (o *PostExternalcontactsBulkContactsUpdateGatewayTimeout) Error() string { return fmt.Sprintf("[POST /api/v2/externalcontacts/bulk/contacts/update][%d] postExternalcontactsBulkContactsUpdateGatewayTimeout %+v", 504, o.Payload) } func (o *PostExternalcontactsBulkContactsUpdateGatewayTimeout) GetPayload() *models.ErrorBody { return o.Payload } func (o *PostExternalcontactsBulkContactsUpdateGatewayTimeout) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
copslock/broadcom_cpri
sdk-6.5.20/libs/sdklt/bcmcth/ctr/eflex/bcmcth_ctr_eflex_group_action.c
<reponame>copslock/broadcom_cpri /*! \file bcmcth_ctr_eflex_group_action.c * * BCMCTH CTR_EFLEX_GROUP_ACTION_PROFILEt IMM handler. */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <sal/sal_libc.h> #include <bcmltd/chip/bcmltd_id.h> #include <bcmlrd/bcmlrd_map.h> #include <bcmptm/bcmptm.h> #include <bcmcth/bcmcth_ctr_eflex_drv.h> #include <bcmcth/bcmcth_state_eflex_drv.h> #include <bcmcth/bcmcth_ctr_eflex_internal.h> /* Debug log target definition */ #define BSL_LOG_MODULE BSL_LS_BCMCTH_CTREFLEX /*! Generate CTR_xxx_GROUP_ACTION_PROFILE LT field ids. */ #define CTR_ING_EGR_GROUP_ACTION_PROFILE_FIDS(x) \ CTR_ING_EFLEX_GROUP_ACTION_PROFILEt_##x, \ CTR_EGR_EFLEX_GROUP_ACTION_PROFILEt_##x /*! Generate STATE_xxx_GROUP_ACTION_PROFILE LT field ids. */ #define STATE_ING_EGR_GROUP_ACTION_PROFILE_FIDS(x) \ FLEX_STATE_ING_GROUP_ACTION_PROFILEt_##x, \ FLEX_STATE_EGR_GROUP_ACTION_PROFILEt_##x /*! Invalid index for mapped action profile id */ #define INVALID_MAP_INDEX 0xFFFF /******************************************************************************* * Local definitions */ /* GROUP_ACTION_PROFILE LT field info */ static const bcmlrd_sid_t group_action_profile_table_sid[][2] = { {CTR_ING_EGR_LT_IDS(EFLEX_GROUP_ACTION_PROFILEt)}, {STATE_ING_EGR_LT_IDS(GROUP_ACTION_PROFILEt)}, }; static const bcmlrd_fid_t group_profile_id_fid[][2] = { {CTR_ING_EFLEX_GROUP_ACTION_PROFILEt_CTR_ING_EFLEX_GROUP_ACTION_PROFILE_IDf, CTR_EGR_EFLEX_GROUP_ACTION_PROFILEt_CTR_EGR_EFLEX_GROUP_ACTION_PROFILE_IDf}, {FLEX_STATE_ING_GROUP_ACTION_PROFILEt_FLEX_STATE_ING_GROUP_ACTION_PROFILE_IDf, FLEX_STATE_EGR_GROUP_ACTION_PROFILEt_FLEX_STATE_EGR_GROUP_ACTION_PROFILE_IDf}, }; static const bcmlrd_fid_t group_fid[][2] = { {CTR_ING_EGR_GROUP_ACTION_PROFILE_FIDS(GROUPf)}, {STATE_ING_EGR_GROUP_ACTION_PROFILE_FIDS(GROUPf)}, }; static const bcmlrd_fid_t pipe_idx_fid[][2] = { {CTR_ING_EGR_GROUP_ACTION_PROFILE_FIDS(PIPEf)}, {STATE_ING_EGR_GROUP_ACTION_PROFILE_FIDS(PIPEf)}, }; static const bcmlrd_fid_t instance_fid[][2] = { {0, 0}, {FLEX_STATE_ING_GROUP_ACTION_PROFILEt_INSTANCEf, 0}, }; static const bcmlrd_fid_t egr_instance_fid[][2] = { {0, 0}, {0, FLEX_STATE_EGR_GROUP_ACTION_PROFILEt_INSTANCEf}, }; static const bcmlrd_fid_t group_action_profile_id_fid[][2] = { {CTR_ING_EFLEX_GROUP_ACTION_PROFILEt_CTR_ING_EFLEX_ACTION_PROFILE_IDf, CTR_EGR_EFLEX_GROUP_ACTION_PROFILEt_CTR_EGR_EFLEX_ACTION_PROFILE_IDf}, {FLEX_STATE_ING_GROUP_ACTION_PROFILEt_FLEX_STATE_ING_ACTION_PROFILE_IDf, FLEX_STATE_EGR_GROUP_ACTION_PROFILEt_FLEX_STATE_EGR_ACTION_PROFILE_IDf}, }; static const bcmlrd_fid_t group_map_fid[][2] = { {CTR_ING_EGR_GROUP_ACTION_PROFILE_FIDS(GROUP_MAPf)}, {STATE_ING_EGR_GROUP_ACTION_PROFILE_FIDS(GROUP_MAPf)}, }; static const bcmlrd_fid_t oper_state_fid[][2] = { {CTR_ING_EGR_GROUP_ACTION_PROFILE_FIDS(OPERATIONAL_STATEf)}, {STATE_ING_EGR_GROUP_ACTION_PROFILE_FIDS(OPERATIONAL_STATEf)}, }; /********************************************************************** * Private functions */ /* Function to initialize GROUP_ACTION_PROFILE entry with invalid values */ static int bcmcth_ctr_eflex_group_action_entry_init( int unit, ctr_eflex_group_action_data_t *entry) { int i, num_actions; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; entry->group_profile_id = CTR_EFLEX_INVALID_VAL; entry->group_id = CTR_EFLEX_INVALID_VAL; entry->action_profile_id = CTR_EFLEX_INVALID_VAL; entry->action_id = CTR_EFLEX_INVALID_VAL; entry->pipe_idx = CTR_EFLEX_INVALID_VAL; entry->inst = CTR_EFLEX_INVALID_VAL; entry->egr_inst = CTR_EFLEX_INVALID_VAL; for (i = 0; i < num_actions; i++) { entry->action_profile_id_map[i] = CTR_EFLEX_INVALID_VAL; } exit: SHR_FUNC_EXIT(); } /* Function to get default values for GROUP_ACTION_PROFILE entry */ static int bcmcth_ctr_eflex_group_action_default_get( int unit, ctr_eflex_group_action_data_t *entry) { bcmlrd_client_field_info_t *f_info = NULL; const bcmlrd_table_rep_t *lt_info = NULL; size_t num_fid = 0, i, num_actions, idx; int select; uint8_t pipe_unique; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; eflex_comp_t comp; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; select = entry->ingress ? 0 : 1; comp = entry->comp; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); SHR_IF_ERR_VERBOSE_EXIT (bcmlrd_field_count_get(unit, group_action_profile_table_sid[comp][select], &num_fid)); lt_info = bcmlrd_table_get(group_action_profile_table_sid[comp][select]); SHR_NULL_CHECK(lt_info, SHR_E_BADID); SHR_ALLOC(f_info, sizeof(bcmlrd_client_field_info_t) * num_fid, "bcmcthCtrEflexGroupAllocFields"); SHR_NULL_CHECK(f_info, SHR_E_MEMORY); SHR_IF_ERR_VERBOSE_EXIT (bcmlrd_table_fields_def_get(unit, lt_info->name, num_fid, f_info, &num_fid)); for (i = 0; i < num_fid; i++) { if (f_info[i].id == group_fid[comp][select]) { entry->group_id = f_info[i].def.u16; } else if (pipe_unique && f_info[i].id == pipe_idx_fid[comp][select]) { entry->pipe_idx = f_info[i].def.u8; } else if (f_info[i].id == group_action_profile_id_fid[comp][select]) { entry->action_profile_id = f_info[i].def.u16; } else if (f_info[i].id == group_map_fid[comp][select]) { for (idx = 0; idx < num_actions; idx++) { entry->action_profile_id_map[idx] = f_info[i].def.u16; } } else if (entry->comp == STATE_EFLEX) { /* Flex state data */ if (entry->ingress == INGRESS && f_info[i].id == instance_fid[comp][select]) { entry->inst = (state_eflex_inst_t)f_info[i].def.u32; } if (entry->ingress == EGRESS && f_info[i].id == egr_instance_fid[comp][select]) { entry->egr_inst = (state_eflex_inst_t)f_info[i].def.u32; } } } exit: SHR_FREE(f_info); SHR_FUNC_EXIT(); } /* * Function to replace GROUP_ACTION_PROFILE entry with values from another * entry if it is invalid * entry -- LT entry with updated values provided by application * cur_entry -- current LT entry present in the table. */ static int bcmcth_ctr_eflex_group_action_fill(int unit, ctr_eflex_group_action_data_t *entry, ctr_eflex_group_action_data_t *cur_entry) { int i, num_actions; uint8_t pipe_unique; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); if (pipe_unique && entry->pipe_idx == CTR_EFLEX_INVALID_VAL) { entry->pipe_idx = cur_entry->pipe_idx; } if (entry->group_id == CTR_EFLEX_INVALID_VAL) { entry->group_id = cur_entry->group_id; } if (entry->action_profile_id == CTR_EFLEX_INVALID_VAL) { entry->action_profile_id = cur_entry->action_profile_id; } if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst == CTR_EFLEX_INVALID_VAL) { entry->inst = cur_entry->inst; } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst == CTR_EFLEX_INVALID_VAL) { entry->egr_inst = cur_entry->inst; } for (i = 0; i < num_actions; i++) { if (entry->action_profile_id_map[i] == CTR_EFLEX_INVALID_VAL) { entry->action_profile_id_map[i] = cur_entry->action_profile_id_map[i]; } } exit: SHR_FUNC_EXIT(); } /* Function to parse data fields in given GROUP_ACTION_PROFILE entry */ static int bcmcth_ctr_eflex_group_action_lt_fields_check( int unit, ctr_eflex_group_action_data_t *entry, const bcmltd_field_t *data_fields) { int select; uint8_t pipe_unique; eflex_comp_t comp; SHR_FUNC_ENTER(unit); select = entry->ingress ? 0 : 1; comp = entry->comp; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); /* data_fields contains the key field for get_first/next IMM API */ if (data_fields->id == group_profile_id_fid[comp][select]) { entry->group_profile_id = data_fields->data; } else if (data_fields->id == group_fid[comp][select]) { entry->group_id = data_fields->data; } else if (pipe_unique && data_fields->id == pipe_idx_fid[comp][select]) { entry->pipe_idx = data_fields->data; } else if (entry->ingress == INGRESS && entry->comp == STATE_EFLEX && data_fields->id == instance_fid[comp][select]) { entry->inst = data_fields->data; } else if (entry->ingress == EGRESS && entry->comp == STATE_EFLEX && data_fields->id == egr_instance_fid[comp][select]) { entry->egr_inst = data_fields->data; } else if (data_fields->id == group_action_profile_id_fid[comp][select]) { entry->action_profile_id = data_fields->data; } else if (data_fields->id == group_map_fid[comp][select]) { entry->action_profile_id_map[data_fields->idx] = data_fields->data; } else if (data_fields->id == oper_state_fid[comp][select]) { entry->oper_state = data_fields->data; } exit: SHR_FUNC_EXIT(); } /* Function to parse given GROUP_ACTION_PROFILE entry */ static int bcmcth_ctr_eflex_group_action_lt_fields_parse( int unit, const bcmltd_field_t *data_fields, ctr_eflex_group_action_data_t *entry) { SHR_FUNC_ENTER(unit); /* Parse data fields */ while (data_fields) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_fields_check(unit, entry, data_fields)); data_fields = data_fields->next; } exit: SHR_FUNC_EXIT(); } /* Function to parse GROUP_ACTION_PROFILE IMM entry */ static int bcmcth_ctr_eflex_group_action_entry_parse( int unit, ctr_eflex_group_action_data_t *entry, const bcmltd_fields_t *flist) { uint32_t i; bcmltd_field_t *data_fields = NULL; SHR_FUNC_ENTER(unit); /* extract data fields */ for (i = 0; i < flist->count; i++) { data_fields = flist->field[i]; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_fields_check(unit, entry, data_fields)); } exit: SHR_FUNC_EXIT(); } /* Function to update OPERATIONAL_STATE in GROUP_ACTION_PROFILE IMM LT */ static int bcmcth_ctr_eflex_group_action_oper_state_update( int unit, ctr_eflex_group_action_data_t *entry) { bcmltd_fields_t key_fields = {0}; size_t num_key_fields, num_readonly_fields; int select; uint32_t t; ctr_eflex_control_t *ctrl = NULL; eflex_comp_t comp; SHR_FUNC_ENTER(unit); select = entry->ingress ? 0 : 1; comp = entry->comp; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); for (t = 0; t < ctrl->lt_info_num; t++) { if (ctrl->ctr_eflex_field_info[t].lt_sid == group_action_profile_table_sid[comp][select]) { break; } } if (t == ctrl->lt_info_num) { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "GROUP_ACTION_PROFILE LT info not found.\n"))); SHR_ERR_EXIT(SHR_E_INTERNAL); } num_key_fields = ctrl->ctr_eflex_field_info[t].num_key_fields; num_readonly_fields = ctrl->ctr_eflex_field_info[t].num_read_only_fields; /* Allocate key field */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_fields_alloc(unit, &key_fields, (num_key_fields + num_readonly_fields))); /* Set the fields.count to include OPERATIONAL_STATE */ key_fields.count = num_key_fields + num_readonly_fields; key_fields.field[0]->id = group_profile_id_fid[comp][select]; key_fields.field[0]->data = entry->group_profile_id; key_fields.field[1]->id = oper_state_fid[comp][select]; key_fields.field[1]->data = entry->oper_state; /* Update IMM entry */ SHR_IF_ERR_VERBOSE_EXIT (bcmimm_entry_update(unit, 0, group_action_profile_table_sid[comp][select], &key_fields)); exit: bcmcth_ctr_eflex_fields_free(unit, &key_fields); SHR_FUNC_EXIT(); } /* * Function to lookup GROUP_ACTION_PROFILE table with given group id. * It populates the LT entry with all fields except the key field * which is provided within the entry as input. */ int bcmcth_ctr_eflex_group_action_lookup(int unit, ctr_eflex_group_action_data_t *entry) { bcmltd_fields_t key_fields = {0}; bcmltd_field_t fld; bcmltd_field_t *fld_ptr_arr[1]; bcmltd_fields_t imm_fields = {0}; size_t num_fields = 0, num_actions; int select; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; eflex_comp_t comp; SHR_FUNC_ENTER(unit); select = entry->ingress ? 0 : 1; comp = entry->comp; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; /* Assign default values */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_default_get(unit, entry)); /* Configure key field */ key_fields.count = 1; key_fields.field = fld_ptr_arr; fld_ptr_arr[0] = &fld; fld.id = group_profile_id_fid[comp][select]; fld.data = entry->group_profile_id; /* Allocate imm fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmlrd_field_count_get(unit, group_action_profile_table_sid[comp][select], &num_fields)); /* * Adjust num_fields for array size * since LRD API counts field array size as 1 */ num_fields += num_actions - 1; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_fields_alloc(unit, &imm_fields, num_fields)); /* lookup IMM table; error if entry not found */ SHR_IF_ERR_VERBOSE_EXIT (bcmimm_entry_lookup(unit, group_action_profile_table_sid[comp][select], &key_fields, &imm_fields)); /* Parse IMM entry fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_parse(unit, entry, &imm_fields)); exit: /* imm_fields.count may be modified by bcmimm_entry_lookup */ imm_fields.count = num_fields; bcmcth_ctr_eflex_fields_free(unit, &imm_fields); SHR_FUNC_EXIT(); } /* Function to help insert PT entry for GROUP_ACTION_PROFILE LT */ static int bcmcth_ctr_eflex_group_action_insert_helper( int unit, size_t action_profile_id_skip_index, ctr_eflex_group_action_data_t *entry) { size_t num_actions, i; uint8_t pipe_unique; ctr_eflex_action_profile_data_t action_entry; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; /* * The number of simultaneous actions is reduced by 1 since one of the * associated counter actions is configured as the group counter * action */ entry->num_actions = num_actions; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); /* Determine first and last pipe number */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_num_pipes_get(unit, entry->ingress, entry->comp, entry->pipe_idx, &entry->start_pipe_idx, &entry->end_pipe_idx)); LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Insert %s Entry:\n" "grp_profile_id %d, grp_id %d, grp_action_profile_id %d\n" "grp_action_id %d, pipe_idx %d, inst %d egr_inst %d\n"), entry->ingress ? "Ingress" : "Egress", entry->group_profile_id, entry->group_id, entry->action_profile_id, entry->action_id, entry->pipe_idx, entry->inst, entry->egr_inst)); /* * Check if each associated action profile id exists in ACTION_PROFILE LT. * If yes, save corresponding action id in counter actions map. * If no, return error and set OPERATIONAL_STATE as INACTIVE. */ for (i = 0; i < entry->num_actions; i++) { /* * If action_profile_id_map[i] is in the middle of being inserted, * then corresponding action_id_map[i] is already populated and * the lookup in ACTION_PROFILE LT must be skipped, else it will fail. */ if (action_profile_id_skip_index == i) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Skipping action profile id %d \n"), entry->action_profile_id_map[i])); continue; } sal_memset(&action_entry, 0, sizeof(ctr_eflex_action_profile_data_t)); action_entry.ingress = entry->ingress; action_entry.comp = entry->comp; if (entry->action_profile_id_map[i] != CTR_EFLEX_INVALID_ACTION_PROFILE_ID) { action_entry.action_profile_id = entry->action_profile_id_map[i]; /* Lookup ACTION_PROFILE LT with given action profile id key */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * In pipe unique mode, check if group action id and associated * counter action id are configured for the same pipe. */ if (pipe_unique && entry->pipe_idx != action_entry.pipe_idx) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action id %d pipe idx %d NOT present in" "group action id %d pipe idx %d\n"), action_entry.action_id, action_entry.pipe_idx, entry->action_id, entry->pipe_idx)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry->action_id, entry->inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d\n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* If found, then save associated counter action. */ entry->action_id_map[i] = action_entry.action_id; /* If found, then save associated counter action. */ entry->action_id_map[i] = action_entry.action_id; LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action id %d is part of group id %d\n"), action_entry.action_id, entry->group_id)); } else { /* Set invalid action id for the associated action */ entry->action_id_map[i] = 0; } } /* Write to group action registers */ if (entry->comp == CTR_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_write(unit, entry)); } else if (entry->comp == STATE_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_state_eflex_group_action_write(unit, entry)); } exit: SHR_FUNC_EXIT(); } /* Function to help delete PT entry for GROUP_ACTION_PROFILE LT */ static int bcmcth_ctr_eflex_group_action_delete_helper( int unit, ctr_eflex_group_action_data_t *entry) { size_t i, num_actions; uint8_t pipe_unique; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; entry->num_actions = num_actions; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); /* Determine first and last pipe number */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_num_pipes_get(unit, entry->ingress, entry->comp, entry->pipe_idx, &entry->start_pipe_idx, &entry->end_pipe_idx)); LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Delete %s Entry:\n" "grp_profile_id %d, grp_id %d, grp_action_profile_id %d" "grp_action_id %d, pipe_unique %d, pipe_idx %d, inst %d egr_inst %d\n"), entry->ingress ? "Ingress" : "Egress", entry->group_profile_id, entry->group_id, entry->action_profile_id, entry->action_id, pipe_unique, entry->pipe_idx, entry->inst, entry->egr_inst)); /* Set invalid action id for group */ entry->action_id = 0; /* Set invalid action id for all associated actions in group */ for (i = 0; i < entry->num_actions; i++) { entry->action_id_map[i] = 0; } /* Write to group action registers */ if (entry->comp == CTR_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_write(unit, entry)); } else if (entry->comp == STATE_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_state_eflex_group_action_write(unit, entry)); } exit: SHR_FUNC_EXIT(); } /* Function to populate GROUP_ACTION_PROFILE entry during insert notification */ static int bcmcth_ctr_eflex_group_action_insert_notify( int unit, bool group_action_profile_id_match, bool map_action_profile_id_match, size_t skip_index, ctr_eflex_action_profile_data_t *action_entry, ctr_eflex_group_action_data_t *entry) { ctr_eflex_action_profile_data_t temp_action_entry; SHR_FUNC_ENTER(unit); /* Incoming ACTION_PROFILE LT matches group action profile id */ if (group_action_profile_id_match) { /* Get group action id from action profile entry */ entry->action_id = action_entry->action_id; /* Insert entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_insert_helper( unit, skip_index, entry)); } /* * Incoming ACTION_PROFILE LT matches one of associated * group action profile id and does not match group action profile id */ if (map_action_profile_id_match && !group_action_profile_id_match) { sal_memset(&temp_action_entry, 0, sizeof(ctr_eflex_action_profile_data_t)); temp_action_entry.ingress = entry->ingress; temp_action_entry.comp = entry->comp; temp_action_entry.action_profile_id = entry->action_profile_id; /* Lookup ACTION_PROFILE entry to get group action id */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup( unit, &temp_action_entry)); /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst != temp_action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d\n"), temp_action_entry.action_id, temp_action_entry.state_ext.inst, entry->action_id, entry->inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst != temp_action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d \n"), temp_action_entry.action_id, temp_action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* Get action_id from action profile entry */ entry->action_id = temp_action_entry.action_id; /* Get action_id from action profile entry */ entry->action_id = temp_action_entry.action_id; /* Copy incoming action id to associated action id */ entry->action_id_map[skip_index] = action_entry->action_id; /* Insert entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_insert_helper( unit, skip_index, entry)); } /* * Update GROUP_ACTION_PROFILE LT entry * OPERATIONAL_STATE to ACTIVE */ entry->oper_state = CTR_EFLEX_OPER_STATE_ACTIVE; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_oper_state_update( unit, entry)); exit: SHR_FUNC_EXIT(); } /* * Function to check if GROUP_ACTION_PROFILE entry * should be updated based on ACTION_PROFILE LT entry insert/delete operation. * * GROUP_ACTION_PROFILE entry includes * - Group action profile id and corresponding action id. * - Associated action profile id array and corresponding action id array. * * Action ids are populated by looking up ACTION_PROFILE LT with the * corresponding action profile ids. * * This function may be called after ACTION_PROFILE entry insert/delete * operation for either one. * * This function iterates over each GROUP_ACTION_PROFILE entry searching * for a match with action profile id in input ACTION_PROFILE entry. * * For INSERT notification, the current OPERATIONAL_STATE must be INACTIVE. * There are 2 cases to consider:- * Case I: ACTION_PROFILE entry matches group action profile id * - Copy input action id as GROUP action id. * - Call insert_helper() with invalid skip index. * * Case II: ACTION_PROFILE entry matches one of associated action profile id * - Lookup ACTION_PROFILE LT to get GROUP action id. * - Copy input action id to matched associated action id. * - Save the array index of matched action profile id. * This index needs to be skipped in insert_helper() since the * lookup in ACTION_PROFILE LT will fail * - Call insert_helper() with skip index. * * In both cases, if insert_helper() returns SUCESS, OPERATIONAL_STATE is * updated to ACTIVE. * * For DELETE notification, the current OPERATIONAL_STATE must be ACTIVE. * For matches on either of the cases above * - Write default values to PT. * - Set OPERATIONAL_STATE to INACTIVE. */ int bcmcth_ctr_eflex_group_action_notify( int unit, bool insert, ctr_eflex_action_profile_data_t *action_entry) { bcmltd_fields_t key_fields = {0}; bcmltd_field_t fld; bcmltd_field_t *fld_ptr_arr[1]; bcmltd_fields_t imm_fields = {0}; ctr_eflex_group_action_data_t entry = {0}; size_t i, num_fields = 0, num_actions, skip_index; int select, rv; bool group_action_profile_id_match, map_action_profile_id_match; bool cur_oper_state; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; eflex_comp_t comp; SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(action_entry, SHR_E_PARAM); select = action_entry->ingress ? 0 : 1; comp = action_entry->comp; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = action_entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; /* * If insert, update GROUP_ACTION_PROFILE entry if it is INACTIVE * If delete, update GROUP_ACTION_PROFILE entry if it is ACTIVE */ cur_oper_state = insert ? CTR_EFLEX_OPER_STATE_INACTIVE : CTR_EFLEX_OPER_STATE_ACTIVE; /* Configure key field */ key_fields.count = 1; key_fields.field = fld_ptr_arr; fld_ptr_arr[0] = &fld; fld.id = group_profile_id_fid[comp][select]; fld.data = entry.group_profile_id; /* Allocate imm fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmlrd_field_count_get(unit, group_action_profile_table_sid[comp][select], &num_fields)); /* * Adjust num_fields for array size * since LRD API counts field array size as 1 */ num_fields += num_actions - 1; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_fields_alloc(unit, &imm_fields, num_fields)); /* Get first entry from GROUP_ACTION_PROFILE IMM LT */ rv = bcmimm_entry_get_first(unit, group_action_profile_table_sid[comp][select], &imm_fields); /* Iterate GROUP_ACTION_PROFILE LT searching for input action profile id */ while (rv == SHR_E_NONE) { sal_memset(&entry, 0, sizeof(ctr_eflex_group_action_data_t)); group_action_profile_id_match = false; map_action_profile_id_match = false; skip_index = INVALID_MAP_INDEX; entry.ingress = action_entry->ingress; entry.comp = action_entry->comp; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_init(unit, &entry)); /* Get default values */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_default_get(unit, &entry)); /* Parse IMM entry fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_parse(unit, &entry, &imm_fields)); /* GROUP_ACTION_PROFILE LT entry OPERATIONAL_STATE is expected value */ if (entry.oper_state == cur_oper_state) { if (entry.ingress == INGRESS && entry.comp == STATE_EFLEX) { /* * For ingress flex state, * instance and action profile id match. */ if (entry.inst == action_entry->state_ext.inst && entry.action_profile_id == action_entry->action_profile_id) { group_action_profile_id_match = true; } } else if (entry.ingress == EGRESS && entry.comp == STATE_EFLEX) { /* * For egress flex state, * instance and action profile id match. */ if (entry.egr_inst == action_entry->state_ext.egr_inst && entry.action_profile_id == action_entry->action_profile_id) { group_action_profile_id_match = true; } } else if (entry.action_profile_id == action_entry->action_profile_id) { /* Action profile id matches group action profile id */ group_action_profile_id_match = true; } /* * Action profile id matches any one of * associated action profile ids */ for (i = 0; i < num_actions; i++) { if (entry.action_profile_id_map[i] == action_entry->action_profile_id) { map_action_profile_id_match = true; skip_index = i; break; } } /* Insert notification */ if (insert) { /* Insert entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_insert_notify( unit, group_action_profile_id_match, map_action_profile_id_match, skip_index, action_entry, &entry)); /* * Update GROUP_ACTION_PROFILE LT entry * OPERATIONAL_STATE to ACTIVE */ entry.oper_state = CTR_EFLEX_OPER_STATE_ACTIVE; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_oper_state_update( unit, &entry)); } else { /* Delete notification */ /* * Incoming action profile id matches either group action * profile id or one of associated action profile ids. * In either case, write defaults to PT and set * OPERATIONAL_STATE to INACTIVE. */ if (group_action_profile_id_match || map_action_profile_id_match) { /* Delete entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_delete_helper(unit, &entry)); /* * Update GROUP_ACTION_PROFILE LT entry * OPERATIONAL_STATE to INACTIVE */ entry.oper_state = CTR_EFLEX_OPER_STATE_INACTIVE; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_oper_state_update( unit, &entry)); } } } /* Setup key for next entry */ key_fields.field[0]->data = entry.group_profile_id; /* imm_fields.count may be modified. */ imm_fields.count = num_fields; /* Get next entry from GROUP_ACTION_PROFILE IMM LT */ rv = bcmimm_entry_get_next(unit, group_action_profile_table_sid[comp][select], &key_fields, &imm_fields); } /* end WHILE */ if (rv == SHR_E_NOT_FOUND) { rv = SHR_E_NONE; } exit: /* imm_fields.count may be modified. */ imm_fields.count = num_fields; bcmcth_ctr_eflex_fields_free(unit, &imm_fields); SHR_FUNC_EXIT(); } /* Function to insert entry into GROUP_ACTION_PROFILE IMM LT */ static int bcmcth_ctr_eflex_group_action_lt_entry_insert( int unit, const bcmltd_field_t *data_fields, ctr_eflex_group_action_data_t *entry) { ctr_eflex_action_profile_data_t action_entry; SHR_FUNC_ENTER(unit); /* Get default values */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_default_get(unit, entry)); /* * Parse user values * default values will be over-written by user values, if present */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_fields_parse(unit, data_fields, entry)); sal_memset(&action_entry, 0, sizeof(ctr_eflex_action_profile_data_t)); action_entry.ingress = entry->ingress; action_entry.comp = entry->comp; action_entry.action_profile_id = entry->action_profile_id; /* Lookup entry with given action profile id in ACTION_PROFILE LT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry->action_id, entry->inst )); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d \n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst )); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* Get action_id from action profile entry */ entry->action_id = action_entry.action_id; /* Get action_id from action profile entry */ entry->action_id = action_entry.action_id; /* Insert entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_insert_helper(unit, INVALID_MAP_INDEX, entry)); /* Notify HITBIT_CONTROL LT */ if (entry->comp == CTR_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_hitbit_ctrl_notify(unit, true, /* insert operation */ true, /* group action entry */ (void *)entry)); } exit: SHR_FUNC_EXIT(); } /* Function to update entry in GROUP_ACTION_PROFILE IMM LT */ static int bcmcth_ctr_eflex_group_action_lt_entry_update( int unit, const bcmltd_field_t *data_fields, ctr_eflex_group_action_data_t *entry, ctr_eflex_group_action_data_t *cur_entry) { size_t i, num_actions; uint8_t pipe_unique; ctr_eflex_action_profile_data_t action_entry = {0}; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, entry->comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry->ingress ? device_info->num_ing_actions : device_info->num_egr_actions; entry->num_actions = cur_entry->num_actions = num_actions; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry->ingress, entry->comp, &pipe_unique)); /* Parse user values */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_fields_parse(unit, data_fields, entry)); cur_entry->group_profile_id = entry->group_profile_id; /* Lookup entry with given key fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lookup(unit, cur_entry)); /* Fill missing fields in new entry with current entry */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_fill(unit, entry, cur_entry)); action_entry.ingress = entry->ingress; action_entry.comp = entry->comp; action_entry.action_profile_id = entry->action_profile_id; /* Lookup entry with given action profile id key in ACTION_PROFILE LT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d \n"), action_entry.action_id, action_entry.state_ext.inst, entry->action_id, entry->inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d \n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* Get pipe idx and action id from action profile entry */ entry->action_id = action_entry.action_id; /* Get pipe idx and action id from action profile entry */ entry->action_id = action_entry.action_id; /* Determine first and last pipe number */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_num_pipes_get(unit, entry->ingress, entry->comp, entry->pipe_idx, &entry->start_pipe_idx, &entry->end_pipe_idx)); LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Update %s Entry:\n" "grp_profile_id %d, grp_id %d, grp_action_profile_id %d\n" "grp_action_id %d, pipe_idx %d, inst %d egr_inst %d\n"), entry->ingress ? "Ingress" : "Egress", entry->group_profile_id, entry->group_id, entry->action_profile_id, entry->action_id, entry->pipe_idx, entry->inst, entry->egr_inst)); /* * Check if each associated action profile id exists in ACTION_PROFILE LT. * If yes, save corresponding action id in counter actions map. * If no, return error and set OPERATIONAL_STATE as INACTIVE. */ for (i = 0; i < entry->num_actions; i++) { sal_memset(&action_entry, 0, sizeof(ctr_eflex_action_profile_data_t)); action_entry.ingress = entry->ingress; action_entry.comp = entry->comp; if (entry->action_profile_id_map[i] != CTR_EFLEX_INVALID_ACTION_PROFILE_ID) { action_entry.action_profile_id = entry->action_profile_id_map[i]; /* * Lookup entry with given action profile id key * in ACTION_PROFILE LT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * Check if group action id and associated counter action id are * configured for the same pipe. */ if (pipe_unique && entry->pipe_idx != action_entry.pipe_idx) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action id %d pipe idx %d NOT present in" "group action id %d pipe idx %d\n"), action_entry.action_id, action_entry.pipe_idx, entry->action_id, entry->pipe_idx)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry->comp == STATE_EFLEX && entry->ingress == INGRESS && entry->inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry->action_id, entry->inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry->comp == STATE_EFLEX && entry->ingress == EGRESS && entry->egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d\n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* If found, then save associated counter action. */ entry->action_id_map[i] = action_entry.action_id; /* If found, then save associated counter action. */ entry->action_id_map[i] = action_entry.action_id; LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action id %d is part of group id %d\n"), action_entry.action_id, entry->group_id)); } else { /* Set invalid action id for the associated action */ entry->action_id_map[i] = 0; } } /* Delete current entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_delete_helper(unit, cur_entry)); /* Write to group action registers */ if (entry->comp == CTR_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_write(unit, entry)); } else if (entry->comp == STATE_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_state_eflex_group_action_write(unit, entry)); } exit: SHR_FUNC_EXIT(); } /* Function to delete entry from GROUP_ACTION_PROFILE IMM LT */ static int bcmcth_ctr_eflex_group_action_lt_entry_delete( int unit, const bcmltd_field_t *data_fields, ctr_eflex_group_action_data_t *entry) { ctr_eflex_action_profile_data_t action_entry = {0}; SHR_FUNC_ENTER(unit); /* Lookup GROUP_ACTION_PROFILE entry to get group action profile id */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lookup(unit, entry)); /* If entry is INACTIVE, no further action is needed */ if (entry->oper_state == CTR_EFLEX_OPER_STATE_INACTIVE) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "GROUP_ACTION_PROFILE entry is INACTIVE.\n"))); SHR_EXIT(); } /* Lookup entry with given action profile id key in ACTION_PROFILE LT */ action_entry.ingress = entry->ingress; action_entry.comp = entry->comp; action_entry.action_profile_id = entry->action_profile_id; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * For ingress flex state, * check if both are configured for same instance. */ if (entry->ingress == INGRESS && entry->comp == STATE_EFLEX && entry->inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry->action_id, entry->inst)); SHR_EXIT(); } if (entry->ingress == EGRESS && entry->comp == STATE_EFLEX && entry->egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d egress inst %d NOT present in" "group action id %d egress inst %d\n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry->action_id, entry->egr_inst)); SHR_EXIT(); } /* Delete entry in PT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_delete_helper(unit, entry)); /* Notify HITBIT_CONTROL LT */ if (entry->comp == CTR_EFLEX) { SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_hitbit_ctrl_notify(unit, false, /* delete operation */ true, /* group action entry */ (void *)entry)); } exit: SHR_FUNC_EXIT(); } static int bcmcth_ctr_eflex_group_action_lt_stage(int unit, bool ingress, eflex_comp_t comp, uint64_t req_flags, bcmimm_entry_event_t event_reason, const bcmltd_field_t *key_fields, const bcmltd_field_t *data_fields, bcmltd_fields_t *out) { int select; ctr_eflex_group_action_data_t entry = {0}; ctr_eflex_group_action_data_t cur_entry = {0}; ctr_eflex_control_t *ctrl = NULL; SHR_FUNC_ENTER(unit); select = ingress ? 0 : 1; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, comp, &ctrl)); entry.ingress = ingress; entry.comp = comp; entry.req_flags = req_flags; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_init(unit, &entry)); /* Parse the key fields to get group profile id */ while (key_fields) { if (key_fields->id == group_profile_id_fid[comp][select]) { entry.group_profile_id = key_fields->data; } key_fields = key_fields->next; } switch (event_reason) { case BCMIMM_ENTRY_INSERT: SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_entry_insert(unit, data_fields, &entry)); break; case BCMIMM_ENTRY_UPDATE: cur_entry.ingress = ingress; cur_entry.comp = comp; cur_entry.req_flags = req_flags; SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_init(unit, &cur_entry)); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_entry_update(unit, data_fields, &entry, &cur_entry)); break; case BCMIMM_ENTRY_DELETE: SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_entry_delete(unit, data_fields, &entry)); break; default: break; } exit: if (out) { out->count = 0; out->field[out->count]->id = oper_state_fid[comp][select]; out->field[out->count]->flags = 0; out->field[out->count]->next = 0; out->field[out->count]->idx = 0; if (SHR_FUNC_VAL_IS(SHR_E_NOT_FOUND)) { /* Set OPERATIONAL_STATE to INACTIVE */ out->field[out->count++]->data = ctrl->ctr_eflex_enum.oper_state_inactive; LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action Id entry not found in ACTION_PROFILE LT, " "Setting operational state to INACTIVE.\n"))); } else { /* Set OPERATIONAL_STATE to ACTIVE */ out->field[out->count++]->data = ctrl->ctr_eflex_enum.oper_state_active; } } if (SHR_FUNC_VAL_IS(SHR_E_NOT_FOUND)) { return SHR_E_NONE; } SHR_FUNC_EXIT(); } /*! Function to lookup GROUP_ACTION_PROFILE IMM LT entry. */ static int bcmcth_ctr_eflex_group_action_lt_lookup(int unit, bool ingress, eflex_comp_t comp, uint64_t req_flags, bcmimm_lookup_type_t lkup_type, const bcmltd_fields_t *in, bcmltd_fields_t *out) { int select; size_t num_actions, i; uint8_t pipe_unique; ctr_eflex_action_profile_data_t action_entry = {0}; ctr_eflex_group_action_data_t entry = {0}; const bcmltd_fields_t *key_fields = NULL; ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; SHR_FUNC_ENTER(unit); select = ingress ? 0 : 1; action_entry.ingress = entry.ingress = ingress; action_entry.comp = entry.comp = comp; entry.req_flags = req_flags; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, comp, &ctrl)); /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, entry.ingress, entry.comp, &pipe_unique)); device_info = ctrl->ctr_eflex_device_info; num_actions = entry.ingress ? device_info->num_ing_actions : device_info->num_egr_actions; /* key fields are in the "out" parameter for traverse operations */ key_fields = (lkup_type == BCMIMM_TRAVERSE) ? out : in; /* Parse the key fields to get group id */ for (i = 0; i < key_fields->count; i++) { if (key_fields->field[i]->id == group_profile_id_fid[comp][select]) { entry.group_profile_id = key_fields->field[i]->data; } } /* Parse IMM fields */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_entry_parse(unit, &entry, out)); action_entry.action_profile_id = entry.action_profile_id; /* Lookup entry with given action profile id key in ACTION_PROFILE LT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry.comp == STATE_EFLEX && entry.ingress == INGRESS && entry.inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d egr_inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry.action_id, entry.inst, entry.egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry.comp == STATE_EFLEX && entry.ingress == EGRESS && entry.egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d egress inst %d egr_inst %d\n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry.action_id, entry.inst, entry.egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* * Check if each associated action profile id exists in ACTION_PROFILE LT. * If no, return error and set OPERATIONAL_STATE as INACTIVE. */ for (i = 0; i < num_actions; i++) { sal_memset(&action_entry, 0, sizeof(ctr_eflex_action_profile_data_t)); action_entry.ingress = entry.ingress; action_entry.comp = entry.comp; if (entry.action_profile_id_map[i] != CTR_EFLEX_INVALID_ACTION_PROFILE_ID) { action_entry.action_profile_id = entry.action_profile_id_map[i]; /* * Lookup entry with given action profile id key * in ACTION_PROFILE LT */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_action_profile_lookup(unit, &action_entry)); /* * In pipe unique mode, check if group action id and associated * counter action id are configured for the same pipe. */ if (pipe_unique && entry.pipe_idx != action_entry.pipe_idx) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action id %d pipe idx %d NOT present in" "group action id %d pipe idx %d\n"), action_entry.action_id, action_entry.pipe_idx, entry.action_id, entry.pipe_idx)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } /* * For ingress flex state, check if group action id and associated * counter action id are configured for the same ingress instance. */ if (entry.comp == STATE_EFLEX && entry.ingress == INGRESS && entry.inst != action_entry.state_ext.inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d ingress inst %d egr_inst %d\n"), action_entry.action_id, action_entry.state_ext.inst, entry.action_id, entry.inst, entry.egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } if (entry.comp == STATE_EFLEX && entry.ingress == EGRESS && entry.egr_inst != action_entry.state_ext.egr_inst) { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Flex state action id %d ingress inst %d NOT present in" "group action id %d egress inst %d egr_inst %d\n"), action_entry.action_id, action_entry.state_ext.egr_inst, entry.action_id, entry.inst, entry.egr_inst)); SHR_VERBOSE_EXIT(SHR_E_NOT_FOUND); } } } exit: if (out) { if (SHR_FUNC_VAL_IS(SHR_E_NOT_FOUND)) { /* Set OPERATIONAL_STATE to INACTIVE . */ (void)bcmcth_ctr_eflex_oper_state_set( unit, oper_state_fid[comp][select], ctrl->ctr_eflex_enum.oper_state_inactive, out); LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit, "Action Id %d entry not found in ACTION_PROFILE LT, " "Setting operational state to INACTIVE.\n"), entry.action_id)); } else { /* Set OPERATIONAL_STATE to ACTIVE . */ (void)bcmcth_ctr_eflex_oper_state_set( unit, oper_state_fid[comp][select], ctrl->ctr_eflex_enum.oper_state_active, out); } } if (SHR_FUNC_VAL_IS(SHR_E_NOT_FOUND)) { return SHR_E_NONE; } SHR_FUNC_EXIT(); } /*! Function to get GROUP_ACTION_PROFILE IMM LT entry limit value. */ static int bcmcth_ctr_eflex_group_action_lt_ent_limit_get(int unit, bool ingress, eflex_comp_t comp, uint32_t *count) { ctr_eflex_control_t *ctrl = NULL; bcmcth_ctr_eflex_device_info_t *device_info; const bcmlrd_map_t *map = NULL; uint8_t pipe_unique; uint32_t num_pipes, k; size_t ent_limit; int rv, select; SHR_FUNC_ENTER(unit); select = ingress ? 0 : 1; /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, comp, &ctrl)); device_info = ctrl->ctr_eflex_device_info; /* Get pipe operating mode */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_pipe_opermode_get(unit, ingress, comp, &pipe_unique)); num_pipes = pipe_unique ? 1: device_info->num_pipes; /* Check if LT is supported for given device */ rv = bcmlrd_map_get(unit, group_action_profile_table_sid[comp][select], &map); if (SHR_SUCCESS(rv) && map) { for (k = 0; k < map->table_attr->attributes; k++) { if (map->table_attr->attr[k].key == BCMLRD_MAP_TABLE_ATTRIBUTE_ENTRY_LIMIT) { ent_limit = map->table_attr->attr[k].value; *count = ent_limit / num_pipes; break; } } } else { LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit,"GROUP_ACTION_PROFILE LT not supported.\n"))); *count = 0; } LOG_VERBOSE(BSL_LOG_MODULE, (BSL_META_U(unit,"comp %d ingress %d entry_limit %d\n"), comp, ingress, *count)); exit: SHR_FUNC_EXIT(); } /******************************************************************************* * IMM event handler */ /*********************** * INGRESS IMM Functions */ /*! * \brief Lookup callback function of CTR_ING_EFLEX_GROUP_ACTION_PROFILE * IMM event handler. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [in] lkup_type Indicates the type of lookup that is being performed. * \param [in] in Structure which contains the key fields but may include * also other fields. The component should only focus on the * key fields. * \param [in,out] out Structure contains all the fields of the table, so that * the component should not delete or add any field to this * structure. The data values of the field were set by the * IMM so the component may only overwrite the data section * of the fields. * * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_ing_group_action_lt_lookup_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, void *context, bcmimm_lookup_type_t lkup_type, const bcmltd_fields_t *in, bcmltd_fields_t *out) { uint32_t t; uint64_t req_flags; ctr_eflex_control_t *ctrl = NULL; SHR_FUNC_ENTER(unit); if (lkup_type == BCMIMM_LOOKUP) { SHR_NULL_CHECK(in, SHR_E_PARAM); } SHR_NULL_CHECK(out, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, CTR_EFLEX, &ctrl)); for (t = 0; t < ctrl->lt_info_num; t++) { if (ctrl->ctr_eflex_field_info[t].lt_sid == CTR_ING_EFLEX_GROUP_ACTION_PROFILEt) { break; } } if (out) { if (t == ctrl->lt_info_num) { SHR_ERR_EXIT(SHR_E_INTERNAL); } else if (out->count < ctrl->ctr_eflex_field_info[t].num_data_fields) { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out fields supplied to lookup is too " "small to hold the desired fields.\n"))); SHR_ERR_EXIT(SHR_E_MEMORY); } } else { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out not supplied to lookup.\n"))); SHR_ERR_EXIT(SHR_E_INTERNAL); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_lookup(unit, INGRESS, CTR_EFLEX, req_flags, lkup_type, in, out)); exit: SHR_FUNC_EXIT(); } /*! * \brief Stage callback function of CTR_ING_EFLEX_GROUP_ACTION_PROFILE * to insert, update, delete IMM LT entry. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] event_reason Reason for the entry event. * \param [in] key_fields Linked list of the key fields identifying * the entry. * \param [in] data_fields Linked list of the data fields in the * modified entry. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [out] output_fields Linked list of the output fields in the * modified entry. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_ing_group_action_lt_stage_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, bcmimm_entry_event_t event_reason, const bcmltd_field_t *key_fields, const bcmltd_field_t *data_fields, void *context, bcmltd_fields_t *output_fields) { uint64_t req_flags; SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(key_fields, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); if (event_reason != BCMIMM_ENTRY_DELETE) { SHR_NULL_CHECK(output_fields, SHR_E_PARAM); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_stage(unit, INGRESS, CTR_EFLEX, req_flags, event_reason, key_fields, data_fields, output_fields)); exit: SHR_FUNC_EXIT(); } /*! * \brief Entry limit get callback function of * CTR_ING_EFLEX_GROUP_ACTION_PROFILE * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] count Entry limit value. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_ing_group_action_lt_ent_limit_get_cb(int unit, uint32_t trans_id, bcmltd_sid_t sid, uint32_t *count) { SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(count, SHR_E_PARAM); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_ent_limit_get(unit, INGRESS, CTR_EFLEX, count)); exit: SHR_FUNC_EXIT(); } /*! * \brief Lookup callback function of FLEX_STATE_ING_GROUP_ACTION_PROFILE * IMM event handler. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [in] lkup_type Indicates the type of lookup that is being performed. * \param [in] in Structure which contains the key fields but may include * also other fields. The component should only focus on the * key fields. * \param [in,out] out Structure contains all the fields of the table, so that * the component should not delete or add any field to this * structure. The data values of the field were set by the * IMM so the component may only overwrite the data section * of the fields. * * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_ing_group_action_lt_lookup_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, void *context, bcmimm_lookup_type_t lkup_type, const bcmltd_fields_t *in, bcmltd_fields_t *out) { uint32_t t; uint64_t req_flags; ctr_eflex_control_t *ctrl = NULL; SHR_FUNC_ENTER(unit); if (lkup_type == BCMIMM_LOOKUP) { SHR_NULL_CHECK(in, SHR_E_PARAM); } SHR_NULL_CHECK(out, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, STATE_EFLEX, &ctrl)); for (t = 0; t < ctrl->lt_info_num; t++) { if (ctrl->ctr_eflex_field_info[t].lt_sid == FLEX_STATE_ING_GROUP_ACTION_PROFILEt) { break; } } if (out) { if (t == ctrl->lt_info_num) { SHR_ERR_EXIT(SHR_E_INTERNAL); } else if (out->count < ctrl->ctr_eflex_field_info[t].num_data_fields) { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out fields supplied to lookup is too " "small to hold the desired fields.\n"))); SHR_ERR_EXIT(SHR_E_MEMORY); } } else { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out not supplied to lookup.\n"))); SHR_ERR_EXIT(SHR_E_INTERNAL); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_lookup(unit, INGRESS, STATE_EFLEX, req_flags, lkup_type, in, out)); exit: SHR_FUNC_EXIT(); } /*! * \brief Stage callback function of FLEX_STATE_ING_GROUP_ACTION_PROFILE * to insert, update, delete IMM LT entry. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] event_reason Reason for the entry event. * \param [in] key_fields Linked list of the key fields identifying * the entry. * \param [in] data_fields Linked list of the data fields in the * modified entry. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [out] output_fields Linked list of the output fields in the * modified entry. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_ing_group_action_lt_stage_cb( int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, bcmimm_entry_event_t event_reason, const bcmltd_field_t *key_fields, const bcmltd_field_t *data_fields, void *context, bcmltd_fields_t *output_fields) { uint64_t req_flags; SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(key_fields, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); if (event_reason != BCMIMM_ENTRY_DELETE) { SHR_NULL_CHECK(output_fields, SHR_E_PARAM); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_stage(unit, INGRESS, STATE_EFLEX, req_flags, event_reason, key_fields, data_fields, output_fields)); exit: SHR_FUNC_EXIT(); } /*! * \brief Entry limit get callback function of FLEX_STATE_ING_ACTION_PROFILE * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] count Entry limit value. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_ing_group_action_lt_ent_limit_get_cb(int unit, uint32_t trans_id, bcmltd_sid_t sid, uint32_t *count) { SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(count, SHR_E_PARAM); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_ent_limit_get(unit, INGRESS, STATE_EFLEX, count)); exit: SHR_FUNC_EXIT(); } /*********************** * EGRESS IMM Functions */ /*! * \brief Lookup callback function of CTR_EGR_EFLEX_GROUP_ACTION_PROFILE * IMM event handler. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [in] lkup_type Indicates the type of lookup that is being performed. * \param [in] in Structure which contains the key fields but may include * also other fields. The component should only focus on the * key fields. * \param [in,out] out Structure contains all the fields of the table, so that * the component should not delete or add any field to this * structure. The data values of the field were set by the * IMM so the component may only overwrite the data section * of the fields. * * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_egr_group_action_lt_lookup_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, void *context, bcmimm_lookup_type_t lkup_type, const bcmltd_fields_t *in, bcmltd_fields_t *out) { uint32_t t; uint64_t req_flags; ctr_eflex_control_t *ctrl = NULL; SHR_FUNC_ENTER(unit); if (lkup_type == BCMIMM_LOOKUP) { SHR_NULL_CHECK(in, SHR_E_PARAM); } SHR_NULL_CHECK(out, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, CTR_EFLEX, &ctrl)); for (t = 0; t < ctrl->lt_info_num; t++) { if (ctrl->ctr_eflex_field_info[t].lt_sid == CTR_EGR_EFLEX_GROUP_ACTION_PROFILEt) { break; } } if (out) { if (t == ctrl->lt_info_num) { SHR_ERR_EXIT(SHR_E_INTERNAL); } else if (out->count < ctrl->ctr_eflex_field_info[t].num_data_fields) { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out fields supplied to lookup is too " "small to hold the desired fields.\n"))); SHR_ERR_EXIT(SHR_E_MEMORY); } } else { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out not supplied to lookup.\n"))); SHR_ERR_EXIT(SHR_E_INTERNAL); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_lookup(unit, EGRESS, CTR_EFLEX, req_flags, lkup_type, in, out)); exit: SHR_FUNC_EXIT(); } /*! * \brief Stage callback function of CTR_EGR_EFLEX_GROUP_ACTION_PROFILE * to insert, update, delete IMM LT entry. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] event_reason Reason for the entry event. * \param [in] key_fields Linked list of the key fields identifying * the entry. * \param [in] data_fields Linked list of the data fields in the * modified entry. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [out] output_fields Linked list of the output fields in the * modified entry. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_egr_group_action_lt_stage_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, bcmimm_entry_event_t event_reason, const bcmltd_field_t *key_fields, const bcmltd_field_t *data_fields, void *context, bcmltd_fields_t *output_fields) { uint64_t req_flags; SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(key_fields, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); if (event_reason != BCMIMM_ENTRY_DELETE) { SHR_NULL_CHECK(output_fields, SHR_E_PARAM); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_stage(unit, EGRESS, CTR_EFLEX, req_flags, event_reason, key_fields, data_fields, output_fields)); exit: SHR_FUNC_EXIT(); } /*! * \brief Entry limit get callback function of * CTR_EGR_EFLEX_GROUP_ACTION_PROFILE * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] count Entry limit value. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_ctr_eflex_egr_group_action_lt_ent_limit_get_cb(int unit, uint32_t trans_id, bcmltd_sid_t sid, uint32_t *count) { SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(count, SHR_E_PARAM); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_ent_limit_get(unit, EGRESS, CTR_EFLEX, count)); exit: SHR_FUNC_EXIT(); } /*! * \brief Lookup callback function of FLEX_STATE_EGR_GROUP_ACTION_PROFILE * IMM event handler. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [in] lkup_type Indicates the type of lookup that is being performed. * \param [in] in Structure which contains the key fields but may include * also other fields. The component should only focus on the * key fields. * \param [in,out] out Structure contains all the fields of the table, so that * the component should not delete or add any field to this * structure. The data values of the field were set by the * IMM so the component may only overwrite the data section * of the fields. * * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_egr_group_action_lt_lookup_cb(int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, void *context, bcmimm_lookup_type_t lkup_type, const bcmltd_fields_t *in, bcmltd_fields_t *out) { uint32_t t; uint64_t req_flags; ctr_eflex_control_t *ctrl = NULL; SHR_FUNC_ENTER(unit); if (lkup_type == BCMIMM_LOOKUP) { SHR_NULL_CHECK(in, SHR_E_PARAM); } SHR_NULL_CHECK(out, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); /* Get flex control struct */ SHR_IF_ERR_VERBOSE_EXIT (bcmcth_eflex_ctrl_get(unit, STATE_EFLEX, &ctrl)); for (t = 0; t < ctrl->lt_info_num; t++) { if (ctrl->ctr_eflex_field_info[t].lt_sid == FLEX_STATE_EGR_GROUP_ACTION_PROFILEt) { break; } } if (out) { if (t == ctrl->lt_info_num) { SHR_ERR_EXIT(SHR_E_INTERNAL); } else if (out->count < ctrl->ctr_eflex_field_info[t].num_data_fields) { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out fields supplied to lookup is too " "small to hold the desired fields.\n"))); SHR_ERR_EXIT(SHR_E_MEMORY); } } else { LOG_ERROR(BSL_LOG_MODULE, (BSL_META_U(unit, "out not supplied to lookup.\n"))); SHR_ERR_EXIT(SHR_E_INTERNAL); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_lookup(unit, EGRESS, STATE_EFLEX, req_flags, lkup_type, in, out)); exit: SHR_FUNC_EXIT(); } /*! * \brief Stage callback function of FLEX_STATE_EGR_GROUP_ACTION_PROFILE * to insert, update, delete IMM LT entry. * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] op_arg The operation arguments. * \param [in] event_reason Reason for the entry event. * \param [in] key_fields Linked list of the key fields identifying * the entry. * \param [in] data_fields Linked list of the data fields in the * modified entry. * \param [in] context Pointer that was given during registration. * The callback can use this pointer to retrieve some * context. * \param [out] output_fields Linked list of the output fields in the * modified entry. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_egr_group_action_lt_stage_cb( int unit, bcmltd_sid_t sid, const bcmltd_op_arg_t *op_arg, bcmimm_entry_event_t event_reason, const bcmltd_field_t *key_fields, const bcmltd_field_t *data_fields, void *context, bcmltd_fields_t *output_fields) { uint64_t req_flags; SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(key_fields, SHR_E_PARAM); SHR_NULL_CHECK(op_arg, SHR_E_PARAM); if (event_reason != BCMIMM_ENTRY_DELETE) { SHR_NULL_CHECK(output_fields, SHR_E_PARAM); } req_flags = bcmptm_lt_entry_attrib_to_ptm_req_flags(op_arg->attrib); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_stage(unit, EGRESS, STATE_EFLEX, req_flags, event_reason, key_fields, data_fields, output_fields)); exit: SHR_FUNC_EXIT(); } /*! * \brief Entry limit get callback function of FLEX_STATE_EGR_ACTION_PROFILE * * \param [in] unit Unit number. * \param [in] sid Logical table ID. * \param [in] count Entry limit value. * \return SHR_E_NONE on success and error code otherwise. */ static int bcmcth_state_eflex_egr_group_action_lt_ent_limit_get_cb(int unit, uint32_t trans_id, bcmltd_sid_t sid, uint32_t *count) { SHR_FUNC_ENTER(unit); SHR_NULL_CHECK(count, SHR_E_PARAM); SHR_IF_ERR_VERBOSE_EXIT (bcmcth_ctr_eflex_group_action_lt_ent_limit_get(unit, EGRESS, STATE_EFLEX, count)); exit: SHR_FUNC_EXIT(); } /********************************************************************** * Public functions */ /* * Function to register callback handlers for * CTR_xxx_EFLEX_GROUP_ACTION_PROFILE LTs */ int bcmcth_ctr_eflex_imm_group_action_register(int unit) { bcmimm_lt_cb_t ctr_eflex_lt_cb; SHR_FUNC_ENTER(unit); /* Register CTR_ING_EFLEX_GROUP_ACTION_PROFILE handler */ sal_memset(&ctr_eflex_lt_cb, 0, sizeof(bcmimm_lt_cb_t)); ctr_eflex_lt_cb.op_stage = bcmcth_ctr_eflex_ing_group_action_lt_stage_cb; ctr_eflex_lt_cb.op_lookup = bcmcth_ctr_eflex_ing_group_action_lt_lookup_cb; ctr_eflex_lt_cb.ent_limit_get = bcmcth_ctr_eflex_ing_group_action_lt_ent_limit_get_cb; SHR_IF_ERR_VERBOSE_EXIT( bcmimm_lt_event_reg(unit, CTR_ING_EFLEX_GROUP_ACTION_PROFILEt, &ctr_eflex_lt_cb, NULL)); /* Register CTR_EGR_EFLEX_GROUP_ACTION_PROFILE handler */ sal_memset(&ctr_eflex_lt_cb, 0, sizeof(bcmimm_lt_cb_t)); ctr_eflex_lt_cb.op_stage = bcmcth_ctr_eflex_egr_group_action_lt_stage_cb; ctr_eflex_lt_cb.op_lookup = bcmcth_ctr_eflex_egr_group_action_lt_lookup_cb; ctr_eflex_lt_cb.ent_limit_get = bcmcth_ctr_eflex_egr_group_action_lt_ent_limit_get_cb; SHR_IF_ERR_VERBOSE_EXIT( bcmimm_lt_event_reg(unit, CTR_EGR_EFLEX_GROUP_ACTION_PROFILEt, &ctr_eflex_lt_cb, NULL)); exit: SHR_FUNC_EXIT(); } /* * Function to register callback handlers for * STATE_xxx_EFLEX_GROUP_ACTION_PROFILE LTs */ int bcmcth_state_eflex_imm_group_action_register(int unit) { bcmimm_lt_cb_t state_eflex_lt_cb; SHR_FUNC_ENTER(unit); /* Register FLEX_STATE_ING_GROUP_ACTION_PROFILE handler */ sal_memset(&state_eflex_lt_cb, 0, sizeof(bcmimm_lt_cb_t)); state_eflex_lt_cb.op_stage = bcmcth_state_eflex_ing_group_action_lt_stage_cb; state_eflex_lt_cb.op_lookup = bcmcth_state_eflex_ing_group_action_lt_lookup_cb; state_eflex_lt_cb.ent_limit_get = bcmcth_state_eflex_ing_group_action_lt_ent_limit_get_cb; SHR_IF_ERR_VERBOSE_EXIT( bcmimm_lt_event_reg(unit, FLEX_STATE_ING_GROUP_ACTION_PROFILEt, &state_eflex_lt_cb, NULL)); /* Register FLEX_STATE_EGR_GROUP_ACTION_PROFILE handler */ sal_memset(&state_eflex_lt_cb, 0, sizeof(bcmimm_lt_cb_t)); state_eflex_lt_cb.op_stage = bcmcth_state_eflex_egr_group_action_lt_stage_cb; state_eflex_lt_cb.op_lookup = bcmcth_state_eflex_egr_group_action_lt_lookup_cb; state_eflex_lt_cb.ent_limit_get = bcmcth_state_eflex_egr_group_action_lt_ent_limit_get_cb; SHR_IF_ERR_VERBOSE_EXIT( bcmimm_lt_event_reg(unit, FLEX_STATE_EGR_GROUP_ACTION_PROFILEt, &state_eflex_lt_cb, NULL)); exit: SHR_FUNC_EXIT(); }
Rossojo/edmm
TOSCin/src/main/java/io/github/edmm/plugins/cfn/model/types/DetectiveType.java
package io.github.edmm.plugins.cfn.model.types; import io.github.edmm.model.edimm.ComponentType; public enum DetectiveType { Graph(ComponentType.DBaaS), MemberInvitation(ComponentType.Software_Component); ComponentType componentType; DetectiveType(ComponentType componentType) { this.componentType = componentType; } public ComponentType toComponentType() { return this.componentType; } }
stfung77/java-stellar-anchor-sdk
platform/src/main/java/org/stellar/anchor/platform/data/PaymentStreamerCursorRepo.java
<gh_stars>1-10 package org.stellar.anchor.platform.data; import java.util.Optional; import org.springframework.data.repository.CrudRepository; public interface PaymentStreamerCursorRepo extends CrudRepository<PaymentStreamerCursor, String> { Optional<PaymentStreamerCursor> findById(String id); Optional<PaymentStreamerCursor> findByAccountId(String accountId); }
NikolaVodenicharov/Java-OOP-Advanced
InterfacesAndAbstraction/MilitaryElite/src/Classes/CommandoImpl.java
package Classes; import Interfaces.Commando; import Interfaces.Mission; import javafx.scene.web.HTMLEditorSkin; import java.util.Collection; public class CommandoImpl extends SpecialisedSoldierImpl implements Commando{ private Collection<Mission> missions; public CommandoImpl( String id, String firstName, String lastName, double salary, String corp, Collection<Mission> missions) { super(id, firstName, lastName, salary, corp); this.missions = missions; } @Override public Collection<Mission> getMissions() { return this.missions; } @Override public void completeMission() { } @Override public String toString(){ StringBuilder formatted = new StringBuilder(); formatted .append(super.toString()) .append(System.lineSeparator()) .append("Missions:") .append(System.lineSeparator()); for (Mission mission : missions) { formatted .append(" ") .append(mission) .append(System.lineSeparator()); } return formatted.toString().trim(); } }
jkim00c/jellyfish-api
db/migrate/20141227172536_alter_orders_for_order_items_and_carts.rb
<gh_stars>0 class AlterOrdersForOrderItemsAndCarts < ActiveRecord::Migration def change remove_column :orders, :product_id remove_column :orders, :cloud_id remove_column :orders, :provision_status end end
ZongoForSpeed/ProjectEuler
problemes/probleme2xx/probleme264.cpp
#include "problemes.h" #include "arithmetique.h" typedef long long nombre; typedef std::vector<nombre> vecteur; namespace { long double f(nombre xa, nombre xb) { // Wolfram alpha return static_cast<long double>(-std::sqrt((-(xa * xa) + 2 * std::sqrt( xa * xa * xa * xa + 2 * xa * xa * xa * xb - 10 * xa * xa * xa + 3 * xa * xa * xb * xb - 50 * xa * xa * xb + 125 * xa * xa + 2 * xa * xb * xb * xb - 50 * xa * xb * xb + 300 * xa * xb - 500 * xa + xb * xb * xb * xb - 10 * xb * xb * xb + 125 * xb * xb - 500 * xb + 625) + 2 * xa * xb - 10 * xa + 2 * xb * xb - 10 * xb + 25) / 3)); } template<typename N> N norme(N x, N y) { return x * x + y * y; } long double perimetre(nombre xa, nombre ya, nombre xb, nombre yb, nombre xc, nombre yc) { return std::hypot(1.0L * xa - xb, ya - yb) + std::hypot(1.0L * xa - xc, ya - yc) + std::hypot(1.0L * xb - xc, yb - yc); } } ENREGISTRER_PROBLEME(264, "Triangle Centres") { // Consider all the triangles having: // // All their vertices on lattice points. // Circumcentre at the origin O. // Orthocentre at the point H(5, 0). // There are nine such triangles having a perimeter ≤ 50. // Listed and shown in ascending order of their perimeter, they are: // // A(-4, 3), B(5, 0), C(4, -3) // A(4, 3), B(5, 0), C(-4, -3) // A(-3, 4), B(5, 0), C(3, -4) // // A(3, 4), B(5, 0), C(-3, -4) // A(0, 5), B(5, 0), C(0, -5) // A(1, 8), B(8, -1), C(-4, -7) // // A(8, 1), B(1, -8), C(-4, 7) // A(2, 9), B(9, -2), C(-6, -7) // A(9, 2), B(2, -9), C(-6, 7) // // The sum of their perimeters, rounded to four decimal places, is 291.0089. // // Find all such triangles with a perimeter ≤ 10^5. // Enter as your answer the sum of their perimeters rounded to four decimal places. long double limite = 100000.0L; // xa² + ya² = xb² + yb² = xc² + yc², xa + xb + xc = 5, ya + yb + yc = 0 long double resultat = 0; nombre gr = 16000; for (nombre xa = 0; xa + gr > 0; --xa) for (nombre xb = xa; xb <= (-xa + 5) / 2; ++xb) { long double fya = f(xa, xb); if (std::abs(fya - std::round(fya)) < std::numeric_limits<long double>::epsilon()) { auto ya = static_cast<nombre>(fya); auto fyb = static_cast<long double>(std::sqrt(xa * xa + ya * ya - xb * xb)); if (std::abs(fyb - std::round(fyb)) < std::numeric_limits<long double>::epsilon()) { auto yb = static_cast<nombre>(fyb); nombre yc = -ya - yb; nombre xc = -xa - xb + 5; long double p = perimetre(xa, ya, xb, yb, xc, yc); if (norme(xa, ya) == norme(xb, yb) && norme(xb, yb) == norme(xc, yc) && p <= limite) if ((xa != xb || ya != yb) && (xc != xb || yc != yb) && (xa != xc || ya != yc)) { if ((xa == xb && ya == -yb && yc == 0) || (xb == xc && yb == -yc && ya == 0)) resultat += p; else resultat += 2 * p; } } } } return std::to_fixed(resultat, 4); }
tuxafgmur/OLD_Dhollmen_Kernel
drivers/staging/brcm80211/brcmsmac/wl_export.h
/* * Copyright (c) 2010 Broadcom Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _wl_export_h_ #define _wl_export_h_ /* misc callbacks */ struct wl_info; struct wl_if; struct wlc_if; extern void wl_init(struct wl_info *wl); extern uint wl_reset(struct wl_info *wl); extern void wl_intrson(struct wl_info *wl); extern u32 wl_intrsoff(struct wl_info *wl); extern void wl_intrsrestore(struct wl_info *wl, u32 macintmask); extern int wl_up(struct wl_info *wl); extern void wl_down(struct wl_info *wl); extern void wl_txflowcontrol(struct wl_info *wl, struct wl_if *wlif, bool state, int prio); extern bool wl_alloc_dma_resources(struct wl_info *wl, uint dmaddrwidth); extern bool wl_rfkill_set_hw_state(struct wl_info *wl); /* timer functions */ struct wl_timer; extern struct wl_timer *wl_init_timer(struct wl_info *wl, void (*fn) (void *arg), void *arg, const char *name); extern void wl_free_timer(struct wl_info *wl, struct wl_timer *timer); extern void wl_add_timer(struct wl_info *wl, struct wl_timer *timer, uint ms, int periodic); extern bool wl_del_timer(struct wl_info *wl, struct wl_timer *timer); extern void wl_msleep(struct wl_info *wl, uint ms); #endif /* _wl_export_h_ */
ethansaxenian/RosettaDecode
lang/Python/literals-string-3.py
<gh_stars>1-10 ''' single triple quote ''' """ double triple quote """
thomasmeadows/uber-api-exmaple-app
server/routes/api/history.js
<filename>server/routes/api/history.js const ensureAuthenticated = require('../policies/ensureAuthenticated'); const { ROUTES } = require('../../config/constants'); module.exports = function(app) { app.get(ROUTES.API.HISTORY, ensureAuthenticated, (req, res) => { return app.models.History.find({ user: req.user._id }) .limit(50) .skip(Number(req.query.skip)) .then(userHistoryFound => { return res.send(userHistoryFound); }) .catch(err => { console.log('error', err); }); }); };
atianxia/cas-study
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/oidc/OidcProperties.java
<filename>core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/oidc/OidcProperties.java package org.apereo.cas.configuration.model.support.oidc; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; /** * This is {@link OidcProperties}. * * @author <NAME> * @since 5.0.0 */ public class OidcProperties { private String issuer = "http://localhost:8080/cas/oidc"; private int skew = 5; private Resource jwksFile = new FileSystemResource("/etc/cas/keystore.jwks"); public String getIssuer() { return issuer; } public void setIssuer(final String issuer) { this.issuer = issuer; } public int getSkew() { return skew; } public void setSkew(final int skew) { this.skew = skew; } public Resource getJwksFile() { return jwksFile; } public void setJwksFile(final Resource jwksFile) { this.jwksFile = jwksFile; } }
casid/jusecase-properties-editor
src/test/java/org/jusecase/properties/usecases/InitializeTest.java
<filename>src/test/java/org/jusecase/properties/usecases/InitializeTest.java package org.jusecase.properties.usecases; import org.junit.Before; import org.junit.Test; import org.jusecase.UsecaseTest; import org.jusecase.properties.gateways.PropertiesGatewayTrainer; import org.jusecase.properties.gateways.SettingsGatewayTrainer; import org.jusecase.properties.gateways.UndoableRequestGateway; import org.jusecase.properties.usecases.Initialize.Request; import org.jusecase.properties.usecases.Initialize.Response; import static org.assertj.core.api.Assertions.assertThat; import static org.jusecase.Builders.a; import static org.jusecase.properties.entities.Builders.settings; import static org.jusecase.properties.entities.Builders.testPath; public class InitializeTest extends UsecaseTest<Request, Response> { private PropertiesGatewayTrainer propertiesGatewayTrainer = new PropertiesGatewayTrainer(); private SettingsGatewayTrainer settingsGatewayTrainer = new SettingsGatewayTrainer(); private UndoableRequestGateway undoableRequestGateway = new UndoableRequestGateway(); @Before public void setUp() { usecase = new Initialize(propertiesGatewayTrainer, settingsGatewayTrainer, undoableRequestGateway); } @Test public void noLastFile() { givenLastFile(null); whenRequestIsExecuted(); propertiesGatewayTrainer.thenNoPropertiesAreLoaded(); } @Test public void lastFileThatDoesNotExist_noPropertiesAreLoaded() { givenLastFile(a(testPath("this-does-not-exist.properties")).toString()); whenRequestIsExecuted(); propertiesGatewayTrainer.thenNoPropertiesAreLoaded(); } @Test public void lastFileThatExists_propertiesAreLoaded() { givenLastFile(a(testPath("resources.properties")).toString()); whenRequestIsExecuted(); thenLoadedPropertiesAre( "resources.properties", "resources_de.properties", "resources_es.properties" ); } private void givenLastFile(String lastFile) { settingsGatewayTrainer.givenSettings(a(settings().withLastFile(lastFile))); } private void thenLoadedPropertiesAre(String... fileNames) { propertiesGatewayTrainer.thenLoadedPropertiesAre(fileNames); assertThat(response.fileNames).containsExactlyInAnyOrder(fileNames); } }
websemantics/oea.svg
src/Java/Awt/Geom/gRectangle.js
/** * Java.js : gRectangle * * @author <NAME>, PhD. <<EMAIL>> * @copyright 2004-2016 Web Semantics, Inc. (http://websemantics.io) * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 6th January 2005 * @package websemantics/oea/java.js/awt/geom */ /** * Class gRectangle [ This was named gRectangle becuase of naming comnfilc * Rectangle from Draw2D.svg ] */ gRectangle.prototype = new Rectangle2D(); function gRectangle(x, y, width, height) { /* implements Shape, Serializable */ // Forms: // ===== // (1) gRectangle(); // (2) gRectangle(gRectangle r); // (3) gRectangle(x,y,width,height); // (4) gRectangle(width,height); // (5) gRectangle(Point p, Dimension d) // (6) gRectangle(Point p) // (7) gRectangle(Dimension d) this.className = "gRectangle"; /* No parameters */ if (x == undefined && y == undefined && width == undefined && height == undefined) { x = 0; y = 0; width = 0; height = 0; } // Two parameters */ if (x != undefined && y != undefined && width == undefined && height == undefined) { if (x instanceof Point && y instanceof Dimension) { var p = x; var d = y; x = p.getX(); y = p.getY(); width = d.getWidth(); height = d.getHeight(); } else { width = x; height = y; x = 0; y = 0; } } /* One parameter */ if (x instanceof gRectangle) { var r = x; x = r.getX(); y = r.getY(); width = r.getWidth(); height = r.getHeight(); } else if (x instanceof Point) { var p = x; x = p.getX(); y = p.getY(); width = 0; height = 0; } else if (x instanceof Dimension) { var d = x; x = 0; y = 0; width = d.getWidth(); height = d.getHeight(); } /* Four parameters or one of the above */ /* int */ this.x = x; /* int */ this.y = y; /* int */ this.width = width; /* int */ this.height = height; } gRectangle.prototype.getX = function() { return this.x; } gRectangle.prototype.getY = function() { return this.y; } gRectangle.prototype.getWidth = function() { return this.width; } gRectangle.prototype.getHeight = function() { return this.height; } gRectangle.prototype.getBounds = function() { // Summary: // Gets the bounding gRectangle of this gRectangle. return new gRectangle(this.x, this.y, this.width, this.height); } gRectangle.prototype.getBounds2D = function() { // Summary: // Return the high precision bounding box of this rectangle return new gRectangle(this.x, this.y, this.width, this.height); } gRectangle.prototype.setBounds = function(x, y, width, height) { // Summary: // Sets the bounding gRectangle of this gRectangle // // Forms: // ====== // (1) setBounds(gRectangle r); // (2) setBounds(x,y,width,height); if (x instanceof gRectangle) { var r = x; this.setBounds(r.getX(), r.getY(), r.getWidth(), r.getHeight()); return; } this.reshape(x, y, width, height); } gRectangle.prototype.setRect = function( /* double */ x, /* double */ y, /* double */ width, /* double */ height) { // Summary: // Sets the bounds of this gRectangle to the specified x, y, width,and height. /* int */ var x0 = Math.floor(x); /* int */ var y0 = Math.floor(y); /* int */ var x1 = Math.ceil(x + width); /* int */ var y1 = Math.ceil(y + height); this.setBounds(x0, y0, x1 - x0, y1 - y0); } gRectangle.prototype.reshape = function( /* int */ x, /* int */ y, /* int */ width, /* int */ height) { // Summary: // Sets the bounding gRectangle of this gRectangle to the specified x, y, width, and height. this.x = x; this.y = y; this.width = width; this.height = height; } gRectangle.prototype.getLocation = function() { // Summary: // Returns the location of this gRectangle. return new Point(this.x, this.y); } gRectangle.prototype.setLocation = function(x, y) { // Summary: // Moves this gRectangle to the specified location. // // Forms: // ====== // (1) setLocation(x,y) // (2) setLocation(Point p) if (x instanceof Point) { var p = x; this.setLocation(p.getX(), p.getY()); return; } this.move(x, y); } gRectangle.prototype.move = function(x, y) { // Summary: // Moves this gRectangle to the specified location. this.x = x; this.y = y; } gRectangle.prototype.translate = function(dx, dy) { // Summary: // Translates this point, at location x,y, by dx and dy this.x += dx; this.y += dy; } gRectangle.prototype.getSize = function() { // Summary: // Gets the size of this gRectangle, represented by the returned Dimension. return new Dimension(this.width, this.height); } gRectangle.prototype.setSize = function(width, height) { // Summary: // Sets the size of this gRectangle // // Forms: // ====== // (1) setSize(width,height) // (2) setSize(Dimension d) if (width instanceof Dimension) { var d = width; this.setSize(d.getWidth(), d.getHeight()); return; } this.resize(width, height); } gRectangle.prototype.resize = function(width, height) { // Summary: // Sets the size of this gRectangle to the specified width and height. this.width = width; this.height = height; } gRectangle.prototype.contains = function(x, y, width, height) { // Summary: // Checks whether or not this gRectangle contains the specified Point. // // Forms: // ====== // (1) contains(x,y) // (2) contains(Point p) // (3) contains(x,y,width,height) // (3) contains(gRectangle r) if (x == undefined) return false; // One parameters if (x instanceof Point) { var p = x; return this.contains(p.getX(), p.getY()); } if (x instanceof gRectangle) { var r = x; return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } // Two parameters if (x && y && !width && !height) return this.inside(x, y); // Four parameters // Checs whether this gRectangle entirely contains the gRectangle at the specified location var X = x; var Y = y; var W = width; var H = height; var x = this.x; var y = this.y; var w = this.width; var h = this.height; if ((w | h | W | H) < 0) { return false; } // At least one of the dimensions is negative... if (X < x || Y < y) { return false; } // Note: if any dimension is zero, tests below must return false... w += x; W += X; if (W <= X) { // X+W overflowed or W was zero, return false if... // either original w or W was zero or // x+w did not overflow or // the overflowed x+w is smaller than the overflowed X+W if (w >= x || W > w) { return false; } } else { // X+W did not overflow and W was not zero, return false if... // original w was zero or // x+w did not overflow and x+w is smaller than X+W if (w >= x && W > w) { return false; } } h += y; H += Y; if (H <= Y) { if (h >= y || H > h) { return false; } } else { if (h >= y && H > h) { return false; } } return true; } gRectangle.prototype.inside = function(X, Y) { // Summary: // Checks whether or not this gRectangle contains the point at the specified location var x = this.x; var y = this.y; var w = this.width; var h = this.height; if ((w | h) < 0) { return false; } // At least one of the dimensions is negative... if (X < x || Y < y) { return false; } // Note: if either dimension is zero, tests below must return false... w += x; h += y; // overflow || intersect return ((w < x || w > X) && (h < y || h > Y)); } gRectangle.prototype.intersects = function( /* gRectangle */ r) { // Summary: // Determines whether or not this gRectangle and the specified gRectangle intersect. // // Two rectangles intersect if their intersection is nonempty. var tw = this.width; var th = this.height; var rw = r.width; var rh = r.height; if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { return false; } var tx = this.x; var ty = this.y; var rx = r.x; var ry = r.y; rw += rx; rh += ry; tw += tx; th += ty; // overflow || intersect return ((rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry)); } gRectangle.prototype.intersection = function( /* gRectangle */ r) { // Summary: // Computes the intersection of this gRectangle with the specified gRectangle. // //Returns a new gRectangle that represents the intersection of the two rectangles. //If the two rectangles do not intersect, the result will be an empty rectangle. var tx1 = this.x; var ty1 = this.y; var rx1 = r.x; var ry1 = r.y; var tx2 = tx1; tx2 += this.width; var ty2 = ty1; ty2 += this.height; var rx2 = rx1; rx2 += r.width; var ry2 = ry1; ry2 += r.height; if (tx1 < rx1) tx1 = rx1; if (ty1 < ry1) ty1 = ry1; if (tx2 > rx2) tx2 = rx2; if (ty2 > ry2) ty2 = ry2; tx2 -= tx1; ty2 -= ty1; // tx2,ty2 will never overflow (they will never be // larger than the smallest of the two source w,h) // they might underflow, though... if (tx2 < this.MIN_VALUE) tx2 = this.MIN_VALUE; if (ty2 < this.MIN_VALUE) ty2 = this.MIN_VALUE; return new gRectangle(tx1, ty1, tx2, ty2); } gRectangle.prototype.union = function( /* gRectangle */ r) { // Summary: // Computes the union of this gRectangle with the specified gRectangle. // // Returns a new gRectangle that represents the union of the two rectangles var x1 = Math.min(this.x, r.x); var x2 = Math.max(this.x + this.width, r.x + r.width); var y1 = Math.min(this.y, r.y); var y2 = Math.max(this.y + this.height, r.y + r.height); return new gRectangle(x1, y1, x2 - x1, y2 - y1); } gRectangle.prototype.add = function(newx, newy, newwidth, newheight) { // Summary: // Adds a point, specified by the integer arguments newx and newy, to this gRectangle. // OR // Adds a gRectangle to this gRectangle. // // The resulting gRectangle is the smallest gRectangle that contains both the original // gRectangle and the specified point OR The resulting gRectangle is the union of the two rectangles. // // After adding a point/rectangle, a call to contains with the added point as an argument does // not necessarily return true. // The contains method does not return true for points on the right or bottom edges of a gRectangle. // Therefore, if the added point falls on the right or bottom edge of the enlarged gRectangle, // contains returns false for that point. // // Forms: // ====== // (1) add(point pt) // (2) add(newx, newy) // (3) add(gRectangle r) if (newx instanceof Point) { var pt = newx; this.add(pt.getX(), pt.getY(), 0, 0); return; } if (newx instanceof gRectangle) { var r = newx; this.add(r.getX(), r.getY(), r.getWidth(), r.getHeight()); return; } var x1 = Math.min(this.x, newx); var x2 = Math.max(this.x + this.width, newx + newwidth); var y1 = Math.min(this.y, newy); var y2 = Math.max(this.y + this.height, newy + newheight); this.x = x1; this.y = y1; this.width = x2 - x1; this.height = y2 - y1; } gRectangle.prototype.grow = function(h, v) { // Summary: // Resizes the gRectangle both horizontally and vertically. // // This method modifies the gRectangle so that it is h units larger on both the left and right side, // and v units larger at both the top and bottom. this.x -= h; this.y -= v; this.width += h * 2; this.height += v * 2; } gRectangle.prototype.isEmpty = function(h, v) { // Summary: // Determines whether or not this gRectangle is empty. // // A gRectangle is empty if its width or its height is less than or equal to zero. return (this.width <= 0) || (this.height <= 0); } gRectangle.prototype.outcode = function( /* double */ x, /* double */ y) { // Summary: // Determines where the specified coordinates lie with respect to this gRectangle. // // This method computes a binary OR of the appropriate mask values indicating, for each side of this // gRectangle, whether or not the specified coordinates are on the same side of the edge as the rest of this gRectangle. /* * Note on casts to double below. If the arithmetic of * x+w or y+h is done in int, then we may get integer * overflow. By converting to double before the addition * we force the addition to be carried out in double to * avoid overflow in the comparison. */ var out = 0; if (this.width <= 0) { out |= this.OUT_LEFT | this.OUT_RIGHT; } else if (x < this.x) { out |= this.OUT_LEFT; } else if (x > this.x + this.width) { out |= this.OUT_RIGHT; } if (this.height <= 0) { out |= this.OUT_TOP | this.OUT_BOTTOM; } else if (y < this.y) { out |= this.OUT_TOP; } else if (y > this.y + this.height) { out |= this.OUT_BOTTOM; } return out; } gRectangle.prototype.createIntersection = function( /* Rectangle2D */ r) { // Summary: // Returns a new Rectangle2D object representing the intersection of this gRectangle with the specified Rectangle2D. // // A gRectangle is empty if its width or its height is less than or equal to zero. if (r instanceof gRectangle) { return this.intersection(r); } /* NOT IMPLEMENTED Rectangle2D var dest = new Rectangle2D.Double(); Rectangle2D.intersect(this, r, dest); return dest; */ } gRectangle.prototype.createUnion = function( /* Rectangle2D */ r) { // Summary: // Returns a new Rectangle2D object representing the union of this gRectangle with the specified Rectangle2D. if (r instanceof gRectangle) { return this.union(r); } /* NOT IMPLEMENTED Rectangle2D dest = new Rectangle2D.Double(); Rectangle2D.union(this, r, dest); return dest; */ return false; // [Remove] } gRectangle.prototype.equals = function( /* Object */ obj) { // Summary: // Checks whether two rectangles are equal. // // The result is true if and only if the argument is not null and is a gRectangle // object that has the same top-left corner, width, and height as this gRectangle. // // Forms: // ====== // (1) equals(gRectangle r) // (2) equals(Rectangle2D r) if (obj instanceof gRectangle) { var r = obj; return ((x == r.x) && (y == r.y) && (width == r.width) && (height == r.height)); } /* NOT IMPLEMENTED return super.equals(obj); */ return false; // [Remove] }
veriktig/scandium
ScUI/src/com/veriktig/scandium/ui/shell/package-info.java
package com.veriktig.scandium.ui.shell;
adrklang/persys
per-parent/per-api/src/main/java/com/lhstack/service/oss/IOssService.java
package com.lhstack.service.oss; import com.lhstack.entity.fastdfs.FastResult; import com.lhstack.entity.oss.OssEntity; import com.lhstack.service.IBaseService; import java.util.List; import java.util.Map; public interface IOssService extends IBaseService<String, OssEntity> { Boolean deleteObjects(String token, List<String> keys) throws Exception; Boolean deleteObject(String token, String key) throws Exception; List<FastResult> uploadMultiFile(String generatorType, Map<String, byte[]> mappingContents, String token, String directory); FastResult upload(String generatorType, byte[] filePartToBytes, String filename, String token, String directory) throws Exception; }
Soundatnj/Codegen
celerio-engine/src/main/java/com/jaxio/celerio/model/support/validation/ValidationRelation.java
/* * Copyright 2015 JAXIO http://www.jaxio.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaxio.celerio.model.support.validation; import com.jaxio.celerio.model.Relation; import com.jaxio.celerio.spi.RelationSpi; import com.jaxio.celerio.template.ImportsContext; import com.jaxio.celerio.util.AnnotationBuilder; import java.util.List; public class ValidationRelation implements RelationSpi { private Relation relation; // --------------------------------------- // Relation SPI Implementation // --------------------------------------- @Override public boolean compatibleWith(Relation relation) { return relation.isManyToOne() || relation.isOneToOne(); } @Override public String velocityVar() { return "validation"; } @Override public Object getTarget() { return this; } @Override public void init(Relation relation) { this.relation = relation; } // -------------------------------------------- // Validation Annotations, used from templates // -------------------------------------------- public List<String> getAnnotations() { AnnotationBuilder result = new AnnotationBuilder(); result.add(getNotNullAnnotation()); return result.getAnnotations(); } /** * Applies only to ManyToOne or OneToOne. * When x to one has an inverse relation, we never mark it as @NotNull * as it would break navigation (indeed, the mandatory value is set transparently once the entity is added to the collection) * However, in test (XxxGenerator), we must take mandatory into account... */ public String getNotNullAnnotation() { if (!relation.isManyToOne() && !relation.isOneToOne()) { return ""; } if (relation.isMandatory() && !relation.hasInverse()) { if (relation.getFromEntity().getName().equals(relation.getToEntity().getName())) { // TODO ?: mandatory relation on self is complicated to handled // in tests (model generator)... so we just ignore it. return ""; } if (relation.getFromAttribute().isInPk()) { // TODO: not sure why, but integration tests fail if we don't skip this case. return ""; } ImportsContext.addImport("javax.validation.constraints.NotNull"); return "@NotNull"; } else { return ""; } } }
riquelz/jubelio-test-frontend
src/components/layout/header.js
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { navigate } from './../../commons/actions/navigate-action' import { logout } from './../auth/store/actions' class Header extends React.Component{ homeClick = () => { this.props.navigate('/') } loginClick = () => { this.props.navigate('/login') } logoutClick = () => { this.props.logout() } renderButton = () => { if(this.props.isAuthenticate){ return(<a href="javascript:;" className="button is-light" onClick={this.logoutClick}> {this.props.email} </a>) } return(<a href="javascript:;" className="button is-light" onClick={this.loginClick}> Log in </a>) } render(){ return( <nav className="navbar" role="navigation" aria-label="main navigation" style={{borderBottom: 'solid 1px #dddddd',}}> <div className="navbar-brand"> <a className="navbar-item" href="javascript:;" onClick={this.homeClick}> <img src="https://www.jubelio.com/images/logo_dark.png" alt="Jubelio Test Frontend" width="112" height="28"/> </a> <a role="button" className="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="navbarBasicExample" className="navbar-menu"> <div className="navbar-start"> <a href="javascript:;" className="navbar-item" onClick={this.homeClick}> Home </a> </div> <div className="navbar-end"> <div className="navbar-item"> <div className="buttons"> {this.renderButton()} </div> </div> </div> </div> </nav> ) } } const mapStateToProps = (state) => ({ ...state.auth, }) const mapDispatchToProps = (dispatch => ({ navigate : navigate, logout : logout }))() export default connect(mapStateToProps, mapDispatchToProps)(Header)
bprager/connector
src/main/java/org/observertc/webrtc/connector/sources/bigquerysources/observabletables/FinishedCalls.java
<gh_stars>0 package org.observertc.webrtc.connector.sources.bigquerysources.observabletables; import com.google.cloud.bigquery.FieldValue; import com.google.cloud.bigquery.FieldValueList; import org.observertc.webrtc.connector.common.BigQueryService; import org.observertc.webrtc.schemas.reports.FinishedCall; import org.observertc.webrtc.schemas.reports.ReportType; import java.util.ArrayList; import java.util.List; public class FinishedCalls extends RecordMapperAbstract { public static final String CALL_UUID_FIELD_NAME = "callUUID"; public static final String CALL_NAME_FIELD_NAME = "callName"; public FinishedCalls(BigQueryService bigQueryService, String tableName) { super(bigQueryService, tableName, ReportType.FINISHED_CALL); } @Override protected Object makePayload(FieldValueList row) { // String type String callUUID = this.getValue(row, CALL_UUID_FIELD_NAME, FieldValue::getStringValue, "NOT FOUND"); String callName = this.getValue(row, CALL_NAME_FIELD_NAME, FieldValue::getStringValue, "NOT FOUND"); var result = FinishedCall.newBuilder() .setCallUUID(callName) .setCallUUID(callUUID); return result.build(); } @Override protected List<String> getPayloadFieldNames() { List<String> result = new ArrayList<>(); result.add(CALL_UUID_FIELD_NAME); result.add(CALL_NAME_FIELD_NAME); return result; } }
cuiyuemin365/books
HowTomcatWorks/apache-tomcat-5.5.36-src/connectors/util/java/org/apache/tomcat/util/threads/Reaper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.threads; /** * The reaper is a background thread with which ticks every minute * and calls registered objects to allow reaping of old session * data. * * @author <NAME> [<EMAIL>] * @author <NAME> */ public class Reaper extends Thread { private static org.apache.commons.logging.Log log= org.apache.commons.logging.LogFactory.getLog(Reaper.class ); private boolean daemon = false; public Reaper() { if (daemon) this.setDaemon(true); this.setName("TomcatReaper"); } public Reaper(String name) { if (daemon) this.setDaemon(true); this.setName(name); } private long interval = 1000 * 60; //ms // XXX TODO Allow per/callback interval, find next, etc // Right now the "interval" is used for all callbacks // and it represent a sleep between runs. ThreadPoolRunnable cbacks[] = new ThreadPoolRunnable[30]; // XXX max Object tdata[][] = new Object[30][]; // XXX max int count = 0; /** Adding and removing callbacks is synchronized */ Object lock = new Object(); static boolean running = true; // XXX Should be called 'interval' not defaultInterval public void setDefaultInterval(long t) { interval = t; } public long getDefaultIntervale() { return interval; } public int addCallback(ThreadPoolRunnable c, int interval) { synchronized (lock) { cbacks[count] = c; count++; return count - 1; } } public void removeCallback(int idx) { synchronized (lock) { count--; cbacks[idx] = cbacks[count]; cbacks[count] = null; } } public void startReaper() { running = true; this.start(); } public synchronized void stopReaper() { running = false; if (log.isDebugEnabled()) log.debug("Stop reaper "); this.interrupt(); // notify() doesn't stop sleep } public void run() { while (running) { if (!running) break; try { Thread.sleep(interval); } catch (InterruptedException ie) { // sometimes will happen } if (!running) break; for (int i = 0; i < count; i++) { ThreadPoolRunnable callB = cbacks[i]; // it may be null if a callback is removed. // I think the code is correct if (callB != null) { callB.runIt(tdata[i]); } if (!running) break; } } } }
LSDuarte/java-orientado-objeto
src/br/com/algaworks/Aulas/Interfaces/TesteInterface.java
package com.algaworks.curso.fjoo.interfaces; public class TesteInterface { public static void main(String[] args) { Imprimivel i = new NotaFiscal(1234); i.imprimir(); EnviavelPorEmail e = (EnviavelPorEmail) i; e.enviar("<EMAIL>"); NotaFiscal n = (NotaFiscal) e; n.adicionarPedido("caixa de leite"); } }
acntech/bussorakel-react
src/js/components/TravelProposals.js
import React from "react"; import Spinner from 'react-webpack-spinner' import TravelProposal from "./TravelProposal" export default class TravelProposals extends React.Component { render() { const { fetching, travels, error } = this.props; if (fetching) { return <Spinner width={32} height={32} color={'black'} />; } if (error) { return <div class="alert alert-danger col-md-4 col-md-offset-4"> <strong>Oh snap!</strong> Noe har feilet, prøv igjen... </div>; } const TravelProposals = travels.map((proposal) => { return <TravelProposal {...proposal} />; }); return ( <div> {TravelProposals} </div> ); } }
lhuett/insights-core
insights/parsers/rhn_conf.py
<reponame>lhuett/insights-core<filename>insights/parsers/rhn_conf.py """ RHNConf - file ``/etc/rhn/rhn.conf`` ==================================== """ from insights import Parser, parser, LegacyItemAccess from insights.parsers import get_active_lines, unsplit_lines from insights.specs import Specs @parser(Specs.rhn_conf) class RHNConf(LegacyItemAccess, Parser): """ Class to parse the configuration file ``rhn.conf``. The special feature of ``rhn.conf`` is that values can span multiple lines with each intermediate line ending with a comma. This parser uses the :class:`insights.core.LegacyItemAccess` mix-in to provide access to its data directly. Attributes: data (dict): A dictionary of values keyed by the configuration item. Values spanning multiple lines are compacted together. Values that include a comma are turned into lists. Sample ``rhn.conf`` input:: # Corporate gateway (hostname:PORT): server.satellite.http_proxy = corporate_gateway.example.com:8080 server.satellite.http_proxy_username = server.satellite.http_proxy_password = traceback_mail = <EMAIL>, <EMAIL> web.default_taskmaster_tasks = RHN::Task::SessionCleanup, RHN::Task::ErrataQueue, RHN::Task::ErrataEngine, RHN::Task::DailySummary, RHN::Task::SummaryPopulation, RHN::Task::RHNProc, RHN::Task::PackageCleanup Examples: >>> conf = shared[RHNConf] >>> conf.data['server.satellite.http_proxy'] # Long form access 'corporate_gateway.example.com:8080' >>> conf['server.satellite.http_proxy'] # Short form access 'corporate_gateway.example.com:8080' >>> conf['traceback_mail'] # split into a list ['<EMAIL>', '<EMAIL>'] >>> conf['web.default_taskmaster_tasks'][3] # Values can span multiple lines 'RHN::Task::DailySummary' """ def parse_content(self, content): self.data = {} for line in unsplit_lines(get_active_lines(content), ',', keep_cont_char=True): if '=' in line: k, v = [i.strip() for i in line.split('=', 1)] self.data[k] = [i.strip() for i in v.split(',')] if ',' in v else v
vczh2/Workflow
Test/SourceCppGen/Property.cpp
<reponame>vczh2/Workflow /*********************************************************************** !!!!!! DO NOT MODIFY !!!!!! Source: ../Resources/Codegen/Property.txt This file is generated by Workflow compiler https://github.com/vczh-libraries ***********************************************************************/ #include "Property.h" #if defined( _MSC_VER) #pragma warning(push) #pragma warning(disable:4250) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wparentheses-equality" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses-equality" #endif #define GLOBAL_SYMBOL ::vl_workflow_global::Property:: #define GLOBAL_NAME ::vl_workflow_global::Property::Instance(). #define GLOBAL_OBJ &::vl_workflow_global::Property::Instance() /*********************************************************************** Global Variables ***********************************************************************/ BEGIN_GLOBAL_STORAGE_CLASS(vl_workflow_global_Property) vl_workflow_global::Property instance; INITIALIZE_GLOBAL_STORAGE_CLASS FINALIZE_GLOBAL_STORAGE_CLASS END_GLOBAL_STORAGE_CLASS(vl_workflow_global_Property) namespace vl_workflow_global { /*********************************************************************** Global Functions ***********************************************************************/ ::vl::WString Property::main() { auto x = [&](){ ::test::Point __vwsn_temp__; __vwsn_temp__.x = static_cast<::vl::vint>(10); __vwsn_temp__.y = static_cast<::vl::vint>(20); return __vwsn_temp__; }(); auto y = ::vl::Ptr<::test::ObservableValue>(new ::test::ObservableValue(static_cast<::vl::vint>(10))); auto s1 = ((((((((::vl::__vwsn::ToString(x.x) + ::vl::WString(L", ", false)) + ::vl::__vwsn::ToString(x.y)) + ::vl::WString(L", ", false)) + ::vl::__vwsn::ToString(::vl::__vwsn::This(y.Obj())->GetValue())) + ::vl::WString(L", ", false)) + ::vl::__vwsn::This(y.Obj())->GetName()) + ::vl::WString(L", ", false)) + ::vl::__vwsn::This(y.Obj())->GetDisplayName()); ::vl::__vwsn::This(y.Obj())->SetValue(static_cast<::vl::vint>(20)); ::vl::__vwsn::This(y.Obj())->SetName(::vl::WString(L"Workflow", false)); auto s2 = ((((::vl::__vwsn::ToString(::vl::__vwsn::This(y.Obj())->GetValue()) + ::vl::WString(L", ", false)) + ::vl::__vwsn::This(y.Obj())->GetName()) + ::vl::WString(L", ", false)) + ::vl::__vwsn::This(y.Obj())->GetDisplayName()); return ((s1 + ::vl::WString(L", ", false)) + s2); } Property& Property::Instance() { return Getvl_workflow_global_Property().instance; } } #undef GLOBAL_SYMBOL #undef GLOBAL_NAME #undef GLOBAL_OBJ #if defined( _MSC_VER) #pragma warning(pop) #elif defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif
joshwcomeau/return-null
presentation/components/Log/Log.js
import { PureComponent } from 'react'; export default class Log extends PureComponent { render() { console.info(this.props.children); return null; } }
NaufalRafi-hub/Learn-Three.js-Third-Edition
src/chapter-09/js/baseLoaderScene.js
/** * Simple base class, which setups a simple scene which is used to * demonstrate the different loaders. This create a scene, three * lights, and slowly rotates the model, around the z-axis */ function BaseLoaderScene(providedCamera, shouldAddLights, shouldRotate, updateMesh) { self = this; // setup some default elements this.scene = new THREE.Scene(); this.stats = initStats(); this.clock = new THREE.Clock(); this.camera = providedCamera; this.withLights = (shouldAddLights !== undefined) ? shouldAddLights : true; this.shouldRotateCheck = (shouldRotate !== undefined) ? shouldRotate : true; this.updateMeshFunction = updateMesh // initialize basic renderer this.renderer = initRenderer({ antialias: true }); this.trackballControls = initTrackballControls(this.camera, this.renderer); /** * Start the render loop of the provided object * * @param {Three.Object3D} mesh render this mesh or object * @param {*} camera render using the provided camera settings */ this.render = function (mesh, camera) { self.scene.add(mesh); self.camera = camera; self.mesh = mesh; self._render(); } /** * Interal function, called continously to render the scene */ this._render = function () { self.stats.update(); requestAnimationFrame(self._render); self.trackballControls.update(self.clock.getDelta()); if (self.updateMeshFunction) { self.updateMeshFunction(self.mesh) } if (self.shouldRotateCheck) { self.mesh.rotation.z += 0.01 } self.renderer.render(self.scene, self.camera); } /** * Internal function, which adds a number of lights to the scene. */ this._addLights = function () { var keyLight = new THREE.SpotLight(0xffffff); keyLight.position.set(00, 80, 80); keyLight.intensity = 2; keyLight.lookAt(new THREE.Vector3(0, 15, 0)); keyLight.castShadow = true; keyLight.shadow.mapSize.height = 4096; keyLight.shadow.mapSize.width = 4096; this.scene.add(keyLight); var backlight1 = new THREE.SpotLight(0xaaaaaa); backlight1.position.set(150, 40, -20); backlight1.intensity = 0.5; backlight1.lookAt(new THREE.Vector3(0, 15, 0)); this.scene.add(backlight1); var backlight2 = new THREE.SpotLight(0xaaaaaa); backlight2.position.set(-150, 40, -20); backlight2.intensity = 0.5; backlight2.lookAt(new THREE.Vector3(0, 15, 0)); this.scene.add(backlight2); } // add the lights if (this.withLights) this._addLights(); }
iterate-ch/ds3_java_sdk
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/PutTapeStorageDomainMemberSpectraS3Request.java
<filename>ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/PutTapeStorageDomainMemberSpectraS3Request.java<gh_stars>1-10 /* * ****************************************************************************** * Copyright 2014-2019 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.spectrads3; import com.spectralogic.ds3client.networking.HttpVerb; import com.spectralogic.ds3client.commands.interfaces.AbstractRequest; import java.util.UUID; import com.google.common.net.UrlEscapers; import java.lang.Integer; import com.spectralogic.ds3client.models.WritePreferenceLevel; public class PutTapeStorageDomainMemberSpectraS3Request extends AbstractRequest { // Variables private final String storageDomainId; private final String tapePartitionId; private final String tapeType; private Integer autoCompactionThreshold; private WritePreferenceLevel writePreference; // Constructor public PutTapeStorageDomainMemberSpectraS3Request(final UUID storageDomainId, final UUID tapePartitionId, final String tapeType) { this.storageDomainId = storageDomainId.toString(); this.tapePartitionId = tapePartitionId.toString(); this.tapeType = tapeType; this.updateQueryParam("storage_domain_id", storageDomainId); this.updateQueryParam("tape_partition_id", tapePartitionId); this.updateQueryParam("tape_type", tapeType); } public PutTapeStorageDomainMemberSpectraS3Request(final String storageDomainId, final String tapePartitionId, final String tapeType) { this.storageDomainId = storageDomainId; this.tapePartitionId = tapePartitionId; this.tapeType = tapeType; this.updateQueryParam("storage_domain_id", storageDomainId); this.updateQueryParam("tape_partition_id", tapePartitionId); this.updateQueryParam("tape_type", tapeType); } public PutTapeStorageDomainMemberSpectraS3Request withAutoCompactionThreshold(final Integer autoCompactionThreshold) { this.autoCompactionThreshold = autoCompactionThreshold; this.updateQueryParam("auto_compaction_threshold", autoCompactionThreshold); return this; } public PutTapeStorageDomainMemberSpectraS3Request withWritePreference(final WritePreferenceLevel writePreference) { this.writePreference = writePreference; this.updateQueryParam("write_preference", writePreference); return this; } @Override public HttpVerb getVerb() { return HttpVerb.POST; } @Override public String getPath() { return "/_rest_/storage_domain_member"; } public String getStorageDomainId() { return this.storageDomainId; } public String getTapePartitionId() { return this.tapePartitionId; } public String getTapeType() { return this.tapeType; } public Integer getAutoCompactionThreshold() { return this.autoCompactionThreshold; } public WritePreferenceLevel getWritePreference() { return this.writePreference; } }
DmitrySemikin/vtk-mirror
IO/Xdmf3/vtkXdmf3ArraySelection.cxx
<gh_stars>1-10 /*========================================================================= Program: Visualization Toolkit Module: vtkXdmf3ArraySelection.cxx Language: C++ Copyright (c) 1993-2002 <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkXdmf3ArraySelection.h" //============================================================================== void vtkXdmf3ArraySelection::Merge(const vtkXdmf3ArraySelection& other) { vtkXdmf3ArraySelection::const_iterator iter = other.begin(); for (; iter != other.end(); ++iter) { (*this)[iter->first] = iter->second; } } //-------------------------------------------------------------------------- void vtkXdmf3ArraySelection::AddArray(const char* name, bool status) { (*this)[name] = status; } //-------------------------------------------------------------------------- bool vtkXdmf3ArraySelection::ArrayIsEnabled(const char* name) { vtkXdmf3ArraySelection::iterator iter = this->find(name); if (iter != this->end()) { return iter->second; } // don't know anything about this array, enable it by default. return true; } //-------------------------------------------------------------------------- bool vtkXdmf3ArraySelection::HasArray(const char* name) { vtkXdmf3ArraySelection::iterator iter = this->find(name); return (iter != this->end()); } //-------------------------------------------------------------------------- int vtkXdmf3ArraySelection::GetArraySetting(const char* name) { return this->ArrayIsEnabled(name) ? 1 : 0; } //-------------------------------------------------------------------------- void vtkXdmf3ArraySelection::SetArrayStatus(const char* name, bool status) { this->AddArray(name, status); } //-------------------------------------------------------------------------- const char* vtkXdmf3ArraySelection::GetArrayName(int index) { int cc = 0; for (vtkXdmf3ArraySelection::iterator iter = this->begin(); iter != this->end(); ++iter) { if (cc == index) { return iter->first.c_str(); } cc++; } return nullptr; } //-------------------------------------------------------------------------- int vtkXdmf3ArraySelection::GetNumberOfArrays() { return static_cast<int>(this->size()); }
kopi39/simple-sockets
src/main/java/org/kopi/socket/ctype/tcp/async/itf/Producer.java
package org.kopi.socket.ctype.tcp.async.itf; @FunctionalInterface public interface Producer { void process(Sender sender); }
elvin3107/caro-game-client
src/components/CaroSquare.js
<gh_stars>0 import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Button } from '@material-ui/core'; const useStyles = makeStyles((theme) => ({ square: { background: '#fff', border: '1px solid #999', float: 'left', fontSize: '24px', fontWeight: 'bold', lineHeight: '34px', height: '34px', marginRight: '-1px', marginTop: '-1px', padding: '0px', textAlight: 'center', minWidth: '34px', borderRadius: '0', '&:focus': { outline: 'none', } }, squareHightLight: { color: 'red', background: 'yellow', fontWeight: 'bold', } })); const CaroSquare = ({ isWinSquare, value, onClick, isStart }) => { const classes = useStyles(); return isWinSquare ? ( <Button className={[classes.square, classes.squareHightLight]} onClick={onClick}> {value} </Button> ) : ( <Button className={classes.square} onClick={onClick} disableRipple={true}> {value} </Button> ) } export default CaroSquare;
njhale/openshift-installer
terraform/providers/aws/vendor/github.com/hashicorp/terraform-provider-aws/internal/service/shield/protection_health_check_association.go
<gh_stars>0 package shield import ( "fmt" "log" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/shield" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) func ResourceProtectionHealthCheckAssociation() *schema.Resource { return &schema.Resource{ Create: ResourceProtectionHealthCheckAssociationCreate, Read: ResourceProtectionHealthCheckAssociationRead, Delete: ResourceProtectionHealthCheckAssociationDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ "shield_protection_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, "health_check_arn": { Type: schema.TypeString, Required: true, ForceNew: true, }, }, } } func ResourceProtectionHealthCheckAssociationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ShieldConn protectionId := d.Get("shield_protection_id").(string) healthCheckArn := d.Get("health_check_arn").(string) id := ProtectionHealthCheckAssociationCreateResourceID(protectionId, healthCheckArn) input := &shield.AssociateHealthCheckInput{ ProtectionId: aws.String(protectionId), HealthCheckArn: aws.String(healthCheckArn), } _, err := conn.AssociateHealthCheck(input) if err != nil { return fmt.Errorf("error associating Route53 Health Check (%s) with Shield Protected resource (%s): %s", d.Get("health_check_arn"), d.Get("shield_protection_id"), err) } d.SetId(id) return ResourceProtectionHealthCheckAssociationRead(d, meta) } func ResourceProtectionHealthCheckAssociationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ShieldConn protectionId, healthCheckArn, err := ProtectionHealthCheckAssociationParseResourceID(d.Id()) if err != nil { return fmt.Errorf("error parsing Shield Protection and Route53 Health Check Association ID: %w", err) } input := &shield.DescribeProtectionInput{ ProtectionId: aws.String(protectionId), } resp, err := conn.DescribeProtection(input) if tfawserr.ErrCodeEquals(err, shield.ErrCodeResourceNotFoundException) { log.Printf("[WARN] Shield Protection itself (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { return fmt.Errorf("error reading Shield Protection Health Check Association (%s): %s", d.Id(), err) } isHealthCheck := stringInSlice(strings.Split(healthCheckArn, "/")[1], aws.StringValueSlice(resp.Protection.HealthCheckIds)) if !isHealthCheck { log.Printf("[WARN] Shield Protection Health Check Association (%s) not found, removing from state", d.Id()) d.SetId("") } d.Set("health_check_arn", healthCheckArn) d.Set("shield_protection_id", resp.Protection.Id) return nil } func ResourceProtectionHealthCheckAssociationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ShieldConn protectionId, healthCheckId, err := ProtectionHealthCheckAssociationParseResourceID(d.Id()) if err != nil { return fmt.Errorf("error parsing Shield Protection and Route53 Health Check Association ID: %w", err) } input := &shield.DisassociateHealthCheckInput{ ProtectionId: aws.String(protectionId), HealthCheckArn: aws.String(healthCheckId), } _, err = conn.DisassociateHealthCheck(input) if err != nil { return fmt.Errorf("error disassociating Route53 Health Check (%s) from Shield Protected resource (%s): %s", d.Get("health_check_arn"), d.Get("shield_protection_id"), err) } return nil } func stringInSlice(expected string, list []string) bool { for _, item := range list { if item == expected { return true } } return false }
yexianyi/Algorithms
src/main/java/com/yxy/algorithms/string/last/word/length/Solution2.java
<reponame>yexianyi/Algorithms<filename>src/main/java/com/yxy/algorithms/string/last/word/length/Solution2.java /** * Copyright (c) 2016, <NAME> * * This project includes software developed by <NAME> * <EMAIL> * * 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.yxy.algorithms.string.last.word.length; /** * 58. Length of Last Word My Submissions Question Total Accepted: 77433 Total Submissions: 273522 Difficulty: Easy Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. * @author xianyiye * 2016/1/6 */ public class Solution2 { public static int lengthOfLastWord(String s) { int count = 0 ; if(s!=null){ s = s.trim() ; } for(int i=s.length()-1; i>=0; i--){ if(s.charAt(i)==' '){ break ; } count++ ; } return count; } public static void main(String[] args) { System.out.println(lengthOfLastWord("hello world ")); } }
M3SOulu/value
value/deliverables/meetings/views/dashboard/factors_groups_comparison.py
<filename>value/deliverables/meetings/views/dashboard/factors_groups_comparison.py # coding: utf-8 import json from django.http import HttpResponse from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from value.factors.models import Group as FactorGroup from value.deliverables.meetings.models import Meeting, Scenario from value.deliverables.meetings.charts import Highcharts from value.deliverables.meetings.utils import * ''' Support functions ''' def get_factors_groups_chart_dict(meeting_item): chart_data = { 'id': meeting_item.pk, 'name': meeting_item.decision_item.name, 'ranking': meeting_item.value_ranking, 'instance': meeting_item, 'instance_type': 'meeting_item', 'remote': reverse( 'deliverables:meetings:factors_groups_chart', args=(meeting_item.meeting.deliverable.pk, meeting_item.meeting.pk, meeting_item.pk) ), 'info_remote': reverse( 'deliverables:details_decision_item', args=(meeting_item.meeting.deliverable.pk, meeting_item.decision_item.pk) ), 'has_rationales': meeting_item.has_rationales, 'rationales_remote': reverse( 'deliverables:meetings:meeting_item_rationale', args=(meeting_item.meeting.deliverable.pk, meeting_item.meeting.pk, meeting_item.pk) ) } return chart_data def get_factors_groups_scenario_chart_dict(scenario): chart_data = { 'id': scenario.pk, 'name': scenario.name, 'ranking': scenario.value_ranking, 'instance': scenario, 'instance_type': 'scenario', 'remote': reverse( 'deliverables:meetings:factors_groups_scenario_chart', args=(scenario.meeting.deliverable.pk, scenario.meeting.pk, scenario.pk) ), 'info_remote': reverse( 'deliverables:meetings:scenario_details', args=(scenario.meeting.deliverable.pk, scenario.meeting.pk, scenario.pk) ) } return chart_data def application_has_factors_groups(): return FactorGroup.objects.exists() ''' Views ''' @login_required def factors_groups_empty(request, meeting): return render(request, 'meetings/dashboard/factors_groups_comparison/empty.html', { 'meeting': meeting, 'chart_menu_active': 'factors_groups'}) @login_required def factors_groups(request, deliverable_id, meeting_id): meeting = get_object_or_404(Meeting, pk=meeting_id, deliverable__id=deliverable_id) if application_has_factors_groups(): chart_order_options = get_charts_order_dict(meeting.measure) order = get_or_set_charts_order_session(request, meeting, 'factors_groups_comparison_order') charts = map(get_factors_groups_chart_dict, meeting.get_ordered_meeting_items(order)) stakeholder_ids = get_stakeholders_ids(meeting) return render(request, 'meetings/dashboard/factors_groups_comparison/list.html', { 'meeting': meeting, 'chart_menu_active': 'factors_groups', 'charts': charts, 'stakeholder_ids': stakeholder_ids, 'chart_order_options': chart_order_options, 'order': order}) else: return factors_groups_empty(request, meeting) @login_required def factors_groups_chart(request, deliverable_id, meeting_id, meeting_item_id): meeting = get_object_or_404(Meeting, pk=meeting_id, deliverable__id=deliverable_id) meeting_item = meeting.meetingitem_set.get(pk=meeting_item_id) stakeholders = request.GET.getlist('stakeholder') stakeholder_ids = get_stakeholders_ids(meeting, stakeholders) options = Highcharts().factors_groups(meeting_item, stakeholder_ids) dump = json.dumps(options) if 'application/json' in request.META.get('HTTP_ACCEPT'): return HttpResponse(dump, content_type='application/json') else: chart = get_factors_groups_chart_dict(meeting_item) return render(request, 'meetings/dashboard/factors_groups_comparison/popup.html', { 'meeting': meeting, 'chart': chart, 'chart_uri': 'features', 'stakeholder_ids': stakeholder_ids, 'dump': dump}) @login_required def factors_groups_scenarios(request, deliverable_id, meeting_id): meeting = get_object_or_404(Meeting, pk=meeting_id, deliverable__id=deliverable_id) if application_has_factors_groups(): chart_order_options = get_scenario_charts_order_dict(meeting.measure) order = get_or_set_scenario_charts_order_session(request, meeting, 'factors_groups_comparison_scenario_order') charts = map(get_factors_groups_scenario_chart_dict, meeting.get_ordered_scenarios(order)) stakeholder_ids = get_stakeholders_ids(meeting) return render(request, 'meetings/dashboard/factors_groups_comparison/scenarios.html', { 'meeting': meeting, 'chart_menu_active': 'factors_groups', 'charts': charts, 'stakeholder_ids': stakeholder_ids, 'chart_order_options': chart_order_options, 'order': order}) else: return factors_groups_empty(request, meeting) @login_required def factors_groups_scenario_chart(request, deliverable_id, meeting_id, scenario_id): meeting = get_object_or_404(Meeting, pk=meeting_id, deliverable__id=deliverable_id) scenario = get_object_or_404(Scenario, pk=scenario_id) stakeholders = request.GET.getlist('stakeholder') stakeholder_ids = get_stakeholders_ids(meeting, stakeholders) options = Highcharts().factors_groups_scenario(meeting, scenario, stakeholder_ids) dump = json.dumps(options) chart = get_factors_groups_scenario_chart_dict(scenario) if 'application/json' in request.META.get('HTTP_ACCEPT'): return HttpResponse(dump, content_type='application/json') else: return render(request, 'meetings/dashboard/factors_groups_comparison/popup.html', { 'meeting': meeting, 'chart': chart, 'stakeholder_ids': stakeholder_ids, 'dump': dump})
cameroncooke/XcodeHeaders
PlugIns/IDEProductsUI/DVTCrashChartView_ViewData.h
<reponame>cameroncooke/XcodeHeaders<filename>PlugIns/IDEProductsUI/DVTCrashChartView_ViewData.h<gh_stars>1-10 // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSColor, NSNumber, NSString; @interface DVTCrashChartView_ViewData : NSObject { NSString *_label; NSNumber *_rawValue; NSString *_displayValue; double _relativeValueToDataSeries; NSColor *_color; } @property(copy, nonatomic) NSColor *color; // @synthesize color=_color; @property(nonatomic) double relativeValueToDataSeries; // @synthesize relativeValueToDataSeries=_relativeValueToDataSeries; @property(copy, nonatomic) NSString *displayValue; // @synthesize displayValue=_displayValue; @property(copy, nonatomic) NSNumber *rawValue; // @synthesize rawValue=_rawValue; @property(copy, nonatomic) NSString *label; // @synthesize label=_label; - (void).cxx_destruct; - (id)initWithLabel:(id)arg1 rawValue:(id)arg2 color:(id)arg3; @end
Andreas237/AndroidPolicyAutomation
ExtractedJars/LibriVox_app.librivox.android/javafiles/com/google/android/gms/internal/ads/ang.java
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal.ads; // Referenced classes of package com.google.android.gms.internal.ads: // ash, atx, aqq, ani, // asj, anh, aug public final class ang extends ash implements atx { private ang() { // 0 0:aload_0 // 1 1:invokespecial #29 <Method void ash()> zzfgk = ""; // 2 4:aload_0 // 3 5:ldc1 #31 <String ""> // 4 7:putfield #33 <Field String zzfgk> zzfgl = aqq.a; // 5 10:aload_0 // 6 11:getstatic #37 <Field aqq aqq.a> // 7 14:putfield #39 <Field aqq zzfgl> // 8 17:return } public static ang c() { return zzfhc; // 0 0:getstatic #23 <Field ang zzfhc> // 1 3:areturn } static ang d() { return zzfhc; // 0 0:getstatic #23 <Field ang zzfhc> // 1 3:areturn } protected final Object a(int i, Object obj, Object obj1) { ani.a[i - 1]; // 0 0:getstatic #48 <Field int[] ani.a> // 1 3:iload_1 // 2 4:iconst_1 // 3 5:isub // 4 6:iaload JVM INSTR tableswitch 1 7: default 48 // 1 153 // 2 144 // 3 116 // 4 112 // 5 63 // 6 58 // 7 56; // 5 7:tableswitch 1 7: default 48 // 1 153 // 2 144 // 3 116 // 4 112 // 5 63 // 6 58 // 7 56 goto _L1 _L2 _L3 _L4 _L5 _L6 _L7 _L8 _L1: throw new UnsupportedOperationException(); // 6 48:new #50 <Class UnsupportedOperationException> // 7 51:dup // 8 52:invokespecial #51 <Method void UnsupportedOperationException()> // 9 55:athrow _L8: return ((Object) (null)); // 10 56:aconst_null // 11 57:areturn _L7: return ((Object) (Byte.valueOf((byte)1))); // 12 58:iconst_1 // 13 59:invokestatic #57 <Method Byte Byte.valueOf(byte)> // 14 62:areturn _L6: obj = ((Object) (zzcas)); // 15 63:getstatic #59 <Field aug zzcas> // 16 66:astore_2 if(obj != null) goto _L10; else goto _L9 // 17 67:aload_2 // 18 68:ifnonnull 110 _L9: com/google/android/gms/internal/ads/ang; // 19 71:ldc1 #2 <Class ang> JVM INSTR monitorenter ; // 20 73:monitorenter obj1 = ((Object) (zzcas)); // 21 74:getstatic #59 <Field aug zzcas> // 22 77:astore_3 obj = obj1; // 23 78:aload_3 // 24 79:astore_2 if(obj1 != null) goto _L12; else goto _L11 // 25 80:aload_3 // 26 81:ifnonnull 99 _L11: obj = ((Object) (new asj(((ash) (zzfhc))))); // 27 84:new #61 <Class asj> // 28 87:dup // 29 88:getstatic #23 <Field ang zzfhc> // 30 91:invokespecial #64 <Method void asj(ash)> // 31 94:astore_2 zzcas = ((aug) (obj)); // 32 95:aload_2 // 33 96:putstatic #59 <Field aug zzcas> _L12: com/google/android/gms/internal/ads/ang; // 34 99:ldc1 #2 <Class ang> JVM INSTR monitorexit ; // 35 101:monitorexit return obj; // 36 102:aload_2 // 37 103:areturn obj; // 38 104:astore_2 com/google/android/gms/internal/ads/ang; // 39 105:ldc1 #2 <Class ang> JVM INSTR monitorexit ; // 40 107:monitorexit throw obj; // 41 108:aload_2 // 42 109:athrow _L10: return obj; // 43 110:aload_2 // 44 111:areturn _L5: return ((Object) (zzfhc)); // 45 112:getstatic #23 <Field ang zzfhc> // 46 115:areturn _L4: return a(((atv) (zzfhc)), "\000\003\000\000\001\003\003\000\000\000\001\u0208\002\n\003\f", new Object[] { "zzfgk", "zzfgl", "zzfhb" }); // 47 116:getstatic #23 <Field ang zzfhc> // 48 119:ldc1 #66 <String "\000\003\000\000\001\003\003\000\000\000\001\u0208\002\n\003\f"> // 49 121:iconst_3 // 50 122:anewarray Object[] // 51 125:dup // 52 126:iconst_0 // 53 127:ldc1 #69 <String "zzfgk"> // 54 129:aastore // 55 130:dup // 56 131:iconst_1 // 57 132:ldc1 #70 <String "zzfgl"> // 58 134:aastore // 59 135:dup // 60 136:iconst_2 // 61 137:ldc1 #71 <String "zzfhb"> // 62 139:aastore // 63 140:invokestatic #74 <Method Object a(atv, String, Object[])> // 64 143:areturn _L3: return ((Object) (new anh(((ani) (null))))); // 65 144:new #76 <Class anh> // 66 147:dup // 67 148:aconst_null // 68 149:invokespecial #79 <Method void anh(ani)> // 69 152:areturn _L2: return ((Object) (new ang())); // 70 153:new #2 <Class ang> // 71 156:dup // 72 157:invokespecial #21 <Method void ang()> // 73 160:areturn } public final String a() { return zzfgk; // 0 0:aload_0 // 1 1:getfield #33 <Field String zzfgk> // 2 4:areturn } public final aqq b() { return zzfgl; // 0 0:aload_0 // 1 1:getfield #39 <Field aqq zzfgl> // 2 4:areturn } private static volatile aug zzcas; private static final ang zzfhc; private String zzfgk; private aqq zzfgl; private int zzfhb; static { zzfhc = new ang(); // 0 0:new #2 <Class ang> // 1 3:dup // 2 4:invokespecial #21 <Method void ang()> // 3 7:putstatic #23 <Field ang zzfhc> ash.a(com/google/android/gms/internal/ads/ang, ((ash) (zzfhc))); // 4 10:ldc1 #2 <Class ang> // 5 12:getstatic #23 <Field ang zzfhc> // 6 15:invokestatic #27 <Method void ash.a(Class, ash)> //* 7 18:return } }
ScalablyTyped/SlinkyTyped
a/activex-libreoffice/src/main/scala/typingsSlinky/activexLibreoffice/com_/sun/star/awt/XDockableWindow.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.activexLibreoffice.com_.sun.star.awt import typingsSlinky.activexLibreoffice.`type` import typingsSlinky.activexLibreoffice.com_.sun.star.uno.XInterface import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * specifies the docking interface for a window component. * * A window can either be docked where it resides as a child window in an application frame window or it can be floating where it will reside in its own * decorated top level window. */ @js.native trait XDockableWindow extends XInterface { /** adds a docking listener to the object. only a single listener may be registered at any time. */ def addDockableWindowListener(xListener: XDockableWindowListener): Unit = js.native /** * enable or disable docking, docking is disabled by default * @param bEnable `TRUE` specifies that docking is enabled `FALSE` specifies that docking is disabled and no {@link com.sun.star.awt.XDockableWindowListene */ def enableDocking(bEnable: Boolean): Unit = js.native /** * queries the current window state * @returns `TRUE` if the window is floating `FALSE` if the window is docked */ def isFloating(): Boolean = js.native /** * queries the current pop-up mode * @returns `TRUE` if the window is in pop-up mode `FALSE` if the window is not in pop-up mode */ def isInPopupMode(): Boolean = js.native /** * queries the current locking state * @returns `TRUE` if the window is locked `FALSE` if the window is not locked */ def isLocked(): Boolean = js.native /** prevents the window from being undocked this has no effect if the window is floating */ def lock(): Unit = js.native /** removes the specified docking listener from the object. */ def removeDockableWindowListener(xListener: XDockableWindowListener): Unit = js.native /** * toggle between floating and docked state * @param bFloating specifies the new floating mode: `TRUE` means floating, `FALSE` means docked */ def setFloatingMode(bFloating: Boolean): Unit = js.native /** * shows the window in a menu like style, i.e. without decoration a special indicator will allow for tearing off the window see {@link * com.sun.star.awt.XDockableWindowListener} for the corresponding events * @param WindowRect specifies the position and size of the pop-up window in frame coordinates */ def startPopupMode(WindowRect: Rectangle): Unit = js.native /** enables undocking this has no effect if the window is floating */ def unlock(): Unit = js.native } object XDockableWindow { @scala.inline def apply( acquire: () => Unit, addDockableWindowListener: XDockableWindowListener => Unit, enableDocking: Boolean => Unit, isFloating: () => Boolean, isInPopupMode: () => Boolean, isLocked: () => Boolean, lock: () => Unit, queryInterface: `type` => js.Any, release: () => Unit, removeDockableWindowListener: XDockableWindowListener => Unit, setFloatingMode: Boolean => Unit, startPopupMode: Rectangle => Unit, unlock: () => Unit ): XDockableWindow = { val __obj = js.Dynamic.literal(acquire = js.Any.fromFunction0(acquire), addDockableWindowListener = js.Any.fromFunction1(addDockableWindowListener), enableDocking = js.Any.fromFunction1(enableDocking), isFloating = js.Any.fromFunction0(isFloating), isInPopupMode = js.Any.fromFunction0(isInPopupMode), isLocked = js.Any.fromFunction0(isLocked), lock = js.Any.fromFunction0(lock), queryInterface = js.Any.fromFunction1(queryInterface), release = js.Any.fromFunction0(release), removeDockableWindowListener = js.Any.fromFunction1(removeDockableWindowListener), setFloatingMode = js.Any.fromFunction1(setFloatingMode), startPopupMode = js.Any.fromFunction1(startPopupMode), unlock = js.Any.fromFunction0(unlock)) __obj.asInstanceOf[XDockableWindow] } @scala.inline implicit class XDockableWindowMutableBuilder[Self <: XDockableWindow] (val x: Self) extends AnyVal { @scala.inline def setAddDockableWindowListener(value: XDockableWindowListener => Unit): Self = StObject.set(x, "addDockableWindowListener", js.Any.fromFunction1(value)) @scala.inline def setEnableDocking(value: Boolean => Unit): Self = StObject.set(x, "enableDocking", js.Any.fromFunction1(value)) @scala.inline def setIsFloating(value: () => Boolean): Self = StObject.set(x, "isFloating", js.Any.fromFunction0(value)) @scala.inline def setIsInPopupMode(value: () => Boolean): Self = StObject.set(x, "isInPopupMode", js.Any.fromFunction0(value)) @scala.inline def setIsLocked(value: () => Boolean): Self = StObject.set(x, "isLocked", js.Any.fromFunction0(value)) @scala.inline def setLock(value: () => Unit): Self = StObject.set(x, "lock", js.Any.fromFunction0(value)) @scala.inline def setRemoveDockableWindowListener(value: XDockableWindowListener => Unit): Self = StObject.set(x, "removeDockableWindowListener", js.Any.fromFunction1(value)) @scala.inline def setSetFloatingMode(value: Boolean => Unit): Self = StObject.set(x, "setFloatingMode", js.Any.fromFunction1(value)) @scala.inline def setStartPopupMode(value: Rectangle => Unit): Self = StObject.set(x, "startPopupMode", js.Any.fromFunction1(value)) @scala.inline def setUnlock(value: () => Unit): Self = StObject.set(x, "unlock", js.Any.fromFunction0(value)) } }
ScalablyTyped/SlinkyTyped
f/firebase__firestore/src/main/scala/typingsSlinky/firebaseFirestore/grpcConnectionMod.scala
<reponame>ScalablyTyped/SlinkyTyped<gh_stars>10-100 package typingsSlinky.firebaseFirestore import typingsSlinky.firebaseFirestore.connectionMod.Connection import typingsSlinky.firebaseFirestore.databaseInfoMod.DatabaseInfo import typingsSlinky.grpcGrpcJs.makeClientMod.GrpcObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation._ @JSImport("@firebase/firestore/dist/lib/src/platform_node/grpc_connection", JSImport.Namespace) @js.native object grpcConnectionMod extends js.Object { @js.native class GrpcConnection protected () extends Connection { def this(protos: GrpcObject, databaseInfo: DatabaseInfo) = this() var cachedStub: js.Any = js.native var databaseInfo: js.Any = js.native var ensureActiveStub: js.Any = js.native var firestore: js.Any = js.native } }
lauralopezreal/opencga-laura
opencga-analysis/src/main/java/org/opencb/opencga/analysis/models/SamplePrivateUpdateParams.java
package org.opencb.opencga.analysis.models; import org.opencb.biodata.models.clinical.Phenotype; import org.opencb.opencga.core.models.common.AnnotationSet; import org.opencb.opencga.core.models.common.CustomStatusParams; import org.opencb.opencga.core.models.sample.*; import java.util.List; import java.util.Map; public class SamplePrivateUpdateParams extends SampleUpdateParams { private SampleInternal internal; public SamplePrivateUpdateParams() { } public SamplePrivateUpdateParams(String id, String description, String creationDate, String modificationDate, String individualId, SampleProcessing processing, SampleCollection collection, SampleQualityControl qualityControl, Boolean somatic, List<Phenotype> phenotypes, List<AnnotationSet> annotationSets, Map<String, Object> attributes, CustomStatusParams status, SampleInternal internal) { super(id, description, creationDate, modificationDate, individualId, processing, collection, qualityControl, somatic, phenotypes, annotationSets, attributes, status); this.internal = internal; } @Override public String toString() { final StringBuilder sb = new StringBuilder("SamplePrivateUpdateParams{"); sb.append("internal=").append(internal); sb.append('}'); return sb.toString(); } public SampleInternal getInternal() { return internal; } public SamplePrivateUpdateParams setInternal(SampleInternal internal) { this.internal = internal; return this; } }
ghsecuritylab/tomato_egg
release/src/router/samba3/source/librpc/gen_ndr/srv_wkssvc.h
<filename>release/src/router/samba3/source/librpc/gen_ndr/srv_wkssvc.h #include "librpc/gen_ndr/ndr_wkssvc.h" #ifndef __SRV_WKSSVC__ #define __SRV_WKSSVC__ WERROR _wkssvc_NetWkstaGetInfo(pipes_struct *p, struct wkssvc_NetWkstaGetInfo *r); WERROR _wkssvc_NetWkstaSetInfo(pipes_struct *p, struct wkssvc_NetWkstaSetInfo *r); WERROR _wkssvc_NetWkstaEnumUsers(pipes_struct *p, struct wkssvc_NetWkstaEnumUsers *r); WERROR _WKSSVC_NETRWKSTAUSERGETINFO(pipes_struct *p, struct WKSSVC_NETRWKSTAUSERGETINFO *r); WERROR _WKSSVC_NETRWKSTAUSERSETINFO(pipes_struct *p, struct WKSSVC_NETRWKSTAUSERSETINFO *r); WERROR _wkssvc_NetWkstaTransportEnum(pipes_struct *p, struct wkssvc_NetWkstaTransportEnum *r); WERROR _WKSSVC_NETRWKSTATRANSPORTADD(pipes_struct *p, struct WKSSVC_NETRWKSTATRANSPORTADD *r); WERROR _WKSSVC_NETRWKSTATRANSPORTDEL(pipes_struct *p, struct WKSSVC_NETRWKSTATRANSPORTDEL *r); WERROR _WKSSVC_NETRUSEADD(pipes_struct *p, struct WKSSVC_NETRUSEADD *r); WERROR _WKSSVC_NETRUSEGETINFO(pipes_struct *p, struct WKSSVC_NETRUSEGETINFO *r); WERROR _WKSSVC_NETRUSEDEL(pipes_struct *p, struct WKSSVC_NETRUSEDEL *r); WERROR _WKSSVC_NETRUSEENUM(pipes_struct *p, struct WKSSVC_NETRUSEENUM *r); WERROR _WKSSVC_NETRMESSAGEBUFFERSEND(pipes_struct *p, struct WKSSVC_NETRMESSAGEBUFFERSEND *r); WERROR _WKSSVC_NETRWORKSTATIONSTATISTICSGET(pipes_struct *p, struct WKSSVC_NETRWORKSTATIONSTATISTICSGET *r); WERROR _WKSSVC_NETRLOGONDOMAINNAMEADD(pipes_struct *p, struct WKSSVC_NETRLOGONDOMAINNAMEADD *r); WERROR _WKSSVC_NETRLOGONDOMAINNAMEDEL(pipes_struct *p, struct WKSSVC_NETRLOGONDOMAINNAMEDEL *r); WERROR _WKSSVC_NETRJOINDOMAIN(pipes_struct *p, struct WKSSVC_NETRJOINDOMAIN *r); WERROR _WKSSVC_NETRUNJOINDOMAIN(pipes_struct *p, struct WKSSVC_NETRUNJOINDOMAIN *r); WERROR _WKSSVC_NETRRENAMEMACHINEINDOMAIN(pipes_struct *p, struct WKSSVC_NETRRENAMEMACHINEINDOMAIN *r); WERROR _WKSSVC_NETRVALIDATENAME(pipes_struct *p, struct WKSSVC_NETRVALIDATENAME *r); WERROR _WKSSVC_NETRGETJOININFORMATION(pipes_struct *p, struct WKSSVC_NETRGETJOININFORMATION *r); WERROR _WKSSVC_NETRGETJOINABLEOUS(pipes_struct *p, struct WKSSVC_NETRGETJOINABLEOUS *r); WERROR _wkssvc_NetrJoinDomain2(pipes_struct *p, struct wkssvc_NetrJoinDomain2 *r); WERROR _wkssvc_NetrUnjoinDomain2(pipes_struct *p, struct wkssvc_NetrUnjoinDomain2 *r); WERROR _wkssvc_NetrRenameMachineInDomain2(pipes_struct *p, struct wkssvc_NetrRenameMachineInDomain2 *r); WERROR _WKSSVC_NETRVALIDATENAME2(pipes_struct *p, struct WKSSVC_NETRVALIDATENAME2 *r); WERROR _WKSSVC_NETRGETJOINABLEOUS2(pipes_struct *p, struct WKSSVC_NETRGETJOINABLEOUS2 *r); WERROR _wkssvc_NetrAddAlternateComputerName(pipes_struct *p, struct wkssvc_NetrAddAlternateComputerName *r); WERROR _wkssvc_NetrRemoveAlternateComputerName(pipes_struct *p, struct wkssvc_NetrRemoveAlternateComputerName *r); WERROR _WKSSVC_NETRSETPRIMARYCOMPUTERNAME(pipes_struct *p, struct WKSSVC_NETRSETPRIMARYCOMPUTERNAME *r); WERROR _WKSSVC_NETRENUMERATECOMPUTERNAMES(pipes_struct *p, struct WKSSVC_NETRENUMERATECOMPUTERNAMES *r); void wkssvc_get_pipe_fns(struct api_struct **fns, int *n_fns); NTSTATUS rpc_wkssvc_init(void); #endif /* __SRV_WKSSVC__ */
kawasima/http-request-router
src/main/java/net/unit8/http/router/segment/OptionalFormatSegment.java
<filename>src/main/java/net/unit8/http/router/segment/OptionalFormatSegment.java package net.unit8.http.router.segment; import net.unit8.http.router.ARStringUtil; import net.unit8.http.router.Options; import java.util.regex.Matcher; public class OptionalFormatSegment extends DynamicSegment { public OptionalFormatSegment(String key, Options options) { super("format", options.$("optional", true)); } public OptionalFormatSegment() { this(null, new Options()); } @Override public String interpolationChunk(Options hash) { return "." + super.interpolationChunk(hash); } @Override public String regexpChunk() { return "/|(\\.[^/?\\.]+)?"; } @Override public String toString() { return "(.:format)?"; } @Override public void matchExtraction(Options params, Matcher match, int nextCapture) { String m = match.group(nextCapture); if (m != null) { params.put(getKey(), ARStringUtil.urldecode(m.substring(1))); } else { params.put(getKey(), ARStringUtil.urldecode(getDefault())); } } }
sailengsi/sls-admin-quick-start
src/layout/routeview/index.js
<reponame>sailengsi/sls-admin-quick-start /** * Created by sailengsi on 2017/5/11. */ import Content from './Content.vue'; import Home from './Home.vue'; export { Home, Content };
Maldrek/EZ-RPG
client/src/components/CharCard.js
<filename>client/src/components/CharCard.js import React from 'react'; import 'tachyons'; import { Card, CardImg, CardTitle, CardText, CardSubtitle, CardBody } from 'reactstrap'; import API from '../utils/API'; import '../images/characters.json' export class CharCard extends React.Component { state = { characters: [], }; componentDidMount() { this.loadCharacters(); } loadCharacters = () => { API.getCharacters() .then(res => this.setState({ characters: res.data }) ) .catch(err => console.log(err)); }; render() { return ( <Card> <CardImg src='../images/characters.json' alt="Card image cap" /> <CardBody> <CardTitle>Name: {character.character_name}</CardTitle> <CardSubtitle>Gender:{character.gender}</CardSubtitle> <CardSubtitle>Race:{character.race}</CardSubtitle> <CardSubtitle>Class:{character.class}</CardSubtitle> <CardText> <ListGroup><ListGroupItem>Dexterity: {character.dex}</ListGroupItem> <ListGroupItem>Intelligence: {character.intel}</ListGroupItem> <ListGroupItem>Charisma: {character.cha}</ListGroupItem> <ListGroupItem>Strength: {character.stre}</ListGroupItem> <ListGroupItem>Constitution: {character.con}</ListGroupItem> <ListGroupItem>Wisdom: {character.wis}</ListGroupItem> </ListGroup> </CardText> </CardBody> </Card> ); } } export default CharCard;
sergaben/KUSOSS-final-year-project
Backend/app/controllers/SignUpController.scala
package controllers import database.StudentRepositoryImpl import javax.inject.Inject import models.Student import org.mindrot.jbcrypt.BCrypt import play.api.data.Forms._ import play.api.data._ import play.api.i18n.Messages import play.api.libs.json.Json import play.api.mvc._ import scala.concurrent.ExecutionContext class SignUpController @Inject()(cc:ControllerComponents, kingstonStudentRepository: StudentRepositoryImpl) (implicit executionContext:ExecutionContext) extends AbstractController(cc){ private val userForm: Form[Student] = Form ( mapping( "id" -> optional(number), "nickname"->nonEmptyText, "email"->nonEmptyText, "password"->nonEmptyText, "subject"->nonEmptyText, "typeOfStudy"->nonEmptyText, "loginToken"->optional(text) )(Student.apply)(Student.unapply) ) def signup = Action{ implicit req => signUpFormAsJson() } private def insertStudentIntoDatabase(kingstonStudent: Student): Unit ={ kingstonStudentRepository.insert(kingstonStudent) } /** * * @param request to be processed * @tparam A type of request * @return a result of Json */ private def signUpFormAsJson[A]()(implicit request: Request[A]):Result = { def failure(badForm: Form[Student]) = { implicit val messages: Messages = messagesApi.preferred(request) BadRequest(badForm.errorsAsJson) } def success(input: Student) = { val hashedPassword = BCrypt.hashpw(input.password,BCrypt.gensalt()) val kStudentWithHashedPassword = input.copy(password = hashedPassword) println(kStudentWithHashedPassword) insertStudentIntoDatabase(kStudentWithHashedPassword) Ok(Json.obj("status"->"OK","successful"->true)) } userForm.bindFromRequest().fold(failure,success) } }
tgodzik/intellij-community
java/java-tests/testData/compileServer/incremental/common/nothingChanged/src/TheSameContent.java
package v; class TheSameContent { void nothingToRebuild() {} }
KoEonYack/fixture-monkey
fixture-monkey/src/main/java/com/navercorp/fixturemonkey/arbitrary/NullArbitraryType.java
<reponame>KoEonYack/fixture-monkey /* * Fixture Monkey * * Copyright (c) 2021-present NAVER Corp. * * 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.navercorp.fixturemonkey.arbitrary; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedType; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; @SuppressWarnings({"unchecked", "rawtypes"}) public final class NullArbitraryType extends ArbitraryType { public static final NullArbitraryType INSTANCE = new NullArbitraryType(); private NullArbitraryType() { super(null); } @Override public List<Annotation> getAnnotations() { return Collections.emptyList(); } @Nullable @Override public Annotation getAnnotation(Class annotationType) { return null; } @Override public ArbitraryType getGenericArbitraryType(int index) { throw new IllegalArgumentException("Null ArbitraryType can not have generics"); } @Override public ArbitraryType getArrayArbitraryType() { throw new IllegalArgumentException("Null ArbitraryType can not be array"); } @Override public boolean isContainer() { return false; } @Override public boolean isArray() { return false; } @Override public boolean isMapEntry() { return false; } @Override public boolean isMap() { return false; } @Override public boolean isGenericType() { return false; } @Override public boolean isOptional() { return false; } @Override public boolean isStream() { return false; } @Override public boolean isPrimitive() { return false; } @Override public boolean isEnum() { return false; } @Override public boolean isInterface() { return false; } @Override public boolean isAbstract() { return false; } @Override public Class<?> getType() { return null; } @Override public AnnotatedType getAnnotatedType() { return null; } }
vascoalramos/misago-deployment
misago/misago/users/migrations/0014_datadownload.py
<filename>misago/misago/users/migrations/0014_datadownload.py # Generated by Django 1.11.13 on 2018-06-24 00:13 import django.db.models.deletion import django.utils.timezone from django.conf import settings from django.db import migrations, models import misago.users.models.datadownload class Migration(migrations.Migration): dependencies = [("misago_users", "0013_auto_20180609_1523")] operations = [ migrations.CreateModel( name="DataDownload", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "status", models.PositiveIntegerField( choices=[ (0, "Pending"), (1, "Processing"), (2, "Ready"), (3, "Expired"), ], db_index=True, default=0, ), ), ("requester_name", models.CharField(max_length=255)), ( "requested_on", models.DateTimeField(default=django.utils.timezone.now), ), ("expires_on", models.DateTimeField(default=django.utils.timezone.now)), ( "file", models.FileField( blank=True, max_length=255, null=True, upload_to=misago.users.models.datadownload.get_data_upload_to, ), ), ( "requester", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="+", to=settings.AUTH_USER_MODEL, ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, ), ), ], options={"ordering": ["-pk"]}, ) ]
Lixu518/leetcode
263/uglyNumber.cpp
#include<iostream> using namespace std; bool isUgly(int n){ if(n < 1) return false; while(n % 2 == 0) n /= 2; while(n % 3 == 0) n /= 3; while(n % 5 == 0) n /= 5; return n == 1; } int main(){ cout<<"14 is Ugly number ? "<<isUgly(14)<<endl; return 0; }
trumanwong/leetcode
algorithms/0561.ArrayPartitionI/arrayPairSum_test.go
<reponame>trumanwong/leetcode package main import ( "leetcode/algorithms/0561.ArrayPartitionI/arrayPairSum" "testing" ) func TestArrayPairSum(t *testing.T) { tests := []struct { nums []int output int }{ {[]int{1, 4, 3, 2}, 4}, } for _, test := range tests { ret := arrayPairSum.ArrayPairSum(test.nums) if ret != test.output { t.Errorf("Got %d for input %v; expected %d", ret, test.nums, test.output) } } }