repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
YuqiaoZhang/USD
pxr/usd/lib/usd/collectionMembershipQuery.h
<gh_stars>1-10 // // Copyright 2019 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #ifndef USD_COLLECTIONMEMBERSHIPQUERY_H #define USD_COLLECTIONMEMBERSHIPQUERY_H /// \file usd/collectionMembershipQuery.h #include "pxr/base/tf/declarePtrs.h" #include "pxr/pxr.h" #include "pxr/usd/sdf/path.h" #include "pxr/usd/usd/common.h" #include "pxr/usd/usd/primFlags.h" #include <unordered_map> PXR_NAMESPACE_OPEN_SCOPE // -------------------------------------------------------------------------- // // UsdCollectionMembershipQuery // // -------------------------------------------------------------------------- // /// \class UsdCollectionMembershipQuery /// /// \brief Represents a flattened view of a collection. For more information /// about collections, please see UsdCollectionAPI as a way to encode and /// retrieve a collection from scene description. A /// UsdCollectionMembershipQuery object can be used to answer queries about /// membership of paths in the collection efficiently. class UsdCollectionMembershipQuery { public: /// Holds an unordered map describing membership of paths in this collection /// and the associated expansionRule for how the paths are to be expanded. /// Valid expansionRules are UsdTokens->explicitOnly, /// UsdTokens->expandPrims, and UsdTokens->expandPrimsAndProperties. For /// more information on the expansion rules, please see the expansionRule /// attribute on UsdCollectionAPI. /// If a collection includes another collection, the included collection's /// PathExpansionRuleMap is merged into this one. If a path is excluded, /// its expansion rule is set to UsdTokens->exclude. using PathExpansionRuleMap = std::unordered_map<SdfPath, TfToken, SdfPath::Hash>; /// Default Constructor, creates an empty UsdCollectionMembershipQuery /// object UsdCollectionMembershipQuery() {} /// Constructor that takes a path expansion rule map. The map is scanned /// for 'excludes' when the UsdCollectionMembershipQuery object is /// constructed. explicit UsdCollectionMembershipQuery( const PathExpansionRuleMap& pathExpansionRuleMap); /// Constructor that takes a path expansion rule map as an rvalue reference explicit UsdCollectionMembershipQuery( PathExpansionRuleMap&& pathExpansionRuleMap); /// \overload /// Returns whether the given path is included in the collection from /// which this UsdCollectionMembershipQuery object was computed. This is the /// API that clients should use for determining if a given object is a /// member of the collection. To enumerate all the members of a collection, /// use \ref UsdComputeIncludedObjectsFromCollection or /// \ref UsdComputeIncludedPathsFromCollection. /// /// If \p expansionRule is not nullptr, it is set to the expansion- /// rule value that caused the path to be included in or excluded from /// the collection. If \p path is not included in the collection, /// \p expansionRule is set to UsdTokens->exclude. /// /// It is useful to specify this parameter and use this overload of /// IsPathIncluded(), when you're interested in traversing a subtree /// and want to know whether the root of the subtree is included in a /// collection. For evaluating membership of descendants of the root, /// please use the other overload of IsPathIncluded(), that takes both /// a path and the parent expansionRule. /// /// The python version of this method only returns the boolean result. /// It does not return \p expansionRule. USD_API bool IsPathIncluded(const SdfPath &path, TfToken *expansionRule=nullptr) const; /// \overload /// Returns whether the given path, \p path is included in the /// collection from which this UsdCollectionMembershipQuery object was /// computed, given the parent-path's inherited expansion rule, /// \p parentExpansionRule. /// /// If \p expansionRule is not nullptr, it is set to the expansion- /// rule value that caused the path to be included in or excluded from /// the collection. If \p path is not included in the collection, /// \p expansionRule is set to UsdTokens->exclude. /// /// The python version of this method only returns the boolean result. /// It does not return \p expansionRule. USD_API bool IsPathIncluded(const SdfPath &path, const TfToken &parentExpansionRule, TfToken *expansionRule=nullptr) const; /// Returns true if the collection excludes one or more paths below an /// included path. bool HasExcludes() const { return _hasExcludes; } /// Equality operator bool operator==(UsdCollectionMembershipQuery const& rhs) const { return _hasExcludes == rhs._hasExcludes && _pathExpansionRuleMap == rhs._pathExpansionRuleMap; } /// Inequality operator bool operator!=(UsdCollectionMembershipQuery const& rhs) const { return !(*this == rhs); } /// Hash functor struct Hash { USD_API size_t operator()(UsdCollectionMembershipQuery const& query) const; }; /// Hash function inline size_t GetHash() const { return Hash()(*this); } /// Returns a raw map of the paths included or excluded in the /// collection along with the expansion rules for the included /// paths. const PathExpansionRuleMap& GetAsPathExpansionRuleMap() const { return _pathExpansionRuleMap; } private: PathExpansionRuleMap _pathExpansionRuleMap; // A cached flag indicating whether _pathExpansionRuleMap contains // any exclude rules. bool _hasExcludes=false; }; /// Returns all the usd objects that satisfy the predicate, \p pred in the /// collection represented by the UsdCollectionMembershipQuery object, \p /// query. /// /// The results depends on the load state of the UsdStage, \p stage. USD_API std::set<UsdObject> UsdComputeIncludedObjectsFromCollection( const UsdCollectionMembershipQuery &query, const UsdStageWeakPtr &stage, const Usd_PrimFlagsPredicate &pred=UsdPrimDefaultPredicate); /// Returns all the paths that satisfy the predicate, \p pred in the /// collection represented by the UsdCollectionMembershipQuery object, \p /// query. /// /// The result depends on the load state of the UsdStage, \p stage. USD_API SdfPathSet UsdComputeIncludedPathsFromCollection( const UsdCollectionMembershipQuery &query, const UsdStageWeakPtr &stage, const Usd_PrimFlagsPredicate &pred=UsdPrimDefaultPredicate); PXR_NAMESPACE_CLOSE_SCOPE #endif
edude545/system0
src/main/java/net/ethobat/system0/registry/S0Progressions.java
<reponame>edude545/system0 package net.ethobat.system0.registry; public final class S0Progressions { public static void init() { } }
sparkling-graph/sparkling-graph
api/src/main/scala/ml/sparkling/graph/api/operators/algorithms/link/MeasureBasedLnkPredictor.scala
package ml.sparkling.graph.api.operators.algorithms.link import ml.sparkling.graph.api.operators.measures.EdgeMeasure import org.apache.spark.graphx.{VertexId, Graph} import org.apache.spark.rdd.RDD import scala.reflect.ClassTag /** * Trait for basic link prediction. Implementation should use similarity measure of type EdgeMeasure * Created by <NAME> (<EMAIL> http://riomus.github.io). */ trait MeasureBasedLnkPredictor { /** * Implementation should predict new links in given graph using suplied vertex similarity measure. * @param graph - input graph * @param edgeMeasure - similarity measure * @param threshold - minimal similarity measure value * @param treatAsUndirected - true if graph should be treated as undirected * @param num - numeric of similarity measure * @tparam V * @tparam E * @tparam EV * @tparam EO * @return */ def predictLinks[V:ClassTag,E:ClassTag,EV:ClassTag,EO:ClassTag](graph:Graph[V,E], edgeMeasure: EdgeMeasure[EO,EV], threshold:EO, treatAsUndirected:Boolean) (implicit num:Numeric[EO]):RDD[(VertexId,VertexId)] }
DiamondLightSource/gda-ispyb-api
src/test/java/uk/ac/diamond/ispyb/test/ContainerStatusTest.java
/*- ******************************************************************************* * Copyright (c) 2011, 2016 Diamond Light Source Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * See git history *******************************************************************************/ package uk.ac.diamond.ispyb.test; import org.junit.Test; import uk.ac.diamond.ispyb.api.ContainerStatus; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class ContainerStatusTest { @Test public void testValidParsing(){ for (ContainerStatus containerStatus: ContainerStatus.values()){ ContainerStatus parsed = ContainerStatus.convert(containerStatus.getStatus()); assertThat(parsed, is(containerStatus)); } } @Test public void testInvalidParsing(){ ContainerStatus parsed = ContainerStatus.convert("not known"); assertThat(parsed, is(ContainerStatus.INVALID)); } }
adambirse/innovation-funding-service
ifs-sil-resources/src/main/java/org/innovateuk/ifs/sil/crm/resource/SilAddress.java
package org.innovateuk.ifs.sil.crm.resource; public class SilAddress { private String buildingName; private String street; private String locality; private String town; private String postcode; private String country; public String getBuildingName() { return buildingName; } public void setBuildingName(String buildingName) { this.buildingName = buildingName; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
vaporgraph/ens-app
src/components/Forms/Button.js
<filename>src/components/Forms/Button.js import React from 'react' import styled from 'react-emotion' import { Link } from 'react-router-dom' function getButtonStyles({ type, color }) { switch (type) { case 'primary': return ` &:hover { cursor: pointer; border: 2px solid ${color[1]}; background: #2c46a6; box-shadow: 0 10px 21px 0 rgba(161, 175, 184, 0.89); border-radius: 23px; } ` case 'hollow': return ` color: #DFDFDF; border: 2px solid #DFDFDF; &:hover { cursor: pointer; border: 2px solid ${color[1]}; background: #2c46a6; box-shadow: 0 10px 21px 0 rgba(161, 175, 184, 0.89); } ` case 'disabled': return ` &:hover { cursor: default } ` default: return '' } } function getButtonDefaultStyles(p) { return ` color: white; background: ${p.color[0]}; padding: 10px 25px; border-radius: 25px; font-size: 14px; font-weight: 700; font-family: Overpass; text-transform: capitalize; letter-spacing: 1.5px; //box-shadow: 0 10px 21px 0 #bed0dc; transition: 0.2s all; border: 2px solid ${p.color[0]}; &:focus { outline: 0; } ` } const ButtonContainer = styled('button')` ${p => getButtonDefaultStyles(p)}; ${p => getButtonStyles(p)}; ` const ButtonLinkContainer = styled(Link)` color: white; &:hover { color: white; } &:visited { color: white; } ${p => getButtonDefaultStyles(p)}; ${p => getButtonStyles(p)}; ` const types = { primary: ['#5384FE', '#2c46a6'], inactive: ['#DFDFDF', '#DFDFDF'], hollow: ['transparent', 'transparent'], disabled: ['#ccc', '#ccc'] } const Button = props => { const { className, children, type = 'primary', onClick } = props return ( <ButtonContainer className={className} color={types[type]} type={type} onClick={onClick} disabled={type === 'disabled'} {...props} > {children} </ButtonContainer> ) } export const ButtonLink = props => { const { className, children, type = 'primary', to = '' } = props return ( <ButtonLinkContainer className={className} to={to} color={types[type]} type={type} {...props} > {children} </ButtonLinkContainer> ) } export default Button
spxuw/RFIM
Source/boost_1_33_1/libs/wave/test/testwave/testfiles/t_9_010.cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2005 <NAME>. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // Tests, whether adjacent tokens are separated by whitespace if the adjacency // is created by macro expansion #define A(x) x //R #line 16 "t_9_010.cpp" A(1)1 //R 1 1 A(1)X //R 1 X A(X)1 //R X 1 A(X)X //R X X #define CAT(a, b) PRIMITIVE_CAT(a, b) #define PRIMITIVE_CAT(a, b) a ## b #define X() B #define ABC 1 //R #line 28 "t_9_010.cpp" CAT(A, X() C) //R AB C CAT(A, X()C) //R AB C
TrueMarketing/trimtileandstone
node_modules/styled-icons/remix-fill/Switch/Switch.esm.js
import { __assign } from "tslib"; import * as React from 'react'; import { StyledIconBase } from '../../StyledIconBase'; export var Switch = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", "xmlns": "http://www.w3.org/2000/svg", }; return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k0" }), React.createElement("path", { d: "M13.619 21c-.085 0-.141-.057-.127-.127V3.127c0-.056.042-.113.113-.113h2.785A4.61 4.61 0 0121 7.624v8.766A4.61 4.61 0 0116.39 21h-2.77zm3.422-9.926c-1.004 0-1.824.82-1.824 1.824s.82 1.824 1.824 1.824 1.824-.82 1.824-1.824-.82-1.824-1.824-1.824zM5.8 8.4a1.7 1.7 0 011.696-1.696A1.7 1.7 0 019.193 8.4c0 .934-.763 1.697-1.697 1.697A1.702 1.702 0 015.8 8.401zM11.54 3c.085 0 .142.057.128.127V20.86c0 .07-.057.127-.128.127H7.61A4.61 4.61 0 013 16.376V7.61A4.61 4.61 0 017.61 3h3.93zm-1.315 16.544V4.442H7.61c-.849 0-1.64.34-2.235.933a3.088 3.088 0 00-.933 2.235v8.766c0 .849.34 1.64.933 2.234a3.088 3.088 0 002.235.934h2.615z", key: "k1" }))); }); Switch.displayName = 'Switch'; export var SwitchDimensions = { height: 24, width: 24 };
landonvg/gedcomx-java
extensions/familysearch/familysearch-api-client/src/main/java/org/familysearch/api/client/FamilySearchReferenceEnvironment.java
/** * Copyright Intellectual Reserve, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.familysearch.api.client; import java.net.URI; /** * @author <NAME> */ public enum FamilySearchReferenceEnvironment { PRODUCTION("https://api.familysearch.org/platform"), BETA("https://apibeta.familysearch.org/platform"), SANDBOX("https://api-integ.familysearch.org/platform"); private final String base; FamilySearchReferenceEnvironment(String base) { this.base = base; } public URI getRootUri() { return URI.create(this.base + "/collection"); } public URI getHistoricalRecordsArchiveUri() { return URI.create(this.base + "/collections/records"); } public URI getMemoriesUri() { return URI.create(this.base + "/collections/memories"); } public URI getPlacesUri() { return URI.create(this.base + "/collections/places"); } public URI getNamesUri() { return URI.create(this.base + "/collections/names"); } public URI getFamilyTreeUri() { return URI.create(this.base + "/collections/tree"); } }
darcyturk/fotographiq
js/auth/ForgotPassword.js
import React, { Component } from 'react'; import { View, Text, StyleSheet, StatusBar, TextInput, Platform } from 'react-native'; import { connect } from 'react-redux'; import t from 'tcomb-form-native'; const Form = t.form.Form; import Button from '../common/Button'; import Toolbar from '../common/Toolbar'; import ResetPasswordSent from './ResetPasswordSent'; import Email from '../forms/Email'; import { sendResetPassword } from '../actions/resetPassword'; class ForgotPassword extends Component { _sendResetPassword() { let value = this.refs.form.getValue(); // if are any validation errors, value will be null if (value !== null) { this.props.dispatch(sendResetPassword(value)); } } componentDidUpdate() { if (this.props.form.success) { this.props.navigator.replace({ component: ResetPasswordSent, title: 'Change Password' }); } } getFormValue() { return { email: this.props.form.email }; } render() { const ResetPassword = t.struct({ email: Email }); const buttonLabel = this.props.form.isLoading ? 'Sending...' : 'Send'; return( <View style={styles.container}> <StatusBar backgroundColor='#C5C5C5' networkActivityIndicatorVisible={this.props.form.isLoading} /> <Toolbar backIcon navigator={this.props.navigator} /> <View style={styles.innerContainer}> <Text style={styles.title}>Change Password</Text> <Text style={styles.info}>Enter your email below:</Text> <Form ref='form' type={ResetPassword} options={this.props.form} value={this.getFormValue()} /> <Text style={styles.info}>You will be emailed a link to reset your password.</Text> <Button containerStyle={styles.button} text={buttonLabel} disabled={this.props.form.isLoading} onPress={this._sendResetPassword.bind(this)} /> </View> </View> ); } } function select(store) { return { form: store.forgotPassword }; } export default connect(select)(ForgotPassword); var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: 'white', marginTop: Platform.OS === 'ios' ? 55 : 0 }, innerContainer: { padding: 20, }, title: { fontSize: 24, textAlign: 'center' }, info: { fontSize: 16, textAlign: 'center', marginBottom: 10 }, button: { marginTop: 20 } });
oirad21/react_oirad
node_modules/@fortawesome/pro-regular-svg-icons/faChartPie.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'far'; var iconName = 'chart-pie'; var width = 544; var height = 512; var ligatures = []; var unicode = 'f200'; var svgPathData = 'M511.96 223.2C503.72 103.74 408.26 8.28 288.8.04c-.35-.03-.7-.04-1.04-.04C279.11 0 272 7.44 272 16.23V240h223.77c9.14 0 16.82-7.68 16.19-16.8zM320 192V53.51C387.56 70.95 441.05 124.44 458.49 192H320zm-96 96V50.72c0-8.83-7.18-16.21-15.74-16.21-.7 0-1.4.05-2.11.15C86.99 51.49-4.1 155.6.14 280.37 4.47 407.53 113.18 512 240.12 512c.98 0 1.93-.01 2.91-.02 50.4-.63 96.97-16.87 135.26-44.03 7.9-5.6 8.42-17.23 1.57-24.08L224 288zm18.44 175.99l-2.31.01c-100.66 0-188.59-84.84-192.01-185.26-2.91-85.4 50.15-160.37 127.88-187.6v216.74l14.06 14.06 126.22 126.22c-23.16 10.1-48.16 15.5-73.84 15.83zM527.79 288H290.5l158.03 158.03c3.17 3.17 7.41 4.81 11.62 4.81 3.82 0 7.62-1.35 10.57-4.13 38.7-36.46 65.32-85.61 73.13-140.86 1.34-9.46-6.51-17.85-16.06-17.85z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faChartPie = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
robertbakker/google-ads-pb
services/smart_campaign_setting_service.pb.go
<reponame>robertbakker/google-ads-pb // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0-devel // protoc v3.17.3 // source: google/ads/googleads/v10/services/smart_campaign_setting_service.proto package services import ( enums "github.com/robertbakker/google-ads-pb/enums" resources "github.com/robertbakker/google-ads-pb/resources" _ "google.golang.org/genproto/googleapis/api/annotations" status "google.golang.org/genproto/googleapis/rpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Request message for // [SmartCampaignSettingService.MutateSmartCampaignSetting][]. type MutateSmartCampaignSettingsRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The ID of the customer whose Smart campaign settings are being modified. CustomerId string `protobuf:"bytes,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Required. The list of operations to perform on individual Smart campaign settings. Operations []*SmartCampaignSettingOperation `protobuf:"bytes,2,rep,name=operations,proto3" json:"operations,omitempty"` // If true, successful operations will be carried out and invalid // operations will return errors. If false, all operations will be carried // out in one transaction if and only if they are all valid. // Default is false. PartialFailure bool `protobuf:"varint,3,opt,name=partial_failure,json=partialFailure,proto3" json:"partial_failure,omitempty"` // If true, the request is validated but not executed. Only errors are // returned, not results. ValidateOnly bool `protobuf:"varint,4,opt,name=validate_only,json=validateOnly,proto3" json:"validate_only,omitempty"` // The response content type setting. Determines whether the mutable resource // or just the resource name should be returned post mutation. ResponseContentType enums.ResponseContentTypeEnum_ResponseContentType `protobuf:"varint,5,opt,name=response_content_type,json=responseContentType,proto3,enum=google.ads.googleads.v10.enums.ResponseContentTypeEnum_ResponseContentType" json:"response_content_type,omitempty"` } func (x *MutateSmartCampaignSettingsRequest) Reset() { *x = MutateSmartCampaignSettingsRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MutateSmartCampaignSettingsRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*MutateSmartCampaignSettingsRequest) ProtoMessage() {} func (x *MutateSmartCampaignSettingsRequest) ProtoReflect() protoreflect.Message { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MutateSmartCampaignSettingsRequest.ProtoReflect.Descriptor instead. func (*MutateSmartCampaignSettingsRequest) Descriptor() ([]byte, []int) { return file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescGZIP(), []int{0} } func (x *MutateSmartCampaignSettingsRequest) GetCustomerId() string { if x != nil { return x.CustomerId } return "" } func (x *MutateSmartCampaignSettingsRequest) GetOperations() []*SmartCampaignSettingOperation { if x != nil { return x.Operations } return nil } func (x *MutateSmartCampaignSettingsRequest) GetPartialFailure() bool { if x != nil { return x.PartialFailure } return false } func (x *MutateSmartCampaignSettingsRequest) GetValidateOnly() bool { if x != nil { return x.ValidateOnly } return false } func (x *MutateSmartCampaignSettingsRequest) GetResponseContentType() enums.ResponseContentTypeEnum_ResponseContentType { if x != nil { return x.ResponseContentType } return enums.ResponseContentTypeEnum_UNSPECIFIED } // A single operation to update Smart campaign settings for a campaign. type SmartCampaignSettingOperation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Update operation: The Smart campaign setting must specify a valid // resource name. Update *resources.SmartCampaignSetting `protobuf:"bytes,1,opt,name=update,proto3" json:"update,omitempty"` // FieldMask that determines which resource fields are modified in an update. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } func (x *SmartCampaignSettingOperation) Reset() { *x = SmartCampaignSettingOperation{} if protoimpl.UnsafeEnabled { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmartCampaignSettingOperation) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmartCampaignSettingOperation) ProtoMessage() {} func (x *SmartCampaignSettingOperation) ProtoReflect() protoreflect.Message { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmartCampaignSettingOperation.ProtoReflect.Descriptor instead. func (*SmartCampaignSettingOperation) Descriptor() ([]byte, []int) { return file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescGZIP(), []int{1} } func (x *SmartCampaignSettingOperation) GetUpdate() *resources.SmartCampaignSetting { if x != nil { return x.Update } return nil } func (x *SmartCampaignSettingOperation) GetUpdateMask() *fieldmaskpb.FieldMask { if x != nil { return x.UpdateMask } return nil } // Response message for campaign mutate. type MutateSmartCampaignSettingsResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Errors that pertain to operation failures in the partial failure mode. // Returned only when partial_failure = true and all errors occur inside the // operations. If any errors occur outside the operations (e.g. auth errors), // we return an RPC level error. PartialFailureError *status.Status `protobuf:"bytes,1,opt,name=partial_failure_error,json=partialFailureError,proto3" json:"partial_failure_error,omitempty"` // All results for the mutate. Results []*MutateSmartCampaignSettingResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` } func (x *MutateSmartCampaignSettingsResponse) Reset() { *x = MutateSmartCampaignSettingsResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MutateSmartCampaignSettingsResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*MutateSmartCampaignSettingsResponse) ProtoMessage() {} func (x *MutateSmartCampaignSettingsResponse) ProtoReflect() protoreflect.Message { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MutateSmartCampaignSettingsResponse.ProtoReflect.Descriptor instead. func (*MutateSmartCampaignSettingsResponse) Descriptor() ([]byte, []int) { return file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescGZIP(), []int{2} } func (x *MutateSmartCampaignSettingsResponse) GetPartialFailureError() *status.Status { if x != nil { return x.PartialFailureError } return nil } func (x *MutateSmartCampaignSettingsResponse) GetResults() []*MutateSmartCampaignSettingResult { if x != nil { return x.Results } return nil } // The result for the Smart campaign setting mutate. type MutateSmartCampaignSettingResult struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Returned for successful operations. ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"` // The mutated Smart campaign setting with only mutable fields after mutate. // The field will only be returned when response_content_type is set to // "MUTABLE_RESOURCE". SmartCampaignSetting *resources.SmartCampaignSetting `protobuf:"bytes,2,opt,name=smart_campaign_setting,json=smartCampaignSetting,proto3" json:"smart_campaign_setting,omitempty"` } func (x *MutateSmartCampaignSettingResult) Reset() { *x = MutateSmartCampaignSettingResult{} if protoimpl.UnsafeEnabled { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MutateSmartCampaignSettingResult) String() string { return protoimpl.X.MessageStringOf(x) } func (*MutateSmartCampaignSettingResult) ProtoMessage() {} func (x *MutateSmartCampaignSettingResult) ProtoReflect() protoreflect.Message { mi := &file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MutateSmartCampaignSettingResult.ProtoReflect.Descriptor instead. func (*MutateSmartCampaignSettingResult) Descriptor() ([]byte, []int) { return file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescGZIP(), []int{3} } func (x *MutateSmartCampaignSettingResult) GetResourceName() string { if x != nil { return x.ResourceName } return "" } func (x *MutateSmartCampaignSettingResult) GetSmartCampaignSetting() *resources.SmartCampaignSetting { if x != nil { return x.SmartCampaignSetting } return nil } var File_google_ads_googleads_v10_services_smart_campaign_setting_service_proto protoreflect.FileDescriptor var file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDesc = []byte{ 0x0a, 0x46, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x63, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x21, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x1a, 0x3a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x2f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x63, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x80, 0x03, 0x0a, 0x22, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x24, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x65, 0x0a, 0x0a, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x40, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0a, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x46, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x4f, 0x6e, 0x6c, 0x79, 0x12, 0x7f, 0x0a, 0x15, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x4b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x45, 0x6e, 0x75, 0x6d, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x13, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x22, 0xae, 0x01, 0x0a, 0x1d, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x50, 0x0a, 0x06, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x06, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x73, 0x6b, 0x22, 0xcc, 0x01, 0x0a, 0x23, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x46, 0x0a, 0x15, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x13, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x46, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x5d, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x43, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x22, 0xeb, 0x01, 0x0a, 0x20, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x57, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x32, 0xfa, 0x41, 0x2f, 0x0a, 0x2d, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6e, 0x0a, 0x16, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x63, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x14, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x32, 0xf4, 0x02, 0x0a, 0x1b, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x8d, 0x02, 0x0a, 0x1b, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x45, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x46, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x5f, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x40, 0x22, 0x3b, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x3d, 0x2a, 0x7d, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x3a, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x16, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x2c, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x1a, 0x45, 0xca, 0x41, 0x18, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x27, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x61, 0x64, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x42, 0x8c, 0x02, 0x0a, 0x25, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x42, 0x20, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6d, 0x70, 0x61, 0x69, 0x67, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x49, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x3b, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0xa2, 0x02, 0x03, 0x47, 0x41, 0x41, 0xaa, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x41, 0x64, 0x73, 0x2e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x2e, 0x56, 0x31, 0x30, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0xca, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x41, 0x64, 0x73, 0x5c, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x5c, 0x56, 0x31, 0x30, 0x5c, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0xea, 0x02, 0x25, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x41, 0x64, 0x73, 0x3a, 0x3a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x3a, 0x3a, 0x56, 0x31, 0x30, 0x3a, 0x3a, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescOnce sync.Once file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescData = file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDesc ) func file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescGZIP() []byte { file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescOnce.Do(func() { file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescData) }) return file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDescData } var file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_goTypes = []interface{}{ (*MutateSmartCampaignSettingsRequest)(nil), // 0: google.ads.googleads.v10.services.MutateSmartCampaignSettingsRequest (*SmartCampaignSettingOperation)(nil), // 1: google.ads.googleads.v10.services.SmartCampaignSettingOperation (*MutateSmartCampaignSettingsResponse)(nil), // 2: google.ads.googleads.v10.services.MutateSmartCampaignSettingsResponse (*MutateSmartCampaignSettingResult)(nil), // 3: google.ads.googleads.v10.services.MutateSmartCampaignSettingResult (enums.ResponseContentTypeEnum_ResponseContentType)(0), // 4: google.ads.googleads.v10.enums.ResponseContentTypeEnum.ResponseContentType (*resources.SmartCampaignSetting)(nil), // 5: google.ads.googleads.v10.resources.SmartCampaignSetting (*fieldmaskpb.FieldMask)(nil), // 6: google.protobuf.FieldMask (*status.Status)(nil), // 7: google.rpc.Status } var file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_depIdxs = []int32{ 1, // 0: google.ads.googleads.v10.services.MutateSmartCampaignSettingsRequest.operations:type_name -> google.ads.googleads.v10.services.SmartCampaignSettingOperation 4, // 1: google.ads.googleads.v10.services.MutateSmartCampaignSettingsRequest.response_content_type:type_name -> google.ads.googleads.v10.enums.ResponseContentTypeEnum.ResponseContentType 5, // 2: google.ads.googleads.v10.services.SmartCampaignSettingOperation.update:type_name -> google.ads.googleads.v10.resources.SmartCampaignSetting 6, // 3: google.ads.googleads.v10.services.SmartCampaignSettingOperation.update_mask:type_name -> google.protobuf.FieldMask 7, // 4: google.ads.googleads.v10.services.MutateSmartCampaignSettingsResponse.partial_failure_error:type_name -> google.rpc.Status 3, // 5: google.ads.googleads.v10.services.MutateSmartCampaignSettingsResponse.results:type_name -> google.ads.googleads.v10.services.MutateSmartCampaignSettingResult 5, // 6: google.ads.googleads.v10.services.MutateSmartCampaignSettingResult.smart_campaign_setting:type_name -> google.ads.googleads.v10.resources.SmartCampaignSetting 0, // 7: google.ads.googleads.v10.services.SmartCampaignSettingService.MutateSmartCampaignSettings:input_type -> google.ads.googleads.v10.services.MutateSmartCampaignSettingsRequest 2, // 8: google.ads.googleads.v10.services.SmartCampaignSettingService.MutateSmartCampaignSettings:output_type -> google.ads.googleads.v10.services.MutateSmartCampaignSettingsResponse 8, // [8:9] is the sub-list for method output_type 7, // [7:8] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_init() } func file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_init() { if File_google_ads_googleads_v10_services_smart_campaign_setting_service_proto != nil { return } if !protoimpl.UnsafeEnabled { file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MutateSmartCampaignSettingsRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmartCampaignSettingOperation); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MutateSmartCampaignSettingsResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MutateSmartCampaignSettingResult); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 1, }, GoTypes: file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_goTypes, DependencyIndexes: file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_depIdxs, MessageInfos: file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_msgTypes, }.Build() File_google_ads_googleads_v10_services_smart_campaign_setting_service_proto = out.File file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_rawDesc = nil file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_goTypes = nil file_google_ads_googleads_v10_services_smart_campaign_setting_service_proto_depIdxs = nil }
ZHAOLIANKE/lindb
replica/wal.go
<gh_stars>0 // Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB 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 replica import ( "context" "errors" "path" "strconv" "sync" "github.com/lindb/lindb/config" "github.com/lindb/lindb/coordinator/storage" "github.com/lindb/lindb/models" "github.com/lindb/lindb/pkg/queue" "github.com/lindb/lindb/rpc" "github.com/lindb/lindb/tsdb" ) //go:generate mockgen -source=./wal.go -destination=./wal_mock.go -package=replica // for testing var ( newFanOutQueue = queue.NewFanOutQueue newWriteAheadLog = NewWriteAheadLog ) // WriteAheadLogManager represents manage all writeTask ahead log. type WriteAheadLogManager interface { // GetOrCreateLog returns writeTask ahead log for database, // if exist returns it, else creates a new log. GetOrCreateLog(database string) WriteAheadLog } // WriteAheadLog represents writeTask ahead log underlying fan out queue. type WriteAheadLog interface { // GetOrCreatePartition returns a partition of writeTask ahead log. // if exist returns it, else create a new partition. GetOrCreatePartition(shardID models.ShardID) (Partition, error) } // writeAheadLogManager implements WriteAheadLogManager. type writeAheadLogManager struct { ctx context.Context cfg config.WAL currentNodeID models.NodeID databaseLogs map[string]WriteAheadLog engine tsdb.Engine cliFct rpc.ClientStreamFactory stateMgr storage.StateManager mutex sync.Mutex } // NewWriteAheadLogManager creates a WriteAheadLogManager instance. func NewWriteAheadLogManager( ctx context.Context, cfg config.WAL, currentNodeID models.NodeID, engine tsdb.Engine, cliFct rpc.ClientStreamFactory, stateMgr storage.StateManager, ) WriteAheadLogManager { return &writeAheadLogManager{ ctx: ctx, cfg: cfg, currentNodeID: currentNodeID, engine: engine, cliFct: cliFct, stateMgr: stateMgr, databaseLogs: make(map[string]WriteAheadLog), } } // GetOrCreateLog returns writeTask ahead log for database, // if exist returns it, else creates a new. func (w *writeAheadLogManager) GetOrCreateLog(database string) WriteAheadLog { w.mutex.Lock() defer w.mutex.Unlock() log, ok := w.databaseLogs[database] if ok { return log } // create new, then put in cache log = newWriteAheadLog(w.ctx, w.cfg, w.currentNodeID, database, w.engine, w.cliFct, w.stateMgr) w.databaseLogs[database] = log return log } // writeAheadLog implements WriteAheadLog. type writeAheadLog struct { ctx context.Context database string cfg config.WAL currentNodeID models.NodeID shardLogs map[models.ShardID]Partition engine tsdb.Engine cliFct rpc.ClientStreamFactory stateMgr storage.StateManager mutex sync.Mutex } // NewWriteAheadLog creates a WriteAheadLog instance. func NewWriteAheadLog(ctx context.Context, cfg config.WAL, currentNodeID models.NodeID, database string, engine tsdb.Engine, cliFct rpc.ClientStreamFactory, stateMgr storage.StateManager, ) WriteAheadLog { return &writeAheadLog{ ctx: ctx, currentNodeID: currentNodeID, database: database, cfg: cfg, engine: engine, cliFct: cliFct, stateMgr: stateMgr, shardLogs: make(map[models.ShardID]Partition), } } // GetOrCreatePartition returns a partition of writeTask ahead log. // if exist returns it, else create a new partition. func (w *writeAheadLog) GetOrCreatePartition(shardID models.ShardID) (Partition, error) { w.mutex.Lock() defer w.mutex.Unlock() p, ok := w.shardLogs[shardID] if ok { return p, nil } shard, ok := w.engine.GetShard(w.database, shardID) if !ok { return nil, errors.New("shard not exist") } dirPath := path.Join(w.cfg.Dir, w.database, strconv.Itoa(int(shardID))) interval := w.cfg.RemoveTaskInterval.Duration() q, err := newFanOutQueue(dirPath, w.cfg.GetDataSizeLimit(), interval) if err != nil { return nil, err } p = NewPartition(w.ctx, shardID, shard, w.currentNodeID, q, w.cliFct, w.stateMgr) w.shardLogs[shardID] = p return p, nil }
hoangvlbk61/HUST-Final-project-2019B-TRMS
TRMS-Frontend/pages/charts/misc.js
<filename>TRMS-Frontend/pages/charts/misc.js import Head from 'next/head'; import Misc from '../../demos/vis/showcase-sections/misc-showcase'; const MiscPage = () => ( <> <Head> <link rel="stylesheet" href="/static/react-vis.css" /> </Head> <Misc /> </> ); export default MiscPage;
tihefrequi/theia-xtext
template/templates/java/utils/sap/cloud/SCIMConstants.java
package {service.namespace}.utils.sap.cloud; /** * Based on SAP SCP documentation (https://help.sap.com/viewer/6d6d63354d1242d185ab4830fc04feb1/Cloud/en-US/7ae17a6da5314246a04d113f902d0fdf.html) * as well as SCIM RFC specification (https://tools.ietf.org/html/rfc7643) * @author storm * */ public class SCIMConstants { //Well-known-schemas public static String SCHEMA_IETF_CORE_USER = "urn:ietf:params:scim:schemas:core:2.0:User"; public static String SCHEMA_IETF_EXTENSION_ENTERPRISE_USER = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"; public static String SCHEMA_SCP_EXTENSION_ENTERPRISE_USER = "urn:sap:cloud:scim:schemas:extension:custom:2.0:User"; //Common public static String ID = "id"; public static String META = "meta"; public static String EXTERNAL_ID = "externalId"; public static String SCHEMAS = "schemas"; //USER //...single public static String U_USER_NAME = "userName"; public static String U_NAME = "name"; public static String U_DISPLAY_NAME = "displayName"; public static String U_NICK_NAME = "nickName"; public static String U_PROFILE_URL = "profileUrl"; public static String U_TITLE = "title"; public static String U_USER_TYPE = "userType"; public static String U_PREFERRED_LANG = "preferredLanguage"; public static String U_LOCALE = "locale"; public static String U_TIME_ZONE = "timeZone"; public static String U_ACTIVE = "active"; public static String U_PASSWORD = "password"; //...SAP SCP specific attributes public static String U_SCP_CONTACT_PREFERENCE_EMAIL = "contactPreferenceEmail"; public static String U_SCP_CONTACT_PREFERENCE_TELEPHONE = "contactPreferenceTelephone"; public static String U_SCP_INDUSTRY_CRM = "industryCrm"; public static String U_SCP_COMPANY = "company"; public static String U_SCP_COMPANY_RELATIONSHIP = "companyRelationship"; public static String U_SCP_DEPARTMENT = "department"; public static String U_SCP_CORPORATE_GROUPS = "corporateGroups"; public static String U_SCP_MAIL_VERIFIED = "mailVerified"; public static String U_SCP_TELEPHONE_VERIFIED = "telephoneVerified"; public static String U_SCP_TELEPHONE_VERIFICATION_ATTEMPTS = "telephoneVerificationAttempts"; public static String U_SCP_PASSWORD_POLICY = "<PASSWORD>"; public static String U_SCP_PASSWORD_STATUS = "<PASSWORD>"; public static String U_SCP_PASSWORD_FAILED_LOGIN_ATTEMPTS = "<PASSWORD>"; public static String U_SCP_OTP_FAILED_LOGIN_ATTEMPTS = "otpFailedLoginAttempts"; public static String U_SCP_TEMRS_OF_USE = "termsOfUse"; public static String U_SCP_TIME_OF_ACCEPTANCE = "timeOfAcceptance"; public static String U_SCP_PRIVACY_POLICY = "privacyPolicy"; public static String U_SCP_SOCIAL_IDENTITIES = "socialIdentities"; public static String U_SCP_PASSWORD_LOGIN_TIME = "<PASSWORD>"; public static String U_SCP_LOGIN_TIME = "loginTime"; public static String U_SCP_PASSWORD_SET_TIME = "passwordSetTime"; //...multi-valued public static String U_EMAILS = "emails"; public static String U_PHONE_NUMBERS = "phoneNumbers"; public static String U_IMS = "ims"; public static String U_PHOTOS = "photos"; public static String U_ADDRESSES = "addresses"; public static String U_GROUPS = "groups"; public static String U_ENTITLEMENTS = "entitlements"; public static String U_ROLES = "roles"; public static String U_X509_CERTIFICATES = "x509Certificates"; //...complex types //......address public static String U_ADDRESS_TYPE = "type"; public static String U_ADDRESS_FORMATTED = "formatted"; public static String U_ADDRESS_STREET_ADDRESS = "streetAddress"; public static String U_ADDRESS_LOCAITY = "locality"; public static String U_ADDRESS_REGION = "region"; public static String U_ADDRESS_POSTAL_CODE = "postalCode"; public static String U_ADDRESS_COUNTRY = "country"; //......name public static String U_NAME_FORMATTED = "formatted"; public static String U_NAME_FAMILY_NAME = "familyName"; public static String U_NAME_GIVEN_NAME = "givenName"; public static String U_NAME_MIDDLE_NAME = "middleName"; public static String U_NAME_HONORIC_PREFIX = "honorificPrefix"; public static String U_NAME_HONORIC_SUFFIX = "honorificSuffix"; //...terms of use (SAP SCP specific) public static String U_SCP_TEMRS_OF_USE_TIME_OF_ACCEPTANCE = "timeOfAcceptance"; public static String U_SCP_TEMRS_OF_USE_NAME = "name"; public static String U_SCP_TEMRS_OF_USE_ID = "id"; public static String U_SCP_TEMRS_OF_USE_LOCALE = "locale"; public static String U_SCP_TEMRS_OF_USE_VERSION = "version"; public static String U_SCP_PRIVACY_POLICY_TIME_OF_ACCEPTANCE = "timeOfAcceptance"; public static String U_SCP_PRIVACY_POLICY_NAME = "name"; public static String U_SCP_PRIVACY_POLICY_ID = "id"; public static String U_SCP_PRIVACY_POLICY_LOCALE = "locale"; public static String U_SCP_PRIVACY_POLICY_VERSION = "version"; //...extension attributes public static String SCH_IETF_EXT_ENTERP_U_EMPLOYEE_NUMBER = "employeeNumber"; public static String SCH_IETF_EXT_ENTERP_U_COST_CENTER = "costCenter"; public static String SCH_IETF_EXT_ENTERP_U_ORGANIZATION = "organization"; public static String SCH_IETF_EXT_ENTERP_U_DIVISION = "division"; public static String SCH_IETF_EXT_ENTERP_U_DEPARTMENT = "department"; public static String SCH_IETF_EXT_ENTERP_U_MANAGER = "manager"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES = "attributes"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_NAME = "name"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_VALUE = "value"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA1 = "customAttribute1"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA2 = "customAttribute2"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA3 = "customAttribute3"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA4 = "customAttribute4"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA5 = "customAttribute5"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA6 = "customAttribute6"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA7 = "customAttribute7"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA8 = "customAttribute8"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA9 = "customAttribute9"; public static String SCH_SCP_EXT_ENTERP_U_ATTRIBUTES_CA10 = "customAttribute10"; //Multi-Value Attributes public static String MV_TYPE = "type"; public static String MV_PRIMARY = "primary"; public static String MV_DISPLAY = "display"; public static String MV_VALUE = "value"; public static String MV_REF = "$ref"; }
pereiray-ryan/commissulator
app/controllers/apartments_controller.rb
<reponame>pereiray-ryan/commissulator<gh_stars>1-10 class ApartmentsController < ApplicationController before_action :set_apartment, only: [:show, :edit, :update, :destroy] def index @apartments = if params[:filtered_attribute] Apartment.where params[:filtered_attribute] => params[:filter_value] else Apartment.all end.page params[:page] end def show end def new @apartment = Apartment.new end def edit end def create @apartment = Apartment.new(apartment_params) respond_to do |format| if @apartment.save format.html { redirect_to @apartment, notice: 'Apartment was successfully created.' } format.json { render :show, status: :created, location: @apartment } else format.html { render :new } format.json { render json: @apartment.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @apartment.update(apartment_params) format.html { redirect_to @apartment, notice: 'Apartment was successfully updated.' } format.json { render :show, status: :ok, location: @apartment } else format.html { render :edit } format.json { render json: @apartment.errors, status: :unprocessable_entity } end end end def destroy @apartment.destroy respond_to do |format| format.html { redirect_to apartments_url, notice: 'Apartment was successfully destroyed.' } format.json { head :no_content } end end private def set_apartment @apartment = Apartment.find(params[:id]) end def apartment_params params.require(:apartment).permit(:unit_number, :street_number, :street_name, :zip_code, :size, :rent, :comment, :registration_id) end end
amitdu6ey/Online-Judge-Submissions
codeforces/382/C.cpp
<reponame>amitdu6ey/Online-Judge-Submissions // [amitdu6ey] #include <bits/stdc++.h> #define hell 1000000009 #define bug(x) cout<<"$ "<<x<<" $"<<endl #define ll long long #define pb push_back #define mp make_pair #define tr(z) for(auto it=z.begin(); it!=z.end(); it++) #define loop(i,a,b) for(long long i=a; i<b; i++) #define vbool vector< bool > #define vvbool vector< vector<bool> > #define vchar vector<char> #define vi vector<int> #define vvi vector< vector<int> > #define vll vector<long long> #define vvl vector< vector<long long> > #define ninf numeric_limits<int>::min() #define pinf numeric_limits<int>::max() using namespace std; bool isAP(vll& a, ll n){ ll diff = a[1]-a[0]; loop(i,1,n){ if(a[i]-a[i-1]!=diff){ return false; } } return true; } void solve(){ ll n; cin>>n; vll a(n); vll b(n+1); loop(i,0,n){ cin>>a[i]; } sort(a.begin(),a.end()); if(n==1){ cout<<-1; return; } if(a[0]==a[n-1]){ cout<<1<<"\n"; cout<<a[0]; return; } if(isAP(a,n)){ ll diff = a[1]-a[0]; if(n==2&&(a[0]+a[1])%2==0){ cout<<3<<"\n"; cout<<a[0]-diff<<" "<<(a[0]+a[1])/2<<" "<<a[1]+diff; return; } else{ cout<<2<<"\n"; cout<<a[0]-diff<<" "<<a[n-1]+diff; return; } } else{ ll diff=pinf,x,y; loop(i,0,n-1){ diff=min(a[i+1]-a[i],diff); } loop(i,1,n){ if(a[i]!=a[i-1]+diff){ x = a[i]; y=a[i-1]; loop(j,i+1,n){ if(a[j]!=a[j-1]+diff){ cout<<0; return; } } if((a[i]+a[i-1])%2==0){ ll k=0; loop(j,0,n){ if(k==i){ b[k]=(a[i]+a[i-1])/2; k++; } b[k]=a[j]; k++; } if(isAP(b,n+1)){ cout<<1<<"\n"; cout<<(a[i]+a[i-1])/2; return; } cout<<0; return; } } } } cout<<0; return; } int main(){ ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); int test_cases=1; //cin>>test_cases; while(test_cases--){ solve(); } return 0; }
zcgitzc/easyframe
easyframe-web/src/main/java/com/zark/easyframe/common/controller/QuartzController.java
package com.zark.easyframe.common.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.zark.easyframe.biz.common.bo.JobBo; import com.zark.easyframe.common.exception.ExceptionControllerAdvice; import com.zark.easyframe.common.module.JobDo; @Controller @RequestMapping("quartz") public class QuartzController extends ExceptionControllerAdvice { @Resource private JobBo jobBo; @RequestMapping("queryAll") public List<JobDo> queryAll() { return jobBo.queryAll(); } @RequestMapping("addJob") public void addJob(JobDo jobDo) { jobBo.addJob(jobDo); } @RequestMapping("deleteJob") public void deleteJob(Long id) { jobBo.deleteJob(id); } @RequestMapping("updateJob") public void updateJob(JobDo jobDo) { jobBo.updateJob(jobDo); } @RequestMapping("pauseJob") public void pauseJob(Long id) { jobBo.pauseJob(id); } @RequestMapping("resumeJob") public void resumeJob(Long id) { jobBo.resumeJob(id); } @RequestMapping("startJob") public void startJob(Long id) { jobBo.startJob(id); } }
f4deb/cen-electronic
common/sensor/current/current.h
<reponame>f4deb/cen-electronic #ifndef CURRENT_H #define CURRENT_H // forward declaration struct Current; typedef struct Current Current; /** * Get the value from the current sensor * @return current the value from the current sensor */ typedef int CurrentReadSensorValueFunction(Current* current); /** * Set the current to know if we are above the value. * @param currentSensorAlert the new limit for the current */ typedef void CurrentWriteAlertLimitFunction(Current* current, int currentSensorAlert); /** * Current sensor wrapping. */ struct Current { /** The function which must be used to read the value of the current (in celcius degree). */ CurrentReadSensorValueFunction* readSensorValue; /** The function which must be used to write the alert limit of the current sensor (in celcius degree). */ CurrentWriteAlertLimitFunction* writeAlertLimit; /** A pointer on generic object (for example to store I2cBus ...). */ void* object; }; /** * Initialize the current object wrapper. * @param current the pointer on current object (POO Programming) * @param readSensorValue the pointer on the callback function to read the value of the current (in celcius degree). * @param writeAlertLimit the pointer on the callback function to write the alert limit of the current sensor (in celcius degree). */ void initCurrent(Current* current, CurrentReadSensorValueFunction* readSensorValue, CurrentWriteAlertLimitFunction* writeAlertLimit, void* object); #endif
guoruijun07/produsupsys
produsupsys-common/src/main/java/com/ruoyi/common/bean/po/ClientWebPscSorting.java
package com.ruoyi.common.bean.po; public class ClientWebPscSorting { /** * id */ private Integer id; /** * * @mbggenerated */ public ClientWebPscSorting(Integer id) { this.id = id; } /** * * @mbggenerated */ public ClientWebPscSorting() { super(); } /** * * @return id */ public Integer getId() { return id; } /** * * @param id */ public void setId(Integer id) { this.id = id; } }
neildhir/DCBO
src/examples/example_setups.py
from networkx.drawing import nx_agraph import pygraphviz from src.utils.sem_utils.toy_sems import StationaryDependentSEM, StationaryIndependentSEM, NonStationaryDependentSEM from src.utils.dag_utils.graph_functions import make_graphical_model from src.experimental.experiments import optimal_sequence_of_interventions from src.utils.sequential_intervention_functions import get_interventional_grids from src.utils.utilities import powerset def setup_stat_scm(T: int = 3): #  Load SEM from figure 1 in paper (upper left quadrant) SEM = StationaryDependentSEM() init_sem = SEM.static() sem = SEM.dynamic() dag_view = make_graphical_model( 0, T - 1, topology="dependent", nodes=["X", "Z", "Y"], verbose=True ) # Base topology that we build on dag = nx_agraph.from_agraph(pygraphviz.AGraph(dag_view.source)) #  Specifiy all the exploration sets based on the manipulative variables in the DAG exploration_sets = list(powerset(["X", "Z"])) # Specify the intervention domain for each variable intervention_domain = {"X": [-4, 1], "Z": [-3, 3]} # Specify a grid over each exploration and use the grid to find the best intevention value for that ES interventional_grids = get_interventional_grids(exploration_sets, intervention_domain, size_intervention_grid=100) _, _, true_objective_values, _, _, _ = optimal_sequence_of_interventions( exploration_sets=exploration_sets, interventional_grids=interventional_grids, initial_structural_equation_model=init_sem, structural_equation_model=sem, G=dag, T=T, model_variables=["X", "Z", "Y"], target_variable="Y", ) return init_sem, sem, dag_view, dag, exploration_sets, intervention_domain, true_objective_values def setup_ind_scm(T: int = 3): #  Load SEM from figure 1 in paper (upper left quadrant) SEM = StationaryIndependentSEM() init_sem = SEM.static() sem = SEM.dynamic() dag_view = make_graphical_model( 0, T - 1, topology="independent", nodes=["X", "Z", "Y"], target_node="Y", verbose=True ) # Base topology that we build on dag = nx_agraph.from_agraph(pygraphviz.AGraph(dag_view.source)) #  Specifiy all the exploration sets based on the manipulative variables in the DAG exploration_sets = list(powerset(["X", "Z"])) # Specify the intervention domain for each variable intervention_domain = {"X": [-4, 1], "Z": [-3, 3]} # Specify a grid over each exploration and use the grid to find the best intevention value for that ES interventional_grids = get_interventional_grids(exploration_sets, intervention_domain, size_intervention_grid=100) _, _, true_objective_values, _, _, _ = optimal_sequence_of_interventions( exploration_sets=exploration_sets, interventional_grids=interventional_grids, initial_structural_equation_model=init_sem, structural_equation_model=sem, G=dag, T=T, model_variables=["X", "Z", "Y"], target_variable="Y", ) return init_sem, sem, dag_view, dag, exploration_sets, intervention_domain, true_objective_values def setup_nonstat_scm(T: int = 3): #  Load SEM from figure 3(c) in paper (upper left quadrant) SEM = NonStationaryDependentSEM(change_point=1) #  Explicitly tell SEM to change at t=1 init_sem = SEM.static() sem = SEM.dynamic() dag_view = make_graphical_model( 0, T - 1, topology="dependent", nodes=["X", "Z", "Y"], verbose=True ) # Base topology that we build on dag = nx_agraph.from_agraph(pygraphviz.AGraph(dag_view.source)) #  Specifiy all the exploration sets based on the manipulative variables in the DAG exploration_sets = list(powerset(["X", "Z"])) # Specify the intervention domain for each variable intervention_domain = {"X": [-4, 1], "Z": [-3, 3]} # Specify a grid over each exploration and use the grid to find the best intevention value for that ES interventional_grids = get_interventional_grids(exploration_sets, intervention_domain, size_intervention_grid=100) _, _, true_objective_values, _, _, _ = optimal_sequence_of_interventions( exploration_sets=exploration_sets, interventional_grids=interventional_grids, initial_structural_equation_model=init_sem, structural_equation_model=sem, G=dag, T=T, model_variables=["X", "Z", "Y"], target_variable="Y", ) return init_sem, sem, dag_view, dag, exploration_sets, intervention_domain, true_objective_values
imtypist/FISCO-BCOS
libsecurity/EncryptedLevelDB.h
/* * @CopyRight: * FISCO-BCOS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/> * (c) 2016-2018 fisco-dev contributors. */ /** * @brief : Encrypt level DB * @author: jimmyshi, websterchen * @date: 2018-11-26 */ #pragma once #include "Common.h" #include <leveldb/db.h> #include <leveldb/slice.h> #include <libdevcore/BasicLevelDB.h> #include <string> namespace dev { namespace db { #define ENCDB_LOG(_OBV) LOG(_OBV) << "[g:" << m_name << "][ENCDB]" class EncryptedLevelDBWriteBatch : public LevelDBWriteBatch { public: EncryptedLevelDBWriteBatch(const dev::bytes& _dataKey, const std::string& _name = "") : m_dataKey(_dataKey), m_name(_name) {} void insertSlice(const leveldb::Slice& _key, const leveldb::Slice& _value) override; private: dev::bytes m_dataKey; std::string m_name; }; class EncryptedLevelDB : public BasicLevelDB { public: EncryptedLevelDB(const leveldb::Options& _options, const std::string& _name, const std::string& _cipherDataKey, const std::string& _dataKey); ~EncryptedLevelDB(){}; static leveldb::Status Open(const leveldb::Options& _options, const std::string& _name, BasicLevelDB** _dbptr, const std::string& _cipherDataKey, const std::string& _dataKey); // DB open leveldb::Status Get(const leveldb::ReadOptions& _options, const leveldb::Slice& _key, std::string* _value) override; leveldb::Status Put(const leveldb::WriteOptions& _options, const leveldb::Slice& _key, const leveldb::Slice& _value) override; std::unique_ptr<LevelDBWriteBatch> createWriteBatch() const override; enum class OpenDBStatus { FirstCreation = 0, NoEncrypted, CipherKeyError, Encrypted }; private: std::string m_cipherDataKey; dev::bytes m_dataKey; private: std::string getKeyOfDatabase(); void setCipherDataKey(std::string _cipherDataKey); EncryptedLevelDB::OpenDBStatus checkOpenDBStatus(); }; } // namespace db } // namespace dev
TrueMarketing/trimtileandstone
node_modules/styled-icons/remix-line/Database2/Database2.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var StyledIconBase_1 = require("../../StyledIconBase"); exports.Database2 = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", "xmlns": "http://www.w3.org/2000/svg", }; return (React.createElement(StyledIconBase_1.StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k0" }), React.createElement("path", { d: "M5 12.5c0 .313.461.858 1.53 1.393C7.914 14.585 9.877 15 12 15c2.123 0 4.086-.415 5.47-1.107 1.069-.535 1.53-1.08 1.53-1.393v-2.171C17.35 11.349 14.827 12 12 12s-5.35-.652-7-1.671V12.5zm14 2.829C17.35 16.349 14.827 17 12 17s-5.35-.652-7-1.671V17.5c0 .313.461.858 1.53 1.393C7.914 19.585 9.877 20 12 20c2.123 0 4.086-.415 5.47-1.107 1.069-.535 1.53-1.08 1.53-1.393v-2.171zM3 17.5v-10C3 5.015 7.03 3 12 3s9 2.015 9 4.5v10c0 2.485-4.03 4.5-9 4.5s-9-2.015-9-4.5zm9-7.5c2.123 0 4.086-.415 5.47-1.107C18.539 8.358 19 7.813 19 7.5c0-.313-.461-.858-1.53-1.393C16.086 5.415 14.123 5 12 5c-2.123 0-4.086.415-5.47 1.107C5.461 6.642 5 7.187 5 7.5c0 .313.461.858 1.53 1.393C7.914 9.585 9.877 10 12 10z", key: "k1" }))); }); exports.Database2.displayName = 'Database2'; exports.Database2Dimensions = { height: 24, width: 24 };
nwashangai/open-school-system
application/models/staff_schedules.js
<gh_stars>0 'use strict'; module.exports = (sequelize, DataTypes) => { const staff_schedules = sequelize.define('staff_schedules', { period_id: DataTypes.UUID, teacher_id: DataTypes.STRING(20), day: DataTypes.ENUM('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'), classroom_id: DataTypes.UUID, class_id: DataTypes.UUID }, {}); staff_schedules.associate = (models) => { staff_schedules.hasOne(models.periods); staff_schedules.hasOne(models.teachers, { as: 'schedule', foreignKey: 'fk_schedule' }); staff_schedules.hasOne(models.classrooms, { as: 'classrooms', foreignKey: 'fk_schedule_classroom' }); staff_schedules.hasOne(models.classes, { as: 'classes', foreignKey: 'fk_schedule_class' }); }; return staff_schedules; };
sarunas-davalga/begiks
buster.js
<gh_stars>1-10 var config = module.exports; config["server.test"] = { rootPath: ".", environment: "node", tests: ["server.test/*.test.js"] };
yoki123/oceanengine
marketing-api/model/file/image.go
<reponame>yoki123/oceanengine<filename>marketing-api/model/file/image.go package file // Image 图片 type Image struct { // ID 图片ID ID string `json:"id,omitempty"` // MaterialID 素材id,即多合一报表中的素材id,一个素材唯一对应一个素材id MaterialID uint64 `json:"material_id,omitempty"` // Size 图片大小 Size uint64 `json:"size,omitempty"` // Width 图片宽度 Width int `json:"width,omitempty"` // Height 图片高度 Height int `json:"height,omitempty"` // URL 图片预览地址,仅限同主体进行素材预览查看,若非同主体会返回“素材所属主体与开发者主体不一致无法获取URL” // 链接仅做预览使用,预览链接有效期为1小时 URL string `json:"url,omitempty"` // Format 图片格式 Format string `json:"format,omitempty"` // Signature 图片md5 Signature string `json:"signature,omitempty"` // CreateTime 素材的上传时间,格式:"yyyy-mm-dd HH:MM:SS" CreateTime string `json:"create_time,omitempty"` // Filename 素材的文件名 Filename string `json:"filename,omitempty"` }
IvayloIV/Spring-in-Action-5
6.Creating_REST_services/taco-cloud-hateoas/src/main/java/sia/tacocloud/assemblers/IngredientResourceAssembler.java
package sia.tacocloud.assemblers; import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; import org.springframework.stereotype.Component; import sia.tacocloud.domain.entity.Ingredient; import sia.tacocloud.domain.model.resource.IngredientResourceModel; import sia.tacocloud.web.controllers.api.IngredientApiController; @Component public class IngredientResourceAssembler extends RepresentationModelAssemblerSupport<Ingredient, IngredientResourceModel> { public IngredientResourceAssembler() { super(IngredientApiController.class, IngredientResourceModel.class); } @Override protected IngredientResourceModel instantiateModel(Ingredient ingredient) { return new IngredientResourceModel(ingredient); } @Override public IngredientResourceModel toModel(Ingredient ingredient) { return instantiateModel(ingredient); } }
Breno-Lima/Linguagem-C
terte.c
#include <stdio.h> #define Alunos 1 double Media(double notas[Alunos]){ double soma=0,media=0; soma=soma+notas[Alunos]; return media=soma/notas[Alunos]; } int main(void){ double notas[Alunos],media=0,variancia,soma=0; int i; for(i=0;i<=Alunos;i++){ printf("Digite a nota do aluno: #%d ",i+1); scanf("%lf",&notas[i]); } media=Media(notas); printf("A media foi: %.1lf",media); return 0; }
Guyutongxue/Introduction_to_Computation
pg_answer/e4cb1cc73ee0415fb9f4f6aa6d0e0664.cpp
#include <string> #include <iostream> int main() { int a[24]; bool visited[24]{}; int n; std::cin >> n; for (int i{1}; i <= n; i++) { std::cin >> a[i]; } int i{1}, step{1}; visited[0] = true; while (i < n + 1) { if (visited[i]) { i++; step += 2; continue; } visited[i] = true; i += a[i]; step += 1; if (i < 0) i = 0; } std::cout << step << std::endl; }
timb-machine-mirrors/tlsmate
tlsmate/plugin.py
# -*- coding: utf-8 -*- """Module providing stuff for plugin handling """ # import basic stuff import logging import abc import sys import argparse from typing import List, Optional, Type, Any # import own stuff import tlsmate.config as conf import tlsmate.structs as structs # import other stuff class Args(object): """Helper class to simplify specification of argparse arguments. Arguments: args: one optional argument kwargs: any number of named arguments """ def __init__(self, *args: Any, **kwargs: Any) -> None: self.arg = args[0] if args else None self.kwargs = kwargs class Plugin(metaclass=abc.ABCMeta): """Base class for plugins A plugin can be: - a subcommand - an argument group - a single argument A plugin may have: - an associated configuration item - a list of plugins which are plugged in into this class - a list of workers, which by default will be registered if - the plugin is a subcommand or - the associated configuration is not False and not None The default plugin behavior can be overruled by specific class methods. Attributes: config: an optional associated configuration item group: parameters for the add_argument_group method (argparse) subcommand: parameters for the add_subparsers method cli_args: parameters for the add_argument method (argparse) plugins: A list of plugin classes which are plugged in into this plugin. workers: a list of worker classes to be registered """ config: Optional[structs.ConfigItem] = None group: Optional[Args] = None subcommand: Optional[Args] = None cli_args: Optional[Args] = None plugins: Optional[List[Type["Plugin"]]] = None workers: Optional[List[Type["Worker"]]] = None @classmethod def args_name(cls) -> str: """Helper method to retrieve the args-attribute from the attribute arguments. Returns: the attribute name for the args object """ assert cls.cli_args if "dest" in cls.cli_args.kwargs: return cls.cli_args.kwargs["dest"] name = cls.cli_args.arg if name.startswith("--"): name = name[2:] return name.replace("-", "_") @classmethod def extend(cls, plugin: Type["Plugin"]) -> Type["Plugin"]: """Decorator to extend a plugin """ if cls.plugins is None: cls.plugins = [] cls.plugins.append(plugin) return plugin @classmethod def extend_parser(cls, parser: argparse.ArgumentParser, subparsers: Any) -> None: """Extends the parser (subcommand, argument group, or argument) Arguments: parser: the CLI parser object subparsers: the subparser object """ if cls.cli_args: parser.add_argument(cls.cli_args.arg, **cls.cli_args.kwargs) elif cls.subcommand and subparsers: parser = subparsers.add_parser(cls.subcommand.arg, **cls.subcommand.kwargs) elif cls.group: parser = parser.add_argument_group(**cls.group.kwargs) # type: ignore if cls.plugins is not None: for plugin in cls.plugins: plugin.extend_parser(parser, subparsers) @classmethod def register_config(cls, config: conf.Configuration) -> None: """Registers its configuration item, if defined. Arguments: config: The configuration object. """ if cls.config: config.register(cls.config) if cls.plugins: for plugin in cls.plugins: plugin.register_config(config) @classmethod def args_parsed( cls, args: Any, parser: argparse.ArgumentParser, subcommand: str, config: conf.Configuration, ) -> None: """Callback after the arguments are parsed. Provides the configuration (based on the argument) and registers the workers. Arguments: args: the parsed arguments object parser: the CLI parser object subcommand: the subcommand that was given config: The configuration object. """ if cls.subcommand and cls.subcommand.arg != subcommand: return register_workers = False if cls.cli_args and cls.config: val = getattr(args, cls.args_name()) if val is not None: config.set(cls.config.name, val) if cls.config: register_workers = config.get(cls.config.name) not in [None, False] elif cls.subcommand: register_workers = True if register_workers and cls.workers is not None: for worker in cls.workers: WorkManager.register(worker) if cls.plugins is not None: for plugin in cls.plugins: plugin.args_parsed(args, parser, subcommand, config) class ArgPlugin(Plugin): """Plugin for specifying the plugins that shall be loaded. """ config = conf.config_plugin cli_args = Args( "--plugin", nargs="*", type=str, help=( "list of plugins to load. The name of each plugin must start with " "`tlsmate_`." ), ) class ArgConfig(Plugin): """Plugin for the config file argument. """ cli_args = Args( "--config", dest="config_file", default=None, help="ini-file to read the configuration from.", ) class ArgLogging(Plugin): """Plugin for the logging argument. """ cli_args = Args( "--logging", choices=["critical", "error", "warning", "info", "debug"], help="sets the logging level. Default is error.", default="error", ) class BaseCommand(Plugin): """The base class for tlsmate. To be extended by plugins. """ plugins = [ArgPlugin, ArgConfig, ArgLogging] @classmethod def create_parser(cls): parser = argparse.ArgumentParser( description=( "tlsmate is an application for testing and analyzing TLS servers. " "Test scenarios can be defined in a simple way with great flexibility. " "A TLS server configuration and vulnerability scan is built in." ) ) subparsers = parser.add_subparsers(title="commands", dest="subcommand") cls.extend_parser(parser, subparsers) return parser @classmethod def args_parsed(cls, args, parser, subcommand, config): if args.subcommand is None: parser.error("Subcommand is mandatory") super().args_parsed(args, parser, args.subcommand, config) class Worker(metaclass=abc.ABCMeta): """Provides a base class for the implementation of a worker. Attributes: name (str): name of the worker, used for logging purposes only prio (int): all workers are executed according to their the priority. A lower value indicates higher priority, i.e., the worker with the lowest value will run first. If two workers have the same priority, their execution order will be determined by the alphabetical order of their name attribute. server_profile (:obj:`tlsmate.server_profile.ServerProfile`): The server profile instance. Can be used to get data from it (e.g. which cipher suites are supported for which TLS versions), or to extend it. client (:obj:`tlsmate.client.Client`): The client object. config (:obj:`tlsmate.config.Configuration`): The configuration object. """ prio = 100 def __init__(self, tlsmate): self._tlsmate = tlsmate self.server_profile = tlsmate.server_profile self.client = tlsmate.client self.config = tlsmate.config @abc.abstractmethod def run(self): """Entry point for the worker. The work manager will call this method which actually let worker do its job. """ raise NotImplementedError class WorkManager(object): """Manages the registered workers and runs them. The worker manager provides an interface to register workers. The registered workers are triggered based on their priority by calling their run method. """ _instance = None def __init__(self): WorkManager._instance = self self._prio_pool = {} def _register(self, worker_class): self._prio_pool.setdefault(worker_class.prio, []) self._prio_pool[worker_class.prio].append(worker_class) @classmethod def register(cls, worker_class): """Register a worker plugin class. Can be used as a decorator. Arguments: worker_class (:class:`Worker`): A worker class to be registered. Returns: :class:`Worker`: the worker class passed as argument """ cls._instance._register(worker_class) return worker_class def run(self, tlsmate): """Function to actually start the work manager. The run method of all registered worker plugins will be called according to the priority of the workers. Arguments: tlsmate (:obj:`tlsmate.tlsmate.TlsMate`): The tlsmate object which is passed to the run methods of the workers. """ for prio_list in sorted(self._prio_pool.keys()): for cls in sorted(self._prio_pool[prio_list], key=lambda cls: cls.name): if tlsmate.config.get("progress"): sys.stderr.write(f"\n{cls.descr}") sys.stderr.flush() logging.debug(f"starting worker {cls.name}") cls(tlsmate).run() logging.debug(f"worker {cls.name} finished")
Mathiasn21/Group_project_software_engineering
src/main/java/no/hiof/set/gruppe/core/interfaces/IPaymentIntegration.java
package no.hiof.set.gruppe.core.interfaces; import com.google.api.client.http.HttpResponse; import java.io.IOException; public interface IPaymentIntegration { HttpResponse response() throws IOException; }
zvam1/gitlab-on-heroku
spec/services/personal_access_tokens/revoke_service_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::RevokeService do shared_examples_for 'a successfully revoked token' do it { expect(subject.success?).to be true } it { expect(service.token.revoked?).to be true } end shared_examples_for 'an unsuccessfully revoked token' do it { expect(subject.success?).to be false } it { expect(service.token.revoked?).to be false } end describe '#execute' do subject { service.execute } let(:service) { described_class.new(current_user, token: token) } context 'when current_user is an administrator' do let_it_be(:current_user) { create(:admin) } let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'a successfully revoked token' end context 'when current_user is not an administrator' do let_it_be(:current_user) { create(:user) } context 'token belongs to a different user' do let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'an unsuccessfully revoked token' end context 'token belongs to current_user' do let_it_be(:token) { create(:personal_access_token, user: current_user) } it_behaves_like 'a successfully revoked token' end end end end
node-dot-cpp/safe-memory
checker/src/safememory-checker/ReferenceOverCoAwaitRule.cpp
<reponame>node-dot-cpp/safe-memory /* ------------------------------------------------------------------------------- * Copyright (c) 2019, OLogN Technologies AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OLogN Technologies AG nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL OLogN Technologies AG BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------------------*/ #include "ReferenceOverCoAwaitRule.h" #include "CheckerASTVisitor.h" #include "nodecpp/NakedPtrHelper.h" #include "ClangTidyDiagnosticConsumer.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" namespace nodecpp { namespace checker { struct MyStack { std::vector<std::vector<const clang::VarDecl*>> Vds; void enter() {Vds.push_back({});} void exit() {Vds.pop_back();} void add(const clang::VarDecl* D) { if(!Vds.empty()) Vds.back().push_back(D); } class Riia { MyStack& St; public: Riia(MyStack& St) :St(St) {St.enter();} ~Riia() {St.exit();} }; }; /// \brief Check that nullable_ptr are not used class CoroutineASTVisitor : public SafetyASTVisitor<CoroutineASTVisitor> { MyStack St; /// \brief Add a diagnostic with the check's name. DiagnosticBuilder diag(SourceLocation Loc, StringRef Message, DiagnosticIDs::Level Level = DiagnosticIDs::Error) { return Context->diag(DiagMsgSrc, Loc, Message, Level); } CheckHelper* getCheckHelper() const { return Context->getCheckHelper(); } public: explicit CoroutineASTVisitor(ClangTidyContext *Context): SafetyASTVisitor<CoroutineASTVisitor>(Context) {} bool TraverseFunctionDecl(clang::FunctionDecl *D) { MyStack::Riia Riia(St); return Super::TraverseFunctionDecl(D);; } bool TraverseCompoundStmt(clang::CompoundStmt *S) { MyStack::Riia Riia(St); return Super::TraverseCompoundStmt(S);; } bool VisitVarDecl(clang::VarDecl *D) { auto Qt = D->getType().getCanonicalType(); if(getCheckHelper()->isStackOnly(Qt)) { St.add(D); } return Super::VisitVarDecl(D); } bool VisitCoawaitExpr(clang::CoawaitExpr *E) { for(auto &Outer : St.Vds) { for(auto &Inner : Outer) { diag(Inner->getLocation(), "(S5.8) variable has 'co_await' in its scope"); diag(E->getExprLoc(), "'co_await' here", DiagnosticIDs::Note); } } return Super::VisitCoawaitExpr(E); } bool VisitCoyieldExpr(clang::CoyieldExpr *E) { for(auto &Outer : St.Vds) { for(auto &Inner : Outer) { diag(Inner->getLocation(), "(S5.8) variable has 'co_yield' in its scope"); diag(E->getExprLoc(), "'co_yield' here", DiagnosticIDs::Note); } } return Super::VisitCoyieldExpr(E); } }; class CoroutineASTConsumer : public clang::ASTConsumer { CoroutineASTVisitor Visitor; public: CoroutineASTConsumer(ClangTidyContext *Context) :Visitor(Context) {} void HandleTranslationUnit(clang::ASTContext &Context) override { Visitor.TraverseDecl(Context.getTranslationUnitDecl()); } }; std::unique_ptr<clang::ASTConsumer> makeReferenceOverCoAwaitRule(ClangTidyContext *Context) { return std::make_unique<CoroutineASTConsumer>(Context); } } // namespace checker } // namespace nodecpp
HaoXuan1988/ZhiYu
ZhiYu/Request/HXNetwork.h
// // HXNetwork.h // HXNetworkDemo // // Created by 吕浩轩 on 16/3/11. // Copyright © 2016年 吕浩轩. All rights reserved. // #ifndef HXNetwork_h #define HXNetwork_h #import "HXResponseManager.h" #endif /* HXNetwork_h */
andreatulimiero/i3pp
include/data.hpp
<reponame>andreatulimiero/i3pp<filename>include/data.hpp /* * vim:ts=4:sw=4:expandtab * * i3 - an improved dynamic tiling window manager * © 2009 <NAME> and contributors (see also: LICENSE) * * include/data.h: This file defines all data structures used by i3 * */ #pragma once #define SN_API_NOT_YET_FROZEN 1 #include <libsn/sn-launcher.h> #include <xcb/randr.h> #include <pcre.h> #include <sys/time.h> #include <cairo/cairo.h> #include "queue.hpp" /* * To get the big concept: There are helper structures like struct * Workspace_Assignment. Every struct which is also defined as type (see * forward definitions) is considered to be a major structure, thus important. * * The following things are all stored in a 'Con', from very high level (the * biggest Cons) to very small (a single window): * * 1) X11 root window (as big as all your outputs combined) * 2) output (like LVDS1) * 3) content container, dockarea containers * 4) workspaces * 5) split containers * ... (you can arbitrarily nest split containers) * 6) X11 window containers * */ /* Forward definitions */ struct Binding; struct Rect; struct xoutput; struct Con; struct Match; struct Assignment; using Output = struct xoutput; namespace i3 { struct Window; } struct mark_t; /****************************************************************************** * Helper types *****************************************************************************/ typedef enum { D_LEFT, D_RIGHT, D_UP, D_DOWN } direction_t; typedef enum { NO_ORIENTATION = 0, HORIZ, VERT } orientation_t; typedef enum { BEFORE, AFTER } position_t; typedef enum { BS_NORMAL = 0, BS_NONE = 1, BS_PIXEL = 2 } border_style_t; /** parameter to specify whether tree_close_internal() and x_window_kill() should kill * only this specific window or the whole X11 client */ enum kill_window { DONT_KILL_WINDOW = 0, KILL_WINDOW = 1, KILL_CLIENT = 2 }; /** describes if the window is adjacent to the output (physical screen) edges. */ typedef enum { ADJ_NONE = 0, ADJ_LEFT_SCREEN_EDGE = (1 << 0), ADJ_RIGHT_SCREEN_EDGE = (1 << 1), ADJ_UPPER_SCREEN_EDGE = (1 << 2), ADJ_LOWER_SCREEN_EDGE = (1 << 4) } adjacent_t; typedef enum { HEBM_NONE = ADJ_NONE, HEBM_VERTICAL = ADJ_LEFT_SCREEN_EDGE | ADJ_RIGHT_SCREEN_EDGE, HEBM_HORIZONTAL = ADJ_UPPER_SCREEN_EDGE | ADJ_LOWER_SCREEN_EDGE, HEBM_BOTH = HEBM_VERTICAL | HEBM_HORIZONTAL, HEBM_SMART = (1 << 5) } hide_edge_borders_mode_t; typedef enum { MM_REPLACE, MM_ADD } mark_mode_t; /** * Container layouts. See Con::layout. */ typedef enum { L_DEFAULT = 0, L_STACKED = 1, L_TABBED = 2, L_DOCKAREA = 3, L_OUTPUT = 4, L_SPLITV = 5, L_SPLITH = 6 } layout_t; /** * Binding input types. See Binding::input_type. */ typedef enum { B_KEYBOARD = 0, B_MOUSE = 1 } input_type_t; /** * Bitmask for matching XCB_XKB_GROUP_1 to XCB_XKB_GROUP_4. */ typedef enum { I3_XKB_GROUP_MASK_ANY = 0, I3_XKB_GROUP_MASK_1 = (1 << 0), I3_XKB_GROUP_MASK_2 = (1 << 1), I3_XKB_GROUP_MASK_3 = (1 << 2), I3_XKB_GROUP_MASK_4 = (1 << 3) } i3_xkb_group_mask_t; /** * The lower 16 bits contain a xcb_key_but_mask_t, the higher 16 bits contain * an i3_xkb_group_mask_t. This type is necessary for the fallback logic to * work when handling XKB groups (see ticket #1775) and makes the code which * locates keybindings upon KeyPress/KeyRelease events simpler. */ typedef uint32_t i3_event_state_mask_t; /** * Mouse pointer warping modes. */ typedef enum { POINTER_WARPING_OUTPUT = 0, POINTER_WARPING_NONE = 1 } warping_t; /** * Focus wrapping modes. */ typedef enum { FOCUS_WRAPPING_OFF = 0, FOCUS_WRAPPING_ON = 1, FOCUS_WRAPPING_FORCE = 2, FOCUS_WRAPPING_WORKSPACE = 3 } focus_wrapping_t; /** * Stores a rectangle, for example the size of a window, the child window etc. * * Note that x and y can contain signed values in some cases (for example when * used for the coordinates of a window, which can be set outside of the * visible area, but not when specifying the position of a workspace for the * _NET_WM_WORKAREA hint). Not declaring x/y as int32_t saves us a lot of * typecasts. * */ struct Rect { uint32_t x; uint32_t y; uint32_t width; uint32_t height; }; /** * Stores the reserved pixels on each screen edge read from a * _NET_WM_STRUT_PARTIAL. * */ struct reservedpx { uint32_t left; uint32_t right; uint32_t top; uint32_t bottom; }; /** * Stores a width/height pair, used as part of deco_render_params to check * whether the rects width/height have changed. * */ struct width_height { uint32_t w; uint32_t h; }; /** * Stores the parameters for rendering a window decoration. This structure is * cached in every Con and no re-rendering will be done if the parameters have * not changed (only the pixmaps will be copied). * */ struct deco_render_params { struct Colortriple *color; int border_style; struct width_height con_rect; struct width_height con_window_rect; Rect con_deco_rect; color_t background; layout_t parent_layout; bool con_is_leaf; }; /** * Stores which workspace (by name or number) goes to which output. * */ struct Workspace_Assignment { char *name; char *output; TAILQ_ENTRY(Workspace_Assignment) ws_assignments; }; struct Ignore_Event { int sequence; int response_type; time_t added; SLIST_ENTRY(Ignore_Event) ignore_events; }; /** * Stores internal information about a startup sequence, like the workspace it * was initiated on. * */ struct Startup_Sequence { /** startup ID for this sequence, generated by libstartup-notification */ char *id; /** workspace on which this startup was initiated */ char *workspace; /** libstartup-notification context for this launch */ SnLauncherContext *context; /** time at which this sequence should be deleted (after it was marked as * completed) */ time_t delete_at; TAILQ_ENTRY(Startup_Sequence) sequences; }; /** * Regular expression wrapper. It contains the pattern itself as a string (like * ^foo[0-9]$) as well as a pointer to the compiled PCRE expression and the * pcre_extra data returned by pcre_study(). * * This makes it easier to have a useful logfile, including the matching or * non-matching pattern. * */ struct regex { char *pattern; pcre *regex; pcre_extra *extra; }; /** * Stores a resolved keycode (from a keysym), including the modifier mask. Will * be passed to xcb_grab_key(). * */ struct Binding_Keycode { xcb_keycode_t keycode; i3_event_state_mask_t modifiers; TAILQ_ENTRY(Binding_Keycode) keycodes; }; /****************************************************************************** * Major types *****************************************************************************/ /** * Holds a keybinding, consisting of a keycode combined with modifiers and the * command which is executed as soon as the key is pressed (see * src/config_parser.c) * */ struct Binding { /* The type of input this binding is for. (Mouse bindings are not yet * implemented. All bindings are currently assumed to be keyboard bindings.) */ input_type_t input_type; /** If true, the binding should be executed upon a KeyRelease event, not a * KeyPress (the default). */ enum { /* This binding will only be executed upon KeyPress events */ B_UPON_KEYPRESS = 0, /* This binding will be executed either upon a KeyRelease event, or… */ B_UPON_KEYRELEASE = 1, /* …upon a KeyRelease event, even if the modifiers don’t match. This * state is triggered from get_binding() when the corresponding * KeyPress (!) happens, so that users can release the modifier keys * before releasing the actual key. */ B_UPON_KEYRELEASE_IGNORE_MODS = 2, } release; /** If this is true for a mouse binding, the binding should be executed * when the button is pressed over the window border. */ bool border; /** If this is true for a mouse binding, the binding should be executed * when the button is pressed over any part of the window, not just the * title bar (default). */ bool whole_window; /** If this is true for a mouse binding, the binding should only be * executed if the button press was not on the titlebar. */ bool exclude_titlebar; /** Keycode to bind */ uint32_t keycode; /** Bitmask which is applied against event->state for KeyPress and * KeyRelease events to determine whether this binding applies to the * current state. */ i3_event_state_mask_t event_state_mask; /** Symbol the user specified in configfile, if any. This needs to be * stored with the binding to be able to re-convert it into a keycode * if the keyboard mapping changes (using Xmodmap for example) */ char *symbol; /** Only in use if symbol != NULL. Contains keycodes which generate the * specified symbol. Useful for unbinding and checking which binding was * used when a key press event comes in. */ TAILQ_HEAD(keycodes_head, Binding_Keycode) keycodes_head; /** Command, like in command mode */ char *command; TAILQ_ENTRY(Binding) bindings; }; /** * Holds a command specified by either an: * - exec-line * - exec_always-line * in the config (see src/config.c) * */ struct Autostart { /** Command, like in command mode */ char *command; /** no_startup_id flag for start_application(). Determines whether a * startup notification context/ID should be created. */ bool no_startup_id; TAILQ_ENTRY(Autostart) autostarts; TAILQ_ENTRY(Autostart) autostarts_always; }; struct output_name { char *name; SLIST_ENTRY(output_name) names; }; /** * An Output is a physical output on your graphics driver. Outputs which * are currently in use have (output->active == true). Each output has a * position and a mode. An output usually corresponds to one connected * screen (except if you are running multiple screens in clone mode). * */ struct xoutput { /** Output id, so that we can requery the output directly later */ xcb_randr_output_t id; /** Whether the output is currently active (has a CRTC attached with a * valid mode) */ bool active; /** Internal flags, necessary for querying RandR screens (happens in * two stages) */ bool changed; bool to_be_disabled; bool primary; /** List of names for the output. * An output always has at least one name; the first name is * considered the primary one. */ SLIST_HEAD(names_head, output_name) names_head; /** Pointer to the Con which represents this output */ Con *con; /** x, y, width, height */ Rect rect; TAILQ_ENTRY(xoutput) outputs; }; namespace i3 { /** * A 'Window' is a type which contains an xcb_window_t and all the related * information (hints like _NET_WM_NAME for that window). * */ struct Window { xcb_window_t id; /** Holds the xcb_window_t (just an ID) for the leader window (logical * parent for toolwindows and similar floating windows) */ xcb_window_t leader; xcb_window_t transient_for; /** Pointers to the Assignments which were already ran for this Window * (assignments run only once) */ uint32_t nr_assignments; Assignment **ran_assignments; char *class_class; char *class_instance; /** The name of the window. */ i3String *name; /** The WM_WINDOW_ROLE of this window (for example, the pidgin buddy window * sets "buddy list"). Useful to match specific windows in assignments or * for_window. */ char *role; /** WM_CLIENT_MACHINE of the window */ char *machine; /** Flag to force re-rendering the decoration upon changes */ bool name_x_changed; /** Whether the application used _NET_WM_NAME */ bool uses_net_wm_name; /** Whether the application needs to receive WM_TAKE_FOCUS */ bool needs_take_focus; /** Whether this window accepts focus. We store this inverted so that the * default will be 'accepts focus'. */ bool doesnt_accept_focus; /** The _NET_WM_WINDOW_TYPE for this window. */ xcb_atom_t window_type; /** The _NET_WM_DESKTOP for this window. */ uint32_t wm_desktop; /** Whether the window says it is a dock window */ enum { W_NODOCK = 0, W_DOCK_TOP = 1, W_DOCK_BOTTOM = 2 } dock; /** When this window was marked urgent. 0 means not urgent */ struct timeval urgent; /** Pixels the window reserves. left/right/top/bottom */ struct reservedpx reserved; /** Depth of the window */ uint16_t depth; /* the wanted size of the window, used in combination with size * increments (see below). */ int base_width; int base_height; /* minimum increment size specified for the window (in pixels) */ int width_increment; int height_increment; /* Minimum size specified for the window. */ int min_width; int min_height; /* Maximum size specified for the window. */ int max_width; int max_height; /* aspect ratio from WM_NORMAL_HINTS (MPlayer uses this for example) */ double min_aspect_ratio; double max_aspect_ratio; /** Window icon, as Cairo surface */ cairo_surface_t *icon; /** The window has a nonrectangular shape. */ bool shaped; /** The window has a nonrectangular input shape. */ bool input_shaped; /* Time when the window became managed. Used to determine whether a window * should be swallowed after initial management. */ time_t managed_since; /* The window has been swallowed. */ bool swallowed; }; } /** * A "match" is a data structure which acts like a mask or expression to match * certain windows or not. For example, when using commands, you can specify a * command like this: [title="*Firefox*"] kill. The title member of the match * data structure will then be filled and i3 will check each window using * match_matches_window() to find the windows affected by this command. * */ struct Match { /* Set if a criterion was specified incorrectly. */ char *error; struct regex *title; struct regex *application; struct regex *class; struct regex *instance; struct regex *mark; struct regex *window_role; struct regex *workspace; struct regex *machine; xcb_atom_t window_type; enum { U_DONTCHECK = -1, U_LATEST = 0, U_OLDEST = 1 } urgent; enum { M_DONTCHECK = -1, M_NODOCK = 0, M_DOCK_ANY = 1, M_DOCK_TOP = 2, M_DOCK_BOTTOM = 3 } dock; xcb_window_t id; enum { WM_ANY = 0, WM_TILING_AUTO, WM_TILING_USER, WM_TILING, WM_FLOATING_AUTO, WM_FLOATING_USER, WM_FLOATING } window_mode; Con *con_id; /* Where the window looking for a match should be inserted: * * M_HERE = the matched container will be replaced by the window * (layout saving) * M_ASSIGN_WS = the matched container will be inserted in the target_ws. * M_BELOW = the window will be inserted as a child of the matched container * (dockareas) * */ enum { M_HERE = 0, M_ASSIGN_WS, M_BELOW } insert_where; TAILQ_ENTRY(Match) matches; /* Whether this match was generated when restarting i3 inplace. * Leads to not setting focus when managing a new window, because the old * focus stack should be restored. */ bool restart_mode; }; /** * An Assignment makes specific windows go to a specific workspace/output or * run a command for that window. With this mechanism, the user can -- for * example -- assign their browser to workspace "www". Checking if a window is * assigned works by comparing the Match data structure with the window (see * match_matches_window()). * */ struct Assignment { /** type of this assignment: * * A_COMMAND = run the specified command for the matching window * A_TO_WORKSPACE = assign the matching window to the specified workspace * A_NO_FOCUS = don't focus matched window when it is managed * * While the type is a bitmask, only one value can be set at a time. It is * a bitmask to allow filtering for multiple types, for example in the * assignment_for() function. * */ enum { A_ANY = 0, A_COMMAND = (1 << 0), A_TO_WORKSPACE = (1 << 1), A_NO_FOCUS = (1 << 2), A_TO_WORKSPACE_NUMBER = (1 << 3), A_TO_OUTPUT = (1 << 4) } type; /** the criteria to check if a window matches */ Match match; /** destination workspace/command/output, depending on the type */ union { char *command; char *workspace; char *output; } dest; TAILQ_ENTRY(Assignment) assignments; }; /** Fullscreen modes. Used by Con.fullscreen_mode. */ typedef enum { CF_NONE = 0, CF_OUTPUT = 1, CF_GLOBAL = 2 } fullscreen_mode_t; struct mark_t { char *name; TAILQ_ENTRY(mark_t) marks; }; /** * A 'Con' represents everything from the X11 root window down to a single X11 window. * */ struct Con { bool mapped; /* Should this container be marked urgent? This gets set when the window * inside this container (if any) sets the urgency hint, for example. */ bool urgent; /** This counter contains the number of UnmapNotify events for this * container (or, more precisely, for its ->frame) which should be ignored. * UnmapNotify events need to be ignored when they are caused by i3 itself, * for example when reparenting or when unmapping the window on a workspace * change. */ uint8_t ignore_unmap; /* The surface used for the frame window. */ surface_t frame; surface_t frame_buffer; bool pixmap_recreated; enum type { CT_ROOT = 0, CT_OUTPUT = 1, CT_CON = 2, CT_FLOATING_CON = 3, CT_WORKSPACE = 4, CT_DOCKAREA = 5 }; type type; /** the workspace number, if this Con is of type CT_WORKSPACE and the * workspace is not a named workspace (for named workspaces, num == -1) */ int num; struct Con *parent; /* The position and size for this con. These coordinates are absolute. Note * that the rect of a container does not include the decoration. */ struct Rect rect; /* The position and size of the actual client window. These coordinates are * relative to the container's rect. */ struct Rect window_rect; /* The position and size of the container's decoration. These coordinates * are relative to the container's parent's rect. */ struct Rect deco_rect; /** the geometry this window requested when getting mapped */ struct Rect geometry; char *name; /** The format with which the window's name should be displayed. */ char *title_format; /** Whether the window icon should be displayed, and with what padding. -1 * means display no window icon (default behavior), 0 means display without * any padding, 1 means display with 1 pixel of padding and so on. */ int window_icon_padding; /* a sticky-group is an identifier which bundles several containers to a * group. The contents are shared between all of them, that is they are * displayed on whichever of the containers is currently visible */ char *sticky_group; /* user-definable marks to jump to this container later */ TAILQ_HEAD(marks_head, mark_t) marks_head; /* cached to decide whether a redraw is needed */ bool mark_changed; double percent; /* the x11 border pixel attribute */ int border_width; int current_border_width; i3::Window *window; /* timer used for disabling urgency */ struct ev_timer *urgency_timer; /** Cache for the decoration rendering */ struct deco_render_params *deco_render_params; /* Only workspace-containers can have floating clients */ TAILQ_HEAD(floating_head, Con) floating_head; TAILQ_HEAD(nodes_head, Con) nodes_head; TAILQ_HEAD(focus_head, Con) focus_head; TAILQ_HEAD(swallow_head, Match) swallow_head; fullscreen_mode_t fullscreen_mode; /* Whether this window should stick to the glass. This corresponds to * the _NET_WM_STATE_STICKY atom and will only be respected if the * window is floating. */ bool sticky; /* layout is the layout of this container: one of split[v|h], stacked or * tabbed. Special containers in the tree (above workspaces) have special * layouts like dockarea or output. * * last_split_layout is one of splitv or splith to support the old "layout * default" command which by now should be "layout splitv" or "layout * splith" explicitly. * * workspace_layout is only for type == CT_WORKSPACE cons. When you change * the layout of a workspace without any children, i3 cannot just set the * layout (because workspaces need to be splitv/splith to allow focus * parent and opening new containers). Instead, it stores the requested * layout in workspace_layout and creates a new split container with that * layout whenever a new container is attached to the workspace. */ layout_t layout, last_split_layout, workspace_layout; border_style_t border_style; /** floating? (= not in tiling layout) This cannot be simply a bool * because we want to keep track of whether the status was set by the * application (by setting _NET_WM_WINDOW_TYPE appropriately) or by the * user. The user’s choice overwrites automatic mode, of course. The * order of the values is important because we check with >= * FLOATING_AUTO_ON if a client is floating. */ enum { FLOATING_AUTO_OFF = 0, FLOATING_USER_OFF = 1, FLOATING_AUTO_ON = 2, FLOATING_USER_ON = 3 } floating; TAILQ_ENTRY(Con) nodes; TAILQ_ENTRY(Con) focused; TAILQ_ENTRY(Con) all_cons; TAILQ_ENTRY(Con) floating_windows; /** callbacks */ void (*on_remove_child)(Con *); enum { /* Not a scratchpad window. */ SCRATCHPAD_NONE = 0, /* Just moved to scratchpad, not resized by the user yet. * Window will be auto-centered and sized appropriately. */ SCRATCHPAD_FRESH = 1, /* The user changed position/size of the scratchpad window. */ SCRATCHPAD_CHANGED = 2 } scratchpad_state; /* The ID of this container before restarting. Necessary to correctly * interpret back-references in the JSON (such as the focus stack). */ int old_id; /* Depth of the container window */ uint16_t depth; /* The colormap for this con if a custom one is used. */ xcb_colormap_t colormap; };
demonsaw/Code
ds4/code/4_client_desktop/widget/search_widget.cpp
<filename>ds4/code/4_client_desktop/widget/search_widget.cpp<gh_stars>100-1000 // // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <cassert> #include <QAction> #include <QFileDialog> #include <QHBoxLayout> #include <QHeaderView> #include <QKeyEvent> #include <QLabel> #include <QMenu> #include <QSortFilterProxyModel> #include <QScrollBar> #include "component/browse_component.h" #include "component/callback/callback.h" #include "component/client/client_service_component.h" #include "component/io/file_component.h" #include "component/io/folder_component.h" #include "component/message/message_component.h" #include "component/search/search_component.h" #include "component/search/search_option_component.h" #include "delegate/io/file_name_delegate.h" #include "entity/entity.h" #include "entity/entity_tree_view_ex.h" #include "factory/client_factory.h" #include "font/font_awesome.h" #include "model/search_model.h" #include "model/proxy/search_proxy_model.h" #include "resource/resource.h" #include "thread/thread_info.h" #include "utility/value.h" #include "utility/io/folder_util.h" #include "widget/search_widget.h" #include "window/main_window.h" namespace eja { // Constructor search_widget::search_widget(const entity::ptr& entity, QWidget* parent /*= nullptr*/) : entity_dock_widget(entity, "Search", fa::search, parent) { assert(thread_info::main()); // Action m_download_action = make_action(" Download", fa::arrow_down); m_download_to_action = make_action(" Download To...", fa::hdd_o); m_clear_action = make_action(" Clear", fa::trash); m_refresh_action = make_action(" Refresh", fa::refresh); m_close_action = make_action(" Close", fa::close); // Menu add_button("Close", fa::close, [&]() { close(); }); // Title const auto search_option = m_entity->get<search_option_component>(); m_title_text = QString::fromStdString(search_option->get_text()); m_title->setText(m_title_text); // Layout const auto hlayout = resource::get_hbox_layout(); hlayout->addWidget(m_icon); hlayout->addWidget(m_title); hlayout->addStretch(1); hlayout->addWidget(m_toolbar); m_titlebar = new QWidget(this); m_titlebar->setObjectName("menubar"); m_titlebar->setLayout(hlayout); setTitleBarWidget(m_titlebar); // Table m_tree = new entity_tree_view_ex(m_entity, this); m_model = new search_model(m_entity, this); init_ex<search_proxy_model>(m_tree, m_model); const auto header = m_tree->header(); header->setSortIndicator(search_model::column::weight, Qt::SortOrder::DescendingOrder); m_tree->setItemDelegateForColumn(search_model::column::name, new file_name_delegate(m_tree)); m_tree->sortByColumn(search_model::column::weight); m_tree->set_column_sizes(); setWidget(m_tree); // Event m_tree->installEventFilter(this); // Signal connect(this, &search_widget::customContextMenuRequested, this, &search_widget::show_menu); connect(m_tree, &entity_tree_view_ex::customContextMenuRequested, this, &search_widget::show_menu); connect(m_tree, &entity_tree_view_ex::doubleClicked, this, &search_widget::on_double_click); connect(header, &QHeaderView::customContextMenuRequested, [&](const QPoint& pos) { show_header_menu({ "Type", "Size", "Modified", "Matches", "Seeds" }, { search_model::column::type, search_model::column::size, search_model::column::time, search_model::column::weight, search_model::column::seeds }, m_tree, m_model, pos); }); connect(m_download_action, &QAction::triggered, this, &search_widget::on_download); connect(m_download_to_action, &QAction::triggered, this, &search_widget::on_download_to); connect(m_clear_action, &QAction::triggered, [&]() { m_entity->async_call(callback::search | callback::clear, m_entity); }); connect(m_refresh_action, &QAction::triggered, [&]() { update(); }); connect(m_close_action, &QAction::triggered, [&]() { close(); }); } // Interface void search_widget::on_create() { assert(thread_info::main()); m_model->clear(); // Title const auto search_option = m_entity->get<search_option_component>(); m_title_text = QString::fromStdString(search_option->get_text()); m_title->setText(m_title_text); } void search_widget::on_add(const entity::ptr entity) { assert(thread_info::main()); assert(!entity->has<file_component>() && !entity->has<folder_component>()); // Message if (entity->has<browse_component>()) { // HACK: Do not add if the parent has expired if (!entity->has_parent()) return; const auto browse = entity->get<browse_component>(); m_messages.insert(browse->get_id()); } // Parent const auto parent = entity->has_parent() ? entity->get_parent() : m_entity; const auto parent_list = parent->get<browse_list_component>(); // List const auto list = browse_list_component::create(); const auto browse_list = entity->get<browse_list_component>(); for (const auto& e : *browse_list) { if (!e->has_parent() && e->has<file_component>()) { const auto file = e->get<file_component>(); const auto browse_map = m_entity->get<browse_map_component>(); const auto it = browse_map->find(file->get_id()); if (it == browse_map->end()) { const auto pair = std::make_pair(file->get_id(), e); browse_map->insert(pair); list->push_back(e); } else { // Swarm const auto& e2 = it->second; const auto search = e->get<search_component>(); const auto s = e2->get<search_component>(); s->add_swarm(); // Matches if (search->get_weight() > s->get_weight()) { s->set_weight(search->get_weight()); e2->add<file_component>(e); } } } else { if (e->has<folder_component>()) { const auto folder = e->get<folder_component>(); auto it = std::find_if(parent_list->begin(), parent_list->end(), [folder](const entity::ptr e2) { if (e2->has<folder_component>()) { const auto f = e2->get<folder_component>(); return (folder->get_size() == f->get_size()) && (folder->get_name() == f->get_name()); } return false; }); if (it == parent_list->end()) { list->push_back(e); } else { // Swarm const auto& e2 = *it; const auto search = e->get<search_component>(); const auto s = e2->get<search_component>(); s->add_swarm(); // Matches if (search->get_weight() > s->get_weight()) { s->set_weight(search->get_weight()); e2->add<folder_component>(e); } } } else { list->push_back(e); } } } entity->set(list); m_model->add(entity); } void search_widget::on_update() { assert(thread_info::main()); reset(); // Clear const auto browse_map = m_entity->get<browse_map_component>(); browse_map->clear(); m_model->clear(); // Service const auto owner = m_entity->get_owner(); const auto service = owner->get<client_service_component>(); if (service->valid()) { const auto search_option = m_entity->get<search_option_component>(); if (search_option->has_text()) service->async_search(m_entity); } } void search_widget::on_clear() { assert(thread_info::main()); reset(); // Clear const auto search_option = m_entity->get<search_option_component>(); search_option->set_text(); const auto browse_map = m_entity->get<browse_map_component>(); browse_map->clear(); m_title_text.clear(); m_title->setText(m_title_text); m_model->clear(); } // Utility void search_widget::reset() { assert(thread_info::main()); // Messages const auto owner = m_entity->get_owner(); const auto message_map = owner->get<message_map_component>(); { if (!m_messages.empty()) { std::for_each(m_messages.begin(), m_messages.end(), [&](const std::string& message_id) { thread_lock(message_map); message_map->erase(message_id); }); m_messages.clear(); } } } void search_widget::on_double_click(const QModelIndex& index) { assert(thread_info::main()); const auto proxy = m_tree->get_proxy(); const auto sindex = proxy->mapToSource(index); const auto entity = m_model->get_entity(sindex); if (entity) { if (entity->has<file_component>()) { const auto owner = m_entity->get_owner(); const auto client = owner->get<client_component>(); download(entity, client->get_path()); open_tabs(); } } } void search_widget::download(const entity::ptr& entity, const boost::filesystem::path& path) { if (entity->has<file_component>()) { // File const auto owner = m_entity->get_owner(); const auto download_entity = client_factory::create_download(owner, entity, path); // Callback m_entity->async_call(callback::download | callback::add, download_entity); } else if (entity->has<folder_component>()) { try { // Folder folder_util::create(path); const auto browse_list = entity->get<browse_list_component>(); if (browse_list->is_expanded()) { for (const auto& e : *browse_list) { if (e->has<file_component>()) { download(e, path); } else if (e->has<folder_component>()) { // Folder boost::filesystem::path subpath(path); const auto folder = e->get<folder_component>(); subpath /= folder->get_data(); const auto bl = e->get<browse_list_component>(); bl->set_download(true); bl->set_path(subpath); bl->set_search(true); download(e, subpath); } } } else { browse_list->set_download(true); browse_list->set_expanded(true); browse_list->set_search(true); // Service const auto owner = m_entity->get_owner(); const auto service = owner->get<client_service_component>(); service->async_browse(entity); } } catch (const std::exception& ex) { m_entity->log(ex); } } } void search_widget::on_download() { assert(thread_info::main()); const auto owner = m_entity->get_owner(); const auto service = owner->get<client_service_component>(); if (service->invalid()) return; m_tree->execute([&](const QModelIndex& index) { const auto entity = m_model->get_entity(index); if (entity) { if (entity->has<file_component>()) { const auto client = owner->get<client_component>(); download(entity, client->get_path()); } else if (entity->has<folder_component>()) { // Client const auto client = owner->get<client_component>(); auto path = client->get_path(); // Folder const auto folder = entity->get<folder_component>(); path /= folder->get_data(); const auto browse_list = entity->get<browse_list_component>(); browse_list->set_path(path); download(entity, path); } } }); open_tabs(); } void search_widget::on_download_to() { assert(thread_info::main()); const auto owner = m_entity->get_owner(); const auto service = owner->get<client_service_component>(); if (service->invalid()) return; QFileDialog dialog; dialog.setWindowTitle("Download To..."); dialog.setOptions(QFileDialog::ShowDirsOnly | QFileDialog::DontUseNativeDialog); dialog.setFileMode(QFileDialog::DirectoryOnly); dialog.setViewMode(QFileDialog::ViewMode::List); const auto client = owner->get<client_component>(); #if _WSTRING dialog.setDirectory(QString::fromStdWString(client->get_path().wstring())); #else dialog.setDirectory(QString::fromStdString(client->get_path().string())); #endif if (dialog.exec()) { const auto qpaths = dialog.selectedFiles(); const auto& qpath = qpaths.at(0); #if _WSTRING const auto root = qpath.toStdWString(); #else const auto root = qpath.toStdString(); #endif m_tree->execute([&](const QModelIndex& index) { const auto entity = m_model->get_entity(index); if (entity) { if (entity->has<file_component>()) { // Folder boost::filesystem::path path(root); // File download(entity, path); } else if (entity->has<folder_component>()) { // Folder boost::filesystem::path path(root); const auto folder = entity->get<folder_component>(); path /= folder->get_data(); const auto browse_list = entity->get<browse_list_component>(); browse_list->set_path(path); download(entity, path); } } }); open_tabs(); } } void search_widget::open_tabs() const { // App const auto& app = main_window::get_app(); if (app.is_auto_open()) { // Callback m_entity->async_call(callback::download | callback::create); m_entity->async_call(callback::finished | callback::create); } } // Event void search_widget::closeEvent(QCloseEvent* event) { assert(thread_info::main()); if (isVisible()) { hide(); reset(); // Callback const auto owner = m_entity->get_owner(); owner->async_call(callback::search | callback::destroy, m_entity); } } bool search_widget::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::KeyPress) { const auto ke = static_cast<QKeyEvent*>(event); switch (ke->key()) { case Qt::Key_F5: { update(); break; } } } return entity_dock_widget::eventFilter(object, event); } // Menu void search_widget::show_menu(const QPoint& pos) { assert(thread_info::main()); QMenu menu; menu.setStyleSheet(QString("QMenu::item { height:%1px; width:%2px; }").arg(resource::get_row_height()).arg(resource::get_row_height() * 3)); const auto owner = m_entity->get_owner(); const auto service = owner->find<client_service_component>(); if (service->valid()) { if (!m_model->empty()) { const auto index = m_tree->indexAt(pos); if (index.isValid()) { menu.addAction(m_download_action); menu.addAction(m_download_to_action); menu.addSeparator(); } menu.addAction(m_clear_action); menu.addSeparator(); } menu.addAction(m_refresh_action); menu.addSeparator(); } menu.addAction(m_close_action); menu.exec(m_tree->viewport()->mapToGlobal(pos)); } }
FIGHB/MicroServer
guns-order/src/main/java/com/stylefeng/guns/order/common/persistence/dao/LRMtimeHallDictTMapper.java
<reponame>FIGHB/MicroServer<gh_stars>0 package com.stylefeng.guns.order.common.persistence.dao; import com.stylefeng.guns.order.common.persistence.model.LRMtimeHallDictT; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * 地域信息表 Mapper 接口 * </p> * * @author LiRui * @since 2019-10-16 */ public interface LRMtimeHallDictTMapper extends BaseMapper<LRMtimeHallDictT> { }
reels-research/iOS-Private-Frameworks
ProVideo.framework/PVComputeGrabCut.h
<reponame>reels-research/iOS-Private-Frameworks /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/ProVideo.framework/ProVideo */ @interface PVComputeGrabCut : NSObject { struct HFGrabCutInterface { int (**x1)(); struct HFGrabCut {} *x2; } * _module; } - (void)dealloc; - (id)init; - (bool)processImage:(id)arg1 trimap:(id)arg2 roi:(struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })arg3 clusters:(int)arg4 gamma:(float)arg5 iterations:(int)arg6 mask:(id)arg7; - (void)reset; @end
jamoum/JavaScript_Challenges_Solutions
very-easy/check-if-the-same-case/code.spec.js
<reponame>jamoum/JavaScript_Challenges_Solutions<gh_stars>10-100 const sameCase = require('./code'); describe('Tests', () => { test('the tests', () => { expect(sameCase('HELLO')).toEqual(true); expect(sameCase('HEllo')).toEqual(false); expect(sameCase('mArmALadE')).toEqual(false); expect(sameCase('marmalade')).toEqual(true); expect(sameCase('MARMALADE')).toEqual(true); expect(sameCase('ketchUP')).toEqual(false); expect(sameCase('pickle')).toEqual(true); expect(sameCase('MUSTARD')).toEqual(true); }); });
isabella232/aistreams
third_party/gst-plugins-bad/ext/teletextdec/gstteletextdec.c
<gh_stars>1-10 /* * GStreamer * Copyright (C) 2009 <NAME> <<EMAIL>> * Copyright (C) 2010 <NAME> <<EMAIL>> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ /** * SECTION:element-teletextdec * @title: teletextdec * * Decode a stream of raw VBI packets containing teletext information to a RGBA * stream. * * ## Example launch line * |[ * gst-launch-1.0 -v -m filesrc location=recording.mpeg ! tsdemux ! teletextdec ! videoconvert ! ximagesink * ]| * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include <gst/video/video.h> #include <string.h> #include <stdlib.h> #include "gstteletextdec.h" GST_DEBUG_CATEGORY_STATIC (gst_teletextdec_debug); #define GST_CAT_DEFAULT gst_teletextdec_debug #define parent_class gst_teletextdec_parent_class #define SUBTITLES_PAGE 888 #define MAX_SLICES 32 #define DEFAULT_FONT_DESCRIPTION "verdana 12" #define PANGO_TEMPLATE "<span font_desc=\"%s\" foreground=\"%s\"> %s \n</span>" /* Filter signals and args */ enum { LAST_SIGNAL }; enum { PROP_0, PROP_PAGENO, PROP_SUBNO, PROP_SUBTITLES_MODE, PROP_SUBS_TEMPLATE, PROP_FONT_DESCRIPTION }; enum { VBI_ERROR = -1, VBI_SUCCESS = 0, VBI_NEW_FRAME = 1 }; typedef enum { DATA_UNIT_EBU_TELETEXT_NON_SUBTITLE = 0x02, DATA_UNIT_EBU_TELETEXT_SUBTITLE = 0x03, DATA_UNIT_EBU_TELETEXT_INVERTED = 0x0C, DATA_UNIT_ZVBI_WSS_CPR1204 = 0xB4, DATA_UNIT_ZVBI_CLOSED_CAPTION_525 = 0xB5, DATA_UNIT_ZVBI_MONOCHROME_SAMPLES_525 = 0xB6, DATA_UNIT_VPS = 0xC3, DATA_UNIT_WSS = 0xC4, DATA_UNIT_CLOSED_CAPTION = 0xC5, DATA_UNIT_MONOCHROME_SAMPLES = 0xC6, DATA_UNIT_STUFFING = 0xFF, } data_unit_id; typedef struct { int pgno; int subno; } page_info; typedef enum { SYSTEM_525 = 0, SYSTEM_625 } systems; /* * ETS 300 706 Table 30: Colour Map */ static const gchar *default_color_map[40] = { "#000000", "#FF0000", "#00FF00", "#FFFF00", "#0000FF", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000", "#770000", "#007700", "#777700", "#000077", "#770077", "#007777", "#777777", "#FF0055", "#FF7700", "#00FF77", "#FFFFBB", "#00CCAA", "#550000", "#665522", "#CC7777", "#333333", "#FF7777", "#77FF77", "#FFFF77", "#7777FF", "#FF77FF", "#77FFFF", "#DDD0DD", /* Private colors */ "#000000", "#FFAA99", "#44EE00", "#FFDD00", "#FFAA99", "#FF00FF", "#00FFFF", "#EEEEEE" }; /* in RGBA mode, one character occupies 12 x 10 pixels. */ #define COLUMNS_TO_WIDTH(cols) ((cols) * 12) #define ROWS_TO_HEIGHT(rows) ((rows) * 10) static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("application/x-teletext;") ); static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGBA") ";" "text/x-raw, format={utf-8,pango-markup} ;") ); G_DEFINE_TYPE (GstTeletextDec, gst_teletextdec, GST_TYPE_ELEMENT); static void gst_teletextdec_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_teletextdec_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void gst_teletextdec_finalize (GObject * object); static GstStateChangeReturn gst_teletextdec_change_state (GstElement * element, GstStateChange transition); static GstFlowReturn gst_teletextdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer); static gboolean gst_teletextdec_sink_event (GstPad * pad, GstObject * parent, GstEvent * event); static gboolean gst_teletextdec_src_event (GstPad * pad, GstObject * parent, GstEvent * event); static void gst_teletextdec_event_handler (vbi_event * ev, void *user_data); static GstFlowReturn gst_teletextdec_push_page (GstTeletextDec * teletext); static GstFlowReturn gst_teletextdec_export_text_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf); static GstFlowReturn gst_teletextdec_export_rgba_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf); static GstFlowReturn gst_teletextdec_export_pango_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf); static void gst_teletextdec_process_telx_buffer (GstTeletextDec * teletext, GstBuffer * buf); static gboolean gst_teletextdec_extract_data_units (GstTeletextDec * teletext, GstTeletextFrame * f, const guint8 * packet, guint * offset, gsize size); static void gst_teletextdec_zvbi_init (GstTeletextDec * teletext); static void gst_teletextdec_zvbi_clear (GstTeletextDec * teletext); static void gst_teletextdec_reset_frame (GstTeletextDec * teletext); /* initialize the gstteletext's class */ static void gst_teletextdec_class_init (GstTeletextDecClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = gst_teletextdec_set_property; gobject_class->get_property = gst_teletextdec_get_property; gobject_class->finalize = gst_teletextdec_finalize; gstelement_class = GST_ELEMENT_CLASS (klass); gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_teletextdec_change_state); g_object_class_install_property (gobject_class, PROP_PAGENO, g_param_spec_int ("page", "Page number", "Number of page that should displayed", 100, 999, 100, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_SUBNO, g_param_spec_int ("subpage", "Sub-page number", "Number of sub-page that should displayed (-1 for all)", -1, 0x99, -1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_SUBTITLES_MODE, g_param_spec_boolean ("subtitles-mode", "Enable subtitles mode", "Enables subtitles mode for text output stripping the blank lines and " "the teletext state lines", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_SUBS_TEMPLATE, g_param_spec_string ("subtitles-template", "Subtitles output template", "Output template used to print each one of the subtitles lines", g_strescape ("%s\n", NULL), G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_FONT_DESCRIPTION, g_param_spec_string ("font-description", "Pango font description", "Font description used for the pango output.", DEFAULT_FONT_DESCRIPTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); gst_element_class_set_static_metadata (gstelement_class, "Teletext decoder", "Decoder", "Decode a raw VBI stream containing teletext information to RGBA and text", "<NAME> <<EMAIL>>, " "<NAME> <<EMAIL>>"); gst_element_class_add_static_pad_template (gstelement_class, &src_template); gst_element_class_add_static_pad_template (gstelement_class, &sink_template); } /* initialize the new element * initialize instance structure */ static void gst_teletextdec_init (GstTeletextDec * teletext) { /* Create sink pad */ teletext->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink"); gst_pad_set_chain_function (teletext->sinkpad, GST_DEBUG_FUNCPTR (gst_teletextdec_chain)); gst_pad_set_event_function (teletext->sinkpad, GST_DEBUG_FUNCPTR (gst_teletextdec_sink_event)); gst_element_add_pad (GST_ELEMENT (teletext), teletext->sinkpad); /* Create src pad */ teletext->srcpad = gst_pad_new_from_static_template (&src_template, "src"); gst_pad_set_event_function (teletext->srcpad, GST_DEBUG_FUNCPTR (gst_teletextdec_src_event)); gst_element_add_pad (GST_ELEMENT (teletext), teletext->srcpad); teletext->segment = NULL; teletext->decoder = NULL; teletext->pageno = 0x100; teletext->subno = -1; teletext->subtitles_mode = FALSE; teletext->subtitles_template = g_strescape ("%s\n", NULL); teletext->font_description = g_strdup (DEFAULT_FONT_DESCRIPTION); teletext->in_timestamp = GST_CLOCK_TIME_NONE; teletext->in_duration = GST_CLOCK_TIME_NONE; teletext->rate_numerator = 0; teletext->rate_denominator = 1; teletext->queue = NULL; g_mutex_init (&teletext->queue_lock); gst_teletextdec_reset_frame (teletext); teletext->last_ts = 0; teletext->export_func = NULL; teletext->buf_pool = NULL; } static void gst_teletextdec_finalize (GObject * object) { GstTeletextDec *teletext = GST_TELETEXTDEC (object); g_mutex_clear (&teletext->queue_lock); g_free (teletext->font_description); g_free (teletext->subtitles_template); g_free (teletext->frame); G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_teletextdec_zvbi_init (GstTeletextDec * teletext) { g_return_if_fail (teletext != NULL); GST_LOG_OBJECT (teletext, "Initializing structures"); teletext->decoder = vbi_decoder_new (); vbi_event_handler_register (teletext->decoder, VBI_EVENT_TTX_PAGE | VBI_EVENT_CAPTION, gst_teletextdec_event_handler, teletext); g_mutex_lock (&teletext->queue_lock); teletext->queue = g_queue_new (); g_mutex_unlock (&teletext->queue_lock); } static void gst_teletextdec_zvbi_clear (GstTeletextDec * teletext) { g_return_if_fail (teletext != NULL); GST_LOG_OBJECT (teletext, "Clearing structures"); if (teletext->decoder != NULL) { vbi_decoder_delete (teletext->decoder); teletext->decoder = NULL; } if (teletext->frame != NULL) { if (teletext->frame->sliced_begin) g_free (teletext->frame->sliced_begin); g_free (teletext->frame); teletext->frame = NULL; } g_mutex_lock (&teletext->queue_lock); if (teletext->queue != NULL) { g_queue_free (teletext->queue); teletext->queue = NULL; } g_mutex_unlock (&teletext->queue_lock); teletext->in_timestamp = GST_CLOCK_TIME_NONE; teletext->in_duration = GST_CLOCK_TIME_NONE; teletext->pageno = 0x100; teletext->subno = -1; teletext->last_ts = 0; } static void gst_teletextdec_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstTeletextDec *teletext = GST_TELETEXTDEC (object); switch (prop_id) { case PROP_PAGENO: teletext->pageno = (gint) vbi_bin2bcd (g_value_get_int (value)); break; case PROP_SUBNO: teletext->subno = g_value_get_int (value); break; case PROP_SUBTITLES_MODE: teletext->subtitles_mode = g_value_get_boolean (value); break; case PROP_SUBS_TEMPLATE: g_free (teletext->subtitles_template); teletext->subtitles_template = g_value_dup_string (value); break; case PROP_FONT_DESCRIPTION: g_free (teletext->font_description); teletext->font_description = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_teletextdec_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstTeletextDec *teletext = GST_TELETEXTDEC (object); switch (prop_id) { case PROP_PAGENO: g_value_set_int (value, (gint) vbi_bcd2dec (teletext->pageno)); break; case PROP_SUBNO: g_value_set_int (value, teletext->subno); break; case PROP_SUBTITLES_MODE: g_value_set_boolean (value, teletext->subtitles_mode); break; case PROP_SUBS_TEMPLATE: g_value_set_string (value, teletext->subtitles_template); break; case PROP_FONT_DESCRIPTION: g_value_set_string (value, teletext->font_description); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static gboolean gst_teletextdec_sink_event (GstPad * pad, GstObject * parent, GstEvent * event) { gboolean ret; GstTeletextDec *teletext = GST_TELETEXTDEC (parent); GST_DEBUG_OBJECT (teletext, "got event %s", gst_event_type_get_name (GST_EVENT_TYPE (event))); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_SEGMENT: /* maybe save and/or update the current segment (e.g. for output * clipping) or convert the event into one in a different format * (e.g. BYTES to TIME) or drop it and set a flag to send a newsegment * event in a different format later */ if (NULL == teletext->export_func) { /* save the segment event and send it after sending caps. replace the * old event if present. */ if (teletext->segment) { gst_event_unref (teletext->segment); } teletext->segment = event; ret = TRUE; } else { ret = gst_pad_push_event (teletext->srcpad, event); } break; case GST_EVENT_EOS: /* end-of-stream, we should close down all stream leftovers here */ gst_teletextdec_zvbi_clear (teletext); ret = gst_pad_push_event (teletext->srcpad, event); break; case GST_EVENT_FLUSH_STOP: gst_teletextdec_zvbi_clear (teletext); gst_teletextdec_zvbi_init (teletext); ret = gst_pad_push_event (teletext->srcpad, event); break; default: ret = gst_pad_event_default (pad, parent, event); break; } return ret; } static gboolean gst_teletextdec_src_event (GstPad * pad, GstObject * parent, GstEvent * event) { gboolean ret; GstTeletextDec *teletext = GST_TELETEXTDEC (parent); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_RECONFIGURE: /* setting export_func to NULL will cause the element to renegotiate caps * before pushing a buffer. */ teletext->export_func = NULL; ret = TRUE; break; default: ret = gst_pad_event_default (pad, parent, event); break; } return ret; } static GstStateChangeReturn gst_teletextdec_change_state (GstElement * element, GstStateChange transition) { GstStateChangeReturn ret; GstTeletextDec *teletext; teletext = GST_TELETEXTDEC (element); switch (transition) { case GST_STATE_CHANGE_READY_TO_PAUSED: gst_teletextdec_zvbi_init (teletext); break; default: break; } ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); if (ret != GST_STATE_CHANGE_SUCCESS) return ret; switch (transition) { case GST_STATE_CHANGE_PAUSED_TO_READY: gst_teletextdec_zvbi_clear (teletext); break; default: break; } return ret; } static void gst_teletextdec_reset_frame (GstTeletextDec * teletext) { if (teletext->frame == NULL) teletext->frame = g_new0 (GstTeletextFrame, 1); if (teletext->frame->sliced_begin == NULL) teletext->frame->sliced_begin = g_new (vbi_sliced, MAX_SLICES); teletext->frame->current_slice = teletext->frame->sliced_begin; teletext->frame->sliced_end = teletext->frame->sliced_begin + MAX_SLICES; teletext->frame->last_field = 0; teletext->frame->last_field_line = 0; teletext->frame->last_frame_line = 0; } static void gst_teletextdec_process_telx_buffer (GstTeletextDec * teletext, GstBuffer * buf) { GstMapInfo buf_map; guint offset = 0; gint res; gst_buffer_map (buf, &buf_map, GST_MAP_READ); teletext->in_timestamp = GST_BUFFER_TIMESTAMP (buf); teletext->in_duration = GST_BUFFER_DURATION (buf); if (teletext->frame == NULL) gst_teletextdec_reset_frame (teletext); while (offset < buf_map.size) { res = gst_teletextdec_extract_data_units (teletext, teletext->frame, buf_map.data, &offset, buf_map.size); if (res == VBI_NEW_FRAME) { /* We have a new frame, it's time to feed the decoder */ vbi_sliced *s; gint n_lines; n_lines = teletext->frame->current_slice - teletext->frame->sliced_begin; GST_LOG_OBJECT (teletext, "Completed frame, decoding new %d lines", n_lines); s = g_memdup (teletext->frame->sliced_begin, n_lines * sizeof (vbi_sliced)); vbi_decode (teletext->decoder, s, n_lines, teletext->last_ts); /* From vbi_decode(): * timestamp shall advance by 1/30 to 1/25 seconds whenever calling this * function. Failure to do so will be interpreted as frame dropping, which * starts a resynchronization cycle, eventually a channel switch may be assumed * which resets even more decoder state. So even if a frame did not contain * any useful data this function must be called, with lines set to zero. */ teletext->last_ts += 0.04; g_free (s); gst_teletextdec_reset_frame (teletext); } else if (res == VBI_ERROR) { gst_teletextdec_reset_frame (teletext); goto beach; } } beach: gst_buffer_unmap (buf, &buf_map); return; } static void gst_teletextdec_event_handler (vbi_event * ev, void *user_data) { page_info *pi; vbi_pgno pgno; vbi_subno subno; GstTeletextDec *teletext = GST_TELETEXTDEC (user_data); switch (ev->type) { case VBI_EVENT_TTX_PAGE: pgno = ev->ev.ttx_page.pgno; subno = ev->ev.ttx_page.subno; if (pgno != teletext->pageno || (teletext->subno != -1 && subno != teletext->subno)) return; GST_DEBUG_OBJECT (teletext, "Received teletext page %03d.%02d", (gint) vbi_bcd2dec (pgno), (gint) vbi_bcd2dec (subno)); pi = g_new (page_info, 1); pi->pgno = pgno; pi->subno = subno; g_mutex_lock (&teletext->queue_lock); g_queue_push_tail (teletext->queue, pi); g_mutex_unlock (&teletext->queue_lock); break; case VBI_EVENT_CAPTION: /* TODO: Handle subtitles in caption teletext pages */ GST_DEBUG_OBJECT (teletext, "Received caption page. Not implemented"); break; default: break; } return; } static void gst_teletextdec_try_get_buffer_pool (GstTeletextDec * teletext, GstCaps * caps, gssize size) { guint pool_bufsize, min_bufs, max_bufs; GstStructure *poolcfg; GstBufferPool *new_pool; GstQuery *alloc = gst_query_new_allocation (caps, TRUE); if (teletext->buf_pool) { /* this function is called only on a caps/size change, so it's practically * impossible that we'll be able to reuse the old pool. */ gst_buffer_pool_set_active (teletext->buf_pool, FALSE); gst_object_unref (teletext->buf_pool); } if (!gst_pad_peer_query (teletext->srcpad, alloc)) { GST_DEBUG_OBJECT (teletext, "Failed to query peer pad for allocation " "parameters"); teletext->buf_pool = NULL; goto beach; } if (gst_query_get_n_allocation_pools (alloc) > 0) { gst_query_parse_nth_allocation_pool (alloc, 0, &new_pool, &pool_bufsize, &min_bufs, &max_bufs); } else { new_pool = gst_buffer_pool_new (); max_bufs = 0; min_bufs = 1; } poolcfg = gst_buffer_pool_get_config (new_pool); gst_buffer_pool_config_set_params (poolcfg, gst_caps_copy (caps), size, min_bufs, max_bufs); if (!gst_buffer_pool_set_config (new_pool, poolcfg)) { GST_DEBUG_OBJECT (teletext, "Failed to configure the buffer pool"); gst_object_unref (new_pool); teletext->buf_pool = NULL; goto beach; } if (!gst_buffer_pool_set_active (new_pool, TRUE)) { GST_DEBUG_OBJECT (teletext, "Failed to make the buffer pool active"); gst_object_unref (new_pool); teletext->buf_pool = NULL; goto beach; } teletext->buf_pool = new_pool; beach: gst_query_unref (alloc); } static gboolean gst_teletextdec_negotiate_caps (GstTeletextDec * teletext, guint width, guint height) { gboolean rv = FALSE; /* get the peer's caps filtered by our own ones. */ GstCaps *ourcaps = gst_pad_query_caps (teletext->srcpad, NULL); GstCaps *peercaps = gst_pad_peer_query_caps (teletext->srcpad, ourcaps); GstStructure *caps_struct; const gchar *caps_name, *caps_fmt; gst_caps_unref (ourcaps); if (gst_caps_is_empty (peercaps)) { goto beach; } /* make them writable in case we need to fixate them (video/x-raw). */ peercaps = gst_caps_make_writable (peercaps); caps_struct = gst_caps_get_structure (peercaps, 0); caps_name = gst_structure_get_name (caps_struct); caps_fmt = gst_structure_get_string (caps_struct, "format"); if (!g_strcmp0 (caps_name, "video/x-raw")) { teletext->width = width; teletext->height = height; teletext->export_func = gst_teletextdec_export_rgba_page; gst_structure_set (caps_struct, "width", G_TYPE_INT, width, "height", G_TYPE_INT, height, "framerate", GST_TYPE_FRACTION, 0, 1, NULL); } else if (!g_strcmp0 (caps_name, "text/x-raw") && !g_strcmp0 (caps_fmt, "utf-8")) { teletext->export_func = gst_teletextdec_export_text_page; } else if (!g_strcmp0 (caps_name, "text/x-raw") && !g_strcmp0 (caps_fmt, "pango-markup")) { teletext->export_func = gst_teletextdec_export_pango_page; } else { goto beach; } if (!gst_pad_push_event (teletext->srcpad, gst_event_new_caps (peercaps))) { goto beach; } /* try to get a bufferpool from the peer pad in case of RGBA output. */ if (gst_teletextdec_export_rgba_page == teletext->export_func) { gst_teletextdec_try_get_buffer_pool (teletext, peercaps, width * height * sizeof (vbi_rgba)); } /* we can happily return a success now. */ rv = TRUE; beach: gst_caps_unref (peercaps); return rv; } /* this function does the actual processing */ static GstFlowReturn gst_teletextdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstTeletextDec *teletext = GST_TELETEXTDEC (parent); GstFlowReturn ret = GST_FLOW_OK; teletext->in_timestamp = GST_BUFFER_TIMESTAMP (buf); teletext->in_duration = GST_BUFFER_DURATION (buf); gst_teletextdec_process_telx_buffer (teletext, buf); gst_buffer_unref (buf); g_mutex_lock (&teletext->queue_lock); if (!g_queue_is_empty (teletext->queue)) { ret = gst_teletextdec_push_page (teletext); if (ret != GST_FLOW_OK) { g_mutex_unlock (&teletext->queue_lock); goto error; } } g_mutex_unlock (&teletext->queue_lock); return ret; /* ERRORS */ error: { if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED && ret != GST_FLOW_FLUSHING) { GST_ELEMENT_FLOW_ERROR (teletext, ret); return GST_FLOW_ERROR; } return ret; } } static GstFlowReturn gst_teletextdec_push_page (GstTeletextDec * teletext) { GstFlowReturn ret = GST_FLOW_OK; GstBuffer *buf; vbi_page page; page_info *pi; gint pgno, subno; gboolean success; guint width, height; pi = g_queue_pop_head (teletext->queue); pgno = vbi_bcd2dec (pi->pgno); subno = vbi_bcd2dec (pi->subno); GST_INFO_OBJECT (teletext, "Fetching teletext page %03d.%02d", pgno, subno); success = vbi_fetch_vt_page (teletext->decoder, &page, pi->pgno, pi->subno, VBI_WST_LEVEL_3p5, 25, FALSE); g_free (pi); if (G_UNLIKELY (!success)) goto fetch_page_failed; width = COLUMNS_TO_WIDTH (page.columns); height = ROWS_TO_HEIGHT (page.rows); /* if output_func is NULL, we need to (re-)negotiate. also, it is possible * (though unlikely) that we received a page of a different size. */ if (G_UNLIKELY (NULL == teletext->export_func || teletext->width != width || teletext->height != height)) { /* if negotiate_caps returns FALSE, that means we weren't able to * negotiate. */ if (G_UNLIKELY (!gst_teletextdec_negotiate_caps (teletext, width, height))) { ret = GST_FLOW_NOT_NEGOTIATED; goto push_failed; } if (G_UNLIKELY (teletext->segment)) { gst_pad_push_event (teletext->srcpad, teletext->segment); teletext->segment = NULL; } } teletext->export_func (teletext, &page, &buf); vbi_unref_page (&page); GST_BUFFER_TIMESTAMP (buf) = teletext->in_timestamp; GST_BUFFER_DURATION (buf) = teletext->in_duration; GST_INFO_OBJECT (teletext, "Pushing buffer of size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf)); ret = gst_pad_push (teletext->srcpad, buf); if (ret != GST_FLOW_OK) goto push_failed; return GST_FLOW_OK; fetch_page_failed: { GST_ELEMENT_ERROR (teletext, RESOURCE, READ, (NULL), (NULL)); return GST_FLOW_ERROR; } push_failed: { GST_ERROR_OBJECT (teletext, "Pushing buffer failed, reason %s", gst_flow_get_name (ret)); return ret; } } static gchar ** gst_teletextdec_vbi_page_to_text_lines (guint start, guint stop, vbi_page * page) { const guint lines_count = stop - start + 1; const guint line_length = page->columns; gchar **lines; guint i; /* allocate a new NULL-terminated array of strings */ lines = (gchar **) g_malloc (sizeof (gchar *) * (lines_count + 1)); lines[lines_count] = NULL; /* export each line in the range of the teletext page in text format */ for (i = start; i <= stop; i++) { lines[i - start] = (gchar *) g_malloc (sizeof (gchar) * (line_length + 1)); vbi_print_page_region (page, lines[i - start], line_length + 1, "UTF-8", TRUE, 0, 0, i, line_length, 1); /* Add the null character */ lines[i - start][line_length] = '\0'; } return lines; } static GstFlowReturn gst_teletextdec_export_text_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf) { gchar *text; guint size; if (teletext->subtitles_mode) { gchar **lines; GString *subs; guint i; lines = gst_teletextdec_vbi_page_to_text_lines (1, 23, page); subs = g_string_new (""); /* Strip white spaces and squash blank lines */ for (i = 0; i < 23; i++) { g_strstrip (lines[i]); if (g_strcmp0 (lines[i], "")) g_string_append_printf (subs, teletext->subtitles_template, lines[i]); } /* if the page is blank and doesn't contain any line of text, just add a * line break */ if (!g_strcmp0 (subs->str, "")) g_string_append (subs, "\n"); text = subs->str; size = subs->len + 1; g_string_free (subs, FALSE); g_strfreev (lines); } else { size = page->columns * page->rows; text = g_malloc (size); vbi_print_page (page, text, size, "UTF-8", FALSE, TRUE); } /* Allocate new buffer */ *buf = gst_buffer_new_wrapped (text, size); return GST_FLOW_OK; } static GstFlowReturn gst_teletextdec_export_rgba_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf) { guint size; GstBuffer *lbuf; GstMapInfo buf_map; size = teletext->width * teletext->height * sizeof (vbi_rgba); /* Allocate new buffer, using the negotiated pool if available. */ if (teletext->buf_pool) { GstFlowReturn acquire_rv = gst_buffer_pool_acquire_buffer (teletext->buf_pool, &lbuf, NULL); if (acquire_rv != GST_FLOW_OK) { return acquire_rv; } } else { lbuf = gst_buffer_new_allocate (NULL, size, NULL); if (NULL == lbuf) return GST_FLOW_ERROR; } if (!gst_buffer_map (lbuf, &buf_map, GST_MAP_WRITE)) { gst_buffer_unref (lbuf); return GST_FLOW_ERROR; } vbi_draw_vt_page (page, VBI_PIXFMT_RGBA32_LE, buf_map.data, FALSE, TRUE); gst_buffer_unmap (lbuf, &buf_map); *buf = lbuf; return GST_FLOW_OK; } static GstFlowReturn gst_teletextdec_export_pango_page (GstTeletextDec * teletext, vbi_page * page, GstBuffer ** buf) { vbi_char *acp; const guint rows = page->rows; gchar **colors; gchar **lines; GString *subs; guint start, stop, k; gint i, j; colors = (gchar **) g_malloc (sizeof (gchar *) * (rows + 1)); colors[rows] = NULL; /* parse all the lines and approximate it's foreground color using the first * non null character */ for (acp = page->text, i = 0; i < page->rows; acp += page->columns, i++) { for (j = 0; j < page->columns; j++) { colors[i] = g_strdup (default_color_map[7]); if (acp[j].unicode != 0x20) { colors[i] = g_strdup (default_color_map[acp[j].foreground]); break; } } } /* get an array of strings with each line of the telext page */ start = teletext->subtitles_mode ? 1 : 0; stop = teletext->subtitles_mode ? rows - 2 : rows - 1; lines = gst_teletextdec_vbi_page_to_text_lines (start, stop, page); /* format each line in pango markup */ subs = g_string_new (""); for (k = start; k <= stop; k++) { g_string_append_printf (subs, PANGO_TEMPLATE, teletext->font_description, colors[k], lines[k - start]); } /* Allocate new buffer */ *buf = gst_buffer_new_wrapped (subs->str, subs->len + 1); g_strfreev (lines); g_strfreev (colors); g_string_free (subs, FALSE); return GST_FLOW_OK; } /* Converts the line_offset / field_parity byte of a VBI data unit. */ static void gst_teletextdec_lofp_to_line (guint * field, guint * field_line, guint * frame_line, guint lofp, systems system) { guint line_offset; /* field_parity */ *field = !(lofp & (1 << 5)); line_offset = lofp & 31; if (line_offset > 0) { static const guint field_start[2][2] = { {0, 263}, {0, 313}, }; *field_line = line_offset; *frame_line = field_start[system][*field] + line_offset; } else { *field_line = 0; *frame_line = 0; } } static int gst_teletextdec_line_address (GstTeletextDec * teletext, GstTeletextFrame * frame, vbi_sliced ** spp, guint lofp, systems system) { guint field; guint field_line; guint frame_line; if (G_UNLIKELY (frame->current_slice >= frame->sliced_end)) { GST_LOG_OBJECT (teletext, "Out of sliced VBI buffer space (%d lines).", (int) (frame->sliced_end - frame->sliced_begin)); return VBI_ERROR; } gst_teletextdec_lofp_to_line (&field, &field_line, &frame_line, lofp, system); GST_LOG_OBJECT (teletext, "Line %u/%u=%u.", field, field_line, frame_line); if (frame_line != 0) { GST_LOG_OBJECT (teletext, "Last frame Line %u.", frame->last_frame_line); if (frame_line <= frame->last_frame_line) { GST_LOG_OBJECT (teletext, "New frame"); return VBI_NEW_FRAME; } /* FIXME : This never happens, since lofp is a guint8 */ #if 0 /* new segment flag */ if (lofp < 0) { GST_LOG_OBJECT (teletext, "New frame"); return VBI_NEW_FRAME; } #endif frame->last_field = field; frame->last_field_line = field_line; frame->last_frame_line = frame_line; *spp = frame->current_slice++; (*spp)->line = frame_line; } else { /* Undefined line. */ return VBI_ERROR; } return VBI_SUCCESS; } static gboolean gst_teletextdec_extract_data_units (GstTeletextDec * teletext, GstTeletextFrame * f, const guint8 * packet, guint * offset, gsize size) { const guint8 *data_unit; guint i; while (*offset < size) { vbi_sliced *s = NULL; gint data_unit_id, data_unit_length; data_unit = packet + *offset; data_unit_id = data_unit[0]; data_unit_length = data_unit[1]; GST_LOG_OBJECT (teletext, "vbi header %02x %02x %02x\n", data_unit[0], data_unit[1], data_unit[2]); switch (data_unit_id) { case DATA_UNIT_STUFFING: { *offset += 2 + data_unit_length; break; } case DATA_UNIT_EBU_TELETEXT_NON_SUBTITLE: case DATA_UNIT_EBU_TELETEXT_SUBTITLE: { gint res; if (G_UNLIKELY (data_unit_length != 1 + 1 + 42)) { /* Skip this data unit */ GST_WARNING_OBJECT (teletext, "The data unit length is not 44 bytes"); *offset += 2 + data_unit_length; break; } res = gst_teletextdec_line_address (teletext, f, &s, data_unit[2], SYSTEM_625); if (G_UNLIKELY (res == VBI_ERROR)) { /* Can't retrieve line address, skip this data unit */ GST_WARNING_OBJECT (teletext, "Could not retrieve line address for this data unit"); return VBI_ERROR; } if (G_UNLIKELY (f->last_field_line > 0 && (f->last_field_line - 7 >= 23 - 7))) { GST_WARNING_OBJECT (teletext, "Bad line: %d", f->last_field_line - 7); return VBI_ERROR; } if (res == VBI_NEW_FRAME) { /* New frame */ return VBI_NEW_FRAME; } s->id = VBI_SLICED_TELETEXT_B; for (i = 0; i < 42; i++) s->data[i] = vbi_rev8 (data_unit[4 + i]); *offset += 46; break; } case DATA_UNIT_ZVBI_WSS_CPR1204: case DATA_UNIT_ZVBI_CLOSED_CAPTION_525: case DATA_UNIT_ZVBI_MONOCHROME_SAMPLES_525: case DATA_UNIT_VPS: case DATA_UNIT_WSS: case DATA_UNIT_CLOSED_CAPTION: case DATA_UNIT_MONOCHROME_SAMPLES: { /*Not supported yet */ *offset += 2 + data_unit_length; break; } default: { /* corrupted stream, increase the offset by one until we sync */ GST_LOG_OBJECT (teletext, "Corrupted, increasing offset by one"); *offset += 1; break; } } } return VBI_SUCCESS; } static gboolean teletext_init (GstPlugin * teletext) { GST_DEBUG_CATEGORY_INIT (gst_teletextdec_debug, "teletext", 0, "Teletext decoder"); return gst_element_register (teletext, "teletextdec", GST_RANK_NONE, GST_TYPE_TELETEXTDEC); } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, teletext, "Teletext plugin", teletext_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
packadic/theme
src/scripts/theme/editor.js
<reponame>packadic/theme require([ 'jquery', '../fn/defined', '../fn/default', '../fn/cre' ], function($, defined, def, cre){ "use strict"; });
turing4ever/restful-services-in-pyramid
src/first_service/svc1_clients/python/svc_client.py
<filename>src/first_service/svc1_clients/python/svc_client.py import requests from pprint import pprint def main(): cars = list_cars() show_cars(cars) car_id = input("What car do you want to see? (car ID): ") show_car_details(car_id) def show_cars(cars): print("Cars for sale: ") for c in cars: print('{}: {}'.format(c[0], c[1])) def show_car_details(car_id): car = get_car(car_id) pprint(car) def list_cars(): url = 'http://localhost:6543/api/autos' resp = requests.get(url) if resp.status_code != 200: print("Error contacting server... {}".format(resp.status_code)) return cars = resp.json() return [ (car.get('id'), car.get('name')) for car in cars ] def get_car(car_id): url = 'http://localhost:6543/api/autos/{}'.format(car_id) resp = requests.get(url) if resp.status_code != 200: print("Error contacting server... {}".format(resp.status_code)) return car = resp.json() return car if __name__ == '__main__': main()
SirWumpus/libsnert
include/io/Log.h
/* * Log.h * * Copyright 2002, 2006 by <NAME>. All rights reserved. */ #ifndef __com_snert_lib_io_Log_h__ #define __com_snert_lib_io_Log_h__ 1 #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdarg.h> extern FILE *logFile; /* * Traditional syslog.h log levels */ #ifndef LOG_EMERG # define LOG_EMERG 0 /* system is unusable */ # define LOG_ALERT 1 /* action must be taken immediately */ # define LOG_CRIT 2 /* critical conditions */ # define LOG_ERR 3 /* error conditions */ # define LOG_WARNING 4 /* warning conditions */ # define LOG_NOTICE 5 /* normal but significant condition */ # define LOG_INFO 6 /* informational */ # define LOG_DEBUG 7 /* debug-level messages */ #endif /* * Snert's applications only use 5 levels with these names: * * LOG_FATAL, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG */ #define LOG_PANIC LOG_EMERG #define LOG_FATAL LOG_CRIT #define LOG_ERROR LOG_ERR #define LOG_WARN LOG_WARNING extern int LogOpen(const char *fname); extern void LogOpenLog(const char *ident, int option, int facility); extern void LogClose(void); extern /*@observer@*/ const char *LogGetProgramName(void); extern void LogSetProgramName(const char *); extern void LogSetMask(unsigned mask); #define LogSetLevel(x) LogSetMask(x) /* * Write to log file. * * @return * Zero if the message was logged, otherwise -1 the message was not * logged, because the priority was not high enough, a NULL fmt string, * or the log file is not opened. */ extern int LogDebug(const char *fmt, ...); extern int LogInfo(const char *fmt, ...); extern int LogWarn(const char *fmt, ...); extern int LogError(const char *fmt, ...); extern int LogErrorV(const char *fmt, va_list args); extern int Log(int level, const char *fmt, ...); extern int LogV(int level, const char *fmt, va_list args); extern int LogPrintV(int level, const char *fmt, va_list args); /* * Write to log file and standard error. */ extern int LogStderr(int level, const char *fmt, ...); extern int LogStderrV(int level, const char *fmt, va_list args); /* * Write to log file and standard error, then exit. */ extern void LogFatal(const char *fmt, ...); #ifndef LOG_PID /*** *** Based on OpenBSD syslog.h and is same for Linux. ***/ /* * priorities/facilities are encoded into a single 32-bit quantity, where the * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility * (0-big number). Both the priorities and the facilities map roughly * one-to-one to strings in the syslogd(8) source code. This mapping is * included in this file. * * priorities (these are ordered) */ # define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */ # define LOG_PRI(p) ((p) & LOG_PRIMASK) # define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri)) /* * arguments to setlogmask. */ # define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */ # define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */ /* * Option flags for openlog. * * LOG_ODELAY no longer does anything. * LOG_NDELAY is the inverse of what it used to be. */ # define LOG_PID 0x01 /* log the pid with each message */ # define LOG_CONS 0x02 /* log on the console if errors in sending */ # define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */ # define LOG_NDELAY 0x08 /* don't delay open */ # define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */ # ifndef LOG_PERROR # define LOG_PERROR 0x20 /* log to stderr as well */ # endif /* facility codes */ # define LOG_KERN (0<<3) /* kernel messages */ # define LOG_USER (1<<3) /* random user-level messages */ # define LOG_MAIL (2<<3) /* mail system */ # define LOG_DAEMON (3<<3) /* system daemons */ # define LOG_AUTH (4<<3) /* authorization messages */ # define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ # define LOG_LPR (6<<3) /* line printer subsystem */ # define LOG_NEWS (7<<3) /* network news subsystem */ # define LOG_UUCP (8<<3) /* UUCP subsystem */ # define LOG_CRON (9<<3) /* clock daemon */ # define LOG_AUTHPRIV (10<<3) /* authorization messages (private) */ /* Facility #10 clashes in DEC UNIX, where */ /* it's defined as LOG_MEGASAFE for AdvFS */ /* event logging. */ # define LOG_FTP (11<<3) /* ftp daemon */ # define LOG_NTP (12<<3) /* NTP subsystem */ # define LOG_SECURITY (13<<3) /* security subsystems (firewalling, etc.) */ # define LOG_CONSOLE (14<<3) /* /dev/console output */ /* other codes through 15 reserved for system use */ # define LOG_LOCAL0 (16<<3) /* reserved for local use */ # define LOG_LOCAL1 (17<<3) /* reserved for local use */ # define LOG_LOCAL2 (18<<3) /* reserved for local use */ # define LOG_LOCAL3 (19<<3) /* reserved for local use */ # define LOG_LOCAL4 (20<<3) /* reserved for local use */ # define LOG_LOCAL5 (21<<3) /* reserved for local use */ # define LOG_LOCAL6 (22<<3) /* reserved for local use */ # define LOG_LOCAL7 (23<<3) /* reserved for local use */ # define LOG_NFACILITIES 24 /* current number of facilities */ # define LOG_FACMASK 0x03f8 /* mask to extract facility part */ /* facility of pri */ # define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3) #endif #if !defined(LOG_PRI) # define LOG_PRI(p) ((p) & LOG_PRIMASK) #endif #if !defined(LOG_FAC) # define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3) #endif /* * This is for syslog.h compatibility. */ #if defined(WITHOUT_SYSLOG) || defined(__WIN32__) || defined(__MINGW32__) #ifdef __FOR_REFERENCE_ONLY__ extern void syslog(int level, const char *fmt, ...); extern void vsyslog(int level, const char *fmt, void *args); extern void closelog(void); extern void openlog(const char *ident, int option, int facility); #endif #define syslog Log #define vsyslog LogV #define closelog LogClose #define openlog LogOpenLog #define setlogmask(x) LogSetMask(x) #endif #ifdef __cplusplus } #endif #endif /* __com_snert_lib_io_Log_h__ */
bygui86/spring-reactive
spring-reactive-web-socket-client/src/main/java/com/rabbit/samples/springreactivewebsocketclient/configs/WebSocketConfig.java
<filename>spring-reactive-web-socket-client/src/main/java/com/rabbit/samples/springreactivewebsocketclient/configs/WebSocketConfig.java package com.rabbit.samples.springreactivewebsocketclient.configs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; import org.springframework.web.reactive.socket.client.WebSocketClient; /** * @author <NAME> * <EMAIL> * 19 Feb 2019 */ @Configuration public class WebSocketConfig { @Bean public WebSocketClient webSocketClient() { return new ReactorNettyWebSocketClient(); } }
ggardet/mr-provisioner
migrations/versions/37af89374583_remove_mac_column_from_machine.py
"""remove MAC column from machine Revision ID: <KEY> Revises: 3e5a16bb9124 Create Date: 2017-06-18 07:25:18.202302 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '3e5a16bb9124' branch_labels = None depends_on = None def upgrade(): op.drop_constraint('machine_mac_key', 'machine', type_='unique') op.drop_column('machine', 'mac') def downgrade(): op.add_column('machine', sa.Column('mac', sa.VARCHAR(), autoincrement=False, nullable=True)) op.create_unique_constraint('machine_mac_key', 'machine', ['mac'])
Keneral/ae1
icu/android_icu4j/src/main/tests/android/icu/dev/test/stringprep/TestAll.java
<reponame>Keneral/ae1<filename>icu/android_icu4j/src/main/tests/android/icu/dev/test/stringprep/TestAll.java /* GENERATED SOURCE. DO NOT MODIFY. */ /* ******************************************************************************* * Copyright (C) 2003-2010, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package android.icu.dev.test.stringprep; import android.icu.dev.test.TestFmwk.TestGroup; import org.junit.runner.RunWith; import android.icu.junit.IcuTestGroupRunner; /** * @author ram * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ @RunWith(IcuTestGroupRunner.class) public class TestAll extends TestGroup { public static void main(String[] args) throws Exception { new TestAll().run(args); } public TestAll() { super( new String[] { "TestIDNA", "TestStringPrep", "TestIDNARef", "IDNAConformanceTest", "TestStringPrepProfiles", }, "StringPrep and IDNA test" ); } public static final String CLASS_TARGET_NAME = "StringPrep"; }
bihe/monorepo
internal/mydms/transports_test.go
package mydms_test import ( "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/stretchr/testify/assert" "golang.binggl.net/monorepo/internal/mydms" "golang.binggl.net/monorepo/internal/mydms/app/appinfo" "golang.binggl.net/monorepo/internal/mydms/app/document" "golang.binggl.net/monorepo/internal/mydms/app/filestore" "golang.binggl.net/monorepo/internal/mydms/app/upload" "golang.binggl.net/monorepo/pkg/config" "golang.binggl.net/monorepo/pkg/logging" "golang.binggl.net/monorepo/pkg/persistence" "golang.binggl.net/monorepo/pkg/security" pkgerr "golang.binggl.net/monorepo/pkg/errors" _ "github.com/mattn/go-sqlite3" // use sqlite for testing ) // -------------------------------------------------------------------------- // mocks for transport tests // -------------------------------------------------------------------------- // FileService -------------------------------------------------------------- // rather small PDF payload // https://stackoverflow.com/questions/17279712/what-is-the-smallest-possible-valid-pdf const pdfPayload = `%PDF-1.0 1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj xref 0 4 0000000000 65535 f 0000000010 00000 n 0000000053 00000 n 0000000102 00000 n trailer<</Size 4/Root 1 0 R>> startxref 149 %EOF ` type mockFileService struct { fail bool } func (m *mockFileService) InitClient() (err error) { return nil } func (m *mockFileService) SaveFile(file filestore.FileItem) (err error) { return nil } func (m *mockFileService) GetFile(filePath string) (item filestore.FileItem, err error) { if m.fail == true { return filestore.FileItem{}, fmt.Errorf("error") } return filestore.FileItem{ MimeType: "application/pdf", Payload: []byte(pdfPayload), }, nil } func (m *mockFileService) DeleteFile(filePath string) (err error) { return nil } var _ filestore.FileService = &mockFileService{} // UploadClient ------------------------------------------------------------- type mockUploadClient struct { fail bool } func (m *mockUploadClient) Get(id, authToken string) (upload.Upload, error) { if m.fail { return upload.Upload{}, fmt.Errorf("error") } return upload.Upload{}, nil } func (m *mockUploadClient) Delete(id, authToken string) error { if m.fail { return fmt.Errorf("error") } return nil } var _ upload.Client = &mockUploadClient{} // AppInfoService ----------------------------------------------------------- type mockAppInfoService struct { fail bool } func (m *mockAppInfoService) GetAppInfo(user *security.User) (ai appinfo.AppInfo, err error) { if m.fail { return appinfo.AppInfo{}, fmt.Errorf("error") } return appinfo.AppInfo{ UserInfo: appinfo.UserInfo{ DisplayName: user.DisplayName, }, VersionInfo: appinfo.VersionInfo{ Version: "1.0", }, }, nil } var _ appinfo.Service = &mockAppInfoService{} // DocumentService ---------------------------------------------------------- type mockDocumentService struct { fail bool } func (s *mockDocumentService) GetDocumentByID(id string) (d document.Document, err error) { if s.fail { return document.Document{}, fmt.Errorf("error") } return document.Document{ ID: "id", }, nil } func (s *mockDocumentService) DeleteDocumentByID(id string) (err error) { if s.fail { return fmt.Errorf("error") } return nil } func (s *mockDocumentService) SearchDocuments(title, tag, sender string, from, until time.Time, limit, skip int) (p document.PagedDocument, err error) { if s.fail { return document.PagedDocument{}, fmt.Errorf("error") } return document.PagedDocument{ Documents: []document.Document{ { ID: "id", }, }, TotalEntries: 1, }, nil } func (s *mockDocumentService) SearchList(name string, st document.SearchType) (l []string, err error) { if s.fail { return nil, fmt.Errorf("error") } return []string{"one", "two"}, nil } func (s *mockDocumentService) SaveDocument(doc document.Document, user security.User) (d document.Document, err error) { if s.fail { return document.Document{}, fmt.Errorf("error") } return doc, nil } var _ document.Service = &mockDocumentService{} // -------------------------------------------------------------------------- // Configuration and common test elements // -------------------------------------------------------------------------- const jwt = "<KEY>" const jwt_different_role = "<KEY>" var logger = logging.NewNop() var jwtConfig = config.Security{ CacheDuration: "10s", CookieName: "login_token", JwtIssuer: "test", JwtSecret: "test", LoginRedirect: "http://localhost/redirect", Claim: config.Claim{ Name: "test", URL: "http://localhost/test", Roles: []string{"roleA"}, }, } var assetConfig = config.AssetSettings{ AssetDir: "./", AssetPrefix: "/assets", } type handlerOps struct { aiSvc appinfo.Service docSvc document.Service fsSvc filestore.FileService } func handler() http.Handler { return handlerWith(nil) } func handlerWith(ops *handlerOps) http.Handler { var ( ai appinfo.Service ds document.Service fs filestore.FileService ) ai = &mockAppInfoService{} ds = &mockDocumentService{} fs = &mockFileService{} if ops != nil { if ops.aiSvc != nil { ai = ops.aiSvc } if ops.docSvc != nil { ds = ops.docSvc } if ops.fsSvc != nil { fs = ops.fsSvc } } endpoints := mydms.MakeServerEndpoints(ai, ds, fs, logger) apiSrv := mydms.MakeHTTPHandler(endpoints, logger, mydms.HTTPHandlerOptions{ BasePath: "./", ErrorPath: "/error", AssetConfig: assetConfig, CookieConfig: config.ApplicationCookies{}, CorsConfig: config.CorsSettings{}, JWTConfig: jwtConfig, }) return apiSrv } func addAuth(r *http.Request) { r.AddCookie(&http.Cookie{Name: "login_token", Value: jwt}) } func addAuthToken(r *http.Request, token string) { r.AddCookie(&http.Cookie{Name: "login_token", Value: token}) } // -------------------------------------------------------------------------- // Test cases // -------------------------------------------------------------------------- // AppInfo ------------------------------------------------------------------ const appinfo_route = "/api/v1/appinfo" func Test_GetAppInfo(t *testing.T) { var ai appinfo.AppInfo // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", appinfo_route, nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &ai); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, "1.0", ai.VersionInfo.Version) } func Test_GetAppInfo_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", appinfo_route, nil) addAuth(req) // act handlerWith(&handlerOps{ aiSvc: &mockAppInfoService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } func Test_GetAppInfo_MissingAuth(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", appinfo_route, nil) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusUnauthorized, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 401, pd.Status) } func Test_GetAppInfo_MissingPermissions(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", appinfo_route, nil) addAuthToken(req, jwt_different_role) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusUnauthorized, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, http.StatusUnauthorized, pd.Status) } // GetDocumentByID ---------------------------------------------------------- const doc_by_id_route = "/api/v1/documents/ID" func Test_GetDocumentByID(t *testing.T) { var doc document.Document // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", doc_by_id_route, nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, "id", doc.ID) } func Test_GetDocumentByID_Invalid_Param(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/documents/", nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) } func Test_GetDocumentByID_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", doc_by_id_route, nil) addAuth(req) // act handlerWith(&handlerOps{ docSvc: &mockDocumentService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } // DeleteDocumentByID ------------------------------------------------------- const delete_doc_by_id_route = "/api/v1/documents/ID" func Test_DeleteDocumentByID(t *testing.T) { var result document.Result // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", delete_doc_by_id_route, nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, document.Deleted, result.ActionResult) } func Test_DeleteDocumentByID_Invalid_Param(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", "/api/v1/documents/", nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) } func Test_DeleteDocumentByID_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", delete_doc_by_id_route, nil) addAuth(req) // act handlerWith(&handlerOps{ docSvc: &mockDocumentService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } // SearchList --------------------------------------------------------------- const search_list_route = "/api/v1/documents/%s/search" func Test_SearchList(t *testing.T) { var result mydms.EntriesResult // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(search_list_route, "tags"), nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 2, result.Lenght) // arrange rec = httptest.NewRecorder() req, _ = http.NewRequest("GET", fmt.Sprintf(search_list_route, "senders"), nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 2, result.Lenght) } func Test_SearchList_Invalid_URL(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(search_list_route, ""), nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) } func Test_SearchList_Invalid_Param(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(search_list_route, "something_else"), nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) } func Test_SearchList_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(search_list_route, "tags"), nil) addAuth(req) // act handlerWith(&handlerOps{ docSvc: &mockDocumentService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } // SearchDocuments ---------------------------------------------------------- const search_documents_route = "/api/v1/documents/search" func Test_SearchDocuments(t *testing.T) { var result document.PagedDocument var url string url = search_documents_route url = url + "?title=a&tag=b&limit=10&skip=0" // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", url, nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 1, result.TotalEntries) } func Test_SearchDocuments_Fail(t *testing.T) { var pd pkgerr.ProblemDetail var url string url = search_documents_route url = url + "?title=a&tag=b&limit=10&skip=0" // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", url, nil) addAuth(req) // act handlerWith(&handlerOps{ docSvc: &mockDocumentService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } } // SaveDocument ------------------------------------------------------------- const save_document_route = "/api/v1/documents" func Test_SaveDocument(t *testing.T) { var result document.Document // arrange rec := httptest.NewRecorder() payload := `{ "id": "ID", "title": "Title", "fileName": "FileName", "senders": ["sender"], "tags": ["tag"] }` req, _ := http.NewRequest("POST", save_document_route, strings.NewReader(payload)) req.Header.Add("Content-Type", "application/json") addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } // invalid document supplied rec = httptest.NewRecorder() var pd pkgerr.ProblemDetail req, _ = http.NewRequest("POST", save_document_route, strings.NewReader("{}")) req.Header.Add("Content-Type", "application/json") addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } } func Test_SaveDocument_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() payload := `{ "id": "ID", "title": "Title", "fileName": "FileName", "senders": ["sender"], "tags": ["tag"] }` req, _ := http.NewRequest("POST", save_document_route, strings.NewReader(payload)) req.Header.Add("Content-Type", "application/json") addAuth(req) // act handlerWith(&handlerOps{ docSvc: &mockDocumentService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } // GetFile ------------------------------------------------------------------ const get_file_route = "/api/v1/file" func Test_GetFile(t *testing.T) { var result []byte // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(get_file_route+"?path=%s", base64.StdEncoding.EncodeToString([]byte("/a"))), nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) result = rec.Body.Bytes() assert.True(t, len(result) > 0) } func Test_GetFile_Validation(t *testing.T) { var pd pkgerr.ProblemDetail // not base64 // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", get_file_route+"?path=/a", nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) // missing path // arrange rec = httptest.NewRecorder() req, _ = http.NewRequest("GET", get_file_route, nil) addAuth(req) // act handler().ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusBadRequest, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 400, pd.Status) } func Test_GetFile_Fail(t *testing.T) { var pd pkgerr.ProblemDetail // arrange rec := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf(get_file_route+"?path=%s", base64.StdEncoding.EncodeToString([]byte("/a"))), nil) addAuth(req) // act handlerWith(&handlerOps{ fsSvc: &mockFileService{fail: true}, }).ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusInternalServerError, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 500, pd.Status) } // ---------------------------------------------------------------------------------------------------------- // E2E-like test // use the real service and the real repository to create a document, read a document and delete a document // ---------------------------------------------------------------------------------------------------------- func e2eHandler(repo document.Repository) http.Handler { var ( ai appinfo.Service ds document.Service fs filestore.FileService uc upload.Client ) ai = &mockAppInfoService{} fs = &mockFileService{} uc = &mockUploadClient{} ds = document.NewService(logger, repo, fs, uc) endpoints := mydms.MakeServerEndpoints(ai, ds, fs, logger) apiSrv := mydms.MakeHTTPHandler(endpoints, logger, mydms.HTTPHandlerOptions{ BasePath: "./", ErrorPath: "/error", AssetConfig: assetConfig, CookieConfig: config.ApplicationCookies{}, CorsConfig: config.CorsSettings{}, JWTConfig: jwtConfig, }) return apiSrv } func getRepo() document.Repository { // persistence store && application version con := persistence.NewConnForDb("sqlite3", "file:test.db?cache=shared&mode=memory") f, err := ioutil.ReadFile("./ddl_test.sql") if err != nil { panic("cannot read ddl_test.sql") } _, err = con.DB.Exec(string(f)) if err != nil { panic("cannot setup sqlite!") } repo, err := document.NewRepository(con) if err != nil { panic(fmt.Sprintf("cannot establish database connection: %v", err)) } return repo } func Test_DocumentCRUD(t *testing.T) { repo := getRepo() handler := e2eHandler(repo) // -------------------- create a new document ----------------------- var result document.IDResult // arrange rec := httptest.NewRecorder() payload := `{ "id": "ID", "title": "Title", "fileName": "FileName", "senders": ["sender"], "tags": ["tag"] }` req, _ := http.NewRequest("POST", save_document_route, strings.NewReader(payload)) req.Header.Add("Content-Type", "application/json") addAuth(req) // act handler.ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.True(t, result.ID != "") // -------------------- read the new document ----------------------- var doc document.Document // arrange rec = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/api/v1/documents/"+result.ID, nil) addAuth(req) // act handler.ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil { t.Errorf("could not unmarshal: %v", err) } // -------------------- update the document ------------------------- // arrange rec = httptest.NewRecorder() payload = `{ "id": "ID", "title": "Title (updated)", "fileName": "FileName (updated)", "senders": ["sender1"], "tags": ["tag1"] }` req, _ = http.NewRequest("POST", save_document_route, strings.NewReader(strings.Replace(payload, "ID", result.ID, 1))) req.Header.Add("Content-Type", "application/json") addAuth(req) // act handler.ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.True(t, result.ID != "") // -------------------- delete the document ------------------------- var dr document.Result // arrange rec = httptest.NewRecorder() req, _ = http.NewRequest("DELETE", "/api/v1/documents/"+result.ID, nil) addAuth(req) // act handler.ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusOK, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &dr); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, document.Deleted, dr.ActionResult) // ----------------- read the document again ------------------------ var pd pkgerr.ProblemDetail // arrange rec = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/api/v1/documents/"+result.ID, nil) addAuth(req) // act handler.ServeHTTP(rec, req) // assert assert.Equal(t, http.StatusNotFound, rec.Code) if err := json.Unmarshal(rec.Body.Bytes(), &pd); err != nil { t.Errorf("could not unmarshal: %v", err) } assert.Equal(t, 404, pd.Status) }
guowilling/iOSDevCollection
ObjC/Animation/AirbnbHomeAnimationDemo/AirbnbHomeAnimationDemo/HomeDetailViewController.h
<reponame>guowilling/iOSDevCollection<gh_stars>1-10 // // DetailViewController.h // AirbnbHomeAnimationDemo // // Created by 郭伟林 on 2017/7/5. // Copyright © 2017年 SR. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^NoParameterBlock)(void); typedef void(^IDParameterBlock)(id); @interface HomeDetailViewController : UIViewController @property (nonatomic, strong) UIImage *coverImage; @property (nonatomic, strong) NoParameterBlock showingAnimationBlock; @property (nonatomic, strong) IDParameterBlock dismissAniamtionBlock; @end
androidworx/andworx
andmore-swt/org.eclipse.andmore.ddmuilib/src/main/java/com/android/ddmuilib/log/event/SyncCommon.java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ddmuilib.log.event; import com.android.ddmlib.log.EventContainer; import com.android.ddmlib.log.EventLogParser; import com.android.ddmlib.log.InvalidTypeException; import java.awt.Color; abstract public class SyncCommon extends EventDisplay { // State information while processing the event stream private int mLastState; // 0 if event started, 1 if event stopped private long mLastStartTime; // ms private long mLastStopTime; //ms private String mLastDetails; private int mLastSyncSource; // poll, server, user, etc. // Some common variables for sync display. These define the sync backends //and how they should be displayed. protected static final int CALENDAR = 0; protected static final int GMAIL = 1; protected static final int FEEDS = 2; protected static final int CONTACTS = 3; protected static final int ERRORS = 4; protected static final int NUM_AUTHS = (CONTACTS + 1); protected static final String AUTH_NAMES[] = {"Calendar", "Gmail", "Feeds", "Contacts", "Errors"}; protected static final Color AUTH_COLORS[] = {Color.MAGENTA, Color.GREEN, Color.BLUE, Color.ORANGE, Color.RED}; // Values from data/etc/event-log-tags final int EVENT_SYNC = 2720; final int EVENT_TICKLE = 2742; final int EVENT_SYNC_DETAILS = 2743; final int EVENT_CONTACTS_AGGREGATION = 2747; protected SyncCommon(String name) { super(name); } /** * Resets the display. */ @Override void resetUI() { mLastStartTime = 0; mLastStopTime = 0; mLastState = -1; mLastSyncSource = -1; mLastDetails = ""; } /** * Updates the display with a new event. This is the main entry point for * each event. This method has the logic to tie together the start event, * stop event, and details event into one graph item. The combined sync event * is handed to the subclass via processSycnEvent. Note that the details * can happen before or after the stop event. * * @param event The event * @param logParser The parser providing the event. */ @Override void newEvent(EventContainer event, EventLogParser logParser) { try { if (event.mTag == EVENT_SYNC) { int state = Integer.parseInt(event.getValueAsString(1)); if (state == 0) { // start mLastStartTime = (long) event.sec * 1000L + (event.nsec / 1000000L); mLastState = 0; mLastSyncSource = Integer.parseInt(event.getValueAsString(2)); mLastDetails = ""; } else if (state == 1) { // stop if (mLastState == 0) { mLastStopTime = (long) event.sec * 1000L + (event.nsec / 1000000L); if (mLastStartTime == 0) { // Log starts with a stop event mLastStartTime = mLastStopTime; } int auth = getAuth(event.getValueAsString(0)); processSyncEvent(event, auth, mLastStartTime, mLastStopTime, mLastDetails, true, mLastSyncSource); mLastState = 1; } } } else if (event.mTag == EVENT_SYNC_DETAILS) { mLastDetails = event.getValueAsString(3); if (mLastState != 0) { // Not inside event long updateTime = (long) event.sec * 1000L + (event.nsec / 1000000L); if (updateTime - mLastStopTime <= 250) { // Got details within 250ms after event, so delete and re-insert // Details later than 250ms (arbitrary) are discarded as probably // unrelated. int auth = getAuth(event.getValueAsString(0)); processSyncEvent(event, auth, mLastStartTime, mLastStopTime, mLastDetails, false, mLastSyncSource); } } } else if (event.mTag == EVENT_CONTACTS_AGGREGATION) { long stopTime = (long) event.sec * 1000L + (event.nsec / 1000000L); long startTime = stopTime - Long.parseLong(event.getValueAsString(0)); String details; int count = Integer.parseInt(event.getValueAsString(1)); if (count < 0) { details = "g" + (-count); } else { details = "G" + count; } processSyncEvent(event, CONTACTS, startTime, stopTime, details, true /* newEvent */, mLastSyncSource); } } catch (InvalidTypeException e) { } } /** * Callback hook for subclass to process a sync event. newEvent has the logic * to combine start and stop events and passes a processed event to the * subclass. * * @param event The sync event * @param auth The sync authority * @param startTime Start time (ms) of events * @param stopTime Stop time (ms) of events * @param details Details associated with the event. * @param newEvent True if this event is a new sync event. False if this event * @param syncSource Poll, user, server, etc. */ abstract void processSyncEvent(EventContainer event, int auth, long startTime, long stopTime, String details, boolean newEvent, int syncSource); /** * Converts authority name to auth number. * * @param authname "calendar", etc. * @return number series number associated with the authority */ protected int getAuth(String authname) throws InvalidTypeException { if ("calendar".equals(authname) || "cl".equals(authname) || "com.android.calendar".equals(authname)) { return CALENDAR; } else if ("contacts".equals(authname) || "cp".equals(authname) || "com.android.contacts".equals(authname)) { return CONTACTS; } else if ("subscribedfeeds".equals(authname)) { return FEEDS; } else if ("gmail-ls".equals(authname) || "mail".equals(authname)) { return GMAIL; } else if ("gmail-live".equals(authname)) { return GMAIL; } else if ("unknown".equals(authname)) { return -1; // Unknown tickles; discard } else { throw new InvalidTypeException("Unknown authname " + authname); } } }
boveloco/Puc
IA/Bob/src/Omega/Player.java
package Omega; import java.util.Random; public abstract class Player { protected Random r; private String name; int THIRSTLIMIT = 450; int thirst; protected StateManager manager; public Player(String name) { r = new Random(); manager = new StateManager(this); this.name = name; Manager.getInstance().registerPlayer(this); } public StateManager getManager(){ return this.manager; } public void addThirsty(int n) { if((this.thirst += n) < 0){ this.thirst = 0; } } public int getThirsty() { return thirst; } public boolean isThirsty() { if (this.thirst >= THIRSTLIMIT) return true; return false; } public String getName(){ return this.name; } public boolean handleMessage(Message msg){ return manager.handleMessage(msg); } }
jonboiser/kolibri
kolibri/content/__init__.py
<reponame>jonboiser/kolibri<filename>kolibri/content/__init__.py default_app_config = 'kolibri.content.apps.KolibriContentConfig'
samuel-reinhardt/nano-community
scripts/import-discord.js
const dayjs = require('dayjs') const debug = require('debug') const db = require('../db') const config = require('../config') const { request, wait } = require('../common') const logger = debug('script') debug.enable('script') const headers = { authorization: config.discordAuthorization } const excludeChannels = [ '403628195548495885', // nt - i hear voices '403628195548495886', // nt - hangouts hd '403630494387798016', // nt - mod general '403637392440819712', // nt - mod corner '403642500973330462', // nt - offtopic '403654013868048384', // nt - mod history '406319587987292160', // nt - mod chat '604423435552030749', // nt - mods and bots '403642625527119872', // nt - the circus '406318878298210314', // nt - hangouts sd '456813985367326720', // nt - worldcup '474959416895078402', // nt - giveaways '476409915888631809', // nt - treasure hunt '486569081785286666', // nt - price check '604731087369011230', // nt - whale alerts '677401078886563840', // nt - hangouts text '725781775716188181', // nt - politics '729829214794154004', // nt - nangry '759284898182856725', // nt - music '792291386237255721', // nt - charts '818725624050614302', // nt - hangouts lofi '415933844038877194', // nt - wallets '419885145210880010', // nt - puzzle solvers // private '523887477757575188', // nano - mod-history '548157077437022208', // nano - user history '523886767372500994', // nano - mod team '499224422180323334', // nano - archived '453645703978156042', // nano - new member '408020942250573834', // nano - 3rdparty-devs '405559981417693185', // nano - brainblocks '400790999166877706', // nano - lykke_tech '403850374005653504', // nano - pos_dev '399952530634833920', // nano - community-management-team '397990432732348416', // nano - rightbtc_tech '397791456321863680', // nano - debug_tech '397769966834941974', // nano - bitflip_tech '396852875810045952', // nano - cobinhood_tech '395910068895350789', // nano - coinfalcon '395828156864659473', // nano - bitz_tech '395410363295989760', // nano - trade_organization '393133169211080724', // nano - raiexchange_tech '392201266085888000', // nano - mercatox_tech '392068024552652810', // nano - next_xrb '372523530274865152', // nano - internal_development '370981975256858625', // nano - Nano Foundation Team '370285432979587103', // nano - exchange_team '805899143570259970', // nano - translations '784454182371459163', // nano - private-test-net '680144761549750377', // nano - research-development '766723792964812801', // nano - test-net '742684686786232392', // nano - moderator-only '727519943419232306', // nano - beta-faucet '725342483705495702', // nano - Nano Dev AMA '690644341479178333', // nano - Nano-Quake '725330577632526358', // nano - dev-ama '676437802690412575', // nano - wikipedia '628987342694252575', // nano - pow '573064313061769226', // nano - events '537549258245668864', // nano - off-topic '467429088190267393', // nano - github commits '465168864200753162', // nano - scam report '414305380869341204', // nano - nwc-wallet '407952439640326146', // nano - bitgrail-chat-temporary '395271536678010882', // nano - bug bounty '370266023905198086', // nano - voice channels '370336821466628096', // nano - charla general '370336888206131202', // nano - tagalog '581832306915016735', // nano - ledger '695323919095300138', // nano - gaming '370336920166858753', // nano - russian '370337132071616512', // nano - indonesian '370339679742066688', // nano - trading '370451429745360896', // nano - italian '370979830948298763', // nano - spanish '370982153237823489', // nano - tagalog 2 '370982157507756032', // nano - anuncios '370982203712208897', // nano - russian 2 '370982260360478721', // nano - indonesian 2 '370982541752139786', // nano - italian 2 '386783830666641418', // nano - german '386783877815074818', // nano - german '387648663306108928', // nano - chinese '387648945116938243', // nano - chinese '387650651204616194', // nano - french '387650699724455949', // nano - french '388079208112455690', // nano - dutch '388079764260519958', // nano - dutch '388839442980274176', // nano - Portuguese '388839547372437505', // nano - portuguese '391837779723550720', // nano - iazo_tech '394244364987006978', // nano - turkish '394244571179253770', // nano - turkish '394257359490383893', // nano - faq_es '395284766812930049', // nano - faq_ru '396051315979190284', // nano - polish '396051360904249344', // nano - polish '397762034089066507', // nano - swedish '397909844251639808', // nano - flowhub '399645337779830784', // nano - korean '399645410970304513', // nano - korean '399674643138478083', // nano - korean '400859958612197376', // nano - japenese '400859985761796096', // nano - japenese '401148013625606166', // nano - israel '401148177899847691', // nano - israel '401149655313809408', // nano - israel '401303506994069505', // nano - croatian '401303570273796098', // nano - croatian '402595560789508096', // nano - arabic '402595593362341889', // nano - arabic '402595617047576607', // nano - arabic '404125241011601408', // nano - vietnamese '404125269528412173', // nano - vietnamese '404125344212189184', // nano - vietnamese '438987154333368320', // nano - Голосовой Чат '438988377283624960', // nano - norwegian '438988637733126144', // nano - danish '677179212041551889', // nano - hindi '677179284540096560', // nano - hindi '712972541584736286', // nano - Scandinavia '712972729258606612', // nano - scandinavian '712972805209325588', // nano - scandinavian '786709469936746576', // nano - greek '786709603261087754' // nano - greek ] const getChannelsForGuildId = async (guildId) => { const channels = [] const url = `https://discord.com/api/v8/guilds/${guildId}/channels` let res try { res = await request({ url, headers }) res.forEach(({ name, id }) => channels.push({ name, id })) } catch (err) { console.log(err) } return channels } const main = async (guildId, { getFullHistory = false } = {}) => { logger(`importing discord server: ${guildId}`) let channels = await getChannelsForGuildId(guildId) channels = channels.filter((c) => !excludeChannels.includes(c.id)) logger(`found ${channels.length} channels`) for (const channel of channels) { logger(`importing channel: ${channel.name}`) const cid = `discord:${channel.id}:` const rows = await db('posts') .where('pid', 'like', `${cid}%`) .orderBy('created_at', 'desc') .limit(1) const messageId = rows.length ? rows[0].pid.split(cid)[1] : undefined logger(`last messageId: ${messageId}`) let beforeId, messageIds, res do { const url = `https://discord.com/api/v8/channels/${channel.id}/messages?limit=100` + (beforeId ? `&before=${beforeId}` : '') logger( `fetching messages from ${channel.name}, before: ${beforeId || 'n/a'}` ) try { res = await request({ url, headers }) } catch (err) { // console.log(err) } if (!res) { break } const posts = res.map((p) => ({ pid: `discord:${p.channel_id}:${p.id}`, sid: `discord:${guildId}`, title: null, url: `https://discord.com/channels/${guildId}/${p.channel_id}/${p.id}`, author: p.author.username, authorid: p.author.id, created_at: dayjs(p.timestamp).unix(), updated_at: p.edited_timestamp ? dayjs(p.edited_timestamp).unix() : null, html: null, text: p.content, score: p.reactions ? Math.max(...p.reactions.map((r) => r.count), 1) : 1 })) if (posts.length) { logger(`saving ${posts.length} posts from ${channel.name}`) await db('posts').insert(posts).onConflict().merge() } messageIds = res.map((p) => p.id) beforeId = messageIds[messageIds.length - 1] if (!getFullHistory && messageIds.includes(messageId)) { break } await wait(2000) } while (res && res.length) } } module.exports = main if (!module.parent) { const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (!argv.gid) { logger('missing gid') process.exit() } const guildId = argv.gid const getFullHistory = argv.full const init = async () => { try { await main(guildId, { getFullHistory }) } catch (err) { console.log(err) } process.exit() } try { init() } catch (err) { console.log(err) process.exit() } }
ainilili/outbatis
src/main/java/org/nico/ourbatis/exception/EmptyMapException.java
package org.nico.ourbatis.exception; public class EmptyMapException extends RuntimeException{ private static final long serialVersionUID = -5819302738797447168L; public EmptyMapException() { super(); } public EmptyMapException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public EmptyMapException(String message, Throwable cause) { super(message, cause); } public EmptyMapException(String message) { super(message); } public EmptyMapException(Throwable cause) { super(cause); } }
danielsunzhongyuan/go_learning
parallel_programming_in_practice/src/basic/map1/cmap_test.go
package map1 import ( "fmt" "math/rand" "reflect" "runtime/debug" "testing" ) func testConcurrentMap( t *testing.T, newConcurrentMap func() ConcurrentMap, genKey func() interface{}, genElem func() interface{}, keyKind reflect.Kind, elemKind reflect.Kind) { mapType := fmt.Sprintf("ConcurrentMap<keyType=%s, elemType=%s>", keyKind, elemKind) defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error: %s: %s\n", mapType, err) } }() t.Logf("Starting Test%s...", mapType) // Basic cmap := newConcurrentMap() expectedLen := 0 if cmap.Len() != expectedLen { t.Errorf("ERROR: The length of %s value %d is not %d!\n", mapType, cmap.Len(), expectedLen) t.FailNow() } expectedLen = 5 testMap := make(map[interface{}]interface{}, expectedLen) var invalidKey interface{} for i := 0; i < expectedLen; i++ { key := genKey() testMap[key] = genElem() if invalidKey == nil { invalidKey = key } } for key, elem := range testMap { oldElem, ok := cmap.Put(key, elem) if !ok { t.Errorf("ERROR: Put (%v, %v) to %s value %d is failing!\n", key, elem, mapType, cmap) t.FailNow() } if oldElem != nil { t.Errorf("ERROR: Already had a (%v, %v) in %s value %d!\n", key, elem, mapType, cmap) t.FailNow() } t.Logf("Put (%v, %v) to the %s value %v.", key, elem, mapType, cmap) } if cmap.Len() != expectedLen { t.Errorf("ERROR: The length of %s value %d is not %d!\n", mapType, cmap.Len(), expectedLen) t.FailNow() } for key, elem := range testMap { contains := cmap.Contains(key) if !contains { t.Errorf("ERROR: The %s value %v do not contains %v!", mapType, cmap, key) t.FailNow() } actualElem := cmap.Get(key) if actualElem == nil { t.Errorf("ERROR: The %s value %v do not contains %v!", mapType, cmap, key) t.FailNow() } t.Logf("The %s value %v contains key %v.", mapType, cmap, key) if actualElem != elem { t.Errorf("ERROR: The element of %s value %v with key %v do not equals %v!\n", mapType, actualElem, key, elem) t.FailNow() } t.Logf("The element of %s value %v to key %v is %v.", mapType, cmap, key, actualElem) } oldElem := cmap.Remove(invalidKey) if oldElem == nil { t.Errorf("ERROR: Remove %v from %s value %d is failing!\n", invalidKey, mapType, cmap) t.FailNow() } t.Logf("Removed (%v, %v) from the %s value %v.", invalidKey, oldElem, mapType, cmap) delete(testMap, invalidKey) // Type actualElemType := cmap.ElemType() if actualElemType == nil { t.Errorf("ERROR: The element type of %s value is nil!\n", mapType) t.FailNow() } actualElemKind := actualElemType.Kind() if actualElemKind != elemKind { t.Errorf("ERROR: The element type of %s value %s is not %s!\n", mapType, actualElemKind, elemKind) t.FailNow() } t.Logf("The element type of %s value %v is %s.", mapType, cmap, actualElemKind) actualKeyKind := cmap.KeyType().Kind() if actualKeyKind != elemKind { t.Errorf("ERROR: The key type of %s value %s is not %s!\n", mapType, actualKeyKind, keyKind) t.FailNow() } t.Logf("The key type of %s value %v is %s.", mapType, cmap, actualKeyKind) // Export keys := cmap.Keys() elems := cmap.Elems() pairs := cmap.ToMap() for key, elem := range testMap { var hasKey bool for _, k := range keys { if k == key { hasKey = true } } if !hasKey { t.Errorf("ERROR: The keys of %s value %v do not contains %v!\n", mapType, cmap, key) t.FailNow() } var hasElem bool for _, e := range elems { if e == elem { hasElem = true } } if !hasElem { t.Errorf("ERROR: The elems of %s value %v do not contains %v!\n", mapType, cmap, elem) t.FailNow() } var hasPair bool for k, e := range pairs { if k == key && e == elem { hasPair = true } } if !hasPair { t.Errorf("ERROR: The elems of %s value %v do not contains (%v, %v)!\n", mapType, cmap, key, elem) t.FailNow() } } // Clear cmap.Clear() if cmap.Len() != 0 { t.Errorf("ERROR: Clear %s value %d is failing!\n", mapType, cmap) t.FailNow() } t.Logf("The %s value %v has been cleared.", mapType, cmap) } func TestInt64Cmap(t *testing.T) { newCmap := func() ConcurrentMap { keyType := reflect.TypeOf(int64(2)) elemType := keyType return NewConcurrentMap(keyType, elemType) } testConcurrentMap( t, newCmap, func() interface{} { return rand.Int63n(1000) }, func() interface{} { return rand.Int63n(1000) }, reflect.Int64, reflect.Int64) } func TestFloat64Cmap(t *testing.T) { newCmap := func() ConcurrentMap { keyType := reflect.TypeOf(float64(2)) elemType := keyType return NewConcurrentMap(keyType, elemType) } testConcurrentMap( t, newCmap, func() interface{} { return rand.Float64() }, func() interface{} { return rand.Float64() }, reflect.Float64, reflect.Float64) } func TestStringCmap(t *testing.T) { newCmap := func() ConcurrentMap { keyType := reflect.TypeOf(string(2)) elemType := keyType return NewConcurrentMap(keyType, elemType) } testConcurrentMap( t, newCmap, func() interface{} { return genRandString() }, func() interface{} { return genRandString() }, reflect.String, reflect.String) } func BenchmarkConcurrentMap(b *testing.B) { keyType := reflect.TypeOf(int32(2)) elemType := keyType cmap := NewConcurrentMap(keyType, elemType) var key, elem int32 fmt.Printf("N=%d.\n", b.N) b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() seed := int32(i) key = seed elem = seed << 10 b.StartTimer() cmap.Put(key, elem) _ = cmap.Get(key) b.StopTimer() b.SetBytes(8) b.StartTimer() } ml := cmap.Len() b.StopTimer() mapType := fmt.Sprintf("ConcurrentMap<%s, %s>", keyType.Kind().String(), elemType.Kind().String()) b.Logf("The length of %s value is %d.\n", mapType, ml) b.StartTimer() } func BenchmarkMap(b *testing.B) { keyType := reflect.TypeOf(int32(2)) elemType := keyType imap := make(map[interface{}]interface{}) var key, elem int32 fmt.Printf("N=%d.\n", b.N) b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() seed := int32(i) key = seed elem = seed << 10 b.StartTimer() imap[key] = elem b.StopTimer() _ = imap[key] b.StopTimer() b.SetBytes(8) b.StartTimer() } ml := len(imap) b.StopTimer() mapType := fmt.Sprintf("Map<%s, %s>", keyType.Kind().String(), elemType.Kind().String()) b.Logf("The length of %s value is %d.\n", mapType, ml) b.StartTimer() }
bitkylin/featureLab
casper-lab/src/main/java/cc/bitky/featurelab/casperlab/service/guavalab/MyGuava.java
package cc.bitky.featurelab.casperlab.service.guavalab; /** * @author liMingLiang * @date 2019-05-11 */ public class MyGuava { public static void main(String[] args) { int[] a1 = {1, 6, 3, 8, 2, 7}; int[] a = {54, 35, 48, 36, 27, 12, 44, 44, 8, 14, 26, 17, 28}; new MyGuava().quickSort(a, 0, a.length - 1); System.out.println(); } private void swap(int[] a, int i, int j) { int k = a[i]; a[i] = a[j]; a[j] = k; } private void quickSort(int[] a, int left, int right) { if (right - left <= 1) { sort(a, left, right); return; } int p = middleByThree(a, left, right); quickSort(a, left, p - 1); quickSort(a, p, right); } private int middleByThree(int[] a, int left, int right) { int middle = (left + right) / 2; sort(a, left, middle, right); int temp = a[middle]; swap(a, middle, --right); while (true) { while (a[++left] < temp) ; while (a[--right] > temp) ; if (left >= right) { break; } else { swap(a, left, right); } } return left; } private void sort(int[] a, int x, int y) { if (a[x] > a[y]) { swap(a, x, y); } } private void sort(int[] a, int x, int y, int z) { sort(a, x, y); sort(a, x, z); sort(a, y, z); } }
bugvm/robovm
Core/rt/vm/core/src/test/test_proxy0.c
/* * Copyright (C) 2012 RoboVM AB * * 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 <bugvm.h> #include <string.h> #include "../private.h" #include "CuTest.h" int main(int argc, char* argv[]) __attribute__ ((weak)); int runTests(int argc, char* argv[]); void (*handler)(CallInfo*); void _bugvmProxyHandler(CallInfo* ci) { handler(ci); } void* bugvmAllocateMemory(Env* env, size_t size) { return calloc(1, size); } static void testProxy0ReturnByte_handler(CallInfo* ci) { jbyte b = proxy0NextInt(ci); proxy0ReturnInt(ci, b << 1); } static void testProxy0ReturnByte(CuTest* tc) { handler = testProxy0ReturnByte_handler; jbyte (*f)(jbyte) = (jbyte (*)(jbyte)) _proxy0; jbyte result = f(16); CuAssertIntEquals(tc, 32, result); } static void testProxy0ReturnInt_handler(CallInfo* ci) { jint i = proxy0NextInt(ci); proxy0ReturnInt(ci, i >> 8); } static void testProxy0ReturnInt(CuTest* tc) { handler = testProxy0ReturnInt_handler; jint (*f)(jint) = (jint (*)(jint)) _proxy0; jint result = f(0xdeadbeef); CuAssertIntEquals(tc, 0xffdeadbe, result); } static void testProxy0ReturnPtr_handler(CallInfo* ci) { void* p = proxy0NextPtr(ci); proxy0ReturnPtr(ci, p + sizeof(void*)); } static void testProxy0ReturnPtr(CuTest* tc) { handler = testProxy0ReturnPtr_handler; void* (*f)(void*) = (void* (*)(void*)) _proxy0; void* result = f(testProxy0ReturnPtr_handler); CuAssertPtrEquals(tc, testProxy0ReturnPtr_handler + sizeof(void*), result); } static void testProxy0ReturnLong_handler(CallInfo* ci) { jlong j = proxy0NextLong(ci); proxy0ReturnLong(ci, j << 8); } static void testProxy0ReturnLong(CuTest* tc) { handler = testProxy0ReturnLong_handler; jlong (*f)(jlong) = (jlong (*)(jlong)) _proxy0; jlong result = f(0xdeadbeefLL); CuAssertTrue(tc, result == 0xdeadbeef00LL); } static void testProxy0ReturnFloat_handler(CallInfo* ci) { jfloat f = proxy0NextFloat(ci); proxy0ReturnFloat(ci, f * f); } static void testProxy0ReturnFloat(CuTest* tc) { handler = testProxy0ReturnFloat_handler; jfloat (*f)(jfloat) = (jfloat (*)(jfloat)) _proxy0; jfloat result = f(3.14f); CuAssertTrue(tc, result == 3.14f * 3.14f); } static void testProxy0ReturnDouble_handler(CallInfo* ci) { jdouble d = proxy0NextDouble(ci); proxy0ReturnDouble(ci, d * d); } static void testProxy0ReturnDouble(CuTest* tc) { handler = testProxy0ReturnDouble_handler; jdouble (*f)(jdouble) = (jdouble (*)(jdouble)) _proxy0; jdouble result = f(-3.14); CuAssertTrue(tc, result == -3.14 * -3.14); } void testProxy0OneArgOfEach_handler(CallInfo* ci) { proxy0ReturnLong(ci, 0); void* p = proxy0NextPtr(ci); jint i = proxy0NextInt(ci); jlong l = proxy0NextLong(ci); jfloat f = proxy0NextFloat(ci); jdouble d = proxy0NextDouble(ci); if (p != testProxy0OneArgOfEach_handler) return; if (i != -100) return; if (l != 0xfedcba9876543210LL) return; if (f != 3.14f) return; if (d != -3.14) return; proxy0ReturnLong(ci, 0x0123456789abcdefLL); } void testProxy0OneArgOfEach(CuTest* tc) { handler = testProxy0OneArgOfEach_handler; jlong (*f)(void*, jint, jlong, jfloat, jdouble) = (jlong (*)(void*, jint, jlong, jfloat, jdouble)) _proxy0; jlong result = f(testProxy0OneArgOfEach_handler, -100, 0xfedcba9876543210LL, 3.14f, -3.14); CuAssertTrue(tc, result == 0x0123456789abcdefLL); } void testProxy0ManyArgsOfEach_handler(CallInfo* ci) { proxy0ReturnInt(ci, 0); void* p1 = proxy0NextPtr(ci); jint i1 = proxy0NextInt(ci); jlong l1 = proxy0NextLong(ci); jfloat f1 = proxy0NextFloat(ci); jdouble d1 = proxy0NextDouble(ci); void* p2 = proxy0NextPtr(ci); jint i2 = proxy0NextInt(ci); jlong l2 = proxy0NextLong(ci); jfloat f2 = proxy0NextFloat(ci); jdouble d2 = proxy0NextDouble(ci); void* p3 = proxy0NextPtr(ci); jint i3 = proxy0NextInt(ci); jlong l3 = proxy0NextLong(ci); jfloat f3 = proxy0NextFloat(ci); jdouble d3 = proxy0NextDouble(ci); void* p4 = proxy0NextPtr(ci); jint i4 = proxy0NextInt(ci); jlong l4 = proxy0NextLong(ci); jfloat f4 = proxy0NextFloat(ci); jdouble d4 = proxy0NextDouble(ci); void* p5 = proxy0NextPtr(ci); jint i5 = proxy0NextInt(ci); jlong l5 = proxy0NextLong(ci); jfloat f5 = proxy0NextFloat(ci); jdouble d5 = proxy0NextDouble(ci); void* p6 = proxy0NextPtr(ci); jint i6 = proxy0NextInt(ci); jlong l6 = proxy0NextLong(ci); jfloat f6 = proxy0NextFloat(ci); jdouble d6 = proxy0NextDouble(ci); void* p7 = proxy0NextPtr(ci); jint i7 = proxy0NextInt(ci); jlong l7 = proxy0NextLong(ci); jfloat f7 = proxy0NextFloat(ci); jdouble d7 = proxy0NextDouble(ci); void* p8 = proxy0NextPtr(ci); jint i8 = proxy0NextInt(ci); jlong l8 = proxy0NextLong(ci); jfloat f8 = proxy0NextFloat(ci); jdouble d8 = proxy0NextDouble(ci); if (p1 != testProxy0ManyArgsOfEach_handler + 0xcab1) return; if (i1 != -100) return; if (l1 != 0xfedcba9876543211LL) return; if (f1 != 3.11f) return; if (d1 != -3.11) return; if (p2 != testProxy0ManyArgsOfEach_handler + 0xcab2) return; if (i2 != -200) return; if (l2 != 0xfedcba9876543212LL) return; if (f2 != 3.12f) return; if (d2 != -3.12) return; if (p3 != testProxy0ManyArgsOfEach_handler + 0xcab3) return; if (i3 != -300) return; if (l3 != 0xfedcba9876543213LL) return; if (f3 != 3.13f) return; if (d3 != -3.13) return; if (p4 != testProxy0ManyArgsOfEach_handler + 0xcab4) return; if (i4 != -400) return; if (l4 != 0xfedcba9876543214LL) return; if (f4 != 3.14f) return; if (d4 != -3.14) return; if (p5 != testProxy0ManyArgsOfEach_handler + 0xcab5) return; if (i5 != -500) return; if (l5 != 0xfedcba9876543215LL) return; if (f5 != 3.15f) return; if (d5 != -3.15) return; if (p6 != testProxy0ManyArgsOfEach_handler + 0xcab6) return; if (i6 != -600) return; if (l6 != 0xfedcba9876543216LL) return; if (f6 != 3.16f) return; if (d6 != -3.16) return; if (p7 != testProxy0ManyArgsOfEach_handler + 0xcab7) return; if (i7 != -700) return; if (l7 != 0xfedcba9876543217LL) return; if (f7 != 3.17f) return; if (d7 != -3.17) return; if (p8 != testProxy0ManyArgsOfEach_handler + 0xcab8) return; if (i8 != -800) return; if (l8 != 0xfedcba9876543218LL) return; if (f8 != 3.18f) return; if (d8 != -3.18) return; proxy0ReturnInt(ci, 1); } void testProxy0ManyArgsOfEach(CuTest* tc) { handler = testProxy0ManyArgsOfEach_handler; jint (*f)(void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble) = (jint (*)( void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble, void*, jint, jlong, jfloat, jdouble)) _proxy0; jint result = f( testProxy0ManyArgsOfEach_handler + 0xcab1, -100, 0xfedcba9876543211LL, 3.11f, -3.11, testProxy0ManyArgsOfEach_handler + 0xcab2, -200, 0xfedcba9876543212LL, 3.12f, -3.12, testProxy0ManyArgsOfEach_handler + 0xcab3, -300, 0xfedcba9876543213LL, 3.13f, -3.13, testProxy0ManyArgsOfEach_handler + 0xcab4, -400, 0xfedcba9876543214LL, 3.14f, -3.14, testProxy0ManyArgsOfEach_handler + 0xcab5, -500, 0xfedcba9876543215LL, 3.15f, -3.15, testProxy0ManyArgsOfEach_handler + 0xcab6, -600, 0xfedcba9876543216LL, 3.16f, -3.16, testProxy0ManyArgsOfEach_handler + 0xcab7, -700, 0xfedcba9876543217LL, 3.17f, -3.17, testProxy0ManyArgsOfEach_handler + 0xcab8, -800, 0xfedcba9876543218LL, 3.18f, -3.18 ); CuAssertIntEquals(tc, 1, result); } void* findFunctionAt(void* pc); static jboolean unwindCallStack(UnwindContext* ctx, void* d) { jint i; void** callers = (void**) d; void* address = findFunctionAt(unwindGetIP(ctx)); for (i = 0; i < 10; i++) { if (!callers[i]) { callers[i] = address; break; } } return (i < 9 && address != main) ? TRUE : FALSE; } void testProxy0Unwind_handler(CallInfo* ci) { void** ptrs = proxy0NextPtr(ci); unwindBacktrace(NULL, unwindCallStack, ptrs); } void testProxy0Unwind(CuTest* tc) { handler = testProxy0Unwind_handler; void* callers[10] = {0}; void (*f)(void*) = (void (*)(void*)) _proxy0; f(callers); CuAssertPtrEquals(tc, testProxy0Unwind_handler, callers[0]); CuAssertPtrEquals(tc, _bugvmProxyHandler, callers[1]); CuAssertPtrEquals(tc, _proxy0, callers[2]); CuAssertPtrEquals(tc, testProxy0Unwind, callers[3]); CuAssertPtrEquals(tc, CuTestRun, callers[4]); CuAssertPtrEquals(tc, CuSuiteRun, callers[5]); CuAssertPtrEquals(tc, runTests, callers[6]); CuAssertPtrEquals(tc, main, callers[7]); CuAssertPtrEquals(tc, NULL, callers[8]); } void* findFunctionAt(void* pc) { void* candidates[8] = {0}; candidates[0] = testProxy0Unwind_handler; candidates[1] = _bugvmProxyHandler; candidates[2] = _proxy0; candidates[3] = testProxy0Unwind; candidates[4] = CuTestRun; candidates[5] = CuSuiteRun; candidates[6] = runTests; candidates[7] = main; void* match = NULL; jint delta = 0x7fffffff; jint i; for (i = 0; i < 8; i++) { if (candidates[i] < pc && pc - candidates[i] < delta) { match = candidates[i]; delta = pc - candidates[i]; } } return (match && delta < 1000) ? match : pc; } int runTests(int argc, char* argv[]) { CuSuite* suite = CuSuiteNew(); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnByte")) SUITE_ADD_TEST(suite, testProxy0ReturnByte); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnInt")) SUITE_ADD_TEST(suite, testProxy0ReturnInt); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnPtr")) SUITE_ADD_TEST(suite, testProxy0ReturnPtr); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnLong")) SUITE_ADD_TEST(suite, testProxy0ReturnLong); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnFloat")) SUITE_ADD_TEST(suite, testProxy0ReturnFloat); if (argc < 2 || !strcmp(argv[1], "testProxy0ReturnDouble")) SUITE_ADD_TEST(suite, testProxy0ReturnDouble); if (argc < 2 || !strcmp(argv[1], "testProxy0OneArgOfEach")) SUITE_ADD_TEST(suite, testProxy0OneArgOfEach); if (argc < 2 || !strcmp(argv[1], "testProxy0ManyArgsOfEach")) SUITE_ADD_TEST(suite, testProxy0ManyArgsOfEach); if (argc < 2 || !strcmp(argv[1], "testProxy0Unwind")) SUITE_ADD_TEST(suite, testProxy0Unwind); CuSuiteRun(suite); if (argc < 2) { CuString *output = CuStringNew(); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\n", output->buffer); } return suite->failCount; } int main(int argc, char* argv[]) { return runTests(argc, argv); }
plewis/phycas
src/cpp/mcmc_param.cpp
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ | Phycas: Python software for phylogenetic analysis | | Copyright (C) 2006 <NAME>, <NAME> and <NAME> | | | | 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. | \~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include "model.hpp" #include "jc.hpp" #include "hky.hpp" #include "gtr.hpp" #include "codon_model.hpp" #include "tree_likelihood.hpp" #include "probability_distribution.hpp" #include "mcmc_param.hpp" #include "mcmc_chain_manager.hpp" #include "basic_tree.hpp" namespace phycas { /*---------------------------------------------------------------------------------------------------------------------- | Constructor calls the base class (MCMCUpdater) constructor and sets `_edge_len_index' to UINT_MAX. */ EdgeLenParam::EdgeLenParam() : MCMCUpdater(), _my_node(NULL), _edge_len_index(UINT_MAX) { curr_value = 0.01; has_slice_sampler = true; is_move = false; is_master_param = false; is_hyper_param = false; } /*---------------------------------------------------------------------------------------------------------------------- | Constructor calls the base class (MCMCUpdater) constructor and sets `_edge_len_index' to the supplied value `i'. */ EdgeLenParam::EdgeLenParam( unsigned i) /**< is the index of this edge length */ : MCMCUpdater(), _my_node(NULL), _edge_len_index(i) { curr_value = 0.01; has_slice_sampler = true; is_move = false; is_master_param = false; is_hyper_param = false; } /*---------------------------------------------------------------------------------------------------------------------- | Destructor. */ EdgeLenParam::~EdgeLenParam() { //std::cerr << "\n>>>>> EdgeLenParam dying..." << std::endl; } /*---------------------------------------------------------------------------------------------------------------------- | Returns true if the edge managed by this EdgeLenParam is an internal edge. */ bool EdgeLenParam::isInternalEdge() { bool is_internal = _my_node->IsInternal(); bool is_subroot = _my_node->IsSubroot(); bool is_internal_edge = is_internal && !is_subroot; //std::cerr << "~~~~~ _my_node number = " << _my_node->GetNodeNumber() << ", is_internal = " << (is_internal ? "yes" : "no") << ", is_subroot = " << (is_subroot ? "yes" : "no") << ", is_internal_edge = " << (is_internal_edge ? "yes" : "no") << std::endl; //@@@ return is_internal_edge; } /*---------------------------------------------------------------------------------------------------------------------- | Returns true if the edge managed by this EdgeLenParam is an external edge. */ bool EdgeLenParam::isExternalEdge() { bool is_tip = _my_node->IsTip(); bool is_subroot = _my_node->IsSubroot(); bool is_external_edge = is_tip || is_subroot; //std::cerr << "~~~~~ _my_node number = " << _my_node->GetNodeNumber() << ", is_tip = " << (is_tip ? "yes" : "no") << ", is_subroot = " << (is_subroot ? "yes" : "no") << ", is_external_edge = " << (is_external_edge ? "yes" : "no") << std::endl; //@@@ return is_external_edge; } /*---------------------------------------------------------------------------------------------------------------------- | Calls the sample() member function of the `slice_sampler' data member. */ bool EdgeLenParam::update() { if (is_fixed) return false; if (_my_node->IsInternal()) likelihood->useAsLikelihoodRoot(_my_node); else likelihood->useAsLikelihoodRoot(_my_node->GetParent()); likelihood->invalidateAwayFromNode(*_my_node); double current_brlen = getCurrValueFromModel(); //std::cerr << "<-- EdgeLenParam::update -->" << std::endl; //@@@ //double last_sampled_brlen = slice_sampler->GetLastSampledXValue(); //if (fabs(current_brlen - last_sampled_brlen) > 0.00001) // { // std::cerr << "BAD BAD! BAD!!" << std::endl; // } slice_sampler->SetXValue(current_brlen); slice_sampler->Sample(); ChainManagerShPtr p = chain_mgr.lock(); if (save_debug_info) { debug_info = str(boost::format("EdgeLenParam %f") % (slice_sampler->GetLastSampledXValue())); } return true; } /*---------------------------------------------------------------------------------------------------------------------- | Overrides base class version to set the edge length to `v'. */ void EdgeLenParam::sendCurrValueToModel(double v) { PHYCAS_ASSERT(_my_node != NULL); _my_node->SetEdgeLen(v); } /*---------------------------------------------------------------------------------------------------------------------- | Overrides base class version to return the edge length currently stored in the tree. */ double EdgeLenParam::getCurrValueFromModel() const { PHYCAS_ASSERT(_my_node != NULL); return _my_node->GetEdgeLen(); } /*---------------------------------------------------------------------------------------------------------------------- | Sets private data member `_my_node' to point to the supplied TreeNode `nd'. */ void EdgeLenParam::setTreeNode(TreeNode & nd) { _my_node = &nd; } /*---------------------------------------------------------------------------------------------------------------------- | This function overrides the base class version to always returns true because this derived class implements a tree | length prior. */ bool EdgeLenParam::computesTreeLengthPrior() const { return true; } /*---------------------------------------------------------------------------------------------------------------------- | Returns string representation of split associated with `_my_node'. */ std::string EdgeLenParam::getSplitReprAsString() const { Split & s = _my_node->GetSplit(); if (s.IsBitSet(0)) s.InvertSplit(); return s.CreatePatternRepresentation(); } /*---------------------------------------------------------------------------------------------------------------------- | EdgeLenParam is a functor whose operator() returns a value proportional to the full-conditional posterior probability | density for a particular value of the edge length managed by this object. If the supplied value `v' is | out of bounds (i.e. <= 0.0), the return value is -DBL_MAX (closest we can come to a log posterior equal to negative | infinity). */ double EdgeLenParam::operator()( double v) /**< is a new value for the edge length parameter */ { PHYCAS_ASSERT(_my_node != NULL); curr_ln_like = ln_zero; curr_ln_prior = 0.0; if (v > 0.0) { sendCurrValueToModel(v); curr_ln_like = (heating_power > 0.0 ? likelihood->calcLnL(tree) : 0.0); //likelihood->startTreeViewer(tree, boost::str(boost::format("After calcLnL: curr_ln_like = %.6f") % curr_ln_like)); ChainManagerShPtr p = chain_mgr.lock(); PHYCAS_ASSERT(p); p->setLastLnLike(curr_ln_like); JointPriorManagerShPtr jpm = p->getJointPriorManager(); if (jpm->isTreeLengthPrior()) jpm->treeLengthModified("tree_length", tree); else jpm->univariateModified(name, v); curr_ln_prior = jpm->getLogJointPrior(); if (is_standard_heating) if (use_ref_dist) { double curr_ln_ref_dist = 0.0; if (likelihood->getTreeLengthRefDist()) { curr_ln_ref_dist = likelihood->getTreeLengthRefDist()->GetLnPDF(tree); } else { PHYCAS_ASSERT(ref_dist); curr_ln_ref_dist = ref_dist->GetLnPDF(v); } return heating_power*(curr_ln_like + curr_ln_prior) + (1.0 - heating_power)*curr_ln_ref_dist; } else return heating_power*(curr_ln_like + curr_ln_prior); else return heating_power*curr_ln_like + curr_ln_prior; } else return ln_zero; } } // namespace phycas
akshat0109/kisan_backend
flasky2/venv/Lib/site-packages/weka/core/stopwords.py
<gh_stars>0 # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # stopwords.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import javabridge from weka.core.classes import OptionHandler class Stopwords(OptionHandler): """ Wrapper class for stopwords handlers. """ def __init__(self, classname="weka.core.stopwords.Null", jobject=None, options=None): """ Initializes the specified stopwords handler using either the classname or the supplied JB_Object. :param classname: the classname of the stopwords handler :type classname: str :param jobject: the JB_Object to use :type jobject: JB_Object :param options: the list of commandline options to set :type options: list """ if jobject is None: jobject = Stopwords.new_instance(classname) self.enforce_type(jobject, "weka.core.stopwords.StopwordsHandler") super(Stopwords, self).__init__(jobject=jobject, options=options) self.__is_stopword = javabridge.make_call(self.jobject, "isStopword", "(Ljava/lang/String;)Z") def is_stopword(self, s): """ Checks a string whether it is a stopword. :param s: the string to check :type s: str :return: True if a stopword :rtype: bool """ return self.__is_stopword(javabridge.get_env().new_string_utf(s))
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
ace/tao/orbsvcs/orbsvcs/esf/ESF_Shutdown_Proxy.h
<gh_stars>10-100 /* -*- C++ -*- */ /** * @file ESF_Shutdown_Proxy.h * * ESF_Shutdown_Proxy.h,v 1.3 2000/10/31 03:11:12 coryan Exp * * @author <NAME> (<EMAIL>) * * http://doc.ece.uci.edu/~coryan/EC/index.html */ #ifndef TAO_ESF_SHUTDOWN_PROXY_H #define TAO_ESF_SHUTDOWN_PROXY_H #include "ESF_Worker.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ /// A worker to invoke the shutdown method of each proxy. template<class PROXY> class TAO_ESF_Shutdown_Proxy : public TAO_ESF_Worker<PROXY> { public: TAO_ESF_Shutdown_Proxy (void); void work (PROXY *proxy, CORBA::Environment &ACE_TRY_ENV); }; // **************************************************************** #if defined (__ACE_INLINE__) #include "ESF_Shutdown_Proxy.i" #endif /* __ACE_INLINE__ */ #if defined (ACE_TEMPLATES_REQUIRE_SOURCE) #include "ESF_Shutdown_Proxy.cpp" #endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ #if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) #pragma implementation ("ESF_Shutdown_Proxy.cpp") #endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ #endif /* TAO_ESF_SHUTDOWN_PROXY_H */
magnublo/msc-darkweb-scraping
useful_scripts/replace_references.py
import os import re dir_path = "/home/magnus/Documents/dream_market/parsed_html" files = os.listdir(dir_path) file_refs = set() valid_files = [f for f in files if re.match(r"[0-9]{13}_[0-9]{4}_[a-z0-9]{40}\.html", f)] for i, file in enumerate(valid_files): k = 0 match = None file_path = f"{dir_path}/{file}" with open(file_path, "rb") as f: file_content_bytes = f.read() try: file_content = file_content_bytes.decode("unicode_escape") except UnicodeDecodeError: file_content = None if file_content: pos = 0 while k == 0 or match is not None: match = re.search(r"(?:(?:src|href)=)\"([a-z0-9.\-\_\/]+\.[a-z0-9]{2,4})\"", file_content[pos:]) if match: k += 1 start_index = match.regs[1][0] + pos pos = end_index = match.regs[1][1] + pos file_ref = file_content[start_index:end_index] file_refs.add(file_ref) new_file_ref = "./../" + file_ref.split("/")[-1] file_content = file_content[:start_index] + new_file_ref + file_content[end_index:] else: break if k > 0: output_file_path = f"{dir_path}/../new_refs_parsed_html/{file}" with open(output_file_path, "w") as f: f.write(file_content) if i % 1000 == 0: print(f"{i}/{len(files)}") print("\n".join(file_refs))
mehrdadzakershahrak/Online-Explanation-Generation
rovers/fastdownward/experiments/issue680/v2.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import suites from lab.reports import Attribute, gm from common_setup import IssueConfig, IssueExperiment from relativescatter import RelativeScatterPlotReport def main(revisions=None): benchmarks_dir=os.path.expanduser('~/projects/downward/benchmarks') suite=suites.suite_optimal() configs = [] for osi in ['103', '107']: for cplex in ['1251', '1263']: if osi == '107' and cplex == '1251': # incompatible versions continue configs += [ IssueConfig( 'astar_seq_landmarks_OSI%s_CPLEX%s' % (osi, cplex), ['--search', 'astar(operatorcounting([state_equation_constraints(), lmcut_constraints()]))'], build_options=['issue680_OSI%s_CPLEX%s' % (osi, cplex)], driver_options=['--build=issue680_OSI%s_CPLEX%s' % (osi, cplex)] ), IssueConfig( 'astar_diverse_potentials_OSI%s_CPLEX%s' % (osi, cplex), ['--search', 'astar(diverse_potentials())'], build_options=['issue680_OSI%s_CPLEX%s' % (osi, cplex)], driver_options=['--build=issue680_OSI%s_CPLEX%s' % (osi, cplex)] ), IssueConfig( 'astar_lmcount_OSI%s_CPLEX%s' % (osi, cplex), ['--search', 'astar(lmcount(lm_merged([lm_rhw(),lm_hm(m=1)]),admissible=true,optimal=true),mpd=true)'], build_options=['issue680_OSI%s_CPLEX%s' % (osi, cplex)], driver_options=['--build=issue680_OSI%s_CPLEX%s' % (osi, cplex)] ), ] exp = IssueExperiment( benchmarks_dir=benchmarks_dir, suite=suite, revisions=revisions, configs=configs, test_suite=['depot:p01.pddl', 'gripper:prob01.pddl'], processes=4, email='<EMAIL>', ) attributes = exp.DEFAULT_TABLE_ATTRIBUTES domains = suites.suite_optimal_strips() exp.add_absolute_report_step(filter_domain=domains) for attribute in ["memory", "total_time"]: for config in ['astar_seq_landmarks', 'astar_diverse_potentials', 'astar_lmcount']: exp.add_report( RelativeScatterPlotReport( attributes=[attribute], filter_config=["{}-{}_OSI{}_CPLEX1263".format(revisions[0], config, osi) for osi in ['103', '107']], filter_domain=domains, get_category=lambda run1, run2: run1.get("domain"), ), outfile="{}-{}-{}_CPLEX1263.png".format(exp.name, attribute, config) ) exp.add_report( RelativeScatterPlotReport( attributes=[attribute], filter_config=["{}-{}_OSI103_CPLEX{}".format(revisions[0], config, cplex) for cplex in ['1251', '1263']], filter_domain=domains, get_category=lambda run1, run2: run1.get("domain"), ), outfile="{}-{}-{}_OSI103.png".format(exp.name, attribute, config) ) exp() main(revisions=['issue680-v2'])
iamsg08/Joing-Parsing-and-Generation-for-Abstractive-Summarization
layers/data_process/Padding.py
<reponame>iamsg08/Joing-Parsing-and-Generation-for-Abstractive-Summarization #==============================# # System Import # #==============================# #==============================# # Platform Import # #==============================# import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable #==============================# # Class/Layer Part Import # #==============================# class Padding(object): @staticmethod def rightEOS(seqs, patch = 2): return [seq + [patch] for seq in seqs] @staticmethod def padding(seqs): lengths = [len(seq) for seq in seqs] maxLength = max(lengths) result = [seqs[i] + [0] * (maxLength - lengths[i]) for i in range(len(seqs))] ret1 = Variable(torch.LongTensor(result), requires_grad = False) ret2 = Variable(torch.LongTensor(lengths), requires_grad = False) #print ret1 #print ret2 if torch.cuda.is_available(): ret1 = ret1.cuda() ret2 = ret2.cuda() #print ret1 #print ret2 return ret1, ret2 @staticmethod def padding_withEOS(seqs, patch = 2): lengths = [len(seq)+1 for seq in seqs] maxLength = max(lengths) result = [seqs[i] + [2] + [0] * (maxLength - lengths[i]) for i in range(len(seqs))] ret1 = Variable(torch.LongTensor(result), requires_grad = False) ret2 = Variable(torch.LongTensor(lengths), requires_grad = False) #print ret1 #print ret2 if torch.cuda.is_available(): ret1 = ret1.cuda() ret2 = ret2.cuda() #print ret1 #print ret2 return ret1, ret2 @staticmethod def unpadding(seqs, lengths): batch_size = lengths.size()[0] return [[int(seqs[i][j]) for j in range(lengths[i])]for i in range(batch_size)] @staticmethod def rightShift(x, patch = 1): res = F.pad(x, (1, 0), "constant", patch) return res @staticmethod def rightShiftCut(x, patch = 1): res = F.pad(x, (1, 0), "constant", patch)[:,:-1] return res @staticmethod def rightPadEnd(x, patch = 2): res = F.pad(x, (0, 1), "constant", patch) return res
LordDeatHunter/ExNihiloFabrico
src/main/java/wraith/fabricaeexnihilo/compatibility/kubejs/recipe/barrel/FluidCombinationRecipeJS.java
<filename>src/main/java/wraith/fabricaeexnihilo/compatibility/kubejs/recipe/barrel/FluidCombinationRecipeJS.java<gh_stars>1-10 package wraith.fabricaeexnihilo.compatibility.kubejs.recipe.barrel; import com.google.gson.JsonPrimitive; import dev.latvian.mods.kubejs.recipe.RecipeJS; import dev.latvian.mods.kubejs.util.ListJS; import dev.latvian.mods.kubejs.util.MapJS; import wraith.fabricaeexnihilo.modules.barrels.modes.BarrelMode; import wraith.fabricaeexnihilo.recipe.util.FluidIngredient; import wraith.fabricaeexnihilo.util.CodecUtils; public class FluidCombinationRecipeJS extends RecipeJS { private BarrelMode result; private FluidIngredient contained; private FluidIngredient other; @Override public void create(ListJS listJS) { result = CodecUtils.fromJson(BarrelMode.CODEC, MapJS.json(listJS.get(0))); contained = CodecUtils.fromJson(FluidIngredient.CODEC, new JsonPrimitive(listJS.get(1).toString())); other = CodecUtils.fromJson(FluidIngredient.CODEC, new JsonPrimitive(listJS.get(2).toString())); } @Override public void deserialize() { result = CodecUtils.fromJson(BarrelMode.CODEC, json.get("result")); contained = CodecUtils.fromJson(FluidIngredient.CODEC, json.get("contained")); other = CodecUtils.fromJson(FluidIngredient.CODEC, json.get("other")); } @Override public void serialize() { json.add("result", CodecUtils.toJson(BarrelMode.CODEC, result)); json.add("contained", CodecUtils.toJson(FluidIngredient.CODEC, contained)); json.add("other", CodecUtils.toJson(FluidIngredient.CODEC, other)); } }
sleyzerzon/soar
Deprecated/SoarPre8.6/soar/kernel/agent.c
<filename>Deprecated/SoarPre8.6/soar/kernel/agent.c /************************************************************************* * * file: agent.c * * ======================================================================= * Initialization for the agent structure. Also the cleanup routine * when an agent is destroyed. These routines are usually replaced * by the same-named routines in the Tcl interface file soarAgent.c * The versions in this file are used only when not linking in Tcl. * HOWEVER, this code should be maintained, and the agent structure * must be kept up to date. * ======================================================================= * * Copyright 1995-2004 Carnegie Mellon University, * University of Michigan, * University of Southern California/Information * Sciences Institute. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE SOAR CONSORTIUM ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE SOAR CONSORTIUM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Carnegie Mellon University, the * University of Michigan, the University of Southern California/Information * Sciences Institute, or the Soar consortium. * ======================================================================= */ /* =================================================================== Agent-related functions =================================================================== */ #include "soarkernel.h" #include "scheduler.h" #include "sysdep.h" #include "rhsfun_examples.h" agent *soar_agent; list *all_soar_agents = NIL; int agent_counter = -1; int agent_count = -1; char *soar_version_string; extern int soar_agent_ids[]; /* Try to assign a unique and previously unassigned id. If none are available, assign a unique, but previously assigned id. */ int next_available_agent_id() { int i; for (i = 0; i < MAX_SIMULTANEOUS_AGENTS; i++) { if (soar_agent_ids[i] == UNTOUCHED) { soar_agent_ids[i] = ALLOCATED; return i; } } for (i = 0; i < MAX_SIMULTANEOUS_AGENTS; i++) { if (soar_agent_ids[i] == TOUCHED) { soar_agent_ids[i] = ALLOCATED; return i; } } { char msg[MESSAGE_SIZE]; snprintf(msg, MESSAGE_SIZE, "agent.c: Error: Too many simultaneous agents (> %d\n", MAX_SIMULTANEOUS_AGENTS); msg[MESSAGE_SIZE - 1] = 0; /* snprintf doesn't set last char to null if output is truncated */ abort_with_fatal_error(msg); } return -1; /* To placate compilier */ } #ifdef ATTENTION_LAPSE /* RMJ; When doing attentional lapsing, we need a function that determines when (and for how long) attentional lapses should occur. This will normally be provided as a user-defined TCL procedure. */ long init_lapse_duration(TIMER_VALUE * tv) { int ret; long time_since_last_lapse; char buf[128]; start_timer(current_real_time); timersub(current_real_time, tv, current_real_time); time_since_last_lapse = (long) (1000 * timer_value(tv)); if (soar_exists_callback(soar_agent, INIT_LAPSE_DURATION_CALLBACK)) { /* SW 11.07.00 * * Modified this to use the generic soar interface, as opposed * to being Tcl specific. This requires a new callback * in particular, here the callback receives the value * time_since_last_lapse, and must RESET this value to * the appropriate number */ soar_invoke_callback(soar_agent, INIT_LAPSE_DURATION_CALLBACK, (void *) &time_since_last_lapse); return time_since_last_lapse; } return 0; } #endif /* =================================================================== Initialization Function =================================================================== */ void init_soar_agent(void) { /* --- initialize everything --- */ init_memory_utilities(); init_symbol_tables(); create_predefined_symbols(); init_production_utilities(); init_built_in_rhs_functions(); /*add_bot_rhs_functions (soar_agent); */ add_bot_rhs_functions(); init_rete(); init_lexer(); init_firer(); init_decider(); init_soar_io(); init_chunker(); init_sysparams(); init_tracing(); init_explain(); /* AGR 564 */ #ifdef REAL_TIME_BEHAVIOR /* RMJ */ init_real_time(); #endif #ifdef ATTENTION_LAPSE /* RMJ */ init_attention_lapse(); #endif /* --- add default object trace formats --- */ add_trace_format(FALSE, FOR_ANYTHING_TF, NIL, "%id %ifdef[(%v[name])]"); add_trace_format(FALSE, FOR_STATES_TF, NIL, "%id %ifdef[(%v[attribute] %v[impasse])]"); { Symbol *evaluate_object_sym; evaluate_object_sym = make_sym_constant("evaluate-object"); add_trace_format(FALSE, FOR_OPERATORS_TF, evaluate_object_sym, "%id (evaluate-object %o[object])"); symbol_remove_ref(evaluate_object_sym); } /* --- add default stack trace formats --- */ add_trace_format(TRUE, FOR_ANYTHING_TF, NIL, "%right[6,%dc]: %rsd[ ]==>S: %id %ifdef[(%v[name])]"); add_trace_format(TRUE, FOR_STATES_TF, NIL, "%right[6,%dc]: %rsd[ ]==>S: %cs"); add_trace_format(TRUE, FOR_OPERATORS_TF, NIL, "%right[6,%dc]: %rsd[ ] O: %co"); reset_statistics(); }
chebykinn/university
mpi/src/main/java/com/ghostflow/database/Employees.java
<gh_stars>1-10 package com.ghostflow.database; import com.ghostflow.database.postgres.entities.UserEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import java.util.List; @NoArgsConstructor(force = true) @AllArgsConstructor @Getter public class Employees { private final List<UserEntity> employees; private final long count; }
artcom/eppsa-ips-evaluation
specs/models/experiment.spec.js
const { describe, it, before, after } = require("mocha") const { expect, assert } = require("chai") const { dbSync, dbDrop } = require("../helpers/db") const Experiment = require("../../src/models/experiment") describe("Model Experiment", () => { before(async () => { await dbSync() }) after(async () => { await dbDrop() }) it("can create an experiment", async () => { await Experiment.create({ name: "test-experiment" }) const experiments = await Experiment.findAll() expect(experiments[0].name).to.equal("test-experiment") }) it("raises an error when the experiment name already exists", async () => { try { await Experiment.bulkCreate( [ { name: "test-experiment" }, { name: "test-experiment" } ] ) assert.fail("", "Validation error", "No error was thrown") } catch (error) { expect(error.message).to.equal("Validation error") } }) })
NIL-zhuang/IRBL
swt/src/graphics/Path.java
<reponame>NIL-zhuang/IRBL /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.graphics; import org.eclipse.swt.*; import org.eclipse.swt.internal.gdip.*; import org.eclipse.swt.internal.win32.*; /** * Instances of this class represent paths through the two-dimensional * coordinate system. Paths do not have to be continuous, and can be * described using lines, rectangles, arcs, cubic or quadratic bezier curves, * glyphs, or other paths. * <p> * Application code must explicitly invoke the <code>Path.dispose()</code> * method to release the operating system resources managed by each instance * when those instances are no longer required. * </p> * * @since 3.1 */ public class Path extends Resource { /** * the OS resource for the Path * (Warning: This field is platform dependent) * <p> * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT * public API. It is marked public only so that it can be shared * within the packages provided by SWT. It is not available on all * platforms and should never be accessed from application code. * </p> */ public int handle; PointF currentPoint = new PointF(), startPoint = new PointF(); /** * Constructs a new empty Path. * * @param device the device on which to allocate the path * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the device is null and there is no current device</li> * </ul> * @exception SWTError <ul> * <li>ERROR_NO_HANDLES if a handle for the path could not be obtained/li> * </ul> * * @see #dispose() */ public Path (Device device) { if (device == null) device = Device.getDevice(); if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); this.device = device; device.checkGDIP(); handle = Gdip.GraphicsPath_new(Gdip.FillModeAlternate); if (handle == 0) SWT.error(SWT.ERROR_NO_HANDLES); if (device.tracking) device.new_Object(this); } /** * Adds to the receiver a circular or elliptical arc that lies within * the specified rectangular area. * <p> * The resulting arc begins at <code>startAngle</code> and extends * for <code>arcAngle</code> degrees. * Angles are interpreted such that 0 degrees is at the 3 o'clock * position. A positive value indicates a counter-clockwise rotation * while a negative value indicates a clockwise rotation. * </p><p> * The center of the arc is the center of the rectangle whose origin * is (<code>x</code>, <code>y</code>) and whose size is specified by the * <code>width</code> and <code>height</code> arguments. * </p><p> * The resulting arc covers an area <code>width + 1</code> pixels wide * by <code>height + 1</code> pixels tall. * </p> * * @param x the x coordinate of the upper-left corner of the arc * @param y the y coordinate of the upper-left corner of the arc * @param width the width of the arc * @param height the height of the arc * @param startAngle the beginning angle * @param arcAngle the angular extent of the arc, relative to the start angle * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void addArc(float x, float y, float width, float height, float startAngle, float arcAngle) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } if (width == 0 || height == 0 || arcAngle == 0) return; Gdip.GraphicsPath_AddArc(handle, x, y, width, height, -startAngle, -arcAngle); Gdip.GraphicsPath_GetLastPoint(handle, currentPoint); } /** * Adds to the receiver the path described by the parameter. * * @param path the path to add to the receiver * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> * <li>ERROR_INVALID_ARGUMENT - if the parameter has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void addPath(Path path) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (path == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (path.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); //TODO - expose connect? Gdip.GraphicsPath_AddPath(handle, path.handle, false); currentPoint.X = path.currentPoint.X; currentPoint.Y = path.currentPoint.Y; } /** * Adds to the receiver the rectangle specified by x, y, width and height. * * @param x the x coordinate of the rectangle to add * @param y the y coordinate of the rectangle to add * @param width the width of the rectangle to add * @param height the height of the rectangle to add * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void addRectangle(float x, float y, float width, float height) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); RectF rect = new RectF(); rect.X = x; rect.Y = y; rect.Width = width; rect.Height = height; Gdip.GraphicsPath_AddRectangle(handle, rect); currentPoint.X = x; currentPoint.Y = y; } /** * Adds to the receiver the pattern of glyphs generated by drawing * the given string using the given font starting at the point (x, y). * * @param string the text to use * @param x the x coordinate of the starting point * @param y the y coordinate of the starting point * @param font the font to use * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the font is null</li> * <li>ERROR_INVALID_ARGUMENT - if the font has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void addString(String string, float x, float y, Font font) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (font == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); int length = string.length(); char[] buffer = new char[length]; string.getChars(0, length, buffer, 0); int hDC = device.internal_new_GC(null); int gdipFont = GC.createGdipFont(hDC, font.handle); PointF point = new PointF(); point.X = x - (Gdip.Font_GetSize(gdipFont) / 6); point.Y = y; int family = Gdip.FontFamily_new(); Gdip.Font_GetFamily(gdipFont, family); int style = Gdip.Font_GetStyle(gdipFont); float size = Gdip.Font_GetSize(gdipFont); Gdip.GraphicsPath_AddString(handle, buffer, length, family, style, size, point, 0); Gdip.GraphicsPath_GetLastPoint(handle, currentPoint); Gdip.FontFamily_delete(family); Gdip.Font_delete(gdipFont); device.internal_dispose_GC(hDC, null); } /** * Closes the current sub path by adding to the receiver a line * from the current point of the path back to the starting point * of the sub path. * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void close() { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); Gdip.GraphicsPath_CloseFigure(handle); /* * Feature in GDI+. CloseFigure() does affect the last * point, so GetLastPoint() does not return the starting * point of the subpath after calling CloseFigure(). The * fix is to remember the subpath starting point and use * it instead. */ currentPoint.X = startPoint.X; currentPoint.Y = startPoint.Y; } /** * Returns <code>true</code> if the specified point is contained by * the receiver and false otherwise. * <p> * If outline is <code>true</code>, the point (x, y) checked for containment in * the receiver's outline. If outline is <code>false</code>, the point is * checked to see if it is contained within the bounds of the (closed) area * covered by the receiver. * * @param x the x coordinate of the point to test for containment * @param y the y coordinate of the point to test for containment * @param gc the GC to use when testing for containment * @param outline controls wether to check the outline or contained area of the path * @return <code>true</code> if the path contains the point and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the gc is null</li> * <li>ERROR_INVALID_ARGUMENT - if the gc has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public boolean contains(float x, float y, GC gc, boolean outline) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (gc == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); //TODO - should use GC transformation gc.initGdip(outline, false); int mode = OS.GetPolyFillMode(gc.handle) == OS.WINDING ? Gdip.FillModeWinding : Gdip.FillModeAlternate; Gdip.GraphicsPath_SetFillMode(handle, mode); if (outline) { return Gdip.GraphicsPath_IsOutlineVisible(handle, x, y, gc.data.gdipPen, gc.data.gdipGraphics); } else { return Gdip.GraphicsPath_IsVisible(handle, x, y, gc.data.gdipGraphics); } } /** * Adds to the receiver a cubic bezier curve based on the parameters. * * @param cx1 the x coordinate of the first control point of the spline * @param cy1 the y coordinate of the first control of the spline * @param cx2 the x coordinate of the second control of the spline * @param cy2 the y coordinate of the second control of the spline * @param x the x coordinate of the end point of the spline * @param y the y coordinate of the end point of the spline * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void cubicTo(float cx1, float cy1, float cx2, float cy2, float x, float y) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); Gdip.GraphicsPath_AddBezier(handle, currentPoint.X, currentPoint.Y, cx1, cy1, cx2, cy2, x, y); Gdip.GraphicsPath_GetLastPoint(handle, currentPoint); } /** * Disposes of the operating system resources associated with * the Path. Applications must dispose of all Paths that * they allocate. */ public void dispose() { if (handle == 0) return; if (device.isDisposed()) return; Gdip.GraphicsPath_delete(handle); handle = 0; if (device.tracking) device.dispose_Object(this); device = null; } /** * Replaces the first four elements in the parameter with values that * describe the smallest rectangle that will completely contain the * receiver (i.e. the bounding box). * * @param bounds the array to hold the result * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> * <li>ERROR_INVALID_ARGUMENT - if the parameter is too small to hold the bounding box</li> * </ul> * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void getBounds(float[] bounds) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (bounds == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (bounds.length < 4) SWT.error(SWT.ERROR_INVALID_ARGUMENT); RectF rect = new RectF(); Gdip.GraphicsPath_GetBounds(handle, rect, 0, 0); bounds[0] = rect.X; bounds[1] = rect.Y; bounds[2] = rect.Width; bounds[3] = rect.Height; } /** * Replaces the first two elements in the parameter with values that * describe the current point of the path. * * @param point the array to hold the result * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parameter is null</li> * <li>ERROR_INVALID_ARGUMENT - if the parameter is too small to hold the end point</li> * </ul> * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void getCurrentPoint(float[] point) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (point.length < 2) SWT.error(SWT.ERROR_INVALID_ARGUMENT); point[0] = currentPoint.X; point[1] = currentPoint.Y; } /** * Returns a device independent representation of the receiver. * * @return the PathData for the receiver * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> * * @see PathData */ public PathData getPathData() { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); int count = Gdip.GraphicsPath_GetPointCount(handle); byte[] gdipTypes = new byte[count]; float[] points = new float[count * 2]; Gdip.GraphicsPath_GetPathTypes(handle, gdipTypes, count); Gdip.GraphicsPath_GetPathPoints(handle, points, count); byte[] types = new byte[count * 2]; int index = 0, typesIndex = 0; while (index < count) { byte type = gdipTypes[index]; boolean close = false; switch (type & Gdip.PathPointTypePathTypeMask) { case Gdip.PathPointTypeStart: types[typesIndex++] = SWT.PATH_MOVE_TO; close = (type & Gdip.PathPointTypeCloseSubpath) != 0; index += 1; break; case Gdip.PathPointTypeLine: types[typesIndex++] = SWT.PATH_LINE_TO; close = (type & Gdip.PathPointTypeCloseSubpath) != 0; index += 1; break; case Gdip.PathPointTypeBezier: types[typesIndex++] = SWT.PATH_CUBIC_TO; close = (gdipTypes[index + 2] & Gdip.PathPointTypeCloseSubpath) != 0; index += 3; break; default: index++; } if (close) { types[typesIndex++] = SWT.PATH_CLOSE; } } if (typesIndex != types.length) { byte[] newTypes = new byte[typesIndex]; System.arraycopy(types, 0, newTypes, 0, typesIndex); types = newTypes; } PathData result = new PathData(); result.types = types; result.points = points; return result; } /** * Adds to the receiver a line from the current point to * the point specified by (x, y). * * @param x the x coordinate of the end of the line to add * @param y the y coordinate of the end of the line to add * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void lineTo(float x, float y) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); Gdip.GraphicsPath_AddLine(handle, currentPoint.X, currentPoint.Y, x, y); Gdip.GraphicsPath_GetLastPoint(handle, currentPoint); } /** * Returns <code>true</code> if the Path has been disposed, * and <code>false</code> otherwise. * <p> * This method gets the dispose state for the Path. * When a Path has been disposed, it is an error to * invoke any other method using the Path. * * @return <code>true</code> when the Path is disposed, and <code>false</code> otherwise */ public boolean isDisposed() { return handle == 0; } /** * Sets the current point of the receiver to the point * specified by (x, y). Note that this starts a new * sub path. * * @param x the x coordinate of the new end point * @param y the y coordinate of the new end point * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void moveTo(float x, float y) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); currentPoint.X = startPoint.X = x; currentPoint.Y = startPoint.Y = y; } /** * Adds to the receiver a quadratic curve based on the parameters. * * @param cx the x coordinate of the control point of the spline * @param cy the y coordinate of the control point of the spline * @param x the x coordinate of the end point of the spline * @param y the y coordinate of the end point of the spline * * @exception SWTException <ul> * <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li> * </ul> */ public void quadTo(float cx, float cy, float x, float y) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); float cx1 = currentPoint.X + 2 * (cx - currentPoint.X) / 3; float cy1 = currentPoint.Y + 2 * (cy - currentPoint.Y) / 3; float cx2 = cx1 + (x - currentPoint.X) / 3; float cy2 = cy1 + (y - currentPoint.Y) / 3; Gdip.GraphicsPath_AddBezier(handle, currentPoint.X, currentPoint.Y, cx1, cy1, cx2, cy2, x, y); Gdip.GraphicsPath_GetLastPoint(handle, currentPoint); } /** * Returns a string containing a concise, human-readable * description of the receiver. * * @return a string representation of the receiver */ public String toString() { if (isDisposed()) return "Path {*DISPOSED*}"; return "Path {" + handle + "}"; } }
ecoo-app/ecoo-backend
apps/verification/migrations/0025_auto_20200915_1450.py
# Generated by Django 3.1 on 2020-09-15 14:50 from django.db import migrations from apps.verification.models import UserVerification def update_user_verifications(apps, schema_editor): UserVerification.objects.filter(address_street__isnull=True).update( address_street="no_street" ) UserVerification.objects.filter(address_town__isnull=True).update( address_town="no_town" ) UserVerification.objects.filter(address_postal_code__isnull=True).update( address_postal_code="no_postal_code" ) class Migration(migrations.Migration): dependencies = [ ("verification", "0024_auto_20200915_1347"), ] operations = [ migrations.RunPython(update_user_verifications), ]
tossp/teaweb-core
teaweb/actions/default/agents/agentutils/menu.go
package agentutils import ( "fmt" "github.com/TeaWeb/code/teaconfigs/agents" "github.com/TeaWeb/code/teaweb/actions/default/notices/noticeutils" "github.com/TeaWeb/code/teaweb/utils" "github.com/iwind/TeaGo/actions" "github.com/iwind/TeaGo/lists" "net/http" ) func AddTabbar(actionWrapper actions.ActionWrapper) { if actionWrapper.Object().Request.Method != http.MethodGet { return } action := actionWrapper.Object() action.Data["teaMenu"] = "agents" // 子菜单 menuGroup := utils.NewMenuGroup() agentId := action.ParamString("agentId") if len(agentId) == 0 { agentId = "local" } actionCode := "board" if action.HasPrefix("/agents/apps") { actionCode = "apps" } else if action.HasPrefix("/agents/settings") { actionCode = "settings" } else if action.HasPrefix("/agents/delete") { actionCode = "delete" } else if action.HasPrefix("/agents/notices") { actionCode = "notices" } state, isWaiting := CheckAgentIsWaiting("local") topSubName := "" if lists.ContainsAny([]string{"/agents/board", "/agents/menu"}, action.Request.URL.Path) { topSubName = "" } menu := menuGroup.FindMenu("", "默认分组"+topSubName) if isWaiting { subName := "已连接" if state != nil && len(state.OsName) > 0 { subName = state.OsName } item := menu.Add("本地", subName, "/agents/"+actionCode+"?agentId=local", agentId == "local" && !action.HasPrefix("/agents/addAgent", "/agents/cluster/add", "/agents/groups")) item.SubColor = "green" } else { menu.Add("本地", "", "/agents/"+actionCode+"?agentId=local", agentId == "local" && !action.HasPrefix("/agents/addAgent", "/agents/cluster/add", "/agents/groups")) } // agent列表 allAgents := agents.SharedAgents() counterMapping := map[string]int{} // groupId => count maxCount := 50 for _, agent := range allAgents { state, isWaiting := CheckAgentIsWaiting(agent.Id) var menu *utils.Menu = nil if len(agent.GroupIds) > 0 { group := agents.SharedGroupConfig().FindGroup(agent.GroupIds[0]) if group == nil { menu = menuGroup.FindMenu("", "默认分组"+topSubName) } else { menu = menuGroup.FindMenu(group.Id, group.Name) menu.Index = group.Index // 计算数量 _, found := counterMapping[group.Id] if found { counterMapping[group.Id]++ } else { counterMapping[group.Id] = 1 } if counterMapping[group.Id] > maxCount { if counterMapping[group.Id] == maxCount+1 { menu.AddSpecial("[更多主机]", "", "/agents/groups/detail?groupId="+group.Id, false) } continue } } } else { menu = menuGroup.FindMenu("", "默认分组"+topSubName) // 计算数量 groupId := "" _, found := counterMapping[groupId] if found { counterMapping[groupId]++ } else { counterMapping[groupId] = 1 } if counterMapping[groupId] > maxCount { if counterMapping[groupId] == maxCount+1 { menu.AddSpecial("[更多主机]", "", "/agents/groups/detail?groupId="+groupId, false) } continue } } if isWaiting { subName := "已连接" if state != nil && len(state.OsName) > 0 { subName = state.OsName } item := menu.Add(agent.Name, subName, "/agents/"+actionCode+"?agentId="+agent.Id, agentId == agent.Id) item.Id = agent.Id item.IsSortable = true item.SubColor = "green" } else if !agent.On { item := menu.Add(agent.Name, "未启用", "/agents/"+actionCode+"?agentId="+agent.Id, agentId == agent.Id) item.Id = agent.Id item.IsSortable = true } else { item := menu.Add(agent.Name, "", "/agents/"+actionCode+"?agentId="+agent.Id, agentId == agent.Id) item.Id = agent.Id item.IsSortable = true } } // 操作按钮 { menu := menuGroup.FindMenu("operations", "[操作]") menu.AlwaysActive = true menu.Index = 10000 menu.Add("[添加新主机]", "", "/agents/addAgent", action.HasPrefix("/agents/addAgent", "/agents/cluster/add")) menu.Add("[分组管理]", "", "/agents/groups", action.HasPrefix("/agents/groups")) } menuGroup.Sort() utils.SetSubMenu(action, menuGroup) // Tabbar if !action.HasPrefix("/agents/addAgent", "/agents/cluster/add", "/agents/groups") { agent := agents.NewAgentConfigFromId(agentId) if agent != nil { tabbar := utils.NewTabbar() // 看板和Apps tabbar.Add("看板", "", "/agents/board?agentId="+agentId, "dashboard", action.HasPrefix("/agents/board")) tabbar.Add("Apps", fmt.Sprintf("%d", len(agent.Apps)), "/agents/apps?agentId="+agentId, "gem outline", action.HasPrefix("/agents/apps")) // 通知 countUnreadNotices := noticeutils.CountUnreadNoticesForAgent(agentId) if countUnreadNotices > 0 { tabbar.Add("通知", fmt.Sprintf("%d", countUnreadNotices), "/agents/notices?agentId="+agentId, "bell blink orange", action.HasPrefix("/agents/notices")) } else { tabbar.Add("通知", fmt.Sprintf("%d", countUnreadNotices), "/agents/notices?agentId="+agentId, "bell", action.HasPrefix("/agents/notices")) } // 设置和删除 tabbar.Add("设置", "", "/agents/settings?agentId="+agentId, "setting", action.HasPrefix("/agents/settings")) if agentId != "local" { tabbar.Add("删除", "", "/agents/delete?agentId="+agentId, "trash", action.HasPrefix("/agents/delete")) } utils.SetTabbar(actionWrapper, tabbar) } } }
paranoid-software/elemental-cms
elementalcms/management/staticcommands/__init__.py
<reponame>paranoid-software/elemental-cms from .list import List from .collect import Collect from .delete import Delete
sebakir/HrmsProject
demo/src/main/java/com/example/core/utilities/imageUpload/ImageUploadManager.java
package com.example.core.utilities.imageUpload; import java.io.IOException; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.cloudinary.Cloudinary; import com.cloudinary.utils.ObjectUtils; import com.example.core.utilities.results.DataResult; import com.example.core.utilities.results.ErrorDataResult; import com.example.core.utilities.results.SuccessDataResult; @Service public class ImageUploadManager implements ImageUploadService { private Cloudinary cloudinary; public ImageUploadManager() { this.cloudinary = new Cloudinary(ObjectUtils.asMap("cloud_name", "dayx2sam5", "api_key", "699443261618643", "api_secret", "<KEY>")); } @Override public DataResult<Map> uploadImageFile(MultipartFile imageFile) { try { @SuppressWarnings("unchecked") Map<String, String> resultMap = (Map<String, String>) cloudinary.uploader().upload(imageFile.getBytes(), ObjectUtils.emptyMap()); return new SuccessDataResult<Map>(resultMap); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ErrorDataResult<Map>(); } }
liusoon/TestAdmin
model/vo/casestepinfovo.go
package vo import "salotto/model/InterfaceTestPartEntity" type CaseStepInfoVO struct { CaseId string `json:"caseId"` ItfId string `json:"interfaceId"` StepId string `json:"stepId"` StepStatus string `json:"stepStatus"` StepLog string `json:"stepLog"` StepNum int `json:"stepNum"` StepName string `json:"stepName"` StepDesc string `json:"stepDesc"` ReqData string `json:"reqData"` ExpRes string `json:"expRes"` Variables []InterfaceTestPartEntity.TCaseStepVarInfo `json:"variables"` //CollectCol string `json:"collectCol"` //CollectColAlias string `json:"collectColAlias"` AssertInfos []InterfaceTestPartEntity.TAssertInfo `json:"assertInfos"` //AssertCol string `json:"assertCol"` //Method string `json:"method"` //ExpValue string `json:"expValue"` }
LegatAbyssWalker/Minecraft-Clone
Minecraft Clone/RayCasting.h
#ifndef RAYCASTING_H #define RAYCASTING_H #include "State.h" #include "Camera.h" #include "GLWindow.h" #include <iostream> #include <algorithm> class RayCasting { public: RayCasting(GLWindow& glWindow, Camera& cam, glm::mat4 projection); void update(); glm::vec3 calculateMouseRay(); glm::vec3 toWorldCoords(glm::vec4 eyeCoords); glm::vec4 toEyeCoords(glm::vec4 clipCoords); glm::vec2 getNormalizedDeviceCoordinates(GLfloat mouseX, GLfloat mouseY); glm::vec3 getCurrentRay() { return currentRay; } private: Camera& camera; GLWindow& glWindow; glm::vec3 currentRay; glm::mat4 projectionMatrix; glm::mat4 viewMatrix; }; #endif
johnoliver/ApplicationInsights-Java
test/smoke/testApps/SystemExit/src/smokeTest/java/com/microsoft/applicationinsights/smoketest/SpringBootAutoTest.java
package com.microsoft.applicationinsights.smoketest; import java.util.List; import com.microsoft.applicationinsights.internal.schemav2.MessageData; import org.junit.Test; import static org.junit.Assert.*; @UseAgent public class SpringBootAutoTest extends AiSmokeTest { @Test @TargetUri("/delayedSystemExit") public void doDelayedSystemExitTest() throws Exception { mockedIngestion.waitForItems("RequestData", 1); mockedIngestion.waitForItems("MessageData", 1); List<MessageData> messageData = mockedIngestion.getTelemetryDataByType("MessageData"); assertEquals(1, messageData.size()); assertEquals("this is an error right before shutdown", messageData.get(0).getMessage()); } }
jacobkim9881/shoppingweb
src/components/router/Nav.js
import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom' import styled from 'styled-components' import Home from '../../pages/Home' import Test from '../../pages/Test' import Item from '../../pages/Item' import JoinIn from '../../pages/JoinIn' import Dress from './Dress' import Edit from '../../pages/EditId' import Admin from '../../pages/Admin' import ButtonGroup from 'react-bootstrap/ButtonGroup' import NavButton from './NavButton' const arr = ["", "dress", "test"]; class Nav extends Component { render() { return ( <Main> <Navigation> <ButtonGroup> <Ul> {/*Mapping list array to NavButton component of Routher Link */} {arr.map(path => <NavButton link={path} />)} </Ul> </ButtonGroup> </Navigation> {/*To add lists you should add a component in Route after adding list in the array */} <Switch> <Route path="/admin" children={<Admin />} /> <Route path="/edit/:id" children={<Edit />} /> <Route path="/join" children={<JoinIn />} /> <Route path="/dress"> <Dress /> </Route> <Route path="/test"> <Test /> </Route> <Route path="/item"> <Item /> </Route> <Route path="/"> <Home /> </Route> </Switch> </Main> ); } } export default Nav; //constants under here are for style sheet. const Navigation = styled.nav` height: 3rem; top: 2rem; display: block; z-index: 1; position: fixed; ` const Ul = styled.ul` list-style-type: none; margin: 0; padding: 0; ` const Main = styled.div` margin: 0 auto; width: 70%; `
DaedalusGame/RequiousFrakto
src/main/java/requious/util/battery/BatteryAccessFE.java
package requious.util.battery; import net.minecraft.item.ItemStack; import net.minecraftforge.energy.IEnergyStorage; public class BatteryAccessFE implements IBatteryAccess { ItemStack battery; IEnergyStorage storage; public BatteryAccessFE(ItemStack battery, IEnergyStorage storage) { this.battery = battery; this.storage = storage; } @Override public int getMaxEnergyStored() { return storage.getMaxEnergyStored(); } @Override public int getEnergyStored() { return storage.getEnergyStored(); } @Override public int receiveEnergy(int maxReceive, boolean simulate) { return storage.receiveEnergy(maxReceive,simulate); } @Override public int extractEnergy(int maxExtract, boolean simulate) { return storage.extractEnergy(maxExtract,simulate); } @Override public ItemStack getStack() { return battery; } }
igncp/diagrams-collection
src/js/diagrams/Layer/helpers/dataFromSpecificToGeneral.js
<filename>src/js/diagrams/Layer/helpers/dataFromSpecificToGeneral.js import { forEach, isEmpty, merge } from "ramda" import { diagramName } from "../constants" import { removeUndefined } from "../../../utils/pure" const generateRecursiveFnState = () => { return { connections: [], finalItems: [], idCounter: -1, } } const createGeneralItem = ({ description, name }, item, state) => { return removeUndefined({ description, graphsData: merge( item.graphsData || {}, { [diagramName]: removeUndefined({ id: item.id, relationships: item.options, }) } ), id: ++state.idCounter, name: name || item.fullText, }) } const recursiveFn = (state, items, generalItemParent) => { const { connections, finalItems } = state forEach((item) => { const firstOccurrence = /(\. |:)/.exec(item.fullText) let name, description if (firstOccurrence) { const splittedText = item.fullText.split(firstOccurrence[0]) name = splittedText[0] description = splittedText.slice(1).join(firstOccurrence) } const generalItem = createGeneralItem({ description, name }, item, state) finalItems.push(generalItem) if (generalItemParent) { connections.push({ from: generalItem.id, to: generalItemParent.id, }) } if (item.items && item.items.length > 0) recursiveFn(state, item.items, generalItem) }, items) } export default (conf) => { const state = generateRecursiveFnState() if (!isEmpty(conf)) recursiveFn(state, [conf]) return { connections: state.connections, items: state.finalItems, } }
brian220/Sketch2PointCloud
configs/config_ui.py
<gh_stars>1-10 # -*- coding: utf-8 -*- # # Developed by <NAME> <<EMAIL>> from easydict import EasyDict as edict __C = edict() cfg = __C # # GraphX # __C.GRAPHX = edict() __C.GRAPHX.USE_GRAPHX = True __C.GRAPHX.NUM_INIT_POINTS = 2048 __C.GRAPHX.RETURN_IMG_FEATURES = False # # Common # __C.CONST = edict() __C.CONST.DEVICE = [0] __C.CONST.DEVICE_NUM = 1 __C.CONST.RNG_SEED = 0 __C.CONST.IMG_W = 224 # Image width for input __C.CONST.IMG_H = 224 # Image height for input __C.CONST.BATCH_SIZE = 8 __C.CONST.BIN_SIZE = 15 __C.CONST.NUM_POINTS = 2048 __C.CONST.WEIGHTS = '/media/caig/FECA2C89CA2C406F/sketch3D/sketch_part_rec/output/checkpoints/ckpt-epoch-0600.pth' # # Refiner # __C.REFINE = edict() __C.REFINE.USE_PRETRAIN_GENERATOR = True __C.REFINE.GENERATOR_WEIGHTS = '/media/caig/FECA2C89CA2C406F/sketch3D/results/outputs/output_v39/checkpoints/best-gan-ckpt.pth' __C.REFINE.GENERATOR_TYPE = 'GAN' __C.REFINE.START_EPOCH = 1000 __C.REFINE.RANGE_MAX = 0.2 __C.REFINE.LEARNING_RATE = 1e-3 __C.REFINE.NOISE_LENGTH = 32 # # Application Settings # __C.INFERENCE = edict() # Ten references reference1_id = '1e283319d1f2782ff2c92c2a4f65876' reference2_id = '3b88922c44e2311519fb4103277a6b93' reference3_id = '27c00ec2b6ec279958e80128fd34c2b1' reference4_id = '4231883e92a3c1a21c62d11641ffbd35' reference5_id = 'f1dac1909107c0eef51f77a6d7299806' reference6_id = '1ab4c6ef68073113cf004563556ddb36' reference7_id = '1aeb17f89e1bea954c6deb9ede0648df' reference8_id = '484f0070df7d5375492d9da2668ec34c' reference9_id = '8f2cc8ff68f3208ec935dd3bb5739fc' reference10_id = '717e28c855c935c94d2d89cc1fd36fca' __C.INFERENCE.REFERENCE1_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference1_id + ".ply" __C.INFERENCE.REFERENCE2_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference2_id + ".ply" __C.INFERENCE.REFERENCE3_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference3_id + ".ply" __C.INFERENCE.REFERENCE4_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference4_id + ".ply" __C.INFERENCE.REFERENCE5_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference5_id + ".ply" __C.INFERENCE.REFERENCE6_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference6_id + ".ply" __C.INFERENCE.REFERENCE7_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference7_id + ".ply" __C.INFERENCE.REFERENCE8_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference8_id + ".ply" __C.INFERENCE.REFERENCE9_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference9_id + ".ply" __C.INFERENCE.REFERENCE10_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/dataset/shape_net_core_uniform_samples_2048/03001627/" + reference10_id + ".ply" __C.INFERENCE.REFERENCE1_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference1_id + "/render_0.png" __C.INFERENCE.REFERENCE2_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference2_id + "/render_5.png" __C.INFERENCE.REFERENCE3_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference3_id + "/render_17.png" __C.INFERENCE.REFERENCE4_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference4_id + "/render_4.png" __C.INFERENCE.REFERENCE5_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference5_id + "/render_12.png" __C.INFERENCE.REFERENCE6_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference6_id + "/render_17.png" __C.INFERENCE.REFERENCE7_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference7_id + "/render_8.png" __C.INFERENCE.REFERENCE8_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference8_id + "/render_11.png" __C.INFERENCE.REFERENCE9_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference9_id + "/render_3.png" __C.INFERENCE.REFERENCE10_ICON_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D/drc/shapenet_obj_render/blenderRenderPreprocess/03001627/" + reference10_id + "/render_12.png" __C.INFERENCE.SKETCH_3D_UI_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/" __C.INFERENCE.TEST_SAMPLES_FOLDER = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/test_samples/" __C.INFERENCE.ICONS_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/icons/" # Cache path __C.INFERENCE.CACHE_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/" __C.INFERENCE.SCREENSHOT_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/screenshot_image.png" __C.INFERENCE.SKETCH_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/sketch_image.png" __C.INFERENCE.REFINE_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/refine_image.png" __C.INFERENCE.EMPTY_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/empty_image.png" __C.INFERENCE.UPDATE_IMAGE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/imgs/update_image.png" __C.INFERENCE.CACHE_POINT_CLOUD_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/cache/pcs/" __C.INFERENCE.USER_EVALUATION_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/user_evaluation/" __C.INFERENCE.GENERATOR_WEIGHTS = "/media/caig/FECA2C89CA2C406F/sketch3D/results/outputs/output_v39/checkpoints/best-gan-ckpt.pth" __C.INFERENCE.REFINER_WEIGHTS = "/media/caig/FECA2C89CA2C406F/sketch3D/results/outputs/output_v44/checkpoints/best-refine-ckpt.pth" # Opitimize __C.INFERENCE.OPTIMIZE_PATH = "/media/caig/FECA2C89CA2C406F/sketch3D_final/sketch_part_rec/sketch_3d_ui/optimize_path"
bgruening/bcbb
nextgen/scripts/barcode_sort_trim.py
<filename>nextgen/scripts/barcode_sort_trim.py #!/usr/bin/env python """Identify fastq reads with barcodes, trimming and sorting for downstream work. Given a fastq file or pair of fastq files containing barcodes, this identifies the barcode in each read and writes it into a unique file. Mismatches are allowed and barcode position within the reads can be specified. Usage: barcode_sort_trim.py <barcode file> <out format> <in file> [<pair file>] --mismatch=n (number of allowed mismatches, default 1) --bc_offset=n (an offset into the read where the barcode starts (5' barcode) or ends (3' barcode)) --read=n Integer read number containing the barcode (default to 1) --five (barcode is on the 5' end of the sequence, default to 3') --noindel (disallow insertion/deletions on barcode matches) --quiet (do not print out summary information on tags) --tag_title (append matched barcode to sequence header) <barcode file> is a text file of: <name> <sequence> for all barcodes present in the fastq multiplex. <out format> specifies how the output files should be written: 1_100721_FC626DUAAX_--b--_--r--_fastq.txt It should contain two values for substitution: --b-- Location of the barcode identifier --r-- Location of the read number (1 or 2) This can be used to specify any output location: /your/output/dir/out_--b--_--r--.txt Requires: Python -- versions 2.6 or 2.7 Biopython -- http://biopython.org """ from __future__ import with_statement import sys import os import itertools import unittest import collections import csv from optparse import OptionParser from Bio import pairwise2 from Bio.SeqIO.QualityIO import FastqGeneralIterator def main(barcode_file, out_format, in1, in2, in3, mismatch, bc_offset, bc_read_i, three_end, allow_indels, metrics_file, verbose, tag_title): barcodes = read_barcodes(barcode_file) stats = collections.defaultdict(int) out_writer = output_to_fastq(out_format) for (name1, seq1, qual1), (name2, seq2, qual2), (name3, seq3, qual3) in itertools.izip( read_fastq(in1), read_fastq(in2), read_fastq(in3)): end_gen = end_generator(seq1, seq2, seq3, bc_read_i, three_end, bc_offset) bc_name, bc_seq, match_seq = best_match(end_gen, barcodes, mismatch, allow_indels) seq1, qual1, seq2, qual2, seq3, qual3 = remove_barcode( seq1, qual1, seq2, qual2, seq3, qual3, match_seq, bc_read_i, three_end, bc_offset) if tag_title: name1 += " %s" % match_seq name2 += " %s" % match_seq name3 += " %s" % match_seq out_writer(bc_name, name1, seq1, qual1, name2, seq2, qual2, name3, seq3, qual3) stats[bc_name] += 1 sort_bcs = [] for bc in stats.keys(): try: sort_bc = float(bc) except ValueError: sort_bc = str(bc) sort_bcs.append((sort_bc, bc)) sort_bcs.sort() sort_bcs = [s[1] for s in sort_bcs] if verbose: print "% -10s %s" % ("barcode", "count") for bc in sort_bcs: print "% -10s %s" % (bc, stats[bc]) print "% -10s %s" % ("total", sum(stats.values())) if metrics_file: with open(metrics_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") for bc in sort_bcs: writer.writerow([bc, stats[bc]]) def best_match(end_gen, barcodes, mismatch, allow_indels=True): """Identify barcode best matching to the test sequence, with mismatch. Returns the barcode id, barcode sequence and match sequence. unmatched is returned for items which can't be matched to a barcode within the provided parameters. """ if len(barcodes) == 1 and barcodes.values() == ["trim"]: size = len(barcodes.keys()[0]) test_seq = end_gen(size) return barcodes.values()[0], test_seq, test_seq # easiest, fastest case -- exact match sizes = list(set(len(b) for b in barcodes.keys())) for s in sizes: test_seq = end_gen(s) try: bc_id = barcodes[test_seq] return bc_id, test_seq, test_seq except KeyError: pass # check for best approximate match within mismatch values match_info = [] if mismatch > 0 or _barcode_has_ambiguous(barcodes): for bc_seq, bc_id in barcodes.iteritems(): test_seq = end_gen(len(bc_seq)) if _barcode_very_ambiguous(barcodes): gapopen_penalty = -18.0 else: gapopen_penalty = -9.0 aligns = pairwise2.align.globalms(bc_seq, test_seq, 5.0, -4.0, gapopen_penalty, -0.5, one_alignment_only=True) (abc_seq, atest_seq) = aligns[0][:2] if len(aligns) == 1 else ("", "") matches = sum(1 for i, base in enumerate(abc_seq) if (base == atest_seq[i] or base == "N")) gaps = abc_seq.count("-") cur_mismatch = len(test_seq) - matches + gaps if cur_mismatch <= mismatch and (allow_indels or gaps == 0): match_info.append((cur_mismatch, bc_id, abc_seq, atest_seq)) if len(match_info) > 0: match_info.sort() name, bc_seq, test_seq = match_info[0][1:] return name, bc_seq.replace("-", ""), test_seq.replace("-", "") else: return "unmatched", "", "" def _barcode_very_ambiguous(barcodes): max_size = max(len(x) for x in barcodes.keys()) max_ns = max(x.count("N") for x in barcodes.keys()) return float(max_ns) / float(max_size) > 0.5 def _barcode_has_ambiguous(barcodes): for seq in barcodes.keys(): if "N" in seq: return True return False def end_generator(seq1, seq2=None, seq3=None, bc_read_i=1, three_end=True, bc_offset=0): """Function which pulls a barcode of a provided size from paired seqs. This respects the provided details about location of the barcode, returning items of the specified size to check against the read. """ seq_choice = {1: seq1, 2: seq2, 3: seq3} seq = seq_choice[bc_read_i] assert seq is not None def _get_end(size): assert size > 0 if three_end: return seq[-size-bc_offset:len(seq)-bc_offset] else: return seq[bc_offset:size+bc_offset] return _get_end def _remove_from_end(seq, qual, match_seq, three_end, bc_offset): if match_seq: if three_end: assert seq[-len(match_seq)-bc_offset:len(seq)-bc_offset] == match_seq seq = seq[:-len(match_seq)-bc_offset] qual = qual[:-len(match_seq)-bc_offset] else: assert seq[bc_offset:len(match_seq)+bc_offset] == match_seq seq = seq[len(match_seq)+bc_offset:] qual = qual[len(match_seq)+bc_offset:] return seq, qual def remove_barcode(seq1, qual1, seq2, qual2, seq3, qual3, match_seq, bc_read_i, three_end, bc_offset=0): """Trim found barcode from the appropriate sequence end. """ if bc_read_i == 1: seq1, qual1 = _remove_from_end(seq1, qual1, match_seq, three_end, bc_offset) elif bc_read_i == 2: assert seq2 and qual2 seq2, qual2 = _remove_from_end(seq2, qual2, match_seq, three_end, bc_offset) else: assert bc_read_i == 3 assert seq3 and qual3 seq3, qual3 = _remove_from_end(seq3, qual3, match_seq, three_end, bc_offset) return seq1, qual1, seq2, qual2, seq3, qual3 def _write_to_handles(name, seq, qual, fname, out_handles): try: out_handle = out_handles[fname] except KeyError: out_handle = open(fname, "w") out_handles[fname] = out_handle out_handle.write("@%s\n%s\n+\n%s\n" % (name, seq, qual)) def output_to_fastq(output_base): """Write a set of paired end reads as fastq, managing output handles. """ work_dir = os.path.dirname(output_base) if not os.path.exists(work_dir) and work_dir: try: os.makedirs(work_dir) except OSError: assert os.path.isdir(work_dir) out_handles = dict() def write_reads(barcode, name1, seq1, qual1, name2, seq2, qual2, name3, seq3, qual3): read1name = output_base.replace("--r--", "1").replace("--b--", barcode) _write_to_handles(name1, seq1, qual1, read1name, out_handles) if seq2: read2name = output_base.replace("--r--", "2").replace("--b--", barcode) _write_to_handles(name2, seq2, qual2, read2name, out_handles) if seq3: read3name = output_base.replace("--r--", "3").replace("--b--", barcode) _write_to_handles(name3, seq3, qual3, read3name, out_handles) return write_reads def read_barcodes(fname): barcodes = {} with open(fname) as in_handle: for line in (l for l in in_handle if not l.startswith("#")): name, seq = line.rstrip("\r\n").split() barcodes[seq] = name return barcodes def read_fastq(fname): """Provide read info from fastq file, potentially not existing. """ if fname: with open(fname) as in_handle: for info in FastqGeneralIterator(in_handle): yield info else: for info in itertools.repeat(("", None, None)): yield info # --- Testing code: run with 'nosetests -v -s barcode_sort_trim.py' class BarcodeTest(unittest.TestCase): """Test identification and removal of barcodes with local alignments. """ def setUp(self): self.barcodes = {"CGATGT": "2", "CAGATC": "7", "TTAGGCATC": "8"} def test_1_end_generator(self): """Ensure the proper end is returned for sequences. """ seq1, seq2 = ("AAATTT", "GGGCCC") end_gen = end_generator(seq1, seq2, None, 1, True) assert end_gen(3) == "TTT" end_gen = end_generator(seq1, seq2, None, 1, False) assert end_gen(3) == "AAA" assert end_gen(4) == "AAAT" end_gen = end_generator(seq1, seq2, None, 2, True) assert end_gen(3) == "CCC" end_gen = end_generator(seq1, seq2, None, 2, False) assert end_gen(3) == "GGG" # Test end generation with an offset end_gen = end_generator(seq1, seq2, None, 1, True,1) assert end_gen(3) == "ATT" end_gen = end_generator(seq1, seq2, None, 1, False,1) assert end_gen(3) == "AAT" assert end_gen(4) == "AATT" end_gen = end_generator(seq1, seq2, None, 2, True,1) assert end_gen(3) == "GCC" end_gen = end_generator(seq1, seq2, None, 2, False,1) def test_2_identical_match(self): """Ensure we can identify identical barcode matches. """ bc_id, seq, _ = best_match(end_generator("CGATGT"), self.barcodes, 0) assert bc_id == "2" assert seq == "CGATGT" def test_3_allowed_mismatch(self): """Identify barcodes with the allowed number of mismatches. """ # 1 and 2 mismatches (bc_id, _, _) = best_match(end_generator("CGTTGT"), self.barcodes, 1) assert bc_id == "2" # with indels permitted, accepts 2 mismatches, even if "1" is specified (bc_id, _, _) = best_match(end_generator("CGAAGT"), self.barcodes, 1) assert bc_id == "2" (bc_id, _, _) = best_match(end_generator("GCATGT"), self.barcodes, 2) assert bc_id == "2" # single gap insertion (bc_id, _, _) = best_match(end_generator("GATTGT"), self.barcodes, 1) # single gap deletion (bc_id, _, _) = best_match(end_generator("GCGAGT"), self.barcodes, 1) assert bc_id == "unmatched" (bc_id, _, _) = best_match(end_generator("GCGAGT"), self.barcodes, 2) assert bc_id == "2" (bc_id, _, _) = best_match(end_generator("GCGAGT"), self.barcodes, 2, False) assert bc_id == "unmatched" # too many errors (bc_id, _, _) = best_match(end_generator("GCATGT"), self.barcodes, 1) assert bc_id == "unmatched" (bc_id, _, _) = best_match(end_generator("GCTTGT"), self.barcodes, 2) assert bc_id == "unmatched" def test_4_custom_barcodes(self): """ Detect longer non-standard custom barcodes, trimming """ # Use the custom long barcode custom_barcode = dict((bc_seq, bc_id) for bc_id, bc_seq in self.barcodes.iteritems()) # Simulate an arbitrary read, attach barcode and remove it from the 3' end seq = "GATTACA" * 5 + custom_barcode["8"] (bc_id, bc_seq, match_seq) = best_match(end_generator(seq), self.barcodes, 1) (removed, _, _, _, _, _) = remove_barcode(seq, "B" * 9, seq, "g" * 9, None, None, match_seq, True, True) # Was the barcode properly identified and removed with 1 mismatch allowed ? assert bc_id == "8" assert bc_seq == match_seq assert removed == "GATTACA" * 5 def test_5_illumina_barcodes(self): """ Test that Illumina reads with a trailing A are demultiplexed correctly """ # Use the first barcode for bc_seq, bc_id in self.barcodes.items(): if bc_id == "2": break # Simulate an arbitrary read, attach barcode and add a trailing A seq = "GATTACA" * 5 + bc_seq + "A" (bc_id, bc_seq, match_seq) = best_match(end_generator(seq,None,None,1,True,1), self.barcodes, 1) (removed, _, _, _, _, _) = remove_barcode(seq, "B" * 9, seq, "g" * 9, None, None, match_seq, True, True, 1) # Was the barcode properly identified and removed with 1 mismatch allowed ? assert bc_id == "2" assert bc_seq == match_seq assert removed == "GATTACA" * 5 def test_6_ambiguous_barcodes(self): """Allow mismatch N characters in specified barcodes. """ bcs = {"CGATGN": "2", "CAGATC": "7"} (bc_id, _, _) = best_match(end_generator("CGATGT"), bcs, 0, False) assert bc_id == "2", bc_id (bc_id, _, _) = best_match(end_generator("CGATGN"), bcs, 0, False) assert bc_id == "2", bc_id (bc_id, _, _) = best_match(end_generator("CGATNT"), bcs, 0, False) assert bc_id == "unmatched", bc_id (bc_id, _, _) = best_match(end_generator("CGATNT"), bcs, 1, False) assert bc_id == "2", bc_id def test_7_very_ambiguous_barcodes(self): """Matching with highly ambiguous barcodes used for sorting.""" bcs = {"ANNNNNN": "A", "CNNNNNN": "C", "GNNNNNN": "G", "TNNNNNN": "T"} (bc_id, _, _) = best_match(end_generator("CGGGAGA", bc_offset=0), bcs, 2, True) assert bc_id == "C", bc_id (bc_id, _, _) = best_match(end_generator("GCGGGAG", bc_offset=0), bcs, 0, False) assert bc_id == "G", bc_id if __name__ == "__main__": parser = OptionParser() parser.add_option("-s", "--second", dest="deprecated_first_read", action="store_false", default=True) parser.add_option("-r", "--read", dest="bc_read_i", action="store", default=1) parser.add_option("-f", "--five", dest="three_end", action="store_false", default=True) parser.add_option("-i", "--noindel", dest="indels", action="store_false", default=True) parser.add_option("-q", "--quiet", dest="verbose", action="store_false", default=True) parser.add_option("-m", "--mismatch", dest="mismatch", default=1) parser.add_option("-b", "--bc_offset", dest="bc_offset", default=0) parser.add_option("-o", "--metrics", dest="metrics_file", default=None) parser.add_option("-t", "--tag_title", dest="tag_title", action="store_true", default=False) options, args = parser.parse_args() in2, in3 = (None, None) if len(args) == 3: barcode_file, out_format, in1 = args elif len(args) == 4: barcode_file, out_format, in1, in2 = args elif len(args) == 5: barcode_file, out_format, in1, in2, in3 = args else: print __doc__ sys.exit() # handle deprecated less general options if options.deprecated_first_read is False: options.bc_read_i = 2 main(barcode_file, out_format, in1, in2, in3, int(options.mismatch), int(options.bc_offset), int(options.bc_read_i), options.three_end, options.indels, options.metrics_file, options.verbose, options.tag_title)
max-vorabhol-zipmex/express-app
packages/ui/src/components/PriceChart/ApexChartContainer.js
import { connect } from 'react-redux'; import get from 'lodash/get'; import ApexChartComponent from './ApexChartComponent'; import { changeTickersInterval } from '../../redux/actions/tickersActions'; import config from '../../config'; import { selectedInstrumentSelector, instrumentSelectorInstruments } from '../../redux/selectors/instrumentPositionSelectors'; const { locale } = config.global; const mapStateToProps = state => { const { tickers, level1, level2, product: { decimalPlaces } } = state; const selectedInstrument = selectedInstrumentSelector(state); const selectedInstrumentId = selectedInstrument.InstrumentId; const instruments = instrumentSelectorInstruments(state); const { Product2Symbol } = instruments.find( i => i.InstrumentId === selectedInstrumentId ) || { Product2Symbol: '' }; const marketPrice = selectedInstrumentId && level1[selectedInstrumentId] ? level1[selectedInstrumentId].LastTradedPx : 0; const precision = get(decimalPlaces, Product2Symbol); return { precision, locale, chartData: { level2, tickers, marketPrice } }; }; const mapDispatchToProps = { changeTickersInterval }; export default connect( mapStateToProps, mapDispatchToProps )(ApexChartComponent);
printercu/rails_stuff
lib/rails_stuff/generators/concern/concern_generator.rb
require 'rails/generators' module RailsStuff module Generators class ConcernGenerator < Rails::Generators::NamedBase # :nodoc: argument :base, type: :string, required: false, banner: 'Base dir with the class', description: 'Use it when class is not inside app/models or app/controllers.' namespace 'rails:concern' source_root File.expand_path('../templates', __FILE__) def create_concern_files template 'concern.rb', File.join(base_path, "#{file_path}.rb") end private def base_path base || file_path.include?('_controller/') ? 'app/controllers' : 'app/models' end end end end
mehrdad-shokri/iot-core-azure-dm-client
src/DMMessage/Models/DeviceHealthAttestation.h
<reponame>mehrdad-shokri/iot-core-azure-dm-client<gh_stars>10-100 /* Copyright 2017 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "IRequestIResponse.h" #include "SerializationHelper.h" #include "DMMessageKind.h" #include "StatusCodeResponse.h" #include "Blob.h" using namespace Platform; using namespace Platform::Metadata; using namespace Windows::Data::Json; namespace Microsoft { namespace Devices { namespace Management { namespace Message { public ref class DeviceHealthAttestationVerifyHealthRequest sealed : public IRequest { public: property String^ HealthAttestationServerEndpoint; virtual Blob^ Serialize() { JsonObject^ jsonObject = ref new JsonObject(); jsonObject->Insert("HealthAttestationServerEndpoint", JsonValue::CreateStringValue(HealthAttestationServerEndpoint)); return SerializationHelper::CreateBlobFromJson((uint32_t)Tag, jsonObject); } static IDataPayload^ Deserialize(Blob^ blob) { assert(blob->Tag == DMMessageKind::DeviceHealthAttestationVerifyHealth); String^ str = SerializationHelper::GetStringFromBlob(blob); JsonObject^ jsonObject = JsonObject::Parse(str); auto request = ref new DeviceHealthAttestationVerifyHealthRequest(); request->HealthAttestationServerEndpoint = jsonObject->Lookup("HealthAttestationServerEndpoint")->GetString(); return request; } virtual property DMMessageKind Tag { DMMessageKind get(); } }; public ref class DeviceHealthAttestationGetReportRequest sealed : public IRequest { public: property String^ Nonce; virtual Blob^ Serialize() { JsonObject^ jsonObject = ref new JsonObject(); jsonObject->Insert("Nonce", JsonValue::CreateStringValue(Nonce)); return SerializationHelper::CreateBlobFromJson((uint32_t)Tag, jsonObject); } static IDataPayload^ Deserialize(Blob^ blob) { assert(blob->Tag == DMMessageKind::DeviceHealthAttestationGetReport); String^ str = SerializationHelper::GetStringFromBlob(blob); JsonObject^ jsonObject = JsonObject::Parse(str); auto request = ref new DeviceHealthAttestationGetReportRequest(); request->Nonce = jsonObject->Lookup("Nonce")->GetString(); return request; } virtual property DMMessageKind Tag { DMMessageKind get(); } }; public ref class DeviceHealthAttestationGetReportResponse sealed : IResponse { String^ healthCertificate; String^ correlationId; public: DeviceHealthAttestationGetReportResponse(String^ healthCertificate, String^ correlationId) : healthCertificate(healthCertificate), correlationId(correlationId) {} virtual Blob^ Serialize() { JsonObject^ jsonObject = ref new JsonObject(); jsonObject->Insert("HealthCertificate", JsonValue::CreateStringValue(healthCertificate)); jsonObject->Insert("CorrelationId", JsonValue::CreateStringValue(correlationId)); return SerializationHelper::CreateBlobFromJson((uint32_t)Tag, jsonObject); } static IDataPayload^ Deserialize(Blob^ bytes) { String^ str = SerializationHelper::GetStringFromBlob(bytes); JsonObject^ jsonObject = JsonObject::Parse(str); String^ healthCertificate = jsonObject->Lookup("HealthCertificate")->GetString(); String^ correlationId = jsonObject->Lookup("CorrelationId")->GetString(); return ref new DeviceHealthAttestationGetReportResponse(healthCertificate, correlationId); } virtual property DMMessageKind Tag { DMMessageKind get(); } virtual property ResponseStatus Status { ResponseStatus get() { return ResponseStatus::Success; } } property String^ HealthCertificate { String^ get() { return healthCertificate; } } property String^ CorrelationId { String^ get() { return correlationId; } } }; } }}}
ennioVisco/MoonLight
core/src/main/java/eu/quanticol/moonlight/monitoring/spatialtemporal/SpatialTemporalMonitorSomewhere.java
/* * MoonLight: a light-weight framework for runtime monitoring * Copyright (C) 2018-2021 * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * 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 eu.quanticol.moonlight.monitoring.spatialtemporal; import java.util.Iterator; import java.util.function.Function; import java.util.function.IntFunction; import eu.quanticol.moonlight.algorithms.SpaceUtilities; import eu.quanticol.moonlight.domain.SignalDomain; import eu.quanticol.moonlight.space.DistanceStructure; import eu.quanticol.moonlight.space.LocationService; import eu.quanticol.moonlight.signal.ParallelSignalCursor; import eu.quanticol.moonlight.space.SpatialModel; import eu.quanticol.moonlight.signal.SpatialTemporalSignal; import eu.quanticol.moonlight.util.Pair; /** * Strategy to interpret the Somewhere spatial logic operator. * * @param <S> Spatial Graph Edge Type * @param <T> Signal Trace Type * @param <R> Semantic Interpretation Semiring Type * * @see SpatialTemporalMonitor */ public class SpatialTemporalMonitorSomewhere<S, T, R> implements SpatialTemporalMonitor<S, T, R> { private SpatialTemporalMonitor<S, T, R> m; private Function<SpatialModel<S>, DistanceStructure<S, ?>> distance; private SignalDomain<R> domain; public SpatialTemporalMonitorSomewhere(SpatialTemporalMonitor<S, T, R> m, Function<SpatialModel<S>, DistanceStructure<S, ?>> distance, SignalDomain<R> domain) { this.m = m; this.distance = distance; this.domain = domain; } @Override public SpatialTemporalSignal<R> monitor(LocationService<Double, S> locationService, SpatialTemporalSignal<T> signal) { return computeSomewhereDynamic(locationService,m.monitor(locationService, signal)); } private SpatialTemporalSignal<R> computeSomewhereDynamic( LocationService<Double, S> l, SpatialTemporalSignal<R> s) { SpatialTemporalSignal<R> toReturn = new SpatialTemporalSignal<R>(s.getNumberOfLocations()); if (l.isEmpty()) { return toReturn; } ParallelSignalCursor<R> cursor = s.getSignalCursor(true); Iterator<Pair<Double, SpatialModel<S>>> locationServiceIterator = l.times(); Pair<Double, SpatialModel<S>> current = locationServiceIterator.next(); Pair<Double, SpatialModel<S>> next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); double time = cursor.getTime(); while ((next != null)&&(next.getFirst()<=time)) { current = next; next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); } //Loop invariant: (current.getFirst()<=time)&&((next==null)||(time<next.getFirst())) while (!cursor.completed() && !Double.isNaN(time)) { IntFunction<R> spatialSignal = cursor.getValue(); SpatialModel<S> sm = current.getSecond(); DistanceStructure<S, ?> f = distance.apply(sm); toReturn.add(time, SpaceUtilities.somewhere(domain, spatialSignal, f)); double nextTime = cursor.forward(); while ((next != null)&&(next.getFirst()<nextTime)) { current = next; time = current.getFirst(); next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); f = distance.apply(current.getSecond()); toReturn.add(time, SpaceUtilities.somewhere(domain, spatialSignal, f)); } time = nextTime; current = (next!=null?next:current); next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); } //TODO: Manage end of signal! return toReturn; } // private SpatialTemporalSignal<T> computeSomewhereDynamic( // LocationService<E> l, SpatialTemporalSignal<T> s) { // SpatialTemporalSignal<T> toReturn = new SpatialTemporalSignal<T>(s.getNumberOfLocations()); // if (l.isEmpty()) { // return toReturn; // } // ParallelSignalCursor<T> cursor = s.getSignalCursor(true); // Iterator<Pair<Double, SpatialModel<E>>> locationServiceIterator = l.times(); // Pair<Double, SpatialModel<E>> current = locationServiceIterator.next(); // Pair<Double, SpatialModel<E>> next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); // double time = cursor.getTime(); // while ((next != null)&&(next.getFirst()<=time)) { // current = next; // next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); // } // //Loop invariant: (current.getFirst()<=time)&&((next==null)||(time<next.getFirst())) // while (!cursor.completed() && !Double.isNaN(time)) { // Function<Integer, T> spatialSignal = cursor.getValue(); // SpatialModel<E> sm = current.getSecond(); // DistanceStructure<E, ?> f = distance.apply(sm); // toReturn.add(time, f.somewhere(domain, spatialSignal)); // double nextTime = cursor.forward(); // while ((next != null)&&(next.getFirst()<nextTime)) { // current = next; // time = current.getFirst(); // next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); // f = distance.apply(current.getSecond()); // toReturn.add(time, f.somewhere(domain, spatialSignal)); // } // time = nextTime; // if ((next!=null)&&(next.getFirst()==time)) { // current = next; // f = distance.apply(current.getSecond()); // next = (locationServiceIterator.hasNext()?locationServiceIterator.next():null); // } // } // // //TODO: Manage end of signal! // return toReturn; // // } }
CoderSong2015/Apache-Trafodion
core/sql/regress/newregr/parallel/gencolumn.h
<filename>core/sql/regress/newregr/parallel/gencolumn.h /********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ //+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // Define a symbol to prevent multiple inclusions of this header file. //+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ #ifndef GenColumn_H #define GenColumn_H #include <fstream> #include "Pseudo.h" #if !defined(__TANDEM) || (__CPLUSPLUS_VERSION >= 3) using namespace std; #endif //<pb> //======================== // Abstract Column Class. //======================== class AbstColumn { private: public: virtual void getNextColumnValue() = 0; virtual void printColumn(ofstream& pStream) const = 0; }; // Class ColumnAbs typedef AbstColumn* AbstColumnPtr; //<pb> //======================= // Integer Column Class. //======================= class IntColumn : public AbstColumn { private: PseudoIntAbs* pseudoInt_; long currentVal_; const long* nullVal_; public: //--------------- // Constructors. //--------------- IntColumn(long pSeed, long pRange, long pModulus, long* pNullVal = 0); IntColumn(long pRange, long* pNullVal = 0); //------------- // Destructor. //------------- virtual ~IntColumn() { delete pseudoInt_; } virtual void getNextColumnValue(); virtual void printColumn(ofstream& pStream) const; }; // Class IntColumn //<pb> //=============================== // Character Array Column Class. //=============================== class CharColumn : public AbstColumn { private: PseudoCharAbs* pseudoChar_; char* currentVal_; const char* nullVal_; public: //--------------- // Constructors. //--------------- CharColumn(long pSeed, long pRange, long pCol0Modulus, long pCol1Modulus, long pArraySize, char* pNullVal = 0); CharColumn(long pCol0Range, long pCol1Range, long pArraySize, char* pNullVal = 0); //------------- // Destructor. //------------- virtual ~CharColumn() { delete pseudoChar_; delete [] currentVal_; } //-------------------------- // Public member functions. //-------------------------- virtual void getNextColumnValue(); virtual void printColumn(ofstream& pStream) const; }; // Class CharColumn //<pb> //======================================== // Variable Character Array Column Class. //======================================== class VarcharColumn : public AbstColumn { private: PseudoCharAbs* pseudoChar_; long valuesGenerated_; char* currentMaxVal_; char* currentMinVal_; const char* nullVal_; void fillArrays(long pMaxArraySize, long pMinArraySize); public: //--------------- // Constructors. //--------------- VarcharColumn(long pSeed, long pRange, long pCol0Modulus, long pCol1Modulus, long pMaxArraySize, long pMinArraySize, char* pNullVal = 0); VarcharColumn(long pCol0Range, long pCol1Range, long pMaxArraySize, long pMinArraySize, char* pNullVal = 0); //------------- // Destructor. //------------- virtual ~VarcharColumn() { delete pseudoChar_; delete [] currentMaxVal_; delete [] currentMinVal_; } //-------------------------- // Public member functions. //-------------------------- virtual void getNextColumnValue(); virtual void printColumn(ofstream& pStream) const; }; // Class VarcharColumn //<pb> //==================== // Date Column Class. //==================== class DateColumn : public AbstColumn { private: PseudoDateAbs* pseudoDate_; __int64 currentVal_; const __int64* nullVal_; public: //--------------- // Constructors. //--------------- DateColumn(long pSeed, long pRange, long pModulus, __int64* pNullVal = 0); DateColumn(long pRange, __int64* pNullVal = 0); //------------- // Destructor. //------------- virtual ~DateColumn() { delete pseudoDate_; } //-------------------------- // Public member functions. //-------------------------- virtual void getNextColumnValue(); virtual void printColumn(ofstream& pStream) const; }; // Class CharColumn //----------------------------------------------------------------- // Julian timestamp constant value associated with 1 Jaunary 2100. //----------------------------------------------------------------- const __int64 kBaseDateTime = 214969204800000000; //<pb> //=========================== // Fixed Point Column Class. //=========================== class FixedPointColumn : public AbstColumn { private: PseudoFixedPointAbs* pseudoFixedPoint_; char* currentVal_; const char* nullVal_; public: //--------------- // Constructors. //--------------- FixedPointColumn(long pSeed, long pRange, long pModulus, long pArraySize, char* pNullVal = 0); //------------- // Destructor. //------------- virtual ~FixedPointColumn() { delete pseudoFixedPoint_; delete [] currentVal_; } //-------------------------- // Public member functions. //-------------------------- virtual void getNextColumnValue(); virtual void printColumn(ofstream& pStream) const; }; // Class FixedPointColumn #endif // ifndef GenColum_H
amwaleh/Hire_more
src/components/MenuItems.js
<reponame>amwaleh/Hire_more import React from 'react' import { Menu } from 'semantic-ui-react' export default () => { return ( <> <Menu.Item name='Spark' href='/' link /> <Menu.Item name='home' href='/' link /> <Menu.Item name='About' href='/about' link /> <Menu.Item name='Explore Developer' href='/explore-developers' link /> </> ) }
QuanDev2/cs-applied-plan-portal
client/src/components/view_plan/CreateComment.js
/** @jsx jsx */ import {useState} from "react"; import {css, jsx} from "@emotion/core"; import {useParams} from "react-router-dom"; import ErrorMessage from "../general/ErrorMessage"; import {login} from "../../utils/authService"; // comment creation text field function CreateComment(props) { const [newComment, setNewComment] = useState(true); const [errorMessage, setErrorMessage] = useState(""); const {planId} = useParams(); const style = css` & { display: inline-flex; flex-direction: column; align-items: center; } #comment-input-container { display: inline-block; padding: 25px; border-radius: 0.5rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); background: white; } #comment-text-input { display: inline; margin: 10px; resize: none; border-radius: 0.5rem; border: 1px solid var(--color-lightgray-600); } #submit-comment-button { display: block; margin: auto; } .toggle-creation-button { /*background: none;*/ /*border: 1px solid black;*/ padding: 0.5rem 1rem; border-radius: 0.5rem; background: var(--color-green-500); color: var(--color-green-50); /*padding: 1rem 1rem;*/ border-radius: 0.5rem; border: none; } #submit-comment-button { display: block; margin: 10px auto; background: var(--color-blue-500); color: var(--color-blue-50); padding: 1rem 1rem; border-radius: 0.5rem; border: none; } .toggle-state-red { background: var(--color-red-500); color: var(--color-red-50); } @media print { & { display: none; } } `; function toggle() { setErrorMessage(""); setNewComment(!newComment); } async function submit(planId) { try { const text = document.getElementById("comment-text-input").value; const url = `/api/comment`; let obj = []; const postObj = { planId: planId, text: text }; // post new comment const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(postObj), }); if (response.ok) { // show the new comment and close window obj = await response.json(); setErrorMessage(""); setNewComment(!newComment); props.onNewComment({ id: obj.insertId + "c", firstName: props.currentUser.firstName, lastName: props.currentUser.lastName, time: obj.time, planId: planId, userId: props.currentUser.id, text: text }); } else if (response.status === 403) { // if the user is not allowed to create a comment on this plan, // redirect to login to allow updating of user info login(); } else { // we got a bad status code. Show the error obj = await response.json(); setErrorMessage(obj.error); } } catch (err) { // this is a server error setErrorMessage("An internal server error occurred. Please try again later."); } } if (props.status !== 0 && props.status !== 4) { if (newComment) { return ( <div id="create-comment-container" css={style}> <button className="toggle-creation-button" onClick={() => toggle()}> Add Comment </button> </div> ); } else { return ( <div id="create-comment-container" css={style}> <button className="toggle-creation-button toggle-state-red" onClick={() => toggle()}> Discard </button> <ErrorMessage text={errorMessage} /> <div id="comment-input-container"> <textarea id="comment-text-input" rows="5" cols="50"/> <button id="submit-comment-button" onClick={() => submit(planId)}> Submit </button> </div> </div> ); } } else { return null; } } export default CreateComment;
NenadPantelic/spring-boot-example-projects
06-spring-paging-and-sorting/src/main/java/com/example/pagingandsorting/demo/model/Product.java
package com.example.pagingandsorting.demo.model; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.math.BigDecimal; import java.time.Instant; @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private Long id; @Column private String name; @Column private BigDecimal price; @CreationTimestamp @Column(name = "created_at") private Instant createdAt; public Product(String name, BigDecimal price){ this.name = name; this.price = price; } }
alex2ching/QQConnector
WPFTencentQQ/CCodecWarpper/ResponeUploadAddressBookV2.cpp
<reponame>alex2ching/QQConnector #include "StdAfx.h" #include "ResponeUploadAddressBookV2.h" #include"MobileContactsFriendInfo.h" #include"MobileContactsNotFriendInfo.h" CResponeUploadAddressBookV2::CResponeUploadAddressBookV2(void) { } CResponeUploadAddressBookV2::~CResponeUploadAddressBookV2(void) { } void CResponeUploadAddressBookV2::readFrom(CJceInputStream& paramd) { paramd.read(&nextFlag,0,true); paramd.read(&sessionSid,1,true); if(BindFriendContacts._value.size()==0) { BindFriendContacts._value.push_back(new CMobileContactsFriendInfo()); } paramd.read(&BindFriendContacts,2,true); if(BindNotFriendContacts._value.size()==0) { BindNotFriendContacts._value.push_back(new CMobileContactsNotFriendInfo()); } paramd.read(&BindNotFriendContacts,3,true); paramd.read(&MaxsignTimeStamp,4,false); paramd.read(&timeStamp,5,true); } void CResponeUploadAddressBookV2::writeTo(CJceOutputStream& paramJceOutputStream) { }
npocmaka/Windows-Server-2003
inetsrv/iis/svcs/smtp/adminsso/binding.h
// binding.h : Declaration of the CServerBinding & CServerBindings classes. #include "resource.h" // main symbols // // Dependencies: // class CMultiSz; // // A simple binding class: // class CBinding { public: CBinding () : m_dwTcpPort ( 0 ), m_dwSslPort ( 0 ) { } CComBSTR m_strIpAddress; long m_dwTcpPort; long m_dwSslPort; HRESULT SetProperties ( BSTR strIpAddress, long dwTcpPort, long dwSslPort ); inline HRESULT SetProperties ( const CBinding & binding ) { return SetProperties ( binding.m_strIpAddress, binding.m_dwTcpPort, binding.m_dwSslPort ); } private: // Don't call this: const CBinding & operator= ( const CBinding & ); }; ///////////////////////////////////////////////////////////////////////////// // The Binding Object class CServerBinding : public CComDualImpl<IServerBinding, &IID_IServerBinding, &LIBID_SMTPADMLib>, public ISupportErrorInfo, public CComObjectRoot { friend class CServerBindings; //friend class CVirtualServer; public: CServerBinding(); virtual ~CServerBinding (); BEGIN_COM_MAP(CServerBinding) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IServerBinding) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() //DECLARE_NOT_AGGREGATABLE(CServerBinding) // Remove the comment from the line above if you don't want your object to // support aggregation. The default is to support it // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IServerBinding public: ////////////////////////////////////////////////////////////////////// // Properties: ////////////////////////////////////////////////////////////////////// STDMETHODIMP get_IpAddress ( BSTR * pstrIpAddress ); STDMETHODIMP put_IpAddress ( BSTR strIpAddress ); STDMETHODIMP get_TcpPort ( long * pdwTcpPort ); STDMETHODIMP put_TcpPort ( long dwTcpPort ); STDMETHODIMP get_SslPort ( long * plSslPort ); STDMETHODIMP put_SslPort ( long lSslPort ); ////////////////////////////////////////////////////////////////////// // Data: ////////////////////////////////////////////////////////////////////// private: inline HRESULT SetProperties ( const CBinding & binding ) { return m_binding.SetProperties ( binding ); } // Property variables: CBinding m_binding; }; ///////////////////////////////////////////////////////////////////////////// // The Bindings Object class CServerBindings : public CComDualImpl<IServerBindings, &IID_IServerBindings, &LIBID_SMTPADMLib>, public ISupportErrorInfo, public CComObjectRoot { friend class CServerBinding; //friend class CVirtualServer; public: CServerBindings(); virtual ~CServerBindings (); BEGIN_COM_MAP(CServerBindings) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IServerBindings) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() //DECLARE_NOT_AGGREGATABLE(CServerBindings) // Remove the comment from the line above if you don't want your object to // support aggregation. The default is to support it // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IServerBindings public: ////////////////////////////////////////////////////////////////////// // Properties: ////////////////////////////////////////////////////////////////////// STDMETHODIMP get_Count ( long * pdwCount ); ////////////////////////////////////////////////////////////////////// // Methods: ////////////////////////////////////////////////////////////////////// STDMETHODIMP Item ( long index, IServerBinding ** ppBinding ); STDMETHODIMP ItemDispatch ( long index, IDispatch ** ppBinding ); STDMETHODIMP Add ( BSTR strIpAddress, long dwTcpPort, long dwSslPort ); STDMETHODIMP ChangeBinding ( long index, IServerBinding * pBinding ); STDMETHODIMP ChangeBindingDispatch ( long index, IDispatch * pBinding ); STDMETHODIMP Remove ( long index ); STDMETHODIMP Clear ( ); ////////////////////////////////////////////////////////////////////// // Data: ////////////////////////////////////////////////////////////////////// private: // Property variables: long m_dwCount; CBinding * m_rgBindings; }; ////////////////////////////////////////////////////////////////////// // // Useful routines to go from IServerBindings to // Metabase data types. // ////////////////////////////////////////////////////////////////////// HRESULT MDBindingsToIBindings ( CMultiSz * pmszBindings, BOOL fTcpBindings, IServerBindings * pBindings ); HRESULT IBindingsToMDBindings ( IServerBindings * pBindings, BOOL fTcpBindings, CMultiSz * pmszBindings );
QutEcoacoustics/baw-client
src/components/services/unitConverters.spec.js
<gh_stars>1-10 describe("The unitConverter service", function () { var unitConverter; var inputArgs = {}; beforeEach(module("bawApp.services.unitConverter")); beforeEach(inject(["bawApp.unitConverter", function (providedUnitConverted) { unitConverter = providedUnitConverted; inputArgs = { sampleRate: undefined, spectrogramWindowSize: undefined, endOffset: undefined, startOffset: undefined, imageElement: undefined, audioRecordingAbsoluteStartDate: undefined }; }])); it("returns an object", function () { expect(unitConverter).toBeObject(); }); it("has one method", function () { var keys = Object.keys(unitConverter); expect(keys.length).toBe(1); expect(keys[0]).toBe("getConversions"); }); it("will accepted one well formatted argument", function () { var c = unitConverter.getConversions(inputArgs); expect(c).toBeObject(); }); Object.keys(inputArgs).forEach(function (key) { it("fails iff the input object is missing the " + key + " property", function () { var obj = angular.copy(inputArgs); delete obj[key]; var f = function () { unitConverter.getConversions(obj); }; expect(f).toThrowError(Error, "Missing property: " + key); }); }); describe("has the getConversions method:", function () { var converters; var now = new Date(); beforeEach(function () { inputArgs.sampleRate = 22050; inputArgs.spectrogramWindowSize = 512; inputArgs.endOffset = 65; inputArgs.startOffset = 35; inputArgs.imageElement = null; inputArgs.audioRecordingAbsoluteStartDate = now; converters = unitConverter.getConversions(inputArgs); }); it("the input object to be embedded in the output", function () { expect(converters.input).toBe(inputArgs); }); ["sampleRate", "spectrogramWindowSize", "startOffset", "endOffset"].forEach(function (key) { it("requires " + key + " be provided as a number", function () { var f = function () { var local = angular.extend({}, inputArgs); local[key] = inputArgs[key].toString(); unitConverter.getConversions(local); }; expect(f).toThrowError("Input data field `" + key + "` should be a number!"); }); }); it("ensure the absolute start date of the input object is output and is a date", function(){ var isDate = converters.input.audioRecordingAbsoluteStartDate instanceof Date; expect(isDate).toBeTrue(); expect(converters.input.audioRecordingAbsoluteStartDate).toBe(now); }); it("returns an object that implements the required API", function () { expect(converters).toImplement({ input: Object, conversions: Object, pixelsToSeconds: Function, secondsToPixels: Function, hertzToPixels: Function, invertHertz: Function, invertPixels: Function }); }); it("ensures the conversion object has the correct value for pixelsPerSecond", function () { expect(converters.conversions.pixelsPerSecond).toBe(43.06640625); }); it("ensures the conversion object has the correct value for pixelsPerHertz", function () { expect(converters.conversions.pixelsPerHertz).toBe(0.02321995464852607709750566893424); }); it("ensures the conversion object has the correct value for nyquistFrequency", function () { expect(converters.conversions.nyquistFrequency).toBe(11025); }); it("ensures the conversion object has the correct value for enforcedImageWidth", function () { expect(converters.conversions.enforcedImageWidth).toBe(1292); }); it("ensures the conversion object has the correct value for enforcedImageHeight", function () { expect(converters.conversions.enforcedImageHeight).toBe(256); }); it("correctly converts seconds to pixels", function () { var pixels = converters.secondsToPixels(120); expect(pixels).toBe(5167.96875); }); it("correctly converts Hertz to pixels", function () { var pixels = converters.hertzToPixels(5000); expect(pixels).toBe(116.09977324263039); }); it("correctly converts pixels to seconds", function () { var pixels = converters.pixelsToSeconds(1000); expect(pixels).toBe(23.219954649 /* 23.219954648526077 */); }); it("correctly converts pixels to Hertz", function () { var pixels = converters.pixelsToHertz(128); expect(pixels).toBe(5512.5 /* 5512.5 */); }); it("correctly inverts hertz", function () { var pixels = converters.invertHertz(1000); expect(pixels).toBe(10025); }); it("correctly inverts pixels", function () { var pixels = converters.invertPixels(200); expect(pixels).toBe(56); }); it("correctly sets width and height given a stretched image", function () { inputArgs.imageElement = {src: "test-image", naturalWidth: 1200, naturalHeight: 250 }; converters = unitConverter.getConversions(inputArgs); expect(converters.conversions.enforcedImageWidth).toBe(1292); expect(converters.conversions.enforcedImageHeight).toBe(256); }); it("correctly calculates the left position of a box - with start offset", function () { var left = converters.toLeft(45.0 /*seconds*/); expect(left).toBe(430.6640625 /*pixels*/); }); it("correctly calculates the left position of a box - less than start offset", function () { var left = converters.toLeft(15.0 /*seconds*/); expect(left).toBe(-861.328125 /*pixels*/); }); it("correctly calculates the left position of a box - greater than offset", function () { var left = converters.toLeft(92.0 /*seconds*/); expect(left).toBe(2454.78515625); }); it("correctly calculates the top position of a box", function () { var top = converters.toTop(10000 /*hertz*/); // remember - inverted y axis expect(top).toBe(23.800453514739218 /*pixels*/); }); it("correctly calculates the top position of a box - if for some reason the annotation high frequency is above the nyquist", function () { var top = converters.toTop(16000 /*hertz*/); // remember - inverted y axis expect(top).toBe(-115.51927437641723 /*pixels*/); }); it("correctly calculates the width of a box", function () { var width = converters.toWidth(32, 16 /*seconds*/); expect(width).toBe(689.0625 /*pixels*/); }); it("correctly calculates the height of a box", function () { var height = converters.toHeight(5000, 1500 /*hertz*/); expect(height).toBe(81.26984126984127 /*pixels*/); }); it("correctly calculates the startSeconds for and audioEvent from the left position of a box - with start offset", function () { var start = converters.toStart(650 /*pixels*/); expect(start).toBe(50.092970522 /*seconds (unrounded = 50.09297052154195)*/); }); it("correctly calculates the startSeconds for and audioEvent from the left position of a box - with pos+ pixels", function () { var start = converters.toStart(2500 /*pixels*/); expect(start).toBe(93.049886621 /*seconds (unrounded = 93.0498866213152)*/); }); it("correctly calculates the startSeconds for and audioEvent from the left position of a box - with negative pixels", function () { var start = converters.toStart(-860 /*pixels*/); expect(start).toBeCloseTo(15.031,3 /*seconds (unrounded = 15.030839002267573)*/); }); it("correctly calculates the endSeconds for an audioEvent from the left position of a box and its width", function () { var end = converters.toEnd(650, 43.06640625 /*pixels*/); expect(end).toBe(51.092970522 /*seconds (unrounded = 51.09297052154195)*/); }); it("correctly calculates the lowFrequency for an audioEvent from the top position of a box and its width", function () { var low = converters.toLow(20, 50 /*pixels*/); expect(low).toBe(8010.351563 /*hertz (unrounded = 8010.3515625)*/); }); it("toLow corrects for heights that are too tall", () => { var low = converters.toLow(245, 18); // pixels expect(low).toBe(0 /* hertz */); }); it("correctly calculates the highFrequency for an audioEvent from the top position of a box", function () { var high = converters.toHigh(20 /*pixels*/); expect(high).toBe(10163.671875 /*hertz (unrounded = 10163.671875)*/); }); }); });
GSKirox/kaepora
main.go
package main import ( "encoding/csv" "errors" "flag" "fmt" "kaepora/internal/back" "kaepora/internal/bot" "kaepora/internal/config" "kaepora/internal/generator/oot" "kaepora/internal/generator/oot/settings" "kaepora/internal/global" "kaepora/internal/web" "log" "os" "os/signal" "path/filepath" "sync" "syscall" "github.com/google/uuid" _ "github.com/mattn/go-sqlite3" ) func main() { log.SetFlags(0) // we syslog in prod so we don't care about time here flag.Parse() switch flag.Arg(0) { // commands not requiring a back case "version": fmt.Fprintf(os.Stdout, "Kaepora %s\n", global.Version) return case "help": fmt.Fprint(os.Stdout, help()) return case "settings": if err := generateSettingsStats(flag.Arg(1)); err != nil { log.Fatal(err) } return } conf, err := config.NewFromUserConfigDir() if err != nil { log.Fatal(err) } log.Printf("info: Starting Kaepora %s", global.Version) b, err := back.New("sqlite3", "./kaepora.db", conf) if err != nil { log.Fatal(err) } switch flag.Arg(0) { case "fixtures": if err := b.LoadFixtures(); err != nil { log.Fatal(err) } case "serve": if err := serve(b, conf); err != nil { log.Fatal(err) } case "rerank": if err := b.Rerank(flag.Arg(1)); err != nil { log.Fatal(err) } default: fmt.Fprint(os.Stderr, help()) os.Exit(1) } } func help() string { return fmt.Sprintf(` Kaepora is a tool to manage the "Ocarina of Time: Randomizer" competitive ladder. Usage: %[1]s COMMAND [ARGS…] COMMANDS fixtures create default data for quick testing during development help display this help serve start the Discord bot version display the current version rerank SHORTCODE recompute all rankings in a league settings FILENAME output settings randomizer stats `, os.Args[0], ) } func serve(b *back.Back, conf *config.Config) error { done := make(chan struct{}) signaled := make(chan os.Signal, 1) signal.Notify(signaled, syscall.SIGINT, syscall.SIGTERM) bot, err := bot.New(b, conf) if err != nil { return err } server, err := web.NewServer(b, conf) if err != nil { return err } var wg sync.WaitGroup go b.Run(&wg, done) go bot.Serve(&wg, done) go server.Serve(&wg, done) sig := <-signaled log.Printf("warning: received signal %d", sig) close(done) log.Print("info: waiting for complete shutdown") wg.Wait() log.Print("info: shutdown complete") return nil } func generateSettingsStats(path string) error { if path == "" { return errors.New("you must specify a shuffled JSON configuration file name") } baseDir, err := oot.GetBaseDir() if err != nil { return err } s, err := settings.Load(filepath.Join(baseDir, path)) if err != nil { return err } max := 102400 count := map[string]map[string]int{} // name => value => count for i := 0; i < max; i++ { settings := s.Shuffle(uuid.New().String(), oot.SettingsCostBudget) for name, value := range settings { if _, ok := count[name]; !ok { count[name] = map[string]int{} } count[name][fmt.Sprintf("%v", value)]++ } } stats := web.NamedPct2DFrom2DMap(count, max) w := csv.NewWriter(os.Stdout) for _, v := range stats { _ = w.Write([]string{v.Name, v.Value, fmt.Sprintf("%.2f", v.Pct)}) } w.Flush() return nil }
Jan200101/zig-wii
vendor/devkitpro/wut/include/gx2/state.h
<reponame>Jan200101/zig-wii #pragma once #include <wut.h> #include "enum.h" /** * \defgroup gx2_state State * \ingroup gx2 * @{ */ #ifdef __cplusplus extern "C" { #endif void GX2Init(uint32_t *attributes); void GX2Shutdown(); void GX2Flush(); void GX2ResetGPU(uint32_t unknown); #ifdef __cplusplus } #endif /** @} */
mmabey/fhir.resources
fhir/resources/STU3/tests/test_processrequest.py
<filename>fhir/resources/STU3/tests/test_processrequest.py # -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/ProcessRequest Release: STU3 Version: 3.0.2 Revision: 11917 Last updated: 2019-10-24T11:53:00+11:00 """ import io import json import os import unittest import pytest from .. import processrequest from ..fhirdate import FHIRDate from .fixtures import force_bytes @pytest.mark.usefixtures("base_settings") class ProcessRequestTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get("FHIR_UNITTEST_DATADIR") or "" with io.open(os.path.join(datadir, filename), "r", encoding="utf-8") as handle: js = json.load(handle) self.assertEqual("ProcessRequest", js["resourceType"]) return processrequest.ProcessRequest(js) def testProcessRequest1(self): inst = self.instantiate_from("processrequest-example-poll-exclusive.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest1(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest1(inst2) def implProcessRequest1(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.exclude[0]), force_bytes("Communication")) self.assertEqual( force_bytes(inst.exclude[1]), force_bytes("PaymentReconciliation") ) self.assertEqual(force_bytes(inst.id), force_bytes("1113")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("113")) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest2(self): inst = self.instantiate_from("processrequest-example-poll-eob.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest2(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest2(inst2) def implProcessRequest2(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("1115")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://www.phr.com/patient/12345/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("115")) self.assertEqual( force_bytes(inst.include[0]), force_bytes("ExplanationOfBenefit") ) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest3(self): inst = self.instantiate_from("processrequest-example-poll-specific.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest3(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest3(inst2) def implProcessRequest3(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("1111")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("111")) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest4(self): inst = self.instantiate_from("processrequest-example-poll-inclusive.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest4(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest4(inst2) def implProcessRequest4(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("1112")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("112")) self.assertEqual( force_bytes(inst.include[0]), force_bytes("PaymentReconciliation") ) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest5(self): inst = self.instantiate_from("processrequest-example-poll-payrec.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest5(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest5(inst2) def implProcessRequest5(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("1114")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("114")) self.assertEqual( force_bytes(inst.include[0]), force_bytes("PaymentReconciliation") ) self.assertEqual(inst.period.end.date, FHIRDate("2014-08-20").date) self.assertEqual(inst.period.end.as_json(), "2014-08-20") self.assertEqual(inst.period.start.date, FHIRDate("2014-08-10").date) self.assertEqual(inst.period.start.as_json(), "2014-08-10") self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest6(self): inst = self.instantiate_from("processrequest-example.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest6(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest6(inst2) def implProcessRequest6(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("poll")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("1110")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("110")) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Poll ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest7(self): inst = self.instantiate_from("processrequest-example-reverse.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest7(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest7(inst2) def implProcessRequest7(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("cancel")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("87654")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("76543")) self.assertFalse(inst.nullify) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Reversal ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest8(self): inst = self.instantiate_from("processrequest-example-reprocess.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest8(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest8(inst2) def implProcessRequest8(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("reprocess")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("44654")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("44543")) self.assertEqual(inst.item[0].sequenceLinkId, 1) self.assertEqual(force_bytes(inst.reference), force_bytes("ABC12345G")) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the ReProcess ProcessRequest resource.</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated")) def testProcessRequest9(self): inst = self.instantiate_from("processrequest-example-status.json") self.assertIsNotNone(inst, "Must have instantiated a ProcessRequest instance") self.implProcessRequest9(inst) js = inst.as_json() self.assertEqual("ProcessRequest", js["resourceType"]) inst2 = processrequest.ProcessRequest(js) self.implProcessRequest9(inst2) def implProcessRequest9(self, inst): self.assertEqual(force_bytes(inst.action), force_bytes("status")) self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date) self.assertEqual(inst.created.as_json(), "2014-08-16") self.assertEqual(force_bytes(inst.id), force_bytes("87655")) self.assertEqual( force_bytes(inst.identifier[0].system), force_bytes("http://happyvalley.com/processrequest"), ) self.assertEqual(force_bytes(inst.identifier[0].value), force_bytes("1776543")) self.assertEqual(force_bytes(inst.status), force_bytes("active")) self.assertEqual( force_bytes(inst.text.div), force_bytes( '<div xmlns="http://www.w3.org/1999/xhtml">A human-readable rendering of the Status ProcessRequest</div>' ), ) self.assertEqual(force_bytes(inst.text.status), force_bytes("generated"))
vladandreiy/Parallel-and-Distribuited-Algorithms
Laboratories/lab02/mutex.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 2 int a = 0; pthread_mutex_t mutex; void *f(void *arg) { pthread_mutex_lock(&mutex); a += 2; pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main(int argc, char *argv[]) { int i, r; void *status; pthread_t threads[NUM_THREADS]; int arguments[NUM_THREADS]; if (pthread_mutex_init(&mutex, NULL) != 0) { printf("Eroare creare mutex.\n"); return 1; } for (i = 0; i < NUM_THREADS; i++) { arguments[i] = i; r = pthread_create(&threads[i], NULL, f, &arguments[i]); if (r) { printf("Eroare la crearea thread-ului %d\n", i); exit(-1); } } for (i = 0; i < NUM_THREADS; i++) { r = pthread_join(threads[i], &status); if (r) { printf("Eroare la asteptarea thread-ului %d\n", i); exit(-1); } } pthread_mutex_destroy(&mutex); printf("a = %d\n", a); return 0; }
benamrou/controlRoom
controlRoom_server/server/server/controller/userprofile.js
<gh_stars>0 // Http method: GET // URI : /userprofiles/?username=:USER_NAME // Read the profile of user given in :USER_NAME module.exports = function (app, SQL) { var module = {}; // Http Method: GET // URI : /user_profiles // Read all the user profiles module.get = function (req,res) { app.get('/api/user_profiles/', function (req, res) { "use strict"; console.log("Param:" + req.query); SQL.executeLibQuery("'ADM0000001'","{(:USER_NAME:,req.query.USER_NAME)}", //{USER_NAME: req.query.USER_NAME}, req.header('USER'), req, res); //JSON.stringify(req.header('USER')), req, res); // Check if the query is for a user or all users (filtered or not) /*if (req.originalUrl.includes("?")) { SQL.execute("SELECT * FROM USER_PROFILES WHERE USER_NAME = :USER_NAME", {USER_NAME: req.query.USER_NAME}, req.header('USER'), req, res); } else { SQL.execute("SELECT * FROM USER_PROFILES ", {}, req.header('USER'), req, res); }*/ }); }; // Http method: POST // URI : /user_profiles // Creates a new user profile module.post = function (req,res) { app.post('/user_profiles/', function (req, res) { "use strict"; SQL.execute("INSERT INTO user_profiles VALUES (" + ":USER_NAME, :DISPLAY_NAME, " + ":DESCRIPTION, :GENDER," + ":AGE, :COUNTRY, :THEME) ", {USER_NAME: req.body.USER_NAME, DISPLAY_NAME: req.body.DISPLAY_NAME, DESCRIPTION: req.body.DESCRIPTION, GENDER: req.body.GENDER, AGE: req.body.AGE, COUNTRY: req.body.COUNTRY, THEME: req.body.THEME}, req.header('USER'), req, res); }); }; // Http method: Delete // URI : /user_profiles // Delete an existing profile module.delete = function (req,res) { app.delete('/user_profiles/', function (req, res) { "use strict"; SQL.execute("DELETE FROM USER_PROFILES WHERE USER_NAME = :USER_NAME", {USER_NAME: req.query.USER_NAME}, req.header('USER'), req, res); }); }; // Http method: PUT // URI : /user_profiles/?username=:USER_NAME // Update the profile of user given in :USER_NAME module.put = function (req,res) { app.put('/user_profiles/:USER_NAME', function (req, res) { "use strict"; var statement = ""; var bindValues = {}; if (req.body.DISPLAY_NAME) { statement += "DISPLAY_NAME = :DISPLAY_NAME"; bindValues.DISPLAY_NAME = req.body.DISPLAY_NAME; } if (req.body.DESCRIPTION) { if (statement) statement = statement + ", "; statement += "DESCRIPTION = :DESCRIPTION"; bindValues.DESCRIPTION = req.body.DESCRIPTION; } if (req.body.GENDER) { if (statement) statement = statement + ", "; statement += "GENDER = :GENDER"; bindValues.GENDER = req.body.GENDER; } if (req.body.AGE) { if (statement) statement = statement + ", "; statement += "AGE = :AGE"; bindValues.AGE = req.body.AGE; } if (req.body.COUNTRY) { if (statement) statement = statement + ", "; statement += "COUNTRY = :COUNTRY"; bindValues.COUNTRY = req.body.COUNTRY; } if (req.body.THEME) { if (statement) statement = statement + ", "; statement += "THEME = :THEME"; bindValues.THEME = req.body.THEME; } statement += " WHERE USER_NAME = :USER_NAME"; bindValues.USER_NAME = req.params.USER_NAME; statement = "UPDATE USER_PROFILES SET " + statement; SQL.execute(statement, bindValues, req.header('USER'), req, res); }); } return module; };
zealoussnow/chromium
third_party/blink/renderer/platform/heap/heap_test_platform.h
// Copyright 2021 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. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TEST_PLATFORM_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TEST_PLATFORM_H_ #include <memory> #include "v8/include/v8-platform.h" namespace blink { // Tests do not require that tasks can actually run, just that they can posted. class HeapTestingMockTaskRunner final : public v8::TaskRunner { public: void PostTask(std::unique_ptr<v8::Task> task) override {} void PostNonNestableTask(std::unique_ptr<v8::Task> task) override {} void PostDelayedTask(std::unique_ptr<v8::Task> task, double delay_in_seconds) override {} void PostNonNestableDelayedTask(std::unique_ptr<v8::Task> task, double delay_in_seconds) override {} void PostIdleTask(std::unique_ptr<v8::IdleTask> task) override {} bool IdleTasksEnabled() override { return false; } bool NonNestableTasksEnabled() const override { return false; } bool NonNestableDelayedTasksEnabled() const override { return false; } }; class HeapTestingPlatformAdapter final : public v8::Platform { public: explicit HeapTestingPlatformAdapter(v8::Platform* platform) : platform_(platform), task_runner_(std::make_shared<HeapTestingMockTaskRunner>()) {} HeapTestingPlatformAdapter(const HeapTestingPlatformAdapter&) = delete; HeapTestingPlatformAdapter& operator=(const HeapTestingPlatformAdapter&) = delete; v8::PageAllocator* GetPageAllocator() final { return platform_->GetPageAllocator(); } void OnCriticalMemoryPressure() final { platform_->OnCriticalMemoryPressure(); } bool OnCriticalMemoryPressure(size_t length) final { return platform_->OnCriticalMemoryPressure(length); } int NumberOfWorkerThreads() final { return platform_->NumberOfWorkerThreads(); } std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner( v8::Isolate* isolate) final { // Provides task runner that allows for incremental tasks even in detached // mode. return task_runner_; } void CallOnWorkerThread(std::unique_ptr<v8::Task> task) final { platform_->CallOnWorkerThread(std::move(task)); } void CallBlockingTaskOnWorkerThread(std::unique_ptr<v8::Task> task) final { platform_->CallBlockingTaskOnWorkerThread(std::move(task)); } void CallLowPriorityTaskOnWorkerThread(std::unique_ptr<v8::Task> task) final { platform_->CallLowPriorityTaskOnWorkerThread(std::move(task)); } void CallDelayedOnWorkerThread(std::unique_ptr<v8::Task> task, double delay_in_seconds) final { platform_->CallDelayedOnWorkerThread(std::move(task), delay_in_seconds); } bool IdleTasksEnabled(v8::Isolate* isolate) final { return platform_->IdleTasksEnabled(isolate); } std::unique_ptr<v8::JobHandle> PostJob( v8::TaskPriority priority, std::unique_ptr<v8::JobTask> job_task) final { return platform_->PostJob(priority, std::move(job_task)); } double MonotonicallyIncreasingTime() final { return platform_->MonotonicallyIncreasingTime(); } double CurrentClockTimeMillis() final { return platform_->CurrentClockTimeMillis(); } StackTracePrinter GetStackTracePrinter() final { return platform_->GetStackTracePrinter(); } v8::TracingController* GetTracingController() final { return platform_->GetTracingController(); } void DumpWithoutCrashing() final { platform_->DumpWithoutCrashing(); } private: v8::Platform* platform_; std::shared_ptr<v8::TaskRunner> task_runner_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TEST_PLATFORM_H_
Cyberpunk-Extended-Development-Team/RED4ext.SDK
include/RED4ext/Types/generated/physics/cloth/State.hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/generated/physics/cloth/PhaseConfig.hpp> #include <RED4ext/Types/generated/physics/cloth/RuntimeInfo.hpp> namespace RED4ext { namespace physics::cloth { struct State { static constexpr const char* NAME = "physicsclothState"; static constexpr const char* ALIAS = NAME; uint8_t unk00[0x10 - 0x0]; // 0 physics::cloth::PhaseConfig bendPhaseData; // 10 physics::cloth::PhaseConfig shearPhaseData; // 20 physics::cloth::PhaseConfig horizontalPhaseData; // 30 physics::cloth::PhaseConfig verticalPhaseData; // 40 physics::cloth::RuntimeInfo runtimeInfo; // 50 }; RED4EXT_ASSERT_SIZE(State, 0xC0); } // namespace physics::cloth } // namespace RED4ext
taiji1985/YangMVC
Boot/src/cn/org/docshare/demo/MyWebSocketListener.java
package cn.org.docshare.demo; import java.util.Date; import org.docshare.log.Log; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.api.annotations.WebSocket; @WebSocket public class MyWebSocketListener implements WebSocketListener { private Session session; @Override public void onWebSocketConnect(Session session) { Log.i("upgrade req "+ session.getUpgradeRequest().getRequestURI()); Log.i("MyWebSocketListener onWebSocketConnect->"+session.getRemoteAddress()); this.session = session; } //发送String @SuppressWarnings("deprecation") @Override public void onWebSocketText(String message) { Log.i("MyWebSocketListener onWebSocketText"); if (session.isOpen()) { // echo the message back session.getRemote().sendString(new Date().toLocaleString() , null); } } //发送byte[] @Override public void onWebSocketBinary(byte[] payload, int offset, int len) { Log.i("MyWebSocketListener onWebSocketBinary"); } @Override public void onWebSocketError(Throwable cause) { Log.i("MyWebSocketListener Error->" + cause.getMessage()); } @Override public void onWebSocketClose(int statusCode, String reason) { Log.i("MyWebSocketListener onWebSocketClose"); this.session = null; } }
gruberjl/gitbit
server/www/sitemap/index.js
<reponame>gruberjl/gitbit const {getSitemap} = require('./middleware') module.exports = {getSitemap}
infobip/oneapi-java
src/main/java/oneapi/model/USSDRequest.java
<gh_stars>1-10 package oneapi.model; public class USSDRequest { private String address = null; private String message = null; private Boolean stopSession = null; public USSDRequest() { } public USSDRequest(String address, String message) { this.address = address; this.message = message; } public USSDRequest(String address, String message, boolean stopSession) { this(address, message); this.stopSession = stopSession; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Boolean isStopSession() { return stopSession; } public void setStopSession(Boolean stopSession) { this.stopSession = stopSession; } }