max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
721
/** * This file is part of the "clip" project * Copyright (c) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. */ #pragma once #include <string> #include <unordered_map> #include <functional> #include <cairo.h> #include <cairo-ft.h> #include <ft2build.h> #include FT_FREETYPE_H #include <harfbuzz/hb.h> #include <harfbuzz/hb-ft.h> #include "text.h" #include "brush.h" #include "layout.h" #include "graphics/draw.h" #include "text_layout.h" namespace clip { class Image; class Rasterizer { public: Rasterizer(uint32_t width, uint32_t height, double dpi); ~Rasterizer(); Rasterizer(const Rasterizer&) = delete; Rasterizer& operator=(const Rasterizer&) = delete; void clear(const Color& c); Status drawShape( const Path& path, const StrokeStyle& stroke_style, const FillStyle& fill_style); Status drawText( const std::vector<text::GlyphPlacementGroup>& glyphs, const TextStyle& style, const Option<mat3>& transform); Status writeToFile(const std::string& path); std::string to_png() const; const unsigned char* data() const; size_t size() const; uint32_t width; uint32_t height; double dpi; cairo_surface_t* cr_surface; cairo_t* cr_ctx; }; using RasterizerRef = std::shared_ptr<Rasterizer>; } // namespace clip
589
12,366
<filename>tests/ios/in-tree-vendor-prebuilt-deps/Pods/Tink/Frameworks/Tink.framework/Headers/TINKAllConfig.h<gh_stars>1000+ /** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************** */ #import <Foundation/Foundation.h> #import "TINKRegistryConfig.h" NS_ASSUME_NONNULL_BEGIN /** * Methods for registering with the Registry all instances of Tink key types supported in a * particular release of Tink. To register all Tink key types provided in the latest release of Tink * one can do: * * NSError *error = nil; * TINKAllConfig *allConfig = [[TINKAllConfig alloc] initWithError:&error]; * if (error || !allConfig) { * // handle error. * } * * if (![TINKConfig registerConfig:allConfig error:&error]) { * // handle error. * } */ @interface TINKAllConfig : TINKRegistryConfig /** Use -initWithError: to get an instance of TINKAllConfig. */ - (instancetype)init NS_UNAVAILABLE; /** Returns config of all implementations supported in the latest version of Tink. */ - (nullable instancetype)initWithError:(NSError **)error NS_SWIFT_NAME(init()) NS_DESIGNATED_INITIALIZER; @end NS_ASSUME_NONNULL_END
522
427
<reponame>ryoon/rustc-1.19.0<filename>src/compiler-rt/lib/scudo/scudo_utils.h //===-- scudo_utils.h -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// Header for scudo_utils.cpp. /// //===----------------------------------------------------------------------===// #ifndef SCUDO_UTILS_H_ #define SCUDO_UTILS_H_ #include <string.h> #include "sanitizer_common/sanitizer_common.h" namespace __scudo { template <class Dest, class Source> inline Dest bit_cast(const Source& source) { static_assert(sizeof(Dest) == sizeof(Source), "Sizes are not equal!"); Dest dest; memcpy(&dest, &source, sizeof(dest)); return dest; } void NORETURN dieWithMessage(const char *Format, ...); enum CPUFeature { CRC32CPUFeature = 0, MaxCPUFeature, }; bool testCPUFeature(CPUFeature feature); // Tiny PRNG based on https://en.wikipedia.org/wiki/Xorshift#xorshift.2B // The state (128 bits) will be stored in thread local storage. struct Xorshift128Plus { public: Xorshift128Plus(); u64 Next() { u64 x = State[0]; const u64 y = State[1]; State[0] = y; x ^= x << 23; State[1] = x ^ y ^ (x >> 17) ^ (y >> 26); return State[1] + y; } private: u64 State[2]; }; // Software CRC32 functions, to be used when hardware support is not detected. u32 computeSoftwareCRC32(u32 Crc, uptr Data); } // namespace __scudo #endif // SCUDO_UTILS_H_
564
751
<gh_stars>100-1000 package okreplay; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; class Network { static Collection<String> getLocalAddresses() { try { InetAddress local = InetAddress.getLocalHost(); return Arrays.asList(local.getHostName(), local.getHostAddress(), "localhost", "127.0.0.1"); } catch (UnknownHostException e) { throw new RuntimeException(e); } } }
179
322
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os import string from lib.core.enums import PRIORITY from lib.core.common import singleTimeWarnMessage __priority__ = PRIORITY.LOW def dependencies(): singleTimeWarnMessage("tamper script '%s' is only meant to be run against ASP web applications" % os.path.basename(__file__).split(".")[0]) def tamper(payload, **kwargs): """ Adds a percentage sign ('%') infront of each character Requirement: * ASP Tested against: * Microsoft SQL Server 2000, 2005 * MySQL 5.1.56, 5.5.11 * PostgreSQL 9.0 Notes: * Useful to bypass weak and bespoke web application firewalls >>> tamper('SELECT FIELD FROM TABLE') '%S%E%L%E%C%T %F%I%E%L%D %F%R%O%M %T%A%B%L%E' """ if payload: retVal = "" i = 0 while i < len(payload): if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: retVal += payload[i:i + 3] i += 3 elif payload[i] != ' ': retVal += '%%%s' % payload[i] i += 1 else: retVal += payload[i] i += 1 return retVal
638
892
{ "schema_version": "1.2.0", "id": "GHSA-2wp2-chmh-r934", "modified": "2022-05-13T01:19:23Z", "published": "2022-05-13T01:19:23Z", "aliases": [ "CVE-2018-17142" ], "details": "The html package (aka x/net/html) through 2018-09-17 in Go mishandles <math><template><mo><template>, leading to a \"panic: runtime error\" in parseCurrentToken in parse.go during an html.Parse call.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-17142" }, { "type": "WEB", "url": "https://github.com/golang/go/issues/27702" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/LREEWY6KNLHRWFZ7OT4HVLMVVCGGUHON/" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/UKRCI7WIOCOCD3H7NXWRGIRABTQOZOBK/" } ], "database_specific": { "cwe_ids": [ "CWE-476" ], "severity": "HIGH", "github_reviewed": false } }
612
476
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.mysql; import io.prestosql.plugin.jdbc.BaseJdbcConfig; import io.prestosql.plugin.mysql.optimization.function.MysqlExternalFunctionHub; import io.prestosql.spi.function.ExternalFunctionInfo; import io.prestosql.spi.type.StandardTypes; import org.testng.annotations.Test; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class TestMySqlRegisterRemoteUdf { @Test public void testDefaults() { MysqlExternalFunctionHub externalFunctionHub = new MysqlExternalFunctionHub(new BaseJdbcConfig()); Set<ExternalFunctionInfo> externalFunctionInfo = externalFunctionHub.getExternalFunctions(); assertTrue(externalFunctionInfo.size() > 0); List<ExternalFunctionInfo> functionList = externalFunctionInfo.stream() .filter(x -> x.getFunctionName().get().equals("lower")) .collect(Collectors.toList()); assertEquals(functionList.size(), 1); ExternalFunctionInfo functionInfo = functionList.get(0); assertEquals(functionInfo.getInputArgs().get(0), StandardTypes.VARCHAR); assertEquals(functionInfo.getReturnType().get(), StandardTypes.VARCHAR); assertTrue(functionInfo.isDeterministic()); assertFalse(functionInfo.isCalledOnNullInput()); } // test over load function register @Test public void testOverloadFunctions() { MysqlExternalFunctionHub externalFunctionHub = new MysqlExternalFunctionHub(new BaseJdbcConfig()); Set<ExternalFunctionInfo> externalFunctionInfo = externalFunctionHub.getExternalFunctions(); assertTrue(externalFunctionInfo.size() > 0); List<ExternalFunctionInfo> functionList = externalFunctionInfo.stream() .filter(x -> x.getFunctionName().get().equals("timestamp")) .collect(Collectors.toList()); assertEquals(functionList.size(), 1); ExternalFunctionInfo functionInfo = functionList.get(0); List<String> inputArgs = functionInfo.getInputArgs(); assertEquals(inputArgs.size(), 2); assertEquals(inputArgs.get(0), StandardTypes.TIMESTAMP); assertEquals(inputArgs.get(1), StandardTypes.TIME); assertEquals(functionInfo.getReturnType().get(), StandardTypes.TIMESTAMP); assertTrue(functionInfo.isDeterministic()); assertFalse(functionInfo.isCalledOnNullInput()); } // test func defination with more than one params @Test public void testMultiParamsFunctions() { MysqlExternalFunctionHub externalFunctionHub = new MysqlExternalFunctionHub(new BaseJdbcConfig()); Set<ExternalFunctionInfo> externalFunctionInfo = externalFunctionHub.getExternalFunctions(); assertTrue(externalFunctionInfo.size() > 0); List<ExternalFunctionInfo> functionList = externalFunctionInfo.stream() .filter(x -> x.getFunctionName().get().equals("abs")) .collect(Collectors.toList()); assertEquals(functionList.size(), 2); } }
1,293
985
<reponame>kastiglione/zld int bar;
18
483
<gh_stars>100-1000 class Solution { public: string ReverseSentence(string str) { auto size = str.size(); if (size==0) return ""; int mark = 0; str += ' '; for (int i = 0;i<size+1;i++){ if (str[i] == ' '){ ReverseWord(str,mark,i-1); mark = i + 1; } } str = str.substr(0,size); ReverseWord(str,0,size-1); return str; } void ReverseWord (string &str, int l, int r){ while(l < r){ swap(str[l], str[r]); ++l; --r; } } };
362
416
<filename>test/compile_failure_tests/packing/material.cpp // This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/array.h> #include <visionaray/material.h> using namespace visionaray; // Material type to check #if defined MATERIAL_MATTE template <typename T> using mat_type = matte<T>; #elif defined MATERIAL_EMISSIVE template <typename T> using mat_type = emissive<T>; #elif defined MATERIAL_PLASTIC template <typename T> using mat_type = plastic<T>; #elif defined MATERIAL_MIRROR template <typename T> using mat_type = mirror<T>; #endif int main() { #if defined MATERIAL_PACK_FLOAT4 array<mat_type<float>, 4> mat_array; mat_type<simd::float4> mat = simd::pack(mat_array); #elif defined MATERIAL_PACK_FLOAT8 array<mat_type<float>, 8> mat_array; mat_type<simd::float8> mat = simd::pack(mat_array); #elif defined MATERIAL_PACK_ILLEGAL_LENGTH_1 array<mat_type<float>, 1> mat_array; auto mat = simd::pack(mat_array); #elif defined MATERIAL_PACK_ILLEGAL_LENGTH_3 array<mat_type<float>, 3> mat_array; auto mat = simd::pack(mat_array); #elif defined MATERIAL_PACK_ILLEGAL_INTEGRAL array<mat_type<int>, 4> mat_array; auto mat = simd::pack(mat_array); #endif return 0; }
534
1,319
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """bert model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import sys import six import logging import numpy as np import paddle.fluid as fluid from paddle.fluid.layers import shape from model.transformer_encoder import encoder, pre_process_layer logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO) logging.getLogger().setLevel(logging.INFO) logger = logging.getLogger(__name__) def dynamic_expand(dynamic_tensor, smaller_tensor): """ :param dynamic_tensor: :param smaller_tensor: :return: """ assert len(dynamic_tensor.shape) > len(smaller_tensor.shape) if type(smaller_tensor.shape) == list: for dim_idx, dim in smaller_tensor.shape: dynamic_tensor_dim_idx = len(dynamic_tensor) - len(smaller_tensor) + dim_idx assert dynamic_tensor.shape[dynamic_tensor_dim_idx] % dim == 0 elif type(smaller_tensor.shape) == int: assert dynamic_tensor.shape[-1] % smaller_tensor.shape == 0 memory_embs_zero = fluid.layers.scale(dynamic_tensor, scale=0.0) smaller_tensor = fluid.layers.elementwise_add(memory_embs_zero, smaller_tensor) return smaller_tensor def print_tensor(tensor, message, print_runtime=False): logger.info("{}: {}".format(message, tensor.shape)) if print_runtime: fluid.layers.Print(tensor, summarize=10, message=message) class MemoryLayer(object): def __init__(self, bert_config, concept_size, mem_emb_size, mem_method='cat', prefix=None): self.initializer_range = bert_config['initializer_range'] self.bert_size = bert_config['hidden_size'] self.concept_size = concept_size self.mem_emb_size = mem_emb_size assert mem_method in ['add', 'cat', 'raw'] self.mem_method = mem_method self.prefix = prefix def forward(self, bert_output, memory_embs, mem_length, ignore_no_memory_token=True): """ :param bert_output: [batch_size, seq_size, bert_size] :param memory_embs: [batch_size, seq_size, concept_size, mem_emb_size] :param mem_length: [batch_size, sent_size, 1] :return: """ bert_size = self.bert_size concept_size = self.concept_size mem_emb_size = self.mem_emb_size print_tensor(bert_output, "bert_output") print_tensor(memory_embs, "memory_embs") print_tensor(mem_length, "mem_length") projected_bert = fluid.layers.fc(bert_output, size=mem_emb_size, num_flatten_dims=2, param_attr=fluid.ParamAttr( name='{}_memory_layer_projection.w_0'.format(self.prefix) if self.prefix else 'memory_layer_projection.w_0', initializer=fluid.initializer.NormalInitializer( loc=0.0, scale=self.initializer_range)), bias_attr=False) # [batch_size *seq_size, mem_emb_size] logger.info("projected_bert: {}".format(projected_bert.shape)) expanded_bert = fluid.layers.unsqueeze(projected_bert, axes=[2]) # [batch_size, seq_size, 1, mem_emb_size] extended_memory, memory_score = self.add_sentinel(expanded_bert, memory_embs, mem_emb_size) # extended_memory: [batch_size, seq_size, 1+concept_size, mem_emb_size] # memory_score: [batch_size, seq_size, 1+concept_size] concept_ordinal = self.get_concept_oridinal(concept_size, memory_score) # [bs,sq,1+cs] memory_reverse_mask = fluid.layers.less_than( fluid.layers.expand(mem_length, expand_times=[1, 1, 1 + concept_size]) , concept_ordinal) # [batch_size, seq_size, 1+concept_size] memory_reverse_mask = fluid.layers.cast(memory_reverse_mask, dtype="float32") print_tensor(memory_reverse_mask, "memory_reverse_mask") memory_reverse_masked_infinity = fluid.layers.scale(memory_reverse_mask, scale=-1e6) # [batch_size, seq_size, 1+concept_size] print_tensor(memory_reverse_masked_infinity, "memory_reverse_masked_infinity") memory_score = fluid.layers.elementwise_add(memory_score, memory_reverse_masked_infinity) # [batch_size, seq_size, 1+concept_size] logger.info("memory_score:{}".format(memory_score.shape)) memory_att = fluid.layers.softmax(memory_score) # [batch_size, seq_size, 1+concept_size] memory_att = fluid.layers.unsqueeze(memory_att, axes=[2]) # [batch_size, seq_size, 1, 1+concept_size] logger.info("memory_att: {}".format(memory_att.shape)) logger.info("extended_memory: {}".format(extended_memory.shape)) summ = fluid.layers.matmul(memory_att,extended_memory) # [batch_size, seq_size,1, mem_emb_size] summ = fluid.layers.squeeze(summ, axes=[2]) # [batch_size, seq_size,mem_emb_size] if ignore_no_memory_token: condition = fluid.layers.less_than( dynamic_expand(mem_length, fluid.layers.zeros([1],"float32")), mem_length) # [bs, sq] # summ_true = fluid.layers.elementwise_mul( # summ, # fluid.layers.cast(condition, "float32")) # [bs, sq, ms] # summ_false = fluid.layers.elementwise_mul( # summ, # fluid.layers.scale(fluid.layers.cast(condition, "float32"), -1)) # [bs, sq, ms] # summ = fluid.layers.elementwise_add(summ_true, summ_false) # [bs, sq, ms] summ = fluid.layers.elementwise_mul( summ, fluid.layers.cast(condition, "float32")) # [bs, sq, ms] print_tensor(summ, "summ") if self.mem_method == "add": summ_transform = fluid.layers.fc(summ, size=bert_size, num_flatten_dims=2) # [batch_size, seq_size, bert_size] output = fluid.layers.sums(input=[summ_transform, bert_output]) # [batch_size, seq_size, bert_size] elif self.mem_method == "cat": logger.info("bert_output: {}".format(bert_output.shape)) logger.info("summ: {}".format(summ.shape)) output = fluid.layers.concat(input=[bert_output, summ], axis=2) # [batch_size, seq_size, bert_size + mem_emb_size] elif self.mem_method == "raw": logger.info("bert_output: {}".format(bert_output.shape)) logger.info("summ: {}".format(summ.shape)) output = summ # [batch_size, seq_size, mem_emb_size] else: raise ValueError("mem_method not supported") logger.info("output: {}".format(output.shape)) return output def get_concept_oridinal(self, concept_size, memory_score): """ :param concept_size: :param memory_score: [batch_size, seq_size, 1+concept_size] :return: """ concept_ordinal = fluid.layers.create_tensor(dtype="float32") fluid.layers.assign(np.arange(start=0, stop=(1 + concept_size), step=1, dtype=np.float32), concept_ordinal) # [1+cs] print_tensor(concept_ordinal, "concept_ordinal") print_tensor(memory_score, "memory_score") concept_ordinal = dynamic_expand(memory_score, concept_ordinal) # [bs,sq,1+cs] logger.info("concept_ordinal: {}".format(concept_ordinal.shape)) return concept_ordinal def add_sentinel(self, expanded_bert, memory_embs, mem_emb_size): """ :param expanded_bert: [batch_size, seq_size, 1, mem_emb_size] :param memory_embs: [batch_size, seq_size, concept_size, mem_emb_size] :param mem_emb_size: :return: """ sentinel = fluid.layers.create_parameter( name='{}_memory_layer_sentinel'.format(self.prefix) if self.prefix else 'memory_layer_sentinel', dtype="float32", shape=[mem_emb_size], default_initializer=fluid.initializer.ConstantInitializer(0)) # [mem_emb_size] print_tensor(sentinel, "sentinel") memory_embs_squeeze = fluid.layers.slice(memory_embs, axes=[2], starts=[0], ends=[1]) # [bs,sq,1,ms] print_tensor(memory_embs_squeeze, "memory_embs_squeeze") sentinel = dynamic_expand(memory_embs_squeeze, sentinel) # [bs,sq,1,ms] print_tensor(sentinel, "sentinel") print_tensor(memory_embs, "memory_embs") extended_memory = fluid.layers.concat([sentinel, memory_embs], axis=2) # [batch_size, seq_size, 1+concept_size, mem_emb_size] extended_memory = fluid.layers.transpose(extended_memory, perm=[0, 1, 3, 2]) # [batch_size, seq_size, mem_emb_size, 1+concept_size] logger.info("extended_memory: {}".format(extended_memory.shape)) memory_score = fluid.layers.matmul(expanded_bert, extended_memory) # [batch_size, seq_size, 1, 1+concept_size] memory_score = fluid.layers.squeeze(memory_score, axes=[2]) # [batch_size, seq_size, 1+concept_size] extended_memory = fluid.layers.transpose(extended_memory, perm=[0, 1, 3, 2]) # [batch_size, seq_size, 1+concept_size, mem_emb_size] return extended_memory, memory_score class TriLinearTwoTimeSelfAttentionLayer(object): def __init__(self, hidden_size, dropout_rate=0.0, cat_mul=False, cat_sub=False, cat_twotime=False, cat_twotime_mul=False, cat_twotime_sub=False): self.hidden_size = hidden_size self.dropout_rate = dropout_rate self.cat_mul = cat_mul self.cat_sub = cat_sub self.cat_twotime = cat_twotime self.cat_twotime_mul = cat_twotime_mul self.cat_twotime_sub = cat_twotime_sub def forward(self, hidden_emb, sequence_mask): """ :param hidden_emb: [batch_size, seq_size, hidden_size] :param sequence_mask: [batch_size, seq_size, 1] :return: """ assert len(hidden_emb.shape) ==3 and len(sequence_mask.shape) == 3 \ and sequence_mask.shape[-1] == 1 assert hidden_emb.shape[:2] == sequence_mask.shape[:2] hidden_size = self.hidden_size bias = fluid.layers.create_parameter(name='self_matching_layer_bias', shape=[1], dtype="float32", default_initializer=fluid.initializer.ConstantInitializer(0)) weight_1 = fluid.layers.create_parameter(name='self_matching_layer_weight1', shape=[hidden_size], dtype="float32", default_initializer=fluid.initializer.XavierInitializer(uniform=True, fan_in=1, fan_out=hidden_size)) # [HS] bs_1_hs = fluid.layers.slice(hidden_emb, axes=[1], starts=[0], ends=[1]) # [bs, 1, hs] print_tensor(bs_1_hs, "bs_1_hs") bs_hs_1 = fluid.layers.transpose(bs_1_hs, perm=[0, 2, 1]) # [bs, hs, 1] print_tensor(bs_hs_1, "bs_hs_1") print_tensor(weight_1, "weight_1") weight_1 = dynamic_expand(bs_1_hs, weight_1) # [BS, 1, HS] (a)jk weight_1 = fluid.layers.transpose(weight_1, perm=[0, 2, 1]) print_tensor(hidden_emb, "hidden_emb") print_tensor(weight_1, "weight_1") r1 = fluid.layers.matmul(hidden_emb, weight_1) # [BS, SQ, 1] aik print_tensor(r1, "r1") weight_2 = fluid.layers.create_parameter(name='self_matching_layer_weight2', shape=[hidden_size], dtype="float32", default_initializer=fluid.initializer.XavierInitializer(uniform=True, fan_in=1, fan_out=hidden_size)) # [HS] weight_2 = dynamic_expand(bs_1_hs, weight_2) # # [BS, 1, HS] (a)jk hidden_emb_transpose = fluid.layers.transpose(hidden_emb, perm=[0, 2, 1]) # [BS, HS, SQ] aji r2 = fluid.layers.matmul(weight_2, hidden_emb_transpose) # [BS, 1, SQ] aki print_tensor(r2, "r2") weight_mul = fluid.layers.create_parameter(name='self_matching_layer_weightmul', shape=[hidden_size], dtype="float32", default_initializer=fluid.initializer.XavierInitializer(uniform=True)) # [HS] weight_mul = dynamic_expand(hidden_emb, weight_mul) rmul_1 = fluid.layers.elementwise_mul(hidden_emb, weight_mul) # for "hidden * self.weight_mul". [bs, sq(i), hs(j)] print_tensor(rmul_1, "rmul_1") rmul_2 = fluid.layers.matmul(rmul_1, hidden_emb_transpose) # [bs, sq(i), hs(j)] mul [bs, hs(j), sq(k)] = [bs, sq(i), sq(k)] print_tensor(rmul_2, "rmul_2") r1 = fluid.layers.squeeze(r1, axes=[2]) # [BS, SQ] aik r1 = dynamic_expand( fluid.layers.transpose(rmul_2, [1, 0, 2]), # [sq, bs, sq] r1) # [ SQ(from 1), bs, SQ] r1 = fluid.layers.transpose(r1, [1, 2, 0]) # [bs, sq, sq(from 1)] r2 = fluid.layers.squeeze(r2, axes=[1]) # [BS, SQ] aik r2 = dynamic_expand( fluid.layers.transpose(rmul_2, [1, 0, 2]), # [sq, bs, sq] r2) # [ SQ(from 1), bs, SQ] r2 = fluid.layers.transpose(r2, [1, 0, 2]) # [bs,sq(from 1),sq] bias = dynamic_expand(rmul_2, bias) # [BS, SQ, SQ] sim_score = fluid.layers.sums(input=[r1, r2, rmul_2, bias]) # [bs,sq,1]+[bs,1,sq]+[bs,sq,sq]+[bs,sq,sq]=[BS,SQ,SQ] print_tensor(sim_score, "sim_score") sequence_mask = fluid.layers.cast(sequence_mask, dtype="float32") # [BS,SQ,1] softmax_mask = fluid.layers.elementwise_sub( sequence_mask, fluid.layers.fill_constant([1], "float32", 1)) # [BS,SQ,1] softmax_mask = fluid.layers.scale(softmax_mask, -1) very_negative_number = fluid.layers.fill_constant([1], value=-1e6, dtype="float32") logger.info("softmax_mask: {}".format(softmax_mask.shape)) logger.info("very_negative_number: {}".format(very_negative_number.shape)) softmax_mask = fluid.layers.elementwise_mul(softmax_mask, very_negative_number) # [BS,SQ,1] softmax_mask = fluid.layers.squeeze(softmax_mask, axes=[2]) # [BS,SQ] softmax_mask = dynamic_expand(fluid.layers.transpose(sim_score, perm=[2, 0, 1]), softmax_mask) # [sq(1),bs,sq] softmax_mask = fluid.layers.transpose(softmax_mask, perm=[1, 0, 2]) # [BS,sq(1),SQ] print_tensor(softmax_mask, "softmax_mask") sim_score = fluid.layers.elementwise_add(sim_score, softmax_mask) # [bs,sq,sq]+[bs,sq(1),sq]=[BS,SQ,SQ] print_tensor(sim_score, "sim_score") attn_prob = fluid.layers.softmax(sim_score) # [BS,SQ,SQ] weighted_sum = fluid.layers.matmul(attn_prob, hidden_emb) # [bs,sq,sq]*[bs,sq,hs]=[BS,SQ,HS] if any([self.cat_twotime, self.cat_twotime_mul, self.cat_twotime_sub]): twotime_att_prob = fluid.layers.matmul(attn_prob, attn_prob) # [bs,sq,sq]*[bs,sq,sq]=[BS,SQ,SQ] twotime_weited_sum = fluid.layers.matmul(twotime_att_prob, hidden_emb) # [BS,SQ,HS] out_tensors = [hidden_emb, weighted_sum] if self.cat_mul: out_tensors.append(fluid.layers.elementwise_mul(hidden_emb, weighted_sum)) if self.cat_sub: out_tensors.append(fluid.layers.elementwise_sub(hidden_emb, weighted_sum)) if self.cat_twotime: out_tensors.append(twotime_weited_sum) if self.cat_twotime_mul: out_tensors.append(fluid.layers.elementwise_mul(hidden_emb, twotime_weited_sum)) if self.cat_twotime_sub: out_tensors.append(fluid.layers.elementwise_sub(hidden_emb, twotime_weited_sum)) output = fluid.layers.concat(out_tensors, axis=2) # [BS,SQ, HS+HS+....] print_tensor(output, "output") return output
7,589
513
<reponame>igit-cn/zeus-iot<filename>zeus-core/src/main/java/com/zmops/iot/core/auth/exception/enums/AuthExceptionEnum.java package com.zmops.iot.core.auth.exception.enums; import com.zmops.iot.model.exception.AbstractBaseExceptionEnum; import lombok.Getter; /** * 认证失败的异常枚举 * * @author fengshuonan */ @Getter public enum AuthExceptionEnum implements AbstractBaseExceptionEnum { NOT_LOGIN_ERROR(1401, "用户未登录"), NOT_EXIST_ERROR(1408, "用户不存在"), USERNAME_PWD_ERROR(1402, "账号密码错误"), LOGIN_EXPPIRED(1403, "登录已过期,请重新登录"), ACCOUNT_FREEZE_ERROR(1404, "账号被冻结"), NO_ROLE_ERROR(1405, "用户没有分配角色,获取菜单失败"), VALID_CODE_ERROR(1406, "验证码错误"), ZBX_LOGIN_ERROR(1407, "Zabbix平台登录获取Token失败"), //用在PermissonException NO_PERMISSION(1500, "用户没有此操作权限"), NO_PAGE_ERROR(1502, "请求接口不存在或用户未登录"), LOGIN_TIMEOUT(409, "登录超时,请重新登录!"); AuthExceptionEnum(int code, String message) { this.code = code; this.message = message; } private Integer code; private String message; }
641
816
/* * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.dynamic.sql.delete; import java.util.Objects; import java.util.function.Function; import org.jetbrains.annotations.NotNull; import org.mybatis.dynamic.sql.SqlTable; import org.mybatis.dynamic.sql.util.Buildable; import org.mybatis.dynamic.sql.where.AbstractWhereDSL; import org.mybatis.dynamic.sql.where.AbstractWhereSupport; import org.mybatis.dynamic.sql.where.WhereModel; public class DeleteDSL<R> extends AbstractWhereSupport<DeleteDSL<R>.DeleteWhereBuilder> implements Buildable<R> { private final Function<DeleteModel, R> adapterFunction; private final SqlTable table; private final DeleteWhereBuilder whereBuilder = new DeleteWhereBuilder(); private DeleteDSL(SqlTable table, Function<DeleteModel, R> adapterFunction) { this.table = Objects.requireNonNull(table); this.adapterFunction = Objects.requireNonNull(adapterFunction); } @Override public DeleteWhereBuilder where() { return whereBuilder; } /** * WARNING! Calling this method could result in an delete statement that deletes * all rows in a table. * * @return the model class */ @NotNull @Override public R build() { DeleteModel deleteModel = DeleteModel.withTable(table) .withWhereModel(whereBuilder.buildWhereModel()) .build(); return adapterFunction.apply(deleteModel); } public static <R> DeleteDSL<R> deleteFrom(Function<DeleteModel, R> adapterFunction, SqlTable table) { return new DeleteDSL<>(table, adapterFunction); } public static DeleteDSL<DeleteModel> deleteFrom(SqlTable table) { return deleteFrom(Function.identity(), table); } public class DeleteWhereBuilder extends AbstractWhereDSL<DeleteWhereBuilder> implements Buildable<R> { private DeleteWhereBuilder() {} @NotNull @Override public R build() { return DeleteDSL.this.build(); } @Override protected DeleteWhereBuilder getThis() { return this; } protected WhereModel buildWhereModel() { return internalBuild(); } } }
992
933
<reponame>android-risc-v/external_perfetto /* * Copyright (C) 2018 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. */ #include "perfetto/ext/ipc/client.h" #include "perfetto/ext/ipc/host.h" #include "src/base/test/test_task_runner.h" #include "src/ipc/test/test_socket.h" #include "test/gtest_and_gmock.h" #include "src/ipc/test/greeter_service.gen.h" #include "src/ipc/test/greeter_service.ipc.h" namespace ipc_test { namespace { using ::testing::_; using ::testing::Invoke; using ::perfetto::ipc::AsyncResult; using ::perfetto::ipc::Client; using ::perfetto::ipc::Deferred; using ::perfetto::ipc::Host; using ::perfetto::ipc::Service; using ::perfetto::ipc::ServiceProxy; using namespace ::ipc_test::gen; ::perfetto::ipc::TestSocket kTestSocket{"ipc_integrationtest"}; class MockEventListener : public ServiceProxy::EventListener { public: MOCK_METHOD0(OnConnect, void()); MOCK_METHOD0(OnDisconnect, void()); }; class MockGreeterService : public ::ipc_test::gen::Greeter { public: MOCK_METHOD2(OnSayHello, void(const GreeterRequestMsg&, DeferredGreeterReplyMsg*)); void SayHello(const GreeterRequestMsg& request, DeferredGreeterReplyMsg reply) override { OnSayHello(request, &reply); } MOCK_METHOD2(OnWaveGoodbye, void(const GreeterRequestMsg&, DeferredGreeterReplyMsg*)); void WaveGoodbye(const GreeterRequestMsg& request, DeferredGreeterReplyMsg reply) override { OnWaveGoodbye(request, &reply); } }; class IPCIntegrationTest : public ::testing::Test { protected: void SetUp() override { kTestSocket.Destroy(); } void TearDown() override { kTestSocket.Destroy(); } perfetto::base::TestTaskRunner task_runner_; MockEventListener svc_proxy_events_; }; TEST_F(IPCIntegrationTest, SayHelloWaveGoodbye) { std::unique_ptr<Host> host = Host::CreateInstance(kTestSocket.name(), &task_runner_); ASSERT_TRUE(host); MockGreeterService* svc = new MockGreeterService(); ASSERT_TRUE(host->ExposeService(std::unique_ptr<Service>(svc))); auto on_connect = task_runner_.CreateCheckpoint("on_connect"); EXPECT_CALL(svc_proxy_events_, OnConnect()).WillOnce(Invoke(on_connect)); std::unique_ptr<Client> cli = Client::CreateInstance( {kTestSocket.name(), /*retry=*/false}, &task_runner_); std::unique_ptr<GreeterProxy> svc_proxy(new GreeterProxy(&svc_proxy_events_)); cli->BindService(svc_proxy->GetWeakPtr()); task_runner_.RunUntilCheckpoint("on_connect"); { GreeterRequestMsg req; req.set_name("<NAME>"); auto on_reply = task_runner_.CreateCheckpoint("on_hello_reply"); Deferred<GreeterReplyMsg> deferred_reply( [on_reply](AsyncResult<GreeterReplyMsg> reply) { ASSERT_TRUE(reply.success()); ASSERT_FALSE(reply.has_more()); ASSERT_EQ("Hello <NAME>", reply->message()); on_reply(); }); EXPECT_CALL(*svc, OnSayHello(_, _)) .WillOnce(Invoke([](const GreeterRequestMsg& host_req, Deferred<GreeterReplyMsg>* host_reply) { auto reply = AsyncResult<GreeterReplyMsg>::Create(); reply->set_message("Hello " + host_req.name()); host_reply->Resolve(std::move(reply)); })); svc_proxy->SayHello(req, std::move(deferred_reply)); task_runner_.RunUntilCheckpoint("on_hello_reply"); } { GreeterRequestMsg req; req.set_name("<NAME>"); auto on_reply = task_runner_.CreateCheckpoint("on_goodbye_reply"); Deferred<GreeterReplyMsg> deferred_reply( [on_reply](AsyncResult<GreeterReplyMsg> reply) { ASSERT_TRUE(reply.success()); ASSERT_FALSE(reply.has_more()); ASSERT_EQ("Goodbye <NAME>", reply->message()); on_reply(); }); EXPECT_CALL(*svc, OnWaveGoodbye(_, _)) .WillOnce(Invoke([](const GreeterRequestMsg& host_req, Deferred<GreeterReplyMsg>* host_reply) { auto reply = AsyncResult<GreeterReplyMsg>::Create(); reply->set_message("Goodbye " + host_req.name()); host_reply->Resolve(std::move(reply)); })); svc_proxy->WaveGoodbye(req, std::move(deferred_reply)); task_runner_.RunUntilCheckpoint("on_goodbye_reply"); } } } // namespace } // namespace ipc_test
1,879
910
<reponame>ThePreviousOne/SVG-Android<filename>docs/action/java/ic_alarm.java package com.github.megatronking.svg.iconlibs; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import com.github.megatronking.svg.support.SVGRenderer; /** * AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * SVG-Generator. It should not be modified by hand. */ public class ic_alarm extends SVGRenderer { public ic_alarm(Context context) { super(context); mAlpha = 1.0f; mWidth = dip2px(24.0f); mHeight = dip2px(24.0f); } @Override public void render(Canvas canvas, int w, int h, ColorFilter filter) { final float scaleX = w / 24.0f; final float scaleY = h / 24.0f; mPath.reset(); mRenderPath.reset(); mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); mFinalPathMatrix.postScale(scaleX, scaleY); mPath.moveTo(22.0f, 5.72f); mPath.rLineTo(-4.6f, -3.86f); mPath.rLineTo(-1.29f, 1.53f); mPath.rLineTo(4.6f, 3.86f); mPath.lineTo(22.0f, 5.72f); mPath.close(); mPath.moveTo(22.0f, 5.72f); mPath.moveTo(7.88f, 3.39f); mPath.lineTo(6.6f, 1.86f); mPath.lineTo(2.0f, 5.71f); mPath.rLineTo(1.29f, 1.53f); mPath.rLineTo(4.59f, -3.85f); mPath.close(); mPath.moveTo(7.88f, 3.39f); mPath.moveTo(12.5f, 8.0f); mPath.lineTo(11.0f, 8.0f); mPath.rLineTo(0f, 6.0f); mPath.rLineTo(4.75f, 2.85f); mPath.rLineTo(0.75f, -1.23f); mPath.rLineTo(-4.0f, -2.37f); mPath.lineTo(12.5f, 8.0f); mPath.close(); mPath.moveTo(12.5f, 8.0f); mPath.moveTo(12.0f, 4.0f); mPath.rCubicTo(-4.97f, 0.0f, -9.0f, 4.03f, -9.0f, 9.0f); mPath.rCubicTo(0.0f, 4.9699993f, 4.02f, 9.0f, 9.0f, 9.0f); mPath.rCubicTo(4.97f, 0.0f, 9.0f, -4.03f, 9.0f, -9.0f); mPath.rCubicTo(0.0f, -4.9699993f, -4.03f, -9.0f, -9.0f, -9.0f); mPath.close(); mPath.moveTo(12.0f, 4.0f); mPath.rMoveTo(0.0f, 16.0f); mPath.rCubicTo(-3.87f, 0.0f, -7.0f, -3.13f, -7.0f, -7.0f); mPath.rCubicTo(0.0f, -3.869999f, 3.13f, -7.0f, 7.0f, -7.0f); mPath.rCubicTo(3.87f, 0.0f, 7.0f, 3.13f, 7.0f, 7.0f); mPath.rCubicTo(0.0f, 3.87f, -3.13f, 7.0f, -7.0f, 7.0f); mPath.close(); mPath.moveTo(12.0f, 20.0f); mRenderPath.addPath(mPath, mFinalPathMatrix); if (mFillPaint == null) { mFillPaint = new Paint(); mFillPaint.setStyle(Paint.Style.FILL); mFillPaint.setAntiAlias(true); } mFillPaint.setColor(applyAlpha(-16777216, 1.0f)); mFillPaint.setColorFilter(filter); canvas.drawPath(mRenderPath, mFillPaint); } }
1,749
5,535
<reponame>reshke/gpdb //--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CRangeTest.h // // @doc: // Test for ranges //--------------------------------------------------------------------------- #ifndef GPOPT_CRangeTest_H #define GPOPT_CRangeTest_H #include "gpos/base.h" #include "gpopt/base/CRange.h" #include "unittest/gpopt/CTestUtils.h" namespace gpopt { using namespace gpos; //--------------------------------------------------------------------------- // @class: // CRangeTest // // @doc: // Static unit tests for ranges // //--------------------------------------------------------------------------- class CRangeTest { using PfPdatum = IDatum *(*) (CMemoryPool *, INT); private: static GPOS_RESULT EresInitAndCheckRanges(CMemoryPool *mp, IMDId *mdid, PfPdatum pf); static void TestRangeRelationship(CMemoryPool *mp, CRange *prange1, CRange *prange2, CRange *prange3, CRange *prange4, CRange *prange5); static void PrintRange(CMemoryPool *mp, CColRef *colref, CRange *prange); // int2 datum static IDatum *CreateInt2Datum(CMemoryPool *mp, INT i); // int4 datum static IDatum *CreateInt4Datum(CMemoryPool *mp, INT i); // int8 datum static IDatum *CreateInt8Datum(CMemoryPool *mp, INT li); public: // unittests static GPOS_RESULT EresUnittest(); static GPOS_RESULT EresUnittest_CRangeInt2(); static GPOS_RESULT EresUnittest_CRangeInt4(); static GPOS_RESULT EresUnittest_CRangeInt8(); static GPOS_RESULT EresUnittest_CRangeFromScalar(); }; // class CRangeTest } // namespace gpopt #endif // !GPOPT_CRangeTest_H // EOF
599
318
/** * @file libnatpmp.h Interface to NAT-PMP Client library * * Copyright (C) 2010 <NAME> */ enum { NATPMP_VERSION = 0, NATPMP_PORT = 5351, }; enum natpmp_op { NATPMP_OP_EXTERNAL = 0, NATPMP_OP_MAPPING_UDP = 1, NATPMP_OP_MAPPING_TCP = 2, }; enum natpmp_result { NATPMP_SUCCESS = 0, NATPMP_UNSUP_VERSION = 1, NATPMP_REFUSED = 2, NATPMP_NETWORK_FAILURE = 3, NATPMP_OUT_OF_RESOURCES = 4, NATPMP_UNSUP_OPCODE = 5 }; struct natpmp_resp { uint8_t vers; uint8_t op; uint16_t result; uint32_t epoch; union { uint32_t ext_addr; struct { uint16_t int_port; uint16_t ext_port; uint32_t lifetime; } map; } u; }; struct natpmp_req; typedef void (natpmp_resp_h)(int err, const struct natpmp_resp *resp, void *arg); int natpmp_external_request(struct natpmp_req **npp, const struct sa *srv, natpmp_resp_h *h, void *arg); int natpmp_mapping_request(struct natpmp_req **natpmpp, const struct sa *srv, uint16_t int_port, uint16_t ext_port, uint32_t lifetime, natpmp_resp_h *resph, void *arg);
533
707
<reponame>shueja-personal/allwpilib<filename>cscore/src/main/native/include/cscore_cv.h // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #ifndef CSCORE_CSCORE_CV_H_ #define CSCORE_CSCORE_CV_H_ #include "cscore_c.h" #ifdef CSCORE_CSCORE_RAW_CV_H_ #error "Cannot include both cscore_cv.h and cscore_raw_cv.h in the same file" #endif #ifdef __cplusplus #include "cscore_oo.h" // NOLINT(build/include_order) #endif #if CV_VERSION_MAJOR < 4 #ifdef __cplusplus extern "C" { // NOLINT(build/include_order) #endif struct CvMat; void CS_PutSourceFrame(CS_Source source, struct CvMat* image, CS_Status* status); uint64_t CS_GrabSinkFrame(CS_Sink sink, struct CvMat* image, CS_Status* status); uint64_t CS_GrabSinkFrameTimeout(CS_Sink sink, struct CvMat* image, double timeout, CS_Status* status); #ifdef __cplusplus } // extern "C" #endif #endif // CV_VERSION_MAJOR < 4 #ifdef __cplusplus #include "cscore_oo.h" namespace cv { class Mat; } // namespace cv namespace cs { /** * @defgroup cscore_cpp_opencv_special cscore C functions taking a cv::Mat* * * These are needed for specific interop implementations. * @{ */ extern "C" { uint64_t CS_GrabSinkFrameCpp(CS_Sink sink, cv::Mat* image, CS_Status* status); uint64_t CS_GrabSinkFrameTimeoutCpp(CS_Sink sink, cv::Mat* image, double timeout, CS_Status* status); void CS_PutSourceFrameCpp(CS_Source source, cv::Mat* image, CS_Status* status); } // extern "C" /** @} */ void PutSourceFrame(CS_Source source, cv::Mat& image, CS_Status* status); uint64_t GrabSinkFrame(CS_Sink sink, cv::Mat& image, CS_Status* status); uint64_t GrabSinkFrameTimeout(CS_Sink sink, cv::Mat& image, double timeout, CS_Status* status); /** * A source for user code to provide OpenCV images as video frames. * These sources require the WPILib OpenCV builds. * For an alternate OpenCV, include "cscore_raw_cv.h" instead, and * include your Mat header before that header. */ class CvSource : public ImageSource { public: CvSource() = default; /** * Create an OpenCV source. * * @param name Source name (arbitrary unique identifier) * @param mode Video mode being generated */ CvSource(std::string_view name, const VideoMode& mode); /** * Create an OpenCV source. * * @param name Source name (arbitrary unique identifier) * @param pixelFormat Pixel format * @param width width * @param height height * @param fps fps */ CvSource(std::string_view name, VideoMode::PixelFormat pixelFormat, int width, int height, int fps); /** * Put an OpenCV image and notify sinks. * * <p>Only 8-bit single-channel or 3-channel (with BGR channel order) images * are supported. If the format, depth or channel order is different, use * cv::Mat::convertTo() and/or cv::cvtColor() to convert it first. * * @param image OpenCV image */ void PutFrame(cv::Mat& image); }; /** * A sink for user code to accept video frames as OpenCV images. * These sinks require the WPILib OpenCV builds. * For an alternate OpenCV, include "cscore_raw_cv.h" instead, and * include your Mat header before that header. */ class CvSink : public ImageSink { public: CvSink() = default; /** * Create a sink for accepting OpenCV images. * * <p>WaitForFrame() must be called on the created sink to get each new * image. * * @param name Source name (arbitrary unique identifier) */ explicit CvSink(std::string_view name); /** * Create a sink for accepting OpenCV images in a separate thread. * * <p>A thread will be created that calls WaitForFrame() and calls the * processFrame() callback each time a new frame arrives. * * @param name Source name (arbitrary unique identifier) * @param processFrame Frame processing function; will be called with a * time=0 if an error occurred. processFrame should call GetImage() * or GetError() as needed, but should not call (except in very * unusual circumstances) WaitForImage(). */ CvSink(std::string_view name, std::function<void(uint64_t time)> processFrame); /** * Wait for the next frame and get the image. * Times out (returning 0) after timeout seconds. * The provided image will have three 8-bit channels stored in BGR order. * * @return Frame time, or 0 on error (call GetError() to obtain the error * message); the frame time is in the same time base as wpi::Now(), * and is in 1 us increments. */ [[nodiscard]] uint64_t GrabFrame(cv::Mat& image, double timeout = 0.225) const; /** * Wait for the next frame and get the image. May block forever. * The provided image will have three 8-bit channels stored in BGR order. * * @return Frame time, or 0 on error (call GetError() to obtain the error * message); the frame time is in the same time base as wpi::Now(), * and is in 1 us increments. */ [[nodiscard]] uint64_t GrabFrameNoTimeout(cv::Mat& image) const; }; inline CvSource::CvSource(std::string_view name, const VideoMode& mode) { m_handle = CreateCvSource(name, mode, &m_status); } inline CvSource::CvSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) { m_handle = CreateCvSource(name, VideoMode{format, width, height, fps}, &m_status); } inline void CvSource::PutFrame(cv::Mat& image) { m_status = 0; PutSourceFrame(m_handle, image, &m_status); } inline CvSink::CvSink(std::string_view name) { m_handle = CreateCvSink(name, &m_status); } inline CvSink::CvSink(std::string_view name, std::function<void(uint64_t time)> processFrame) { m_handle = CreateCvSinkCallback(name, processFrame, &m_status); } inline uint64_t CvSink::GrabFrame(cv::Mat& image, double timeout) const { m_status = 0; return GrabSinkFrameTimeout(m_handle, image, timeout, &m_status); } inline uint64_t CvSink::GrabFrameNoTimeout(cv::Mat& image) const { m_status = 0; return GrabSinkFrame(m_handle, image, &m_status); } } // namespace cs #endif #endif // CSCORE_CSCORE_CV_H_
2,397
398
<reponame>zhanghqgit/joyrpc<filename>joyrpc-plugin/joyrpc-codec/joyrpc-serialization-protostuff/src/main/java/io/joyrpc/codec/serialization/protostuff/schema/ZonedDateTimeSchema.java package io.joyrpc.codec.serialization.protostuff.schema; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import io.protostuff.Input; import io.protostuff.Output; import java.io.IOException; import java.lang.reflect.Field; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; public class ZonedDateTimeSchema extends AbstractJava8Schema<ZonedDateTime> { public static final ZonedDateTimeSchema INSTANCE = new ZonedDateTimeSchema(); public static final String DATE_TIME = "dateTime"; public static final String OFFSET = "offset"; public static final String ZONE = "zone"; protected static final Map<String, Integer> FIELD_MAP = new HashMap(); protected static Field FIELD_DATE_TIME = getWriteableField(ZonedDateTime.class, DATE_TIME); protected static Field FIELD_ZONE_OFFSET = getWriteableField(ZonedDateTime.class, OFFSET); protected static Field FIELD_ZONE_ID = getWriteableField(ZonedDateTime.class, ZONE); static { FIELD_MAP.put(DATE_TIME, 1); FIELD_MAP.put(OFFSET, 2); FIELD_MAP.put(ZONE, 3); } public ZonedDateTimeSchema() { super(ZonedDateTime.class); } @Override public String getFieldName(int number) { switch (number) { case 1: return DATE_TIME; case 2: return OFFSET; case 3: return ZONE; default: return null; } } @Override public int getFieldNumber(final String name) { return FIELD_MAP.get(name); } @Override public ZonedDateTime newMessage() { return ZonedDateTime.now(); } @Override public void mergeFrom(final Input input, final ZonedDateTime message) throws IOException { while (true) { int number = input.readFieldNumber(this); switch (number) { case 0: return; case 1: LocalDateTime localDateTime = LocalDateTime.now(); input.mergeObject(localDateTime, LocalDateTimeSchema.INSTANCE); setValue(FIELD_DATE_TIME, message, localDateTime); break; case 2: //不能使用0,0会缓存结果对象 ZoneOffset offset = ZoneOffset.ofTotalSeconds(1); input.mergeObject(offset, ZoneOffsetSchema.INSTANCE); setValue(FIELD_ZONE_OFFSET, message, offset); break; case 3: ZoneId zoneId = ZoneId.of("America/New_York"); input.mergeObject(zoneId, ZoneIdSchema.INSTANCE); setValue(FIELD_ZONE_ID, message, zoneId); break; default: input.handleUnknownField(number, this); } } } @Override public void writeTo(final Output output, final ZonedDateTime message) throws IOException { output.writeObject(1, message.toLocalDateTime(), LocalDateTimeSchema.INSTANCE, false); output.writeObject(2, message.getOffset(), ZoneOffsetSchema.INSTANCE, false); if (message.getZone() != null) { output.writeObject(3, message.getZone(), ZoneIdSchema.INSTANCE, false); } } }
1,816
1,457
// // S1Sequencer.hpp // AudioKitSynthOne // // Created by AudioKit Contributors on 3/06/19. // Copyright © 2019 AudioKit. All rights reserved. // #include <array> #include <atomic> #include <functional> #include <list> #include <vector> #import "Foundation/Foundation.h" #import "S1AudioUnit.h" #import "S1Parameter.h" #import "S1SeqNoteNumber.hpp" @class AEArray; #ifdef __cplusplus using DSPParameters = std::array<float, S1Parameter::S1ParameterCount>; using BeatCounterChangedCallback = std::function<void()>; using KeyOnCallback = std::function<void(int, int)>; using KeyOffCallback = std::function<void(int)>; class S1Sequencer { public: S1Sequencer() = delete; S1Sequencer(KeyOnCallback keyOnCb, KeyOffCallback keyOffCb, BeatCounterChangedCallback beatChangedCb); void setSampleRate(double sampleRate); void init(); void reset(bool resetNotes); void setNotesPerOctave(int notes); int getArpBeatCount(); void process(DSPParameters &params, AEArray *heldNoteNumbersAE); private: double mSampleRate = 0; const int maxSequencerNotes = 1024; // 128 midi note numbers * 4 arp octaves * up+down void reserveNotes(); // Allocate notes before rendering // Array of midi note numbers of NoteState's which have had a noteOn event but not yet a noteOff event. int previousHeldNoteNumbersAECount; // previous render loop held key count // Beattime Counter double mBeatTime = 0; std::atomic<int> mStepCounter = 0; ///once init'd: sequencerNotes can be accessed and mutated only within process and resetDSP std::vector<SeqNoteNumber> sequencerNotes; std::vector<NoteNumber> sequencerNotes2; ///once init'd: sequencerLastNotes can be accessed and mutated only within process and resetDSP std::list<int> sequencerLastNotes; std::atomic<int> mNotesPerOctave{12}; // Change notifications BeatCounterChangedCallback mBeatCounterDidChange; KeyOnCallback mTurnOnKey; KeyOffCallback mTurnOffKey; }; #endif
665
4,054
<filename>vdslib/src/main/java/com/yahoo/vdslib/state/NodeType.java // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vdslib.state; public enum NodeType { STORAGE("storage"), DISTRIBUTOR("distributor"); private final String serializeAs; private NodeType(String serializeAs) { this.serializeAs = serializeAs; } public String toString() { return serializeAs; } public static NodeType get(String serialized) { for(NodeType type : values()) { if (type.serializeAs.equals(serialized)) return type; } throw new IllegalArgumentException("Unknown node type '" + serialized + "'. Legal values are 'storage' and 'distributor'."); } public static NodeType[] getTypes() { NodeType types[] = new NodeType[2]; types[0] = STORAGE; types[1] = DISTRIBUTOR; return types; } }
369
480
# domain management # # Copyright <NAME> 2009 # Copyright <NAME> 2009 # Copyright <NAME> 2007-2012 # Copyright <NAME> 2011 # Copyright <NAME> <<EMAIL>> 2011 # Copyright <NAME> 2008 # Copyright <NAME> 2012 # # 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/>. # import samba.getopt as options import ldb import string import os import sys import tempfile import logging from samba.net import Net, LIBNET_JOIN_AUTOMATIC import samba.ntacls from samba.join import join_RODC, join_DC, join_subdomain from samba.auth import system_session from samba.samdb import SamDB from samba.dcerpc import drsuapi from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT from samba.netcmd import ( Command, CommandError, SuperCommand, Option ) from samba.netcmd.common import netcmd_get_domain_infos_via_cldap from samba.samba3 import Samba3 from samba.samba3 import param as s3param from samba.upgrade import upgrade_from_samba3 from samba.drs_utils import ( sendDsReplicaSync, drsuapi_connect, drsException, sendRemoveDsServer) from samba.dsdb import ( DS_DOMAIN_FUNCTION_2000, DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2003_MIXED, DS_DOMAIN_FUNCTION_2008, DS_DOMAIN_FUNCTION_2008_R2, DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL, DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL, UF_WORKSTATION_TRUST_ACCOUNT, UF_SERVER_TRUST_ACCOUNT, UF_TRUSTED_FOR_DELEGATION ) from samba.credentials import DONT_USE_KERBEROS from samba.provision import ( provision, FILL_FULL, FILL_NT4SYNC, FILL_DRS, ProvisioningError, ) def get_testparm_var(testparm, smbconf, varname): cmd = "%s -s -l --parameter-name='%s' %s 2>/dev/null" % (testparm, varname, smbconf) output = os.popen(cmd, 'r').readline() return output.strip() try: import samba.dckeytab class cmd_domain_export_keytab(Command): """Dump Kerberos keys of the domain into a keytab.""" synopsis = "%prog <keytab> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_options = [ Option("--principal", help="extract only this principal", type=str), ] takes_args = ["keytab"] def run(self, keytab, credopts=None, sambaopts=None, versionopts=None, principal=None): lp = sambaopts.get_loadparm() net = Net(None, lp) net.export_keytab(keytab=keytab, principal=principal) except: cmd_domain_export_keytab = None class cmd_domain_info(Command): """Print basic info about a domain and the DC passed as parameter.""" synopsis = "%prog <ip_address> [options]" takes_options = [ ] takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_args = ["address"] def run(self, address, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() try: res = netcmd_get_domain_infos_via_cldap(lp, None, address) except RuntimeError: raise CommandError("Invalid IP address '" + address + "'!") self.outf.write("Forest : %s\n" % res.forest) self.outf.write("Domain : %s\n" % res.dns_domain) self.outf.write("Netbios domain : %s\n" % res.domain_name) self.outf.write("DC name : %s\n" % res.pdc_dns_name) self.outf.write("DC netbios name : %s\n" % res.pdc_name) self.outf.write("Server site : %s\n" % res.server_site) self.outf.write("Client site : %s\n" % res.client_site) class cmd_domain_provision(Command): """Provision a domain.""" synopsis = "%prog [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("--interactive", help="Ask for names", action="store_true"), Option("--domain", type="string", metavar="DOMAIN", help="set domain"), Option("--domain-guid", type="string", metavar="GUID", help="set domainguid (otherwise random)"), Option("--domain-sid", type="string", metavar="SID", help="set domainsid (otherwise random)"), Option("--ntds-guid", type="string", metavar="GUID", help="set NTDS object GUID (otherwise random)"), Option("--invocationid", type="string", metavar="GUID", help="set invocationid (otherwise random)"), Option("--host-name", type="string", metavar="HOSTNAME", help="set hostname"), Option("--host-ip", type="string", metavar="IPADDRESS", help="set IPv4 ipaddress"), Option("--host-ip6", type="string", metavar="IP6ADDRESS", help="set IPv6 ipaddress"), Option("--adminpass", type="string", metavar="PASSWORD", help="choose admin password (otherwise random)"), Option("--krbtgtpass", type="string", metavar="PASSWORD", help="choose krbtgt password (otherwise random)"), Option("--machinepass", type="string", metavar="PASSWORD", help="choose machine password (otherwise random)"), Option("--dns-backend", type="choice", metavar="NAMESERVER-BACKEND", choices=["SAMBA_INTERNAL", "BIND9_FLATFILE", "BIND9_DLZ", "NONE"], help="The DNS server backend. SAMBA_INTERNAL is the builtin name server (default), " "BIND9_FLATFILE uses bind9 text database to store zone information, " "BIND9_DLZ uses samba4 AD to store zone information, " "NONE skips the DNS setup entirely (not recommended)", default="SAMBA_INTERNAL"), Option("--dnspass", type="string", metavar="PASSWORD", help="choose dns password (otherwise random)"), Option("--ldapadminpass", type="string", metavar="PASSWORD", help="choose password to set between Samba and it's LDAP backend (otherwise random)"), Option("--root", type="string", metavar="USERNAME", help="choose 'root' unix username"), Option("--nobody", type="string", metavar="USERNAME", help="choose 'nobody' user"), Option("--users", type="string", metavar="GROUPNAME", help="choose 'users' group"), Option("--quiet", help="Be quiet", action="store_true"), Option("--blank", action="store_true", help="do not add users or groups, just the structure"), Option("--ldap-backend-type", type="choice", metavar="LDAP-BACKEND-TYPE", help="Test initialisation support for unsupported LDAP backend type (fedora-ds or openldap) DO NOT USE", choices=["fedora-ds", "openldap"]), Option("--server-role", type="choice", metavar="ROLE", choices=["domain controller", "dc", "member server", "member", "standalone"], help="The server role (domain controller | dc | member server | member | standalone). Default is dc.", default="domain controller"), Option("--function-level", type="choice", metavar="FOR-FUN-LEVEL", choices=["2000", "2003", "2008", "2008_R2"], help="The domain and forest function level (2000 | 2003 | 2008 | 2008_R2 - always native). Default is (Windows) 2003 Native.", default="2003"), Option("--next-rid", type="int", metavar="NEXTRID", default=1000, help="The initial nextRid value (only needed for upgrades). Default is 1000."), Option("--partitions-only", help="Configure Samba's partitions, but do not modify them (ie, join a BDC)", action="store_true"), Option("--targetdir", type="string", metavar="DIR", help="Set target directory"), Option("--ol-mmr-urls", type="string", metavar="LDAPSERVER", help="List of LDAP-URLS [ ldap://<FQHN>:<PORT>/ (where <PORT> has to be different than 389!) ] separated with comma (\",\") for use with OpenLDAP-MMR (Multi-Master-Replication), e.g.: \"ldap://s4dc1:9000,ldap://s4dc2:9000\""), Option("--use-xattrs", type="choice", choices=["yes", "no", "auto"], help="Define if we should use the native fs capabilities or a tdb file for storing attributes likes ntacl, auto tries to make an inteligent guess based on the user rights and system capabilities", default="auto"), Option("--use-ntvfs", action="store_true", help="Use NTVFS for the fileserver (default = no)"), Option("--use-rfc2307", action="store_true", help="Use AD to store posix attributes (default = no)"), ] takes_args = [] def run(self, sambaopts=None, credopts=None, versionopts=None, interactive=None, domain=None, domain_guid=None, domain_sid=None, ntds_guid=None, invocationid=None, host_name=None, host_ip=None, host_ip6=None, adminpass=None, krbtgtpass=None, machinepass=None, dns_backend=None, dns_forwarder=None, dnspass=None, ldapadminpass=None, root=None, nobody=None, users=None, quiet=None, blank=None, ldap_backend_type=None, server_role=None, function_level=None, next_rid=None, partitions_only=None, targetdir=None, ol_mmr_urls=None, use_xattrs=None, use_ntvfs=None, use_rfc2307=None): self.logger = self.get_logger("provision") if quiet: self.logger.setLevel(logging.WARNING) else: self.logger.setLevel(logging.INFO) lp = sambaopts.get_loadparm() smbconf = lp.configfile creds = credopts.get_credentials(lp) creds.set_kerberos_state(DONT_USE_KERBEROS) if dns_forwarder is not None: suggested_forwarder = dns_forwarder else: suggested_forwarder = self._get_nameserver_ip() if suggested_forwarder is None: suggested_forwarder = "none" if len(self.raw_argv) == 1: interactive = True if interactive: from getpass import getpass import socket def ask(prompt, default=None): if default is not None: print "%s [%s]: " % (prompt, default), else: print "%s: " % (prompt,), return sys.stdin.readline().rstrip("\n") or default try: default = socket.getfqdn().split(".", 1)[1].upper() except IndexError: default = None realm = ask("Realm", default) if realm in (None, ""): raise CommandError("No realm set!") try: default = realm.split(".")[0] except IndexError: default = None domain = ask("Domain", default) if domain is None: raise CommandError("No domain set!") server_role = ask("Server Role (dc, member, standalone)", "dc") dns_backend = ask("DNS backend (SAMBA_INTERNAL, BIND9_FLATFILE, BIND9_DLZ, NONE)", "SAMBA_INTERNAL") if dns_backend in (None, ''): raise CommandError("No DNS backend set!") if dns_backend == "SAMBA_INTERNAL": dns_forwarder = ask("DNS forwarder IP address (write 'none' to disable forwarding)", suggested_forwarder) if dns_forwarder.lower() in (None, 'none'): suggested_forwarder = None dns_forwarder = None while True: adminpassplain = getpass("Administrator password: ") if not adminpassplain: self.errf.write("Invalid administrator password.\n") else: adminpassverify = getpass("Retype password: ") if not adminpassplain == adminpassverify: self.errf.write("Sorry, passwords do not match.\n") else: adminpass = adminpassplain break else: realm = sambaopts._lp.get('realm') if realm is None: raise CommandError("No realm set!") if domain is None: raise CommandError("No domain set!") if not adminpass: self.logger.info("Administrator password will be set randomly!") if function_level == "2000": dom_for_fun_level = DS_DOMAIN_FUNCTION_2000 elif function_level == "2003": dom_for_fun_level = DS_DOMAIN_FUNCTION_2003 elif function_level == "2008": dom_for_fun_level = DS_DOMAIN_FUNCTION_2008 elif function_level == "2008_R2": dom_for_fun_level = DS_DOMAIN_FUNCTION_2008_R2 if dns_backend == "SAMBA_INTERNAL" and dns_forwarder is None: dns_forwarder = suggested_forwarder samdb_fill = FILL_FULL if blank: samdb_fill = FILL_NT4SYNC elif partitions_only: samdb_fill = FILL_DRS if targetdir is not None: if not os.path.isdir(targetdir): os.mkdir(targetdir) eadb = True if use_xattrs == "yes": eadb = False elif use_xattrs == "auto" and not lp.get("posix:eadb"): if targetdir: file = tempfile.NamedTemporaryFile(dir=os.path.abspath(targetdir)) else: file = tempfile.NamedTemporaryFile(dir=os.path.abspath(os.path.dirname(lp.get("private dir")))) try: try: samba.ntacls.setntacl(lp, file.name, "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native") eadb = False except Exception: self.logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. ") finally: file.close() if eadb: self.logger.info("not using extended attributes to store ACLs and other metadata. If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.") session = system_session() try: result = provision(self.logger, session, creds, smbconf=smbconf, targetdir=targetdir, samdb_fill=samdb_fill, realm=realm, domain=domain, domainguid=domain_guid, domainsid=domain_sid, hostname=host_name, hostip=host_ip, hostip6=host_ip6, ntdsguid=ntds_guid, invocationid=invocationid, adminpass=<PASSWORD>, krbtgtpass=krbtgtpass, machinepass=machinepass, dns_backend=dns_backend, dns_forwarder=dns_forwarder, dnspass=dnspass, root=root, nobody=nobody, users=users, serverrole=server_role, dom_for_fun_level=dom_for_fun_level, backend_type=ldap_backend_type, ldapadminpass=<PASSWORD>, ol_mmr_urls=ol_mmr_urls, useeadb=eadb, next_rid=next_rid, lp=lp, use_ntvfs=use_ntvfs, use_rfc2307=use_rfc2307, skip_sysvolacl=False) except ProvisioningError, e: raise CommandError("Provision failed", e) result.report_logger(self.logger) def _get_nameserver_ip(self): """Grab the nameserver IP address from /etc/resolv.conf.""" from os import path RESOLV_CONF="/etc/resolv.conf" if not path.isfile(RESOLV_CONF): self.logger.warning("Failed to locate %s" % RESOLV_CONF) return None handle = None try: handle = open(RESOLV_CONF, 'r') for line in handle: if not line.startswith('nameserver'): continue # we want the last non-space continuous string of the line return line.strip().split()[-1] finally: if handle is not None: handle.close() self.logger.warning("No nameserver found in %s" % RESOLV_CONF) class cmd_domain_dcpromo(Command): """Promote an existing domain member or NT4 PDC to an AD DC.""" synopsis = "%prog <dnsdomain> [DC|RODC] [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("--server", help="DC to join", type=str), Option("--site", help="site to join", type=str), Option("--targetdir", help="where to store provision", type=str), Option("--domain-critical-only", help="only replicate critical domain objects", action="store_true"), Option("--machinepass", type=str, metavar="PASSWORD", help="choose machine password (otherwise random)"), Option("--use-ntvfs", help="Use NTVFS for the fileserver (default = no)", action="store_true"), Option("--dns-backend", type="choice", metavar="NAMESERVER-BACKEND", choices=["SAMBA_INTERNAL", "BIND9_DLZ", "NONE"], help="The DNS server backend. SAMBA_INTERNAL is the builtin name server (default), " "BIND9_DLZ uses samba4 AD to store zone information, " "NONE skips the DNS setup entirely (this DC will not be a DNS server)", default="SAMBA_INTERNAL") ] takes_args = ["domain", "role?"] def run(self, domain, role=None, sambaopts=None, credopts=None, versionopts=None, server=None, site=None, targetdir=None, domain_critical_only=False, parent_domain=None, machinepass=None, use_ntvfs=False, dns_backend=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) net = Net(creds, lp, server=credopts.ipaddress) if site is None: site = "Default-First-Site-Name" netbios_name = lp.get("netbios name") if not role is None: role = role.upper() if role == "DC": join_DC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend, promote_existing=True) elif role == "RODC": join_RODC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend, promote_existing=True) else: raise CommandError("Invalid role '%s' (possible values: DC, RODC)" % role) class cmd_domain_join(Command): """Join domain as either member or backup domain controller.""" synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("--server", help="DC to join", type=str), Option("--site", help="site to join", type=str), Option("--targetdir", help="where to store provision", type=str), Option("--parent-domain", help="parent domain to create subdomain under", type=str), Option("--domain-critical-only", help="only replicate critical domain objects", action="store_true"), Option("--machinepass", type=str, metavar="PASSWORD", help="choose machine password (otherwise random)"), Option("--use-ntvfs", help="Use NTVFS for the fileserver (default = no)", action="store_true"), Option("--dns-backend", type="choice", metavar="NAMESERVER-BACKEND", choices=["SAMBA_INTERNAL", "BIND9_DLZ", "NONE"], help="The DNS server backend. SAMBA_INTERNAL is the builtin name server (default), " "BIND9_DLZ uses samba4 AD to store zone information, " "NONE skips the DNS setup entirely (this DC will not be a DNS server)", default="SAMBA_INTERNAL") ] takes_args = ["domain", "role?"] def run(self, domain, role=None, sambaopts=None, credopts=None, versionopts=None, server=None, site=None, targetdir=None, domain_critical_only=False, parent_domain=None, machinepass=None, use_ntvfs=False, dns_backend=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) net = Net(creds, lp, server=credopts.ipaddress) if site is None: site = "Default-First-Site-Name" netbios_name = lp.get("netbios name") if not role is None: role = role.upper() if role is None or role == "MEMBER": (join_password, sid, domain_name) = net.join_member( domain, netbios_name, LIBNET_JOIN_AUTOMATIC, machinepass=machinepass) self.errf.write("Joined domain %s (%s)\n" % (domain_name, sid)) elif role == "DC": join_DC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend) elif role == "RODC": join_RODC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend) elif role == "SUBDOMAIN": netbios_domain = lp.get("workgroup") if parent_domain is None: parent_domain = ".".join(domain.split(".")[1:]) join_subdomain(server=server, creds=creds, lp=lp, dnsdomain=domain, parent_domain=parent_domain, site=site, netbios_name=netbios_name, netbios_domain=netbios_domain, targetdir=targetdir, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend) else: raise CommandError("Invalid role '%s' (possible values: MEMBER, DC, RODC, SUBDOMAIN)" % role) class cmd_domain_demote(Command): """Demote ourselves from the role of Domain Controller.""" synopsis = "%prog [options]" takes_options = [ Option("--server", help="DC to force replication before demote", type=str), Option("--targetdir", help="where provision is stored", type=str), ] takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } def run(self, sambaopts=None, credopts=None, versionopts=None, server=None, targetdir=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) net = Net(creds, lp, server=credopts.ipaddress) netbios_name = lp.get("netbios name") samdb = SamDB(session_info=system_session(), credentials=creds, lp=lp) if not server: res = samdb.search(expression='(&(objectClass=computer)(serverReferenceBL=*))', attrs=["dnsHostName", "name"]) if (len(res) == 0): raise CommandError("Unable to search for servers") if (len(res) == 1): raise CommandError("You are the latest server in the domain") server = None for e in res: if str(e["name"]).lower() != netbios_name.lower(): server = e["dnsHostName"] break ntds_guid = samdb.get_ntds_GUID() msg = samdb.search(base=str(samdb.get_config_basedn()), scope=ldb.SCOPE_SUBTREE, expression="(objectGUID=%s)" % ntds_guid, attrs=['options']) if len(msg) == 0 or "options" not in msg[0]: raise CommandError("Failed to find options on %s" % ntds_guid) ntds_dn = msg[0].dn dsa_options = int(str(msg[0]['options'])) res = samdb.search(expression="(fSMORoleOwner=%s)" % str(ntds_dn), controls=["search_options:1:2"]) if len(res) != 0: raise CommandError("Current DC is still the owner of %d role(s), use the role command to transfer roles to another DC" % len(res)) self.errf.write("Using %s as partner server for the demotion\n" % server) (drsuapiBind, drsuapi_handle, supportedExtensions) = drsuapi_connect(server, lp, creds) self.errf.write("Desactivating inbound replication\n") nmsg = ldb.Message() nmsg.dn = msg[0].dn dsa_options |= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) if not (dsa_options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) and not samdb.am_rodc(): self.errf.write("Asking partner server %s to synchronize from us\n" % server) for part in (samdb.get_schema_basedn(), samdb.get_config_basedn(), samdb.get_root_basedn()): try: sendDsReplicaSync(drsuapiBind, drsuapi_handle, ntds_guid, str(part), drsuapi.DRSUAPI_DRS_WRIT_REP) except drsException, e: self.errf.write( "Error while demoting, " "re-enabling inbound replication\n") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) raise CommandError("Error while sending a DsReplicaSync for partion %s" % str(part), e) try: remote_samdb = SamDB(url="ldap://%s" % server, session_info=system_session(), credentials=creds, lp=lp) self.errf.write("Changing userControl and container\n") res = remote_samdb.search(base=str(remote_samdb.get_root_basedn()), expression="(&(objectClass=user)(sAMAccountName=%s$))" % netbios_name.upper(), attrs=["userAccountControl"]) dc_dn = res[0].dn uac = int(str(res[0]["userAccountControl"])) except Exception, e: self.errf.write( "Error while demoting, re-enabling inbound replication\n") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) raise CommandError("Error while changing account control", e) if (len(res) != 1): self.errf.write( "Error while demoting, re-enabling inbound replication") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) raise CommandError("Unable to find object with samaccountName = %s$" " in the remote dc" % netbios_name.upper()) olduac = uac uac ^= (UF_SERVER_TRUST_ACCOUNT|UF_TRUSTED_FOR_DELEGATION) uac |= UF_WORKSTATION_TRUST_ACCOUNT msg = ldb.Message() msg.dn = dc_dn msg["userAccountControl"] = ldb.MessageElement("%d" % uac, ldb.FLAG_MOD_REPLACE, "userAccountControl") try: remote_samdb.modify(msg) except Exception, e: self.errf.write( "Error while demoting, re-enabling inbound replication") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) raise CommandError("Error while changing account control", e) parent = msg.dn.parent() rdn = str(res[0].dn) rdn = string.replace(rdn, ",%s" % str(parent), "") # Let's move to the Computer container i = 0 newrdn = rdn computer_dn = ldb.Dn(remote_samdb, "CN=Computers,%s" % str(remote_samdb.get_root_basedn())) res = remote_samdb.search(base=computer_dn, expression=rdn, scope=ldb.SCOPE_ONELEVEL) if (len(res) != 0): res = remote_samdb.search(base=computer_dn, expression="%s-%d" % (rdn, i), scope=ldb.SCOPE_ONELEVEL) while(len(res) != 0 and i < 100): i = i + 1 res = remote_samdb.search(base=computer_dn, expression="%s-%d" % (rdn, i), scope=ldb.SCOPE_ONELEVEL) if i == 100: self.errf.write( "Error while demoting, re-enabling inbound replication\n") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) msg = ldb.Message() msg.dn = dc_dn msg["userAccountControl"] = ldb.MessageElement("%d" % uac, ldb.FLAG_MOD_REPLACE, "userAccountControl") remote_samdb.modify(msg) raise CommandError("Unable to find a slot for renaming %s," " all names from %s-1 to %s-%d seemed used" % (str(dc_dn), rdn, rdn, i - 9)) newrdn = "%s-%d" % (rdn, i) try: newdn = ldb.Dn(remote_samdb, "%s,%s" % (newrdn, str(computer_dn))) remote_samdb.rename(dc_dn, newdn) except Exception, e: self.errf.write( "Error while demoting, re-enabling inbound replication\n") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) msg = ldb.Message() msg.dn = dc_dn msg["userAccountControl"] = ldb.MessageElement("%d" % uac, ldb.FLAG_MOD_REPLACE, "userAccountControl") remote_samdb.modify(msg) raise CommandError("Error while renaming %s to %s" % (str(dc_dn), str(newdn)), e) server_dsa_dn = samdb.get_serverName() domain = remote_samdb.get_root_basedn() try: sendRemoveDsServer(drsuapiBind, drsuapi_handle, server_dsa_dn, domain) except drsException, e: self.errf.write( "Error while demoting, re-enabling inbound replication\n") dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options") samdb.modify(nmsg) msg = ldb.Message() msg.dn = newdn msg["userAccountControl"] = ldb.MessageElement("%d" % uac, ldb.FLAG_MOD_REPLACE, "userAccountControl") print str(dc_dn) remote_samdb.modify(msg) remote_samdb.rename(newdn, dc_dn) raise CommandError("Error while sending a removeDsServer", e) for s in ("CN=Entreprise,CN=Microsoft System Volumes,CN=System,CN=Configuration", "CN=%s,CN=Microsoft System Volumes,CN=System,CN=Configuration" % lp.get("realm"), "CN=Domain System Volumes (SYSVOL share),CN=File Replication Service,CN=System"): try: remote_samdb.delete(ldb.Dn(remote_samdb, "%s,%s,%s" % (str(rdn), s, str(remote_samdb.get_root_basedn())))) except ldb.LdbError, l: pass for s in ("CN=Entreprise,CN=NTFRS Subscriptions", "CN=%s, CN=NTFRS Subscriptions" % lp.get("realm"), "CN=Domain system Volumes (SYSVOL Share), CN=NTFRS Subscriptions", "CN=NTFRS Subscriptions"): try: remote_samdb.delete(ldb.Dn(remote_samdb, "%s,%s" % (s, str(newdn)))) except ldb.LdbError, l: pass self.errf.write("Demote successfull\n") class cmd_domain_level(Command): """Raise domain and forest function levels.""" synopsis = "%prog (show|raise <options>) [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server", type=str, metavar="URL", dest="H"), Option("--quiet", help="Be quiet", action="store_true"), Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2"], help="The forest function level (2003 | 2008 | 2008_R2)"), Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2"], help="The domain function level (2003 | 2008 | 2008_R2)") ] takes_args = ["subcommand"] def run(self, subcommand, H=None, forest_level=None, domain_level=None, quiet=False, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = samdb.domain_dn() res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(), scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"]) assert len(res_forest) == 1 res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version", "nTMixedDomain"]) assert len(res_domain) == 1 res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(), scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)", attrs=["msDS-Behavior-Version"]) assert len(res_dc_s) >= 1 try: level_forest = int(res_forest[0]["msDS-Behavior-Version"][0]) level_domain = int(res_domain[0]["msDS-Behavior-Version"][0]) level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0]) min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value for msg in res_dc_s: if int(msg["msDS-Behavior-Version"][0]) < min_level_dc: min_level_dc = int(msg["msDS-Behavior-Version"][0]) if level_forest < 0 or level_domain < 0: raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!") if min_level_dc < 0: raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!") if level_forest > level_domain: raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!") if level_domain > min_level_dc: raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!") except KeyError: raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!") if subcommand == "show": self.message("Domain and forest function level for domain '%s'" % domain_dn) if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0: self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!") if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0: self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!") if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0: self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!") self.message("") if level_forest == DS_DOMAIN_FUNCTION_2000: outstr = "2000" elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED: outstr = "2003 with mixed domains/interim (NT4 DC support)" elif level_forest == DS_DOMAIN_FUNCTION_2003: outstr = "2003" elif level_forest == DS_DOMAIN_FUNCTION_2008: outstr = "2008" elif level_forest == DS_DOMAIN_FUNCTION_2008_R2: outstr = "2008 R2" else: outstr = "higher than 2008 R2" self.message("Forest function level: (Windows) " + outstr) if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0: outstr = "2000 mixed (NT4 DC support)" elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0: outstr = "2000" elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED: outstr = "2003 with mixed domains/interim (NT4 DC support)" elif level_domain == DS_DOMAIN_FUNCTION_2003: outstr = "2003" elif level_domain == DS_DOMAIN_FUNCTION_2008: outstr = "2008" elif level_domain == DS_DOMAIN_FUNCTION_2008_R2: outstr = "2008 R2" else: outstr = "higher than 2008 R2" self.message("Domain function level: (Windows) " + outstr) if min_level_dc == DS_DOMAIN_FUNCTION_2000: outstr = "2000" elif min_level_dc == DS_DOMAIN_FUNCTION_2003: outstr = "2003" elif min_level_dc == DS_DOMAIN_FUNCTION_2008: outstr = "2008" elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2: outstr = "2008 R2" else: outstr = "higher than 2008 R2" self.message("Lowest function level of a DC: (Windows) " + outstr) elif subcommand == "raise": msgs = [] if domain_level is not None: if domain_level == "2003": new_level_domain = DS_DOMAIN_FUNCTION_2003 elif domain_level == "2008": new_level_domain = DS_DOMAIN_FUNCTION_2008 elif domain_level == "2008_R2": new_level_domain = DS_DOMAIN_FUNCTION_2008_R2 if new_level_domain <= level_domain and level_domain_mixed == 0: raise CommandError("Domain function level can't be smaller than or equal to the actual one!") if new_level_domain > min_level_dc: raise CommandError("Domain function level can't be higher than the lowest function level of a DC!") # Deactivate mixed/interim domain support if level_domain_mixed != 0: # Directly on the base DN m = ldb.Message() m.dn = ldb.Dn(samdb, domain_dn) m["nTMixedDomain"] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "nTMixedDomain") samdb.modify(m) # Under partitions m = ldb.Message() m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % samdb.get_config_basedn()) m["nTMixedDomain"] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "nTMixedDomain") try: samdb.modify(m) except ldb.LdbError, (enum, emsg): if enum != ldb.ERR_UNWILLING_TO_PERFORM: raise # Directly on the base DN m = ldb.Message() m.dn = ldb.Dn(samdb, domain_dn) m["msDS-Behavior-Version"]= ldb.MessageElement( str(new_level_domain), ldb.FLAG_MOD_REPLACE, "msDS-Behavior-Version") samdb.modify(m) # Under partitions m = ldb.Message() m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % samdb.get_config_basedn()) m["msDS-Behavior-Version"]= ldb.MessageElement( str(new_level_domain), ldb.FLAG_MOD_REPLACE, "msDS-Behavior-Version") try: samdb.modify(m) except ldb.LdbError, (enum, emsg): if enum != ldb.ERR_UNWILLING_TO_PERFORM: raise level_domain = new_level_domain msgs.append("Domain function level changed!") if forest_level is not None: if forest_level == "2003": new_level_forest = DS_DOMAIN_FUNCTION_2003 elif forest_level == "2008": new_level_forest = DS_DOMAIN_FUNCTION_2008 elif forest_level == "2008_R2": new_level_forest = DS_DOMAIN_FUNCTION_2008_R2 if new_level_forest <= level_forest: raise CommandError("Forest function level can't be smaller than or equal to the actual one!") if new_level_forest > level_domain: raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!") m = ldb.Message() m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn()) m["msDS-Behavior-Version"]= ldb.MessageElement( str(new_level_forest), ldb.FLAG_MOD_REPLACE, "msDS-Behavior-Version") samdb.modify(m) msgs.append("Forest function level changed!") msgs.append("All changes applied successfully!") self.message("\n".join(msgs)) else: raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand) class cmd_domain_passwordsettings(Command): """Set password settings. Password complexity, history length, minimum password length, the minimum and maximum password age) on a Samba4 server. """ synopsis = "%prog (show|set <options>) [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server", type=str, metavar="URL", dest="H"), Option("--quiet", help="Be quiet", action="store_true"), Option("--complexity", type="choice", choices=["on","off","default"], help="The password complexity (on | off | default). Default is 'on'"), Option("--store-plaintext", type="choice", choices=["on","off","default"], help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"), Option("--history-length", help="The password history length (<integer> | default). Default is 24.", type=str), Option("--min-pwd-length", help="The minimum password length (<integer> | default). Default is 7.", type=str), Option("--min-pwd-age", help="The minimum password age (<integer in days> | default). Default is 1.", type=str), Option("--max-pwd-age", help="The maximum password age (<integer in days> | default). Default is 43.", type=str), ] takes_args = ["subcommand"] def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None, quiet=False, complexity=None, store_plaintext=None, history_length=None, min_pwd_length=None, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = samdb.domain_dn() res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", "minPwdAge", "maxPwdAge"]) assert(len(res) == 1) try: pwd_props = int(res[0]["pwdProperties"][0]) pwd_hist_len = int(res[0]["pwdHistoryLength"][0]) cur_min_pwd_len = int(res[0]["minPwdLength"][0]) # ticks -> days cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24)) if int(res[0]["maxPwdAge"][0]) == -0x8000000000000000: cur_max_pwd_age = 0 else: cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24)) except Exception, e: raise CommandError("Could not retrieve password properties!", e) if subcommand == "show": self.message("Password informations for domain '%s'" % domain_dn) self.message("") if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0: self.message("Password complexity: on") else: self.message("Password complexity: off") if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0: self.message("Store plaintext passwords: on") else: self.message("Store plaintext passwords: off") self.message("Password history length: %d" % pwd_hist_len) self.message("Minimum password length: %d" % cur_min_pwd_len) self.message("Minimum password age (days): %d" % cur_min_pwd_age) self.message("Maximum password age (days): %d" % cur_max_pwd_age) elif subcommand == "set": msgs = [] m = ldb.Message() m.dn = ldb.Dn(samdb, domain_dn) if complexity is not None: if complexity == "on" or complexity == "default": pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX msgs.append("Password complexity activated!") elif complexity == "off": pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX) msgs.append("Password complexity deactivated!") if store_plaintext is not None: if store_plaintext == "on" or store_plaintext == "default": pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT msgs.append("Plaintext password storage for changed passwords activated!") elif store_plaintext == "off": pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT) msgs.append("Plaintext password storage for changed passwords deactivated!") if complexity is not None or store_plaintext is not None: m["pwdProperties"] = ldb.MessageElement(str(pwd_props), ldb.FLAG_MOD_REPLACE, "pwdProperties") if history_length is not None: if history_length == "default": pwd_hist_len = 24 else: pwd_hist_len = int(history_length) if pwd_hist_len < 0 or pwd_hist_len > 24: raise CommandError("Password history length must be in the range of 0 to 24!") m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len), ldb.FLAG_MOD_REPLACE, "pwdHistoryLength") msgs.append("Password history length changed!") if min_pwd_length is not None: if min_pwd_length == "default": min_pwd_len = 7 else: min_pwd_len = int(min_pwd_length) if min_pwd_len < 0 or min_pwd_len > 14: raise CommandError("Minimum password length must be in the range of 0 to 14!") m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len), ldb.FLAG_MOD_REPLACE, "minPwdLength") msgs.append("Minimum password length changed!") if min_pwd_age is not None: if min_pwd_age == "default": min_pwd_age = 1 else: min_pwd_age = int(min_pwd_age) if min_pwd_age < 0 or min_pwd_age > 998: raise CommandError("Minimum password age must be in the range of 0 to 998!") # days -> ticks min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7)) m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks), ldb.FLAG_MOD_REPLACE, "minPwdAge") msgs.append("Minimum password age changed!") if max_pwd_age is not None: if max_pwd_age == "default": max_pwd_age = 43 else: max_pwd_age = int(max_pwd_age) if max_pwd_age < 0 or max_pwd_age > 999: raise CommandError("Maximum password age must be in the range of 0 to 999!") # days -> ticks if max_pwd_age == 0: max_pwd_age_ticks = -0x8000000000000000 else: max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7)) m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks), ldb.FLAG_MOD_REPLACE, "maxPwdAge") msgs.append("Maximum password age changed!") if max_pwd_age > 0 and min_pwd_age >= max_pwd_age: raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age)) if len(m) == 0: raise CommandError("You must specify at least one option to set. Try --help") samdb.modify(m) msgs.append("All changes applied successfully!") self.message("\n".join(msgs)) else: raise CommandError("Wrong argument '%s'!" % subcommand) class cmd_domain_classicupgrade(Command): """Upgrade from Samba classic (NT4-like) database to Samba AD DC database. Specify either a directory with all Samba classic DC databases and state files (with --dbdir) or the testparm utility from your classic installation (with --testparm). """ synopsis = "%prog [options] <classic_smb_conf>" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions } takes_options = [ Option("--dbdir", type="string", metavar="DIR", help="Path to samba classic DC database directory"), Option("--testparm", type="string", metavar="PATH", help="Path to samba classic DC testparm utility from the previous installation. This allows the default paths of the previous installation to be followed"), Option("--targetdir", type="string", metavar="DIR", help="Path prefix where the new Samba 4.0 AD domain should be initialised"), Option("--quiet", help="Be quiet", action="store_true"), Option("--verbose", help="Be verbose", action="store_true"), Option("--use-xattrs", type="choice", choices=["yes","no","auto"], metavar="[yes|no|auto]", help="Define if we should use the native fs capabilities or a tdb file for storing attributes likes ntacl, auto tries to make an inteligent guess based on the user rights and system capabilities", default="auto"), Option("--use-ntvfs", help="Use NTVFS for the fileserver (default = no)", action="store_true"), Option("--dns-backend", type="choice", metavar="NAMESERVER-BACKEND", choices=["SAMBA_INTERNAL", "BIND9_FLATFILE", "BIND9_DLZ", "NONE"], help="The DNS server backend. SAMBA_INTERNAL is the builtin name server (default), " "BIND9_FLATFILE uses bind9 text database to store zone information, " "BIND9_DLZ uses samba4 AD to store zone information, " "NONE skips the DNS setup entirely (this DC will not be a DNS server)", default="SAMBA_INTERNAL") ] takes_args = ["smbconf"] def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None, quiet=False, verbose=False, use_xattrs=None, sambaopts=None, versionopts=None, dns_backend=None, use_ntvfs=False): if not os.path.exists(smbconf): raise CommandError("File %s does not exist" % smbconf) if testparm and not os.path.exists(testparm): raise CommandError("Testparm utility %s does not exist" % testparm) if dbdir and not os.path.exists(dbdir): raise CommandError("Directory %s does not exist" % dbdir) if not dbdir and not testparm: raise CommandError("Please specify either dbdir or testparm") logger = self.get_logger() if verbose: logger.setLevel(logging.DEBUG) elif quiet: logger.setLevel(logging.WARNING) else: logger.setLevel(logging.INFO) if dbdir and testparm: logger.warning("both dbdir and testparm specified, ignoring dbdir.") dbdir = None lp = sambaopts.get_loadparm() s3conf = s3param.get_context() if sambaopts.realm: s3conf.set("realm", sambaopts.realm) if targetdir is not None: if not os.path.isdir(targetdir): os.mkdir(targetdir) eadb = True if use_xattrs == "yes": eadb = False elif use_xattrs == "auto" and not s3conf.get("posix:eadb"): if targetdir: tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(targetdir)) else: tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(os.path.dirname(lp.get("private dir")))) try: try: samba.ntacls.setntacl(lp, tmpfile.name, "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native") eadb = False except Exception: # FIXME: Don't catch all exceptions here logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. " "If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.") finally: tmpfile.close() # Set correct default values from dbdir or testparm paths = {} if dbdir: paths["state directory"] = dbdir paths["private dir"] = dbdir paths["lock directory"] = dbdir paths["smb passwd file"] = dbdir + "/smbpasswd" else: paths["state directory"] = get_testparm_var(testparm, smbconf, "state directory") paths["private dir"] = get_testparm_var(testparm, smbconf, "private dir") paths["smb passwd file"] = get_testparm_var(testparm, smbconf, "smb passwd file") paths["lock directory"] = get_testparm_var(testparm, smbconf, "lock directory") # "testparm" from Samba 3 < 3.4.x is not aware of the parameter # "state directory", instead make use of "lock directory" if len(paths["state directory"]) == 0: paths["state directory"] = paths["lock directory"] for p in paths: s3conf.set(p, paths[p]) # load smb.conf parameters logger.info("Reading smb.conf") s3conf.load(smbconf) samba3 = Samba3(smbconf, s3conf) logger.info("Provisioning") upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(), useeadb=eadb, dns_backend=dns_backend, use_ntvfs=use_ntvfs) class cmd_domain_samba3upgrade(cmd_domain_classicupgrade): __doc__ = cmd_domain_classicupgrade.__doc__ # This command is present for backwards compatibility only, # and should not be shown. hidden = True class cmd_domain(SuperCommand): """Domain management.""" subcommands = {} subcommands["demote"] = cmd_domain_demote() if cmd_domain_export_keytab is not None: subcommands["exportkeytab"] = cmd_domain_export_keytab() subcommands["info"] = cmd_domain_info() subcommands["provision"] = cmd_domain_provision() subcommands["join"] = cmd_domain_join() subcommands["dcpromo"] = cmd_domain_dcpromo() subcommands["level"] = cmd_domain_level() subcommands["passwordsettings"] = cmd_domain_passwordsettings() subcommands["classicupgrade"] = cmd_domain_classicupgrade() subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()
29,234
425
import pytest import numpy as np from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel from PythonLinearNonlinearControl.configs.two_wheeled \ import TwoWheeledConfigModule class TestTwoWheeledModel(): """ """ def test_step(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) curr_x = np.ones(config.STATE_SIZE) curr_x[-1] = np.pi / 6. u = np.ones((1, config.INPUT_SIZE)) next_x = two_wheeled_model.predict_traj(curr_x, u) pos_x = np.cos(curr_x[-1]) * u[0, 0] * config.DT + curr_x[0] pos_y = np.sin(curr_x[-1]) * u[0, 0] * config.DT + curr_x[1] expected = np.array([[1., 1., np.pi / 6.], [pos_x, pos_y, curr_x[-1] + u[0, 1] * config.DT]]) assert next_x == pytest.approx(expected) def test_predict_traj(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) curr_x = np.ones(config.STATE_SIZE) curr_x[-1] = np.pi / 6. u = np.ones((1, config.INPUT_SIZE)) pred_xs = two_wheeled_model.predict_traj(curr_x, u) u = np.tile(u, (1, 1, 1)) pred_xs_alltogether = two_wheeled_model.predict_traj(curr_x, u)[0] assert pred_xs_alltogether == pytest.approx(pred_xs) def test_gradient_state(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) xs = np.ones((1, config.STATE_SIZE)) xs[0, -1] = np.pi / 6. us = np.ones((1, config.INPUT_SIZE)) grad = two_wheeled_model.calc_f_x(xs, us, config.DT) # expected cost expected_grad = np.zeros((1, config.STATE_SIZE, config.STATE_SIZE)) eps = 1e-4 for i in range(config.STATE_SIZE): tmp_x = xs.copy() tmp_x[0, i] = xs[0, i] + eps forward = \ two_wheeled_model.predict_next_state(tmp_x[0], us[0]) tmp_x = xs.copy() tmp_x[0, i] = xs[0, i] - eps backward = \ two_wheeled_model.predict_next_state(tmp_x[0], us[0]) expected_grad[0, :, i] = (forward - backward) / (2. * eps) assert grad == pytest.approx(expected_grad) def test_gradient_input(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) xs = np.ones((1, config.STATE_SIZE)) xs[0, -1] = np.pi / 6. us = np.ones((1, config.INPUT_SIZE)) grad = two_wheeled_model.calc_f_u(xs, us, config.DT) # expected cost expected_grad = np.zeros((1, config.STATE_SIZE, config.INPUT_SIZE)) eps = 1e-4 for i in range(config.INPUT_SIZE): tmp_u = us.copy() tmp_u[0, i] = us[0, i] + eps forward = \ two_wheeled_model.predict_next_state(xs[0], tmp_u[0]) tmp_u = us.copy() tmp_u[0, i] = us[0, i] - eps backward = \ two_wheeled_model.predict_next_state(xs[0], tmp_u[0]) expected_grad[0, :, i] = (forward - backward) / (2. * eps) assert grad == pytest.approx(expected_grad)
1,711
458
package ghidra.app.cmd.data.rtti; import java.util.List; import ghidra.program.model.address.Address; import ghidra.program.model.data.DataType; import ghidra.program.model.listing.Function; public interface GnuVtable extends Vtable { public static final String PURE_VIRTUAL_FUNCTION_NAME = "__cxa_pure_virtual"; /** * Gets the ptrdiff_t value within the base offset array. * * @param index the index in the vtable_prefix array. * @param ordinal the offset ordinal. * @return the offset value. */ long getOffset(int index, int ordinal); /** * Gets the DataTypes that compose this Vtable * * @return the list of DataTypes this Vtable is made of */ List<DataType> getDataTypes(); /** * Gets the vtable prefixes that compose this vtable * * @return the list of vtable prefixes */ List<VtablePrefix> getPrefixes(); default int getLength() { return getDataTypes().stream() .mapToInt(DataType::getLength) .sum(); } interface VtablePrefix { /** * Gets the whole ptrdiff_t array. * * @return the whole ptrdiff_t array. */ List<Long> getOffsets(); List<Function> getFunctionTable(); List<DataType> getDataTypes(); Address getAddress(); } }
425
14,668
// Copyright (c) 2012 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. #include "base/sequence_checker_impl.h" #include <utility> #include "base/check.h" #include "base/debug/stack_trace.h" #include "base/memory/ptr_util.h" #include "base/sequence_token.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_checker_impl.h" #include "base/threading/thread_local_storage.h" namespace base { // static void SequenceCheckerImpl::EnableStackLogging() { ThreadChecker::EnableStackLogging(); } class SequenceCheckerImpl::Core { public: Core() : sequence_token_(SequenceToken::GetForCurrentThread()) {} ~Core() = default; bool CalledOnValidSequence( std::unique_ptr<debug::StackTrace>* out_bound_at) const { // SequenceToken::GetForCurrentThread() accesses thread-local storage. // During destruction the state of thread-local storage is not guaranteed to // be in a consistent state. Further, task-runner only installs the // SequenceToken when running a task. For this reason, |sequence_token_| is // not checked during thread destruction. if (!SequenceCheckerImpl::HasThreadLocalStorageBeenDestroyed() && sequence_token_.IsValid()) { if (sequence_token_ != SequenceToken::GetForCurrentThread()) { if (out_bound_at) *out_bound_at = thread_checker_.GetBoundAt(); return false; } return true; } // SequenceChecker behaves as a ThreadChecker when it is not bound to a // valid sequence token. return thread_checker_.CalledOnValidThread(out_bound_at); } private: SequenceToken sequence_token_{SequenceToken::GetForCurrentThread()}; // Used when |sequence_token_| is invalid, or during thread destruction. ThreadCheckerImpl thread_checker_; }; SequenceCheckerImpl::SequenceCheckerImpl() : core_(std::make_unique<Core>()) {} SequenceCheckerImpl::~SequenceCheckerImpl() = default; SequenceCheckerImpl::SequenceCheckerImpl(SequenceCheckerImpl&& other) { // Verify that |other| is called on its associated sequence and bind it now if // it is currently detached (even if this isn't a DCHECK build). const bool other_called_on_valid_sequence = other.CalledOnValidSequence(); DCHECK(other_called_on_valid_sequence); core_ = std::move(other.core_); } SequenceCheckerImpl& SequenceCheckerImpl::operator=( SequenceCheckerImpl&& other) { // If |this| is not in a detached state it needs to be bound to the current // sequence. DCHECK(CalledOnValidSequence()); // Verify that |other| is called on its associated sequence and bind it now if // it is currently detached (even if this isn't a DCHECK build). const bool other_called_on_valid_sequence = other.CalledOnValidSequence(); DCHECK(other_called_on_valid_sequence); // Intentionally not using either |lock_| in this method to let TSAN catch // racy assign. TS_UNCHECKED_READ(core_) = std::move(TS_UNCHECKED_READ(other.core_)); return *this; } bool SequenceCheckerImpl::CalledOnValidSequence( std::unique_ptr<debug::StackTrace>* bound_at) const { AutoLock auto_lock(lock_); if (!core_) core_ = std::make_unique<Core>(); return core_->CalledOnValidSequence(bound_at); } void SequenceCheckerImpl::DetachFromSequence() { AutoLock auto_lock(lock_); core_.reset(); } // static bool SequenceCheckerImpl::HasThreadLocalStorageBeenDestroyed() { return ThreadLocalStorage::HasBeenDestroyed(); } } // namespace base
1,149
819
<reponame>yidao620c/core-algorithm<filename>algorithms/ch02sort/m08_radix_sort.py #!/usr/bin/env python # -*- encoding: utf-8 -*- # 基数排序 """ Topic: sample Desc : 基数排序 有时需要对记录的几个关键字分别排序,比如用三个关键字年、月、日对日期排序。 可以用基数排序,用一种稳定排序算法(比如计数排序)对这些信息进行三次排序: 优先级从低到高,权重从低到高。 """ def radixSort(A, digit, base): """ digit: 代表排序数组的最大位数 base: 代表进制 """ for di in range(1, digit + 1): B = [0] * len(A) # 最终输出的排序数组 C = [0] * base # 临时存储数组 for i in range(0, len(A)): # split the specified digit from the element tmpSplitDigit = A[i] // pow(10, di - 1) - (A[i] // pow(10, di)) * 10 C[tmpSplitDigit] += 1 # C[i]现在代表数组A中元素等于i的个数 for i in range(1, base): C[i] += C[i - 1] # C[i]现在代表数组A中元素小于等于i的个数 for j in range(len(A) - 1, -1, -1): tmpSplitDigit = A[j] // pow(10, di - 1) - (A[j] // pow(10, di)) * 10 B[C[tmpSplitDigit] - 1] = A[j] C[tmpSplitDigit] -= 1 # 防止数组A有重复的数,占据了相同的位置 A[:] = B[:] if __name__ == '__main__': A = [9, 7, 8, 10, 16, 3, 14, 2, 1, 4] radixSort(A, 2, 10) print(A)
931
465
/* * Copyright (c) 2018 Uber Technologies, Inc. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.uber.marmaray.common.dataset; import com.google.common.annotations.VisibleForTesting; import com.uber.marmaray.utilities.SparkUtil; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.hadoop.fs.Path; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Encoder; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import java.io.IOException; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import static com.uber.marmaray.utilities.DateUtil.DATE_PARTITION_FORMAT; /** * {@link UtilTable} is represented as a {@link Dataset} of {@link UtilRecord}, * which is converted from a {@link JavaRDD} of {@link UtilRecord}. We can extend * the functionality of {@link UtilTable} same as that of {@link Dataset} */ @Slf4j @AllArgsConstructor public class UtilTable<T extends UtilRecord> { private final SparkSession spark; private final Dataset<T> dataset; private final Path destPath; private final boolean isDatePartitioned; public UtilTable(@NonNull final Class<T> type, @NonNull final JavaRDD<T> javaRDD, @NonNull final Path destPath, final boolean isDatePartitioned) { this(type, javaRDD, destPath, isDatePartitioned, SparkUtil.getOrCreateSparkSession()); } public UtilTable(@NonNull final Class<T> type, @NonNull final JavaRDD<T> javaRDD, @NonNull final Path destPath, final boolean isDatePartitioned, @NonNull final SparkSession sparkSession) { this.spark = sparkSession; final RDD<T> rdd = javaRDD.rdd(); final Encoder<T> bean = Encoders.bean(type); this.dataset = this.spark.createDataset(rdd, bean); this.destPath = destPath; this.isDatePartitioned = isDatePartitioned; } public void writeParquet() throws IOException { // TODO: Consider having a configuration to limit number records written out this.dataset.write().mode(SaveMode.Append).parquet(getDestWritePath().toString()); } public Long size() { return this.dataset.count(); } @VisibleForTesting public void show() { this.dataset.show(); } public Path getDestWritePath() { return this.isDatePartitioned ? getDestDatePartitionedPath() : this.destPath; } private Path getDestDatePartitionedPath() { final ZonedDateTime date = ZonedDateTime.now(ZoneOffset.UTC); final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PARTITION_FORMAT); return new Path(this.destPath, date.format(formatter)); } }
1,396
1,117
<filename>phxrpc/http/http_msg_handler_factory.h<gh_stars>1000+ /* Tencent is pleased to support the open source community by making PhxRPC available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #pragma once #include "phxrpc/msg.h" namespace phxrpc { class HttpMessageHandlerFactory : virtual public BaseMessageHandlerFactory { public: HttpMessageHandlerFactory() = default; virtual ~HttpMessageHandlerFactory() override = default; virtual std::unique_ptr<BaseMessageHandler> Create() override; }; } // namespace phxrpc
325
320
/* * emudore, Commodore 64 emulator * Copyright (c) 2016, <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "loader.h" Loader::Loader(C64 *c64) { c64_ = c64; io_ = c64_->io(); cpu_ = c64_->cpu(); mem_ = c64_->memory(); booted_up_ = false; format_ = kNone; } // common /////////////////////////////////////////////////////////////////// uint16_t Loader::read_short_le() { char b; uint16_t v = 0; is_.get(b); v |= (b); is_.get(b); v |= b << 8; return v; } // BASIC listings /////////////////////////////////////////////////////////// void Loader::bas(const std::string &f) { format_ = kBasic; is_.open(f,std::ios::in); } void Loader::load_basic() { char c; if(is_.is_open()) { while(is_.good()) { is_.get(c); io_->IO::type_character(c); } } } // PRG ////////////////////////////////////////////////////////////////////// void Loader::prg(const std::string &f) { format_ = kPRG; is_.open(f,std::ios::in|std::ios::binary); } void Loader::load_prg() { char b; uint16_t pbuf, addr; pbuf = addr = read_short_le(); if(is_.is_open()) { while(is_.good()) { is_.get(b); mem_->write_byte_no_io(pbuf++,b); } /* basic-tokenized prg */ if(addr == kBasicPrgStart) { /* make BASIC happy */ mem_->write_word_no_io(kBasicTxtTab,kBasicPrgStart); mem_->write_word_no_io(kBasicVarTab,pbuf); mem_->write_word_no_io(kBasicAryTab,pbuf); mem_->write_word_no_io(kBasicStrEnd,pbuf); /* exec RUN */ for(char &c: std::string("RUN\n")) io_->IO::type_character(c); } /* ML */ else cpu_->pc(addr); } } // emulate ////////////////////////////////////////////////////////////////// bool Loader::emulate() { if(booted_up_) { switch(format_) { case kBasic: load_basic(); break; case kPRG: load_prg(); break; default: break; } return false; } else { /* at this point BASIC is ready */ if(cpu_->pc() == 0xa65c) booted_up_ = true; } return true; }
1,053
777
<reponame>google-ar/chromium<gh_stars>100-1000 // Copyright 2015 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. #include "mash/task_viewer/task_viewer.h" #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/catalog/public/interfaces/catalog.mojom.h" #include "services/catalog/public/interfaces/constants.mojom.h" #include "services/service_manager/public/cpp/connection.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_registry.h" #include "services/service_manager/public/cpp/service_context.h" #include "services/service_manager/public/interfaces/constants.mojom.h" #include "services/service_manager/public/interfaces/service_manager.mojom.h" #include "ui/base/models/table_model.h" #include "ui/base/resource/resource_bundle.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/background.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/table/table_view.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/mus/aura_init.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace mash { namespace task_viewer { namespace { using service_manager::mojom::RunningServiceInfoPtr; class TaskViewerContents : public views::WidgetDelegateView, public ui::TableModel, public views::ButtonListener, public service_manager::mojom::ServiceManagerListener { public: TaskViewerContents( TaskViewer* task_viewer, service_manager::mojom::ServiceManagerListenerRequest request, catalog::mojom::CatalogPtr catalog) : task_viewer_(task_viewer), binding_(this, std::move(request)), catalog_(std::move(catalog)), table_view_(nullptr), table_view_parent_(nullptr), kill_button_( views::MdTextButton::Create(this, base::ASCIIToUTF16("Kill Process"))), observer_(nullptr), weak_ptr_factory_(this) { // We don't want to show an empty UI on startup, so just block until we // receive the initial set of applications. binding_.WaitForIncomingMethodCall(); table_view_ = new views::TableView(this, GetColumns(), views::TEXT_ONLY, false); set_background(views::Background::CreateStandardPanelBackground()); table_view_parent_ = table_view_->CreateParentIfNecessary(); AddChildView(table_view_parent_); AddChildView(kill_button_); } ~TaskViewerContents() override { table_view_->SetModel(nullptr); task_viewer_->RemoveWindow(GetWidget()); } private: struct InstanceInfo { InstanceInfo(const service_manager::Identity& identity, base::ProcessId pid) : identity(identity), pid(pid) {} service_manager::Identity identity; uint32_t pid; std::string display_name; }; // Overridden from views::WidgetDelegate: base::string16 GetWindowTitle() const override { // TODO(beng): use resources. return base::ASCIIToUTF16("Tasks"); } bool CanResize() const override { return true; } bool CanMaximize() const override { return true; } bool CanMinimize() const override { return true; } gfx::ImageSkia GetWindowAppIcon() override { // TODO(jamescook): Create a new .pak file for this app and make a custom // icon, perhaps one that looks like the Chrome OS task viewer icon. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); return *rb.GetImageSkiaNamed(IDR_NOTIFICATION_SETTINGS); } // Overridden from views::View: void Layout() override { gfx::Rect bounds = GetLocalBounds(); bounds.Inset(10, 10); gfx::Size ps = kill_button_->GetPreferredSize(); bounds.set_height(bounds.height() - ps.height() - 10); kill_button_->SetBounds(bounds.width() - ps.width(), bounds.bottom() + 10, ps.width(), ps.height()); table_view_parent_->SetBoundsRect(bounds); } // Overridden from ui::TableModel: int RowCount() override { return static_cast<int>(instances_.size()); } base::string16 GetText(int row, int column_id) override { switch(column_id) { case 0: DCHECK(row < static_cast<int>(instances_.size())); return base::UTF8ToUTF16(instances_[row]->display_name); case 1: DCHECK(row < static_cast<int>(instances_.size())); return base::UTF8ToUTF16(instances_[row]->identity.name()); case 2: DCHECK(row < static_cast<int>(instances_.size())); return base::IntToString16(instances_[row]->pid); default: NOTREACHED(); break; } return base::string16(); } void SetObserver(ui::TableModelObserver* observer) override { observer_ = observer; } // Overridden from views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override { DCHECK_EQ(sender, kill_button_); DCHECK_EQ(table_view_->selection_model().size(), 1UL); int row = table_view_->FirstSelectedRow(); DCHECK(row < static_cast<int>(instances_.size())); base::Process process = base::Process::Open(instances_[row]->pid); process.Terminate(9, true); } // Overridden from service_manager::mojom::ServiceManagerListener: void OnInit(std::vector<RunningServiceInfoPtr> instances) override { // This callback should only be called with an empty model. DCHECK(instances_.empty()); std::vector<std::string> names; names.reserve(instances.size()); for (size_t i = 0; i < instances.size(); ++i) { const service_manager::Identity& identity = instances[i]->identity; InsertInstance(identity, instances[i]->pid); names.push_back(identity.name()); } catalog_->GetEntries(std::move(names), base::Bind(&TaskViewerContents::OnGotCatalogEntries, weak_ptr_factory_.GetWeakPtr())); } void OnServiceCreated(RunningServiceInfoPtr instance) override { service_manager::Identity identity = instance->identity; DCHECK(!ContainsIdentity(identity)); InsertInstance(identity, instance->pid); observer_->OnItemsAdded(static_cast<int>(instances_.size()), 1); std::vector<std::string> names; names.push_back(identity.name()); catalog_->GetEntries(std::move(names), base::Bind(&TaskViewerContents::OnGotCatalogEntries, weak_ptr_factory_.GetWeakPtr())); } void OnServiceStarted(const service_manager::Identity& identity, uint32_t pid) override { for (auto it = instances_.begin(); it != instances_.end(); ++it) { if ((*it)->identity == identity) { (*it)->pid = pid; observer_->OnItemsChanged( static_cast<int>(it - instances_.begin()), 1); return; } } } void OnServiceFailedToStart( const service_manager::Identity& identity) override { } void OnServiceStopped(const service_manager::Identity& identity) override { for (auto it = instances_.begin(); it != instances_.end(); ++it) { if ((*it)->identity == identity) { observer_->OnItemsRemoved( static_cast<int>(it - instances_.begin()), 1); instances_.erase(it); return; } } NOTREACHED(); } bool ContainsIdentity(const service_manager::Identity& identity) const { for (auto& it : instances_) { if (it->identity == identity) return true; } return false; } void InsertInstance(const service_manager::Identity& identity, uint32_t pid) { instances_.push_back(base::MakeUnique<InstanceInfo>(identity, pid)); } void OnGotCatalogEntries(std::vector<catalog::mojom::EntryPtr> entries) { for (auto it = instances_.begin(); it != instances_.end(); ++it) { for (auto& entry : entries) { if (entry->name == (*it)->identity.name()) { (*it)->display_name = entry->display_name; observer_->OnItemsChanged( static_cast<int>(it - instances_.begin()), 1); break; } } } } static std::vector<ui::TableColumn> GetColumns() { std::vector<ui::TableColumn> columns; ui::TableColumn name_column; name_column.id = 0; // TODO(beng): use resources. name_column.title = base::ASCIIToUTF16("Name"); name_column.width = -1; name_column.percent = 0.4f; name_column.sortable = true; columns.push_back(name_column); ui::TableColumn url_column; url_column.id = 1; // TODO(beng): use resources. url_column.title = base::ASCIIToUTF16("URL"); url_column.width = -1; url_column.percent = 0.4f; url_column.sortable = true; columns.push_back(url_column); ui::TableColumn pid_column; pid_column.id = 2; // TODO(beng): use resources. pid_column.title = base::ASCIIToUTF16("PID"); pid_column.width = 50; pid_column.sortable = true; columns.push_back(pid_column); return columns; } TaskViewer* task_viewer_; mojo::Binding<service_manager::mojom::ServiceManagerListener> binding_; catalog::mojom::CatalogPtr catalog_; views::TableView* table_view_; views::View* table_view_parent_; views::MdTextButton* kill_button_; ui::TableModelObserver* observer_; std::vector<std::unique_ptr<InstanceInfo>> instances_; base::WeakPtrFactory<TaskViewerContents> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TaskViewerContents); }; } // namespace TaskViewer::TaskViewer() {} TaskViewer::~TaskViewer() {} void TaskViewer::RemoveWindow(views::Widget* widget) { auto it = std::find(windows_.begin(), windows_.end(), widget); DCHECK(it != windows_.end()); windows_.erase(it); if (windows_.empty()) base::MessageLoop::current()->QuitWhenIdle(); } void TaskViewer::OnStart() { tracing_.Initialize(context()->connector(), context()->identity().name()); aura_init_ = base::MakeUnique<views::AuraInit>( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); } bool TaskViewer::OnConnect(const service_manager::ServiceInfo& remote_info, service_manager::InterfaceRegistry* registry) { registry->AddInterface<::mash::mojom::Launchable>(this); return true; } void TaskViewer::Launch(uint32_t what, mojom::LaunchMode how) { bool reuse = how == mojom::LaunchMode::REUSE || how == mojom::LaunchMode::DEFAULT; if (reuse && !windows_.empty()) { windows_.back()->Activate(); return; } service_manager::mojom::ServiceManagerPtr service_manager; context()->connector()->BindInterface(service_manager::mojom::kServiceName, &service_manager); service_manager::mojom::ServiceManagerListenerPtr listener; service_manager::mojom::ServiceManagerListenerRequest request(&listener); service_manager->AddListener(std::move(listener)); catalog::mojom::CatalogPtr catalog; context()->connector()->BindInterface(catalog::mojom::kServiceName, &catalog); TaskViewerContents* task_viewer = new TaskViewerContents( this, std::move(request), std::move(catalog)); views::Widget* window = views::Widget::CreateWindowWithContextAndBounds( task_viewer, nullptr, gfx::Rect(10, 10, 500, 500)); window->Show(); windows_.push_back(window); } void TaskViewer::Create(const service_manager::Identity& remote_identity, ::mash::mojom::LaunchableRequest request) { bindings_.AddBinding(this, std::move(request)); } } // namespace task_viewer } // namespace main
4,618
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Sabadel-Latronquière","circ":"2ème circonscription","dpt":"Lot","inscrits":86,"abs":29,"votants":57,"blancs":6,"nuls":3,"exp":48,"res":[{"nuance":"REM","nom":"<NAME>","voix":25},{"nuance":"SOC","nom":"<NAME>","voix":23}]}
112
5,342
<reponame>suryatmodulus/lepton<gh_stars>1000+ #ifndef _WIN32 void fork_serve(); #endif
39
377
import diffrax import jax import jax.numpy as jnp import jax.random as jrandom import pytest @pytest.mark.parametrize( "stepsize_controller", (diffrax.ConstantStepSize(), diffrax.PIDController(rtol=1e-3, atol=1e-6)), ) def test_vmap_y0(stepsize_controller): t0 = 0 t1 = 1 dt0 = 0.1 key = jrandom.PRNGKey(5678) y0 = jrandom.normal(key, (10, 2)) a = jnp.array([[-0.2, 1], [1, -0.2]]) def f(t, y, args): return a @ y saveat = diffrax.SaveAt(t0=True) sol = jax.vmap( lambda y0i: diffrax.diffeqsolve( diffrax.ODETerm(f), diffrax.Heun(), t0, t1, dt0, y0i, stepsize_controller=stepsize_controller, saveat=saveat, ) )(y0) assert jnp.array_equal(sol.t0, jnp.full((10,), t0)) assert jnp.array_equal(sol.t1, jnp.full((10,), t1)) assert jnp.array_equal(sol.ts, jnp.full((10, 1), t0)) assert sol.ys.shape == (10, 1, 2) saveat = diffrax.SaveAt(t1=True) sol = jax.vmap( lambda y0i: diffrax.diffeqsolve( diffrax.ODETerm(f), diffrax.Heun(), t0, t1, dt0, y0i, stepsize_controller=stepsize_controller, saveat=saveat, ) )(y0) assert jnp.array_equal(sol.t0, jnp.full((10,), t0)) assert jnp.array_equal(sol.t1, jnp.full((10,), t1)) assert jnp.array_equal(sol.ts, jnp.full((10, 1), t1)) assert sol.ys.shape == (10, 1, 2) _t = jnp.array([0, 0.3, 0.7, 1]) saveat = diffrax.SaveAt(ts=_t) sol = jax.vmap( lambda y0i: diffrax.diffeqsolve( diffrax.ODETerm(f), diffrax.Heun(), t0, t1, dt0, y0i, stepsize_controller=stepsize_controller, saveat=saveat, ) )(y0) assert jnp.array_equal(sol.t0, jnp.full((10,), t0)) assert jnp.array_equal(sol.t1, jnp.full((10,), t1)) assert jnp.array_equal(sol.ts, jnp.broadcast_to(_t, (10, 4))) assert sol.ys.shape == (10, 4, 2) saveat = diffrax.SaveAt(steps=True) sol = jax.vmap( lambda y0i: diffrax.diffeqsolve( diffrax.ODETerm(f), diffrax.Heun(), t0, t1, dt0, y0i, stepsize_controller=stepsize_controller, saveat=saveat, ) )(y0) num_steps = sol.stats["num_steps"] if not isinstance(stepsize_controller, diffrax.ConstantStepSize): # not the same number of steps for every batch element assert len(set(num_steps.to_py())) > 1 assert jnp.array_equal(sol.t0, jnp.full((10,), t0)) assert jnp.array_equal(sol.t1, jnp.full((10,), t1)) assert sol.ts.shape == ( 10, 4096, ) # 4096 is the default diffeqsolve(max_steps=...) assert sol.ys.shape == (10, 4096, 2) saveat = diffrax.SaveAt(dense=True) sol = jax.vmap( lambda y0i: diffrax.diffeqsolve( diffrax.ODETerm(f), diffrax.Heun(), t0, t1, dt0, y0i, stepsize_controller=stepsize_controller, saveat=saveat, ) )(y0) assert jnp.array_equal(sol.t0, jnp.full((10,), t0)) assert jnp.array_equal(sol.t1, jnp.full((10,), t1)) assert sol.ts is None assert sol.ys is None assert jax.vmap(lambda sol: sol.evaluate(0.5))(sol).shape == (10, 2) assert jax.vmap(lambda sol: sol.derivative(0.5))(sol).shape == (10, 2)
1,954
306
#ifndef QFOBJECT_H #define QFOBJECT_H #include <QObject> #include <QQmlListProperty> /// QFObject provides an QtObject with default children property to hold nested items class QFObject : public QObject { Q_OBJECT Q_PROPERTY(QQmlListProperty<QObject> children READ children) Q_CLASSINFO("DefaultProperty", "children") public: explicit QFObject(QObject *parent = 0); QQmlListProperty<QObject> children(); signals: public slots: private: QObjectList m_children; }; #endif // QFOBJECT_H
188
653
<filename>src/test/java/se/michaelthelin/spotify/requests/data/library/GetUsersSavedShowsRequestTest.java package se.michaelthelin.spotify.requests.data.library; import org.apache.hc.core5.http.ParseException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import se.michaelthelin.spotify.ITest; import se.michaelthelin.spotify.TestUtil; import se.michaelthelin.spotify.exceptions.SpotifyWebApiException; import se.michaelthelin.spotify.model_objects.specification.Paging; import se.michaelthelin.spotify.model_objects.specification.SavedShow; import se.michaelthelin.spotify.requests.data.AbstractDataTest; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(MockitoJUnitRunner.class) public class GetUsersSavedShowsRequestTest extends AbstractDataTest<Paging<SavedShow>> { private final GetUsersSavedShowsRequest defaultRequest = ITest.SPOTIFY_API.getUsersSavedShows() .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/library/GetUsersSavedShowsRequest.json")) .limit(ITest.LIMIT) .offset(ITest.OFFSET) .build(); public GetUsersSavedShowsRequestTest() throws Exception { } @Test public void shouldComplyWithReference() { assertHasAuthorizationHeader(defaultRequest); Assert.assertEquals( "https://api.spotify.com:443/v1/me/shows?limit=10&offset=0", defaultRequest.getUri().toString()); } @Test public void shouldReturnDefault_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefault(defaultRequest.execute()); } @Test public void shouldReturnDefault_async() throws ExecutionException, InterruptedException { shouldReturnDefault(defaultRequest.executeAsync().get()); } public void shouldReturnDefault(final Paging<SavedShow> savedShowPaging) { assertEquals( "https://api.spotify.com/v1/me/shows?offset=0&limit=20", savedShowPaging.getHref()); assertEquals( 3, savedShowPaging.getItems().length); assertEquals( 20, (int) savedShowPaging.getLimit()); assertNull( savedShowPaging.getNext()); assertEquals( 0, (int) savedShowPaging.getOffset()); assertNull( savedShowPaging.getPrevious()); assertEquals( 3, (int) savedShowPaging.getTotal()); } }
903
4,403
package cn.hutool.poi.excel.cell.setters; import cn.hutool.poi.excel.cell.CellSetter; import org.apache.poi.ss.usermodel.Cell; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.TemporalAccessor; import java.util.Date; /** * {@link TemporalAccessor} 值单元格设置器 * * @author looly * @since 5.7.8 */ public class TemporalAccessorCellSetter implements CellSetter { private final TemporalAccessor value; /** * 构造 * * @param value 值 */ TemporalAccessorCellSetter(TemporalAccessor value) { this.value = value; } @Override public void setValue(Cell cell) { if (value instanceof Instant) { cell.setCellValue(Date.from((Instant) value)); } else if (value instanceof LocalDateTime) { cell.setCellValue((LocalDateTime) value); } else if (value instanceof LocalDate) { cell.setCellValue((LocalDate) value); } } }
352
892
{ "schema_version": "1.2.0", "id": "GHSA-c8f9-q937-86mv", "modified": "2022-05-01T02:22:37Z", "published": "2022-05-01T02:22:37Z", "aliases": [ "CVE-2005-3923" ], "details": "NetObjects Fusion 9 (NOF9) allows remote attackers to obtain sensitive information, including passwords, by downloading the _versioning_repository_/rollbacklog.xml file, then using it to download and modify the associated ZIP file to edit and republish the site.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2005-3923" }, { "type": "WEB", "url": "http://secunia.com/advisories/17667" }, { "type": "WEB", "url": "http://www.schneier.com/blog/archives/2005/11/possible_net_ob.html" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2005/2555" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
465
931
<gh_stars>100-1000 // 7X7 // Problem Description // CODU is solving a 7x7 sudoku. Help him in solving the unique Sudoku. // Rules are as follows // 1. There are 7 regions coloured differently. Each region must have a single occurrence of numbers between range [1, 7]. // 2. Regions don't have a fix shape and it can change from input to input. // 3. Each row must have a single occurrence of numbers between range [1, 7] across all input. // 4. Each column must have a single occurrence of numbers between range [1, 7] across all input. // Some numbers in some rows, columns and regions will be given. These will be between [1, 7]. // Zero (0) denotes that the number is covered. Uncovering it will give a number between [1, 7]. // Your task is to fill the numbers [1,7] where there is a 0 such that the 7x7 Sudoku is solved. // 7x7 Sudoku is said to be solved when every region, every column, every row has exactly one occurrence of numbers [1,7]. // Constraints // 7 < Known/Given numbers in Entire Sudoku < 14 // Input // Input consists of 14 lines. // First 7 lines denote the positions of numbers [1,7] in respective row and column. // Next 7 lines denote the shape of the regions inside the Sudoku. These will be denoted by 7 unique characters between alphabets [a-z]. // Output // Print the solved Sudoku. // 7 lines, each line containing 7 space separated integers honoring all the conditions. // Time Limit // 1 // Examples // Example 1 // Input // 0 0 0 0 0 6 0 // 0 0 0 0 0 0 0 // 2 6 5 1 7 4 3 // 0 0 0 3 0 0 0 // 0 0 0 0 0 0 0 // 0 0 0 0 0 0 0 // 0 0 0 0 0 0 0 // a a a b b b b // a a a a b b c // d d d e e b c // d d d d e e c // f f f h e e c // f f h h e c c // f f h h h h c // Output // 1 2 4 5 3 6 7 // 3 5 6 7 1 2 4 // 2 6 5 1 7 4 3 // 4 7 1 3 2 5 6 // 7 1 2 6 4 3 5 // 5 4 3 2 6 7 1 // 6 3 7 4 5 1 2 // Explanation // There could be many different solutions. Producing any solution as output is acceptable.
644
4,842
<reponame>justStarNew/gpmall package com.gpmall.search.dto; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/24-19:08 */ @Data public class ProductDto implements Serializable { private static final long serialVersionUID = 2763986506997467400L; private Long productId; private BigDecimal salePrice; private String productName; private String subTitle; private String picUrl; }
224
9,680
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os API_ROOT_URL = '/api/v1/nni-pai' BASE_URL = 'http://{}' LOG_DIR = os.environ['NNI_OUTPUT_DIR'] NNI_PLATFORM = os.environ['NNI_PLATFORM'] STDOUT_FULL_PATH = os.path.join(LOG_DIR, 'stdout') STDERR_FULL_PATH = os.path.join(LOG_DIR, 'stderr') STDOUT_API = '/stdout' VERSION_API = '/version' PARAMETER_META_API = '/parameter-file-meta' NNI_SYS_DIR = os.environ['NNI_SYS_DIR'] NNI_TRIAL_JOB_ID = os.environ['NNI_TRIAL_JOB_ID'] NNI_EXP_ID = os.environ['NNI_EXP_ID'] MULTI_PHASE = os.environ['MULTI_PHASE']
270
1,163
<reponame>kintel/iree // Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #ifndef IREE_COMPILER_DIALECT_VM_IR_VMFUNCENCODER_H_ #define IREE_COMPILER_DIALECT_VM_IR_VMFUNCENCODER_H_ #include "mlir/IR/OpDefinition.h" #include "mlir/IR/SymbolTable.h" namespace mlir { namespace iree_compiler { // Interface for encoding of VM operations within functions. // This base manages source map construction and vm.func walking while // subclasses provide actual emission. class VMFuncEncoder { public: virtual ~VMFuncEncoder() = default; // Begins encoding the contents of a block. virtual LogicalResult beginBlock(Block *block) = 0; // Ends encoding the contents of a block. virtual LogicalResult endBlock(Block *block) = 0; // Begins encoding an operation. virtual LogicalResult beginOp(Operation *op) = 0; // Ends encoding an operation. virtual LogicalResult endOp(Operation *op) = 0; // Encodes an 8-bit integer. Fails if |value| cannot be represented as a byte. virtual LogicalResult encodeI8(int value) = 0; // Encodes an opcode of the given value. virtual LogicalResult encodeOpcode(StringRef name, int opcode) = 0; // Encodes a global or function symbol ordinal. virtual LogicalResult encodeSymbolOrdinal(SymbolTable &syms, StringRef name) = 0; // Encodes a value type as an integer kind. virtual LogicalResult encodeType(Value value) = 0; virtual LogicalResult encodeType(Type type) = 0; // Encodes an integer or floating-point primitive attribute as a fixed byte // length based on bitwidth. virtual LogicalResult encodePrimitiveAttr(Attribute value) = 0; // Encodes a variable-length integer or floating-point array attribute. virtual LogicalResult encodePrimitiveArrayAttr(DenseElementsAttr value) = 0; // Encodes a string attribute as a B-string. virtual LogicalResult encodeStrAttr(StringAttr value) = 0; // Encodes a branch target and the operand mappings. virtual LogicalResult encodeBranch(Block *targetBlock, Operation::operand_range operands, int successorIndex) = 0; // Encodes an operand value (by reference). virtual LogicalResult encodeOperand(Value value, int ordinal) = 0; // Encodes a variable list of operands (by reference), including a count. virtual LogicalResult encodeOperands(Operation::operand_range values) = 0; // Encodes a result value (by reference). virtual LogicalResult encodeResult(Value value) = 0; // Encodes a variable list of results (by reference), including a count. virtual LogicalResult encodeResults(Operation::result_range values) = 0; }; } // namespace iree_compiler } // namespace mlir #endif // IREE_COMPILER_DIALECT_VM_IR_VMFUNCENCODER_H_
969
386
<filename>test/IECoreImage/SummedAreaOpTest.py ########################################################################## # # Copyright (c) 2008, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import unittest import math import imath import IECore import IECoreImage class SummedAreaOpTest( unittest.TestCase ) : def test( self ) : b = imath.Box2i( imath.V2i( 0 ), imath.V2i( 1 ) ) i = IECoreImage.ImagePrimitive( b, b ) i["Y"] = IECore.FloatVectorData( [ 1, 2, 3, 4 ] ) ii = IECoreImage.SummedAreaOp()( input=i, channels=IECore.StringVectorData( ["Y"] ) ) yy = ii["Y"] self.assertEqual( yy[0], 1 ) self.assertEqual( yy[1], 3 ) self.assertEqual( yy[2], 4 ) self.assertEqual( yy[3], 10 ) if __name__ == "__main__": unittest.main()
773
14,425
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.datanode; import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.hdfs.DFSUtilClient; import org.apache.hadoop.hdfs.protocol.BlockChecksumOptions; import org.apache.hadoop.hdfs.protocol.BlockChecksumType; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.StripedBlockInfo; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil; import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair; import org.apache.hadoop.hdfs.protocol.datatransfer.Op; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos; import org.apache.hadoop.hdfs.protocolPB.PBHelperClient; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.server.datanode.erasurecode.StripedBlockChecksumCompositeCrcReconstructor; import org.apache.hadoop.hdfs.server.datanode.erasurecode.StripedBlockChecksumMd5CrcReconstructor; import org.apache.hadoop.hdfs.server.datanode.erasurecode.StripedBlockChecksumReconstructor; import org.apache.hadoop.hdfs.server.datanode.erasurecode.StripedReconstructionInfo; import org.apache.hadoop.hdfs.server.datanode.fsdataset.LengthInputStream; import org.apache.hadoop.hdfs.util.StripedBlockUtil; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.CrcComposer; import org.apache.hadoop.util.CrcUtil; import org.apache.hadoop.util.DataChecksum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; /** * Utilities for Block checksum computing, for both replicated and striped * blocks. */ @InterfaceAudience.Private final class BlockChecksumHelper { static final Logger LOG = LoggerFactory.getLogger(BlockChecksumHelper.class); private BlockChecksumHelper() { } /** * The abstract block checksum computer. */ static abstract class AbstractBlockChecksumComputer { private final DataNode datanode; private final BlockChecksumOptions blockChecksumOptions; private byte[] outBytes; private int bytesPerCRC = -1; private DataChecksum.Type crcType = null; private long crcPerBlock = -1; private int checksumSize = -1; AbstractBlockChecksumComputer( DataNode datanode, BlockChecksumOptions blockChecksumOptions) throws IOException { this.datanode = datanode; this.blockChecksumOptions = blockChecksumOptions; } abstract void compute() throws IOException; Sender createSender(IOStreamPair pair) { DataOutputStream out = (DataOutputStream) pair.out; return new Sender(out); } DataNode getDatanode() { return datanode; } BlockChecksumOptions getBlockChecksumOptions() { return blockChecksumOptions; } InputStream getBlockInputStream(ExtendedBlock block, long seekOffset) throws IOException { return datanode.data.getBlockInputStream(block, seekOffset); } void setOutBytes(byte[] bytes) { this.outBytes = bytes; } byte[] getOutBytes() { return outBytes; } int getBytesPerCRC() { return bytesPerCRC; } public void setBytesPerCRC(int bytesPerCRC) { this.bytesPerCRC = bytesPerCRC; } public void setCrcType(DataChecksum.Type crcType) { this.crcType = crcType; } public void setCrcPerBlock(long crcPerBlock) { this.crcPerBlock = crcPerBlock; } public void setChecksumSize(int checksumSize) { this.checksumSize = checksumSize; } DataChecksum.Type getCrcType() { return crcType; } long getCrcPerBlock() { return crcPerBlock; } int getChecksumSize() { return checksumSize; } } /** * The abstract base block checksum computer, mainly for replicated blocks. */ static abstract class BlockChecksumComputer extends AbstractBlockChecksumComputer { private final ExtendedBlock block; // client side now can specify a range of the block for checksum private final long requestLength; private final LengthInputStream metadataIn; private final DataInputStream checksumIn; private final long visibleLength; private final boolean partialBlk; private BlockMetadataHeader header; private DataChecksum checksum; BlockChecksumComputer(DataNode datanode, ExtendedBlock block, BlockChecksumOptions blockChecksumOptions) throws IOException { super(datanode, blockChecksumOptions); this.block = block; this.requestLength = block.getNumBytes(); Preconditions.checkArgument(requestLength >= 0); this.metadataIn = datanode.data.getMetaDataInputStream(block); this.visibleLength = datanode.data.getReplicaVisibleLength(block); this.partialBlk = requestLength < visibleLength; int ioFileBufferSize = DFSUtilClient.getIoFileBufferSize(datanode.getConf()); this.checksumIn = new DataInputStream( new BufferedInputStream(metadataIn, ioFileBufferSize)); } Sender createSender(IOStreamPair pair) { DataOutputStream out = (DataOutputStream) pair.out; return new Sender(out); } ExtendedBlock getBlock() { return block; } long getRequestLength() { return requestLength; } LengthInputStream getMetadataIn() { return metadataIn; } DataInputStream getChecksumIn() { return checksumIn; } long getVisibleLength() { return visibleLength; } boolean isPartialBlk() { return partialBlk; } BlockMetadataHeader getHeader() { return header; } DataChecksum getChecksum() { return checksum; } /** * Perform the block checksum computing. * * @throws IOException */ abstract void compute() throws IOException; /** * Read block metadata header. * * @throws IOException */ void readHeader() throws IOException { //read metadata file header = BlockMetadataHeader.readHeader(checksumIn); checksum = header.getChecksum(); setChecksumSize(checksum.getChecksumSize()); setBytesPerCRC(checksum.getBytesPerChecksum()); long crcPerBlock = checksum.getChecksumSize() <= 0 ? 0 : (metadataIn.getLength() - BlockMetadataHeader.getHeaderSize()) / checksum.getChecksumSize(); setCrcPerBlock(crcPerBlock); setCrcType(checksum.getChecksumType()); } /** * Calculate partial block checksum. * * @return * @throws IOException */ byte[] crcPartialBlock() throws IOException { int partialLength = (int) (requestLength % getBytesPerCRC()); if (partialLength > 0) { byte[] buf = new byte[partialLength]; final InputStream blockIn = getBlockInputStream(block, requestLength - partialLength); try { // Get the CRC of the partialLength. IOUtils.readFully(blockIn, buf, 0, partialLength); } finally { IOUtils.closeStream(blockIn); } checksum.update(buf, 0, partialLength); byte[] partialCrc = new byte[getChecksumSize()]; checksum.writeValue(partialCrc, 0, true); return partialCrc; } return null; } } /** * Replicated block checksum computer. */ static class ReplicatedBlockChecksumComputer extends BlockChecksumComputer { ReplicatedBlockChecksumComputer(DataNode datanode, ExtendedBlock block, BlockChecksumOptions blockChecksumOptions) throws IOException { super(datanode, block, blockChecksumOptions); } @Override void compute() throws IOException { try { readHeader(); BlockChecksumType type = getBlockChecksumOptions().getBlockChecksumType(); switch (type) { case MD5CRC: computeMd5Crc(); break; case COMPOSITE_CRC: computeCompositeCrc(getBlockChecksumOptions().getStripeLength()); break; default: throw new IOException(String.format( "Unrecognized BlockChecksumType: %s", type)); } } finally { IOUtils.closeStream(getChecksumIn()); IOUtils.closeStream(getMetadataIn()); } } private void computeMd5Crc() throws IOException { MD5Hash md5out; if (isPartialBlk() && getCrcPerBlock() > 0) { md5out = checksumPartialBlock(); } else { md5out = checksumWholeBlock(); } setOutBytes(md5out.getDigest()); LOG.debug("block={}, bytesPerCRC={}, crcPerBlock={}, md5out={}", getBlock(), getBytesPerCRC(), getCrcPerBlock(), md5out); } private MD5Hash checksumWholeBlock() throws IOException { MD5Hash md5out = MD5Hash.digest(getChecksumIn()); return md5out; } private MD5Hash checksumPartialBlock() throws IOException { byte[] buffer = new byte[4 * 1024]; MessageDigest digester = MD5Hash.getDigester(); long remaining = (getRequestLength() / getBytesPerCRC()) * getChecksumSize(); for (int toDigest = 0; remaining > 0; remaining -= toDigest) { toDigest = getChecksumIn().read(buffer, 0, (int) Math.min(remaining, buffer.length)); if (toDigest < 0) { break; } digester.update(buffer, 0, toDigest); } byte[] partialCrc = crcPartialBlock(); if (partialCrc != null) { digester.update(partialCrc); } return new MD5Hash(digester.digest()); } private void computeCompositeCrc(long stripeLength) throws IOException { long checksumDataLength = Math.min(getVisibleLength(), getRequestLength()); if (stripeLength <= 0 || stripeLength > checksumDataLength) { stripeLength = checksumDataLength; } CrcComposer crcComposer = CrcComposer.newStripedCrcComposer( getCrcType(), getBytesPerCRC(), stripeLength); DataInputStream checksumIn = getChecksumIn(); // Whether getting the checksum for the entire block (which itself may // not be a full block size and may have a final chunk smaller than // getBytesPerCRC()), we begin with a number of full chunks, all of size // getBytesPerCRC(). long numFullChunks = checksumDataLength / getBytesPerCRC(); crcComposer.update(checksumIn, numFullChunks, getBytesPerCRC()); // There may be a final partial chunk that is not full-sized. Unlike the // MD5 case, we still consider this a "partial chunk" even if // getRequestLength() == getVisibleLength(), since the CRC composition // depends on the byte size of that final chunk, even if it already has a // precomputed CRC stored in metadata. So there are two cases: // 1. Reading only part of a block via getRequestLength(); we get the // crcPartialBlock() explicitly. // 2. Reading full visible length; the partial chunk already has a CRC // stored in block metadata, so we just continue reading checksumIn. long partialChunkSize = checksumDataLength % getBytesPerCRC(); if (partialChunkSize > 0) { if (isPartialBlk()) { byte[] partialChunkCrcBytes = crcPartialBlock(); crcComposer.update( partialChunkCrcBytes, 0, partialChunkCrcBytes.length, partialChunkSize); } else { int partialChunkCrc = checksumIn.readInt(); crcComposer.update(partialChunkCrc, partialChunkSize); } } byte[] composedCrcs = crcComposer.digest(); setOutBytes(composedCrcs); if (LOG.isDebugEnabled()) { LOG.debug( "block={}, getBytesPerCRC={}, crcPerBlock={}, compositeCrc={}", getBlock(), getBytesPerCRC(), getCrcPerBlock(), CrcUtil.toMultiCrcString(composedCrcs)); } } } /** * Non-striped block group checksum computer for striped blocks. */ static class BlockGroupNonStripedChecksumComputer extends AbstractBlockChecksumComputer { private final ExtendedBlock blockGroup; private final ErasureCodingPolicy ecPolicy; private final DatanodeInfo[] datanodes; private final Token<BlockTokenIdentifier>[] blockTokens; private final byte[] blockIndices; private final long requestedNumBytes; private final DataOutputBuffer blockChecksumBuf = new DataOutputBuffer(); // Keeps track of the positions within blockChecksumBuf where each data // block's checksum begins; for fixed-size block checksums this is easily // calculated as a multiple of the checksum size, but for striped block // CRCs, it's less error-prone to simply keep track of exact byte offsets // before each block checksum is populated into the buffer. private final int[] blockChecksumPositions; BlockGroupNonStripedChecksumComputer( DataNode datanode, StripedBlockInfo stripedBlockInfo, long requestedNumBytes, BlockChecksumOptions blockChecksumOptions) throws IOException { super(datanode, blockChecksumOptions); this.blockGroup = stripedBlockInfo.getBlock(); this.ecPolicy = stripedBlockInfo.getErasureCodingPolicy(); this.datanodes = stripedBlockInfo.getDatanodes(); this.blockTokens = stripedBlockInfo.getBlockTokens(); this.blockIndices = stripedBlockInfo.getBlockIndices(); this.requestedNumBytes = requestedNumBytes; this.blockChecksumPositions = new int[this.ecPolicy.getNumDataUnits()]; } private static class LiveBlockInfo { private final DatanodeInfo dn; private final Token<BlockTokenIdentifier> token; LiveBlockInfo(DatanodeInfo dn, Token<BlockTokenIdentifier> token) { this.dn = dn; this.token = token; } DatanodeInfo getDn() { return dn; } Token<BlockTokenIdentifier> getToken() { return token; } } @Override void compute() throws IOException { assert datanodes.length == blockIndices.length; Map<Byte, LiveBlockInfo> liveDns = new HashMap<>(datanodes.length); int blkIndxLen = blockIndices.length; int numDataUnits = ecPolicy.getNumDataUnits(); // Prepare live datanode list. Missing data blocks will be reconstructed // and recalculate checksum. for (int idx = 0; idx < blkIndxLen; idx++) { liveDns.put(blockIndices[idx], new LiveBlockInfo(datanodes[idx], blockTokens[idx])); } long checksumLen = 0; for (int idx = 0; idx < numDataUnits && idx < blkIndxLen; idx++) { // Before populating the blockChecksum at this index, record the byte // offset where it will begin. blockChecksumPositions[idx] = blockChecksumBuf.getLength(); ExtendedBlock block = null; try { block = getInternalBlock(numDataUnits, idx); LiveBlockInfo liveBlkInfo = liveDns.get((byte) idx); if (liveBlkInfo == null) { // reconstruct block and calculate checksum for missing node recalculateChecksum(idx, block.getNumBytes()); } else { try { checksumBlock(block, idx, liveBlkInfo.getToken(), liveBlkInfo.getDn()); } catch (IOException ioe) { LOG.warn("Exception while reading checksum", ioe); // reconstruct block and calculate checksum for the failed node recalculateChecksum(idx, block.getNumBytes()); } } checksumLen += block.getNumBytes(); if (checksumLen >= requestedNumBytes) { break; // done with the computation, simply return. } } catch (IOException e) { LOG.warn("Failed to get the checksum for block {} at index {} " + "in blockGroup {}", block, idx, blockGroup, e); throw e; } } BlockChecksumType type = getBlockChecksumOptions().getBlockChecksumType(); switch (type) { case MD5CRC: MD5Hash md5out = MD5Hash.digest(blockChecksumBuf.getData()); setOutBytes(md5out.getDigest()); break; case COMPOSITE_CRC: byte[] digest = reassembleNonStripedCompositeCrc(checksumLen); setOutBytes(digest); break; default: throw new IOException(String.format( "Unrecognized BlockChecksumType: %s", type)); } } /** * @param checksumLen The sum of bytes associated with the block checksum * data being digested into a block-group level checksum. */ private byte[] reassembleNonStripedCompositeCrc(long checksumLen) throws IOException { int numDataUnits = ecPolicy.getNumDataUnits(); CrcComposer crcComposer = CrcComposer.newCrcComposer( getCrcType(), ecPolicy.getCellSize()); // This should hold all the cell-granularity checksums of blk0 // followed by all cell checksums of blk1, etc. We must unstripe the // cell checksums in order of logical file bytes. Also, note that the // length of this array may not equal the the number of actually valid // bytes in the buffer (blockChecksumBuf.getLength()). byte[] flatBlockChecksumData = blockChecksumBuf.getData(); // Initialize byte-level cursors to where each block's checksum begins // inside the combined flattened buffer. int[] blockChecksumCursors = new int[numDataUnits]; for (int idx = 0; idx < numDataUnits; ++idx) { blockChecksumCursors[idx] = blockChecksumPositions[idx]; } // Reassemble cell-level CRCs in the right order. long numFullCells = checksumLen / ecPolicy.getCellSize(); for (long cellIndex = 0; cellIndex < numFullCells; ++cellIndex) { int blockIndex = (int) (cellIndex % numDataUnits); int checksumCursor = blockChecksumCursors[blockIndex]; int cellCrc = CrcUtil.readInt( flatBlockChecksumData, checksumCursor); blockChecksumCursors[blockIndex] += 4; crcComposer.update(cellCrc, ecPolicy.getCellSize()); } if (checksumLen % ecPolicy.getCellSize() != 0) { // Final partial cell. int blockIndex = (int) (numFullCells % numDataUnits); int checksumCursor = blockChecksumCursors[blockIndex]; int cellCrc = CrcUtil.readInt( flatBlockChecksumData, checksumCursor); blockChecksumCursors[blockIndex] += 4; crcComposer.update(cellCrc, checksumLen % ecPolicy.getCellSize()); } byte[] digest = crcComposer.digest(); if (LOG.isDebugEnabled()) { LOG.debug("flatBlockChecksumData.length={}, numDataUnits={}, " + "checksumLen={}, digest={}", flatBlockChecksumData.length, numDataUnits, checksumLen, CrcUtil.toSingleCrcString(digest)); } return digest; } private ExtendedBlock getInternalBlock(int numDataUnits, int idx) { // Sets requested number of bytes in blockGroup which is required to // construct the internal block for computing checksum. long actualNumBytes = blockGroup.getNumBytes(); blockGroup.setNumBytes(requestedNumBytes); ExtendedBlock block = StripedBlockUtil.constructInternalBlock(blockGroup, ecPolicy.getCellSize(), numDataUnits, idx); // Set back actualNumBytes value in blockGroup. blockGroup.setNumBytes(actualNumBytes); return block; } private void checksumBlock(ExtendedBlock block, int blockIdx, Token<BlockTokenIdentifier> blockToken, DatanodeInfo targetDatanode) throws IOException { int timeout = getDatanode().getDnConf().getEcChecksumSocketTimeout(); try (IOStreamPair pair = getDatanode().connectToDN(targetDatanode, timeout, block, blockToken)) { LOG.debug("write to {}: {}, block={}", getDatanode(), Op.BLOCK_CHECKSUM, block); // get block checksum // A BlockGroupCheckum of type COMPOSITE_CRC uses underlying // BlockChecksums also of type COMPOSITE_CRC but with // stripeLength == ecPolicy.getCellSize(). BlockChecksumOptions childOptions; BlockChecksumType groupChecksumType = getBlockChecksumOptions().getBlockChecksumType(); switch (groupChecksumType) { case MD5CRC: childOptions = getBlockChecksumOptions(); break; case COMPOSITE_CRC: childOptions = new BlockChecksumOptions( BlockChecksumType.COMPOSITE_CRC, ecPolicy.getCellSize()); break; default: throw new IOException( "Unknown BlockChecksumType: " + groupChecksumType); } createSender(pair).blockChecksum(block, blockToken, childOptions); final DataTransferProtos.BlockOpResponseProto reply = DataTransferProtos.BlockOpResponseProto.parseFrom( PBHelperClient.vintPrefixed(pair.in)); String logInfo = "for block " + block + " from datanode " + targetDatanode; DataTransferProtoUtil.checkBlockOpStatus(reply, logInfo); DataTransferProtos.OpBlockChecksumResponseProto checksumData = reply.getChecksumResponse(); // read crc-type final DataChecksum.Type ct; if (checksumData.hasCrcType()) { ct = PBHelperClient.convert(checksumData.getCrcType()); } else { LOG.debug("Retrieving checksum from an earlier-version DataNode: " + "inferring checksum by reading first byte"); ct = DataChecksum.Type.DEFAULT; } setOrVerifyChecksumProperties(blockIdx, checksumData.getBytesPerCrc(), checksumData.getCrcPerBlock(), ct); switch (groupChecksumType) { case MD5CRC: //read md5 final MD5Hash md5 = new MD5Hash(checksumData.getBlockChecksum().toByteArray()); md5.write(blockChecksumBuf); LOG.debug("got reply from datanode:{}, md5={}", targetDatanode, md5); break; case COMPOSITE_CRC: BlockChecksumType returnedType = PBHelperClient.convert( checksumData.getBlockChecksumOptions().getBlockChecksumType()); if (returnedType != BlockChecksumType.COMPOSITE_CRC) { throw new IOException(String.format( "Unexpected blockChecksumType '%s', expecting COMPOSITE_CRC", returnedType)); } byte[] checksumBytes = checksumData.getBlockChecksum().toByteArray(); blockChecksumBuf.write(checksumBytes, 0, checksumBytes.length); if (LOG.isDebugEnabled()) { LOG.debug("got reply from datanode:{} for blockIdx:{}, checksum:{}", targetDatanode, blockIdx, CrcUtil.toMultiCrcString(checksumBytes)); } break; default: throw new IOException( "Unknown BlockChecksumType: " + groupChecksumType); } } } /** * Reconstruct this data block and recalculate checksum. * * @param errBlkIndex * error index to be reconstructed and recalculate checksum. * @param blockLength * number of bytes in the block to compute checksum. * @throws IOException */ private void recalculateChecksum(int errBlkIndex, long blockLength) throws IOException { LOG.debug("Recalculate checksum for the missing/failed block index {}", errBlkIndex); byte[] errIndices = new byte[1]; errIndices[0] = (byte) errBlkIndex; StripedReconstructionInfo stripedReconInfo = new StripedReconstructionInfo( blockGroup, ecPolicy, blockIndices, datanodes, errIndices); BlockChecksumType groupChecksumType = getBlockChecksumOptions().getBlockChecksumType(); try (StripedBlockChecksumReconstructor checksumRecon = groupChecksumType == BlockChecksumType.COMPOSITE_CRC ? new StripedBlockChecksumCompositeCrcReconstructor( getDatanode().getErasureCodingWorker(), stripedReconInfo, blockChecksumBuf, blockLength) : new StripedBlockChecksumMd5CrcReconstructor( getDatanode().getErasureCodingWorker(), stripedReconInfo, blockChecksumBuf, blockLength)) { checksumRecon.reconstruct(); DataChecksum checksum = checksumRecon.getChecksum(); long crcPerBlock = checksum.getChecksumSize() <= 0 ? 0 : checksumRecon.getChecksumDataLen() / checksum.getChecksumSize(); setOrVerifyChecksumProperties(errBlkIndex, checksum.getBytesPerChecksum(), crcPerBlock, checksum.getChecksumType()); LOG.debug("Recalculated checksum for the block index:{}, checksum={}", errBlkIndex, checksumRecon.getDigestObject()); } } private void setOrVerifyChecksumProperties(int blockIdx, int bpc, final long cpb, DataChecksum.Type ct) throws IOException { //read byte-per-checksum if (blockIdx == 0) { //first block setBytesPerCRC(bpc); } else if (bpc != getBytesPerCRC()) { throw new IOException("Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + getBytesPerCRC()); } //read crc-per-block if (blockIdx == 0) { setCrcPerBlock(cpb); } if (blockIdx == 0) { // first block setCrcType(ct); } else if (getCrcType() != DataChecksum.Type.MIXED && getCrcType() != ct) { BlockChecksumType groupChecksumType = getBlockChecksumOptions().getBlockChecksumType(); if (groupChecksumType == BlockChecksumType.COMPOSITE_CRC) { throw new IOException(String.format( "BlockChecksumType COMPOSITE_CRC doesn't support MIXED " + "underlying types; previous block was %s, next block is %s", getCrcType(), ct)); } else { setCrcType(DataChecksum.Type.MIXED); } } if (blockIdx == 0) { LOG.debug("set bytesPerCRC={}, crcPerBlock={}", getBytesPerCRC(), getCrcPerBlock()); } } } }
11,395
1,264
package org.springframework.data.mongodb.core.index; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class SampleEntity { @Id String id; @Indexed String prop; }
79
338
package com.camnter.reduce.dependency.packaging.plugin.host; import dalvik.system.DexClassLoader; /** * @author CaMnter */ public class PluginClassloader extends DexClassLoader { public PluginClassloader(String dexPath, String optimizedDirectory, String librarySearchPath, ClassLoader parent) { super(dexPath, optimizedDirectory, librarySearchPath, parent); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { return super.findClass(name); } }
165
1,014
{ "WUF1V.HE": { "short_name": "Wulff Group Plc", "long_name": "Wulff-Yhti\u00f6<NAME>", "summary": "Wulff-Yhti\u00c3\u00b6t Oyj, together with its subsidiaries, sells and markets workplace products, catering solutions, facility management products, cleaning supplies, office and IT supplies, ergonomics, first aid products, and other products for worksites. It operates through two segments, Contract Customers and Expertise Sales. The company also provides printing services, data management solutions, ICT outsourcing services, and large-format printing services; maintenance and remote monitoring solutions; meeting and event catering services; exhibition; novelties for everyday life; first aid solutions, products, and training services; and professional solutions for post-treatment of paper, and products for worksites and real estates. It serves micro, small, and medium-sized companies through wulffinkulma.fi, a webshop; and wulff.fi, as well as through sales professionals and stores in Finland, Sweden, Norway, Denmark, Estonia, other European countries, and internationally. The company was formerly known as Beltton Group Plc and changed its name to Wulff-Yhti\u00c3\u00b6t Oyj in 2008. Wulff-Yhti\u00c3\u00b6t Oyj was founded in 1890 and is headquartered in Espoo, Finland.", "currency": "EUR", "sector": "Industrials", "industry": "Business Equipment & Supplies", "exchange": "HEL", "market": "fi_market", "country": "Finland", "state": null, "city": "Espoo", "zipcode": "02610", "website": "http://www.wulffyhtiot.fi", "market_cap": "Small Cap" } }
564
571
# Copyright (c) 2016 - 2018 Dell Inc. or its subsidiaries. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import functools from unittest import mock import ddt from oslo_utils import units from cinder import exception from cinder.tests.unit import test from cinder.tests.unit.volume.drivers.dell_emc.unity \ import fake_enum as enums from cinder.tests.unit.volume.drivers.dell_emc.unity \ import fake_exception as ex from cinder.tests.unit.volume.drivers.dell_emc.unity import test_client from cinder.volume.drivers.dell_emc.unity import adapter from cinder.volume.drivers.dell_emc.unity import client from cinder.volume.drivers.dell_emc.unity import replication ######################## # # Start of Mocks # ######################## class MockConfig(object): def __init__(self): self.config_group = 'test_backend' self.unity_storage_pool_names = ['pool1', 'pool2'] self.unity_io_ports = None self.reserved_percentage = 5 self.max_over_subscription_ratio = 300 self.volume_backend_name = 'backend' self.san_ip = '1.2.3.4' self.san_login = 'user' self.san_password = '<PASSWORD>' self.driver_ssl_cert_verify = True self.driver_ssl_cert_path = None self.remove_empty_host = False def safe_get(self, name): return getattr(self, name) class MockConnector(object): @staticmethod def disconnect_volume(data, device): pass class MockDriver(object): def __init__(self): self.configuration = mock.Mock(volume_dd_blocksize='1M') self.replication_manager = MockReplicationManager() self.protocol = 'iSCSI' @staticmethod def _connect_device(conn): return {'connector': MockConnector(), 'device': {'path': 'dev'}, 'conn': {'data': {}}} def get_version(self): return '1.0.0' class MockReplicationManager(object): def __init__(self): self.is_replication_configured = False self.replication_devices = {} self.active_backend_id = None self.is_service_failed_over = None self.default_device = None self.active_adapter = None def failover_service(self, backend_id): if backend_id == 'default': self.is_service_failed_over = False elif backend_id == 'secondary_unity': self.is_service_failed_over = True else: raise exception.VolumeBackendAPIException() class MockClient(object): def __init__(self): self._system = test_client.MockSystem() self.host = '10.10.10.10' # fake unity IP @staticmethod def get_pools(): return test_client.MockResourceList(['pool0', 'pool1']) @staticmethod def create_lun(name, size, pool, description=None, io_limit_policy=None, is_thin=None, is_compressed=None, tiering_policy=None): lun_id = name if is_thin is not None and not is_thin: lun_id += '_thick' if tiering_policy: if tiering_policy is enums.TieringPolicyEnum.AUTOTIER: lun_id += '_auto' elif tiering_policy is enums.TieringPolicyEnum.LOWEST: lun_id += '_low' return test_client.MockResource(_id=lun_id, name=name) @staticmethod def lun_has_snapshot(lun): return lun.name == 'volume_has_snapshot' @staticmethod def get_lun(name=None, lun_id=None): if lun_id is None: lun_id = 'lun_4' if lun_id in ('lun_43',): # for thin clone cases return test_client.MockResource(_id=lun_id, name=name) if name == 'not_exists': ret = test_client.MockResource(name=lun_id) ret.existed = False else: if name is None: name = lun_id ret = test_client.MockResource(_id=lun_id, name=name) return ret @staticmethod def delete_lun(lun_id): if lun_id != 'lun_4': raise ex.UnexpectedLunDeletion() @staticmethod def get_serial(): return 'CLIENT_SERIAL' @staticmethod def create_snap(src_lun_id, name=None): if src_lun_id in ('lun_53', 'lun_55'): # for thin clone cases return test_client.MockResource( _id='snap_clone_{}'.format(src_lun_id)) return test_client.MockResource(name=name, _id=src_lun_id) @staticmethod def get_snap(name=None): if name in ('snap_50',): # for thin clone cases return name snap = test_client.MockResource(name=name, _id=name) if name is not None: ret = snap else: ret = [snap] return ret @staticmethod def delete_snap(snap): if snap.name in ('abc-def_snap',): raise ex.SnapDeleteIsCalled() @staticmethod def create_host(name): return test_client.MockResource(name=name) @staticmethod def create_host_wo_lock(name): return test_client.MockResource(name=name) @staticmethod def delete_host_wo_lock(host): if host.name == 'empty-host': raise ex.HostDeleteIsCalled() @staticmethod def attach(host, lun_or_snap): return 10 @staticmethod def detach(host, lun_or_snap): error_ids = ['lun_43', 'snap_0'] if host.name == 'host1' and lun_or_snap.get_id() in error_ids: raise ex.DetachIsCalled() @staticmethod def detach_all(lun): error_ids = ['lun_44'] if lun.get_id() in error_ids: raise ex.DetachAllIsCalled() @staticmethod def get_iscsi_target_info(allowed_ports=None): return [{'portal': '1.2.3.4:1234', 'iqn': 'iqn.1-1.com.e:c.a.a0'}, {'portal': '1.2.3.5:1234', 'iqn': 'iqn.1-1.com.e:c.a.a1'}] @staticmethod def get_fc_target_info(host=None, logged_in_only=False, allowed_ports=None): if host and host.name == 'no_target': ret = [] else: ret = ['8899AABBCCDDEEFF', '8899AABBCCDDFFEE'] return ret @staticmethod def create_lookup_service(): return {} @staticmethod def get_io_limit_policy(specs): mock_io_policy = (test_client.MockResource(name=specs.get('id')) if specs else None) return mock_io_policy @staticmethod def extend_lun(lun_id, size_gib): if size_gib <= 0: raise ex.ExtendLunError @staticmethod def get_fc_ports(): return test_client.MockResourceList(ids=['spa_iom_0_fc0', 'spa_iom_0_fc1']) @staticmethod def get_ethernet_ports(): return test_client.MockResourceList(ids=['spa_eth0', 'spb_eth0']) @staticmethod def thin_clone(obj, name, io_limit_policy, description, new_size_gb): if (obj.name, name) in ( ('snap_61', 'lun_60'), ('lun_63', 'lun_60')): return test_client.MockResource(_id=name) elif (obj.name, name) in (('snap_71', 'lun_70'), ('lun_72', 'lun_70')): raise ex.UnityThinCloneNotAllowedError() else: raise ex.UnityThinCloneLimitExceededError @staticmethod def update_host_initiators(host, wwns): return None @property def system(self): return self._system def restore_snapshot(self, snap_name): return test_client.MockResource(name="back_snap") def get_pool_id_by_name(self, name): pools = {'PoolA': 'pool_1', 'PoolB': 'pool_2', 'PoolC': 'pool_3'} return pools.get(name, None) def migrate_lun(self, lun_id, dest_pool_id, provision=None): if dest_pool_id == 'pool_2': return True if dest_pool_id == 'pool_3': return False def get_remote_system(self, name=None): if name == 'not-found-remote-system': return None return test_client.MockResource(_id='RS_1') def get_replication_session(self, name=None): if name == 'not-found-rep-session': raise client.ClientReplicationError() rep_session = test_client.MockResource(_id='rep_session_id_1') rep_session.name = name rep_session.src_resource_id = 'sv_1' rep_session.dst_resource_id = 'sv_99' return rep_session def create_replication(self, src_lun, max_time_out_of_sync, dst_pool_id, remote_system): if (src_lun.get_id() == 'sv_1' and max_time_out_of_sync == 60 and dst_pool_id == 'pool_1' and remote_system.get_id() == 'RS_1'): rep_session = test_client.MockResource(_id='rep_session_id_1') rep_session.name = 'rep_session_name_1' return rep_session return None def failover_replication(self, rep_session): if rep_session.name != 'rep_session_name_1': raise client.ClientReplicationError() def failback_replication(self, rep_session): if rep_session.name != 'rep_session_name_1': raise client.ClientReplicationError() def is_cg_replicated(self, cg_id): return cg_id and 'is_replicated' in cg_id def get_cg(self, name): return test_client.MockResource(_id=name) def create_cg_replication(self, group_id, pool_id, remote_system, max_time): if group_id and 'error' in group_id: raise Exception('has issue when creating cg replication session.') def delete_cg_rep_session(self, group_id): if group_id and 'error' in group_id: raise Exception('has issue when deleting cg replication session.') def failover_cg_rep_session(self, group_id, need_sync): if group_id and 'error' in group_id: raise Exception('has issue when failover cg replication session.') def failback_cg_rep_session(self, group_id): if group_id and 'error' in group_id: raise Exception('has issue when failback cg replication session.') class MockLookupService(object): @staticmethod def get_device_mapping_from_network(initiator_wwns, target_wwns): return { 'san_1': { 'initiator_port_wwn_list': ('200000051e55a100', '200000051e55a121'), 'target_port_wwn_list': ('100000051e55a100', '100000051e55a121') } } class MockOSResource(mock.Mock): def __init__(self, *args, **kwargs): super(MockOSResource, self).__init__(*args, **kwargs) if 'name' in kwargs: self.name = kwargs['name'] self.kwargs = kwargs def __getitem__(self, key): return self.kwargs[key] def mock_replication_device(device_conf=None, serial_number=None, max_time_out_of_sync=None, destination_pool_id=None): if device_conf is None: device_conf = { 'backend_id': 'secondary_unity', 'san_ip': '2.2.2.2' } if serial_number is None: serial_number = 'SECONDARY_UNITY_SN' if max_time_out_of_sync is None: max_time_out_of_sync = 60 if destination_pool_id is None: destination_pool_id = 'pool_1' rep_device = replication.ReplicationDevice(device_conf, MockDriver()) rep_device._adapter = mock_adapter(adapter.CommonAdapter) rep_device._adapter._serial_number = serial_number rep_device.max_time_out_of_sync = max_time_out_of_sync rep_device._dst_pool = test_client.MockResource(_id=destination_pool_id) return rep_device def mock_adapter(driver_clz): ret = driver_clz() ret._client = MockClient() with mock.patch('cinder.volume.drivers.dell_emc.unity.adapter.' 'CommonAdapter.validate_ports'), patch_storops(): ret.do_setup(MockDriver(), MockConfig()) ret.lookup_service = MockLookupService() return ret def get_backend_qos_specs(volume): return None def get_connector_properties(): return {'host': 'host1', 'wwpns': 'abcdefg'} def get_lun_pl(name): return 'id^%s|system^CLIENT_SERIAL|type^lun|version^None' % name def get_snap_lun_pl(name): return 'id^%s|system^CLIENT_SERIAL|type^snap_lun|version^None' % name def get_snap_pl(name): return 'id^%s|system^CLIENT_SERIAL|type^snapshot|version^None' % name def get_connector_uids(adapter, connector): return [] def get_connection_info(adapter, hlu, host, connector): return {} def get_volume_type_qos_specs(qos_id): if qos_id == 'qos': return {'qos_specs': {'id': u'qos_type_id_1', 'consumer': u'back-end', u'maxBWS': u'102400', u'maxIOPS': u'500'}} if qos_id == 'qos_2': return {'qos_specs': {'id': u'qos_type_id_2', 'consumer': u'back-end', u'maxBWS': u'102402', u'maxIOPS': u'502'}} return {'qos_specs': {}} def get_volume_type_extra_specs(type_id): if type_id == 'thick': return {'provisioning:type': 'thick', 'thick_provisioning_support': '<is> True'} if type_id == 'tier_auto': return {'storagetype:tiering': 'Auto', 'fast_support': '<is> True'} if type_id == 'tier_lowest': return {'storagetype:tiering': 'LowestAvailable', 'fast_support': '<is> True'} if type_id == 'compressed': return {'provisioning:type': 'compressed', 'compression_support': '<is> True'} return {} def get_group_type_specs(group_type_id): if group_type_id == '': return {'consistent_group_snapshot_enabled': '<is> True', 'group_type_id': group_type_id} return {} def group_is_cg(group): return group.id != 'not_cg' def patch_for_unity_adapter(func): @functools.wraps(func) @mock.patch('cinder.volume.volume_types.get_volume_type_extra_specs', new=get_volume_type_extra_specs) @mock.patch('cinder.volume.group_types.get_group_type_specs', new=get_group_type_specs) @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs', new=get_volume_type_qos_specs) @mock.patch('cinder.volume.drivers.dell_emc.unity.utils.' 'get_backend_qos_specs', new=get_backend_qos_specs) @mock.patch('cinder.volume.drivers.dell_emc.unity.utils.' 'group_is_cg', new=group_is_cg) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties', new=get_connector_properties) def func_wrapper(*args, **kwargs): return func(*args, **kwargs) return func_wrapper def patch_for_concrete_adapter(clz_str): def inner_decorator(func): @functools.wraps(func) @mock.patch('%s.get_connector_uids' % clz_str, new=get_connector_uids) @mock.patch('%s.get_connection_info' % clz_str, new=get_connection_info) def func_wrapper(*args, **kwargs): return func(*args, **kwargs) return func_wrapper return inner_decorator patch_for_iscsi_adapter = patch_for_concrete_adapter( 'cinder.volume.drivers.dell_emc.unity.adapter.ISCSIAdapter') patch_for_fc_adapter = patch_for_concrete_adapter( 'cinder.volume.drivers.dell_emc.unity.adapter.FCAdapter') @contextlib.contextmanager def patch_thin_clone(cloned_lun): with mock.patch.object(adapter.CommonAdapter, '_thin_clone') as tc: tc.return_value = cloned_lun yield tc @contextlib.contextmanager def patch_dd_copy(copied_lun): with mock.patch.object(adapter.CommonAdapter, '_dd_copy') as dd: dd.return_value = copied_lun yield dd @contextlib.contextmanager def patch_copy_volume(): with mock.patch('cinder.volume.volume_utils.copy_volume') as mocked: yield mocked @contextlib.contextmanager def patch_storops(): with mock.patch.object(adapter, 'storops') as storops: storops.ThinCloneActionEnum = mock.Mock(DD_COPY='DD_COPY') yield storops class IdMatcher(object): def __init__(self, obj): self._obj = obj def __eq__(self, other): return self._obj._id == other._id ######################## # # Start of Tests # ######################## @ddt.ddt @mock.patch.object(adapter, 'storops_ex', new=ex) @mock.patch.object(adapter, 'enums', new=enums) @mock.patch.object(adapter.volume_utils, 'is_group_a_cg_snapshot_type', new=lambda x: True) class CommonAdapterTest(test.TestCase): def setUp(self): super(CommonAdapterTest, self).setUp() self.adapter = mock_adapter(adapter.CommonAdapter) def test_get_managed_pools(self): ret = self.adapter.get_managed_pools() self.assertIn('pool1', ret) self.assertNotIn('pool0', ret) self.assertNotIn('pool2', ret) @patch_for_unity_adapter def test_create_volume(self): volume = MockOSResource(name='lun_3', size=5, host='unity#pool1', group=None) ret = self.adapter.create_volume(volume) expected = get_lun_pl('lun_3') self.assertEqual(expected, ret['provider_location']) @patch_for_unity_adapter def test_create_volume_thick(self): volume = MockOSResource(name='lun_3', size=5, host='unity#pool1', group=None, volume_type_id='thick') ret = self.adapter.create_volume(volume) expected = get_lun_pl('lun_3_thick') self.assertEqual(expected, ret['provider_location']) @patch_for_unity_adapter def test_create_compressed_volume(self): volume_type = MockOSResource( extra_specs={'compression_support': '<is> True'}) volume = MockOSResource(name='lun_3', size=5, host='unity#pool1', group=None, volume_type=volume_type) ret = self.adapter.create_volume(volume) expected = get_lun_pl('lun_3') self.assertEqual(expected, ret['provider_location']) @patch_for_unity_adapter def test_create_auto_tiering_volume(self): volume = MockOSResource(name='lun_3', size=5, host='unity#pool1', group=None, volume_type_id='tier_auto') ret = self.adapter.create_volume(volume) expected = get_lun_pl('lun_3_auto') self.assertEqual(expected, ret['provider_location']) @patch_for_unity_adapter def test_create_lowest_tiering_volume(self): volume = MockOSResource(name='lun_3', size=5, host='unity#pool1', group=None, volume_type_id='tier_lowest') ret = self.adapter.create_volume(volume) expected = get_lun_pl('lun_3_low') self.assertEqual(expected, ret['provider_location']) def test_create_snapshot(self): volume = MockOSResource(provider_location='id^lun_43') snap = MockOSResource(volume=volume, name='abc-def_snap') result = self.adapter.create_snapshot(snap) self.assertEqual(get_snap_pl('lun_43'), result['provider_location']) self.assertEqual('lun_43', result['provider_id']) def test_delete_snap(self): def f(): snap = MockOSResource(name='abc-def_snap') self.adapter.delete_snapshot(snap) self.assertRaises(ex.SnapDeleteIsCalled, f) def test_get_lun_id_has_location(self): volume = MockOSResource(provider_location='id^lun_43') self.assertEqual('lun_43', self.adapter.get_lun_id(volume)) def test_get_lun_id_no_location(self): volume = MockOSResource(provider_location=None) self.assertEqual('lun_4', self.adapter.get_lun_id(volume)) def test_delete_volume(self): volume = MockOSResource(provider_location='id^lun_4') self.adapter.delete_volume(volume) @patch_for_unity_adapter def test_retype_volume_has_snapshot(self): volume = MockOSResource(name='volume_has_snapshot', size=5, host='HostA@BackendB#PoolB') ctxt = None diff = None new_type = {'name': u'type01', 'id': 'compressed'} host = {'host': 'HostA@BackendB#PoolB'} result = self.adapter.retype(ctxt, volume, new_type, diff, host) self.assertFalse(result) @patch_for_unity_adapter def test_retype_volume_thick_to_compressed(self): volume = MockOSResource(name='thick_volume', size=5, host='HostA@BackendB#PoolA', provider_location='id^lun_33') ctxt = None diff = None new_type = {'name': u'compressed_type', 'id': 'compressed'} host = {'host': 'HostA@BackendB#PoolB'} result = self.adapter.retype(ctxt, volume, new_type, diff, host) self.assertEqual((True, {}), result) @patch_for_unity_adapter def test_retype_volume_to_compressed(self): volume = MockOSResource(name='thin_volume', size=5, host='HostA@BackendB#PoolB') ctxt = None diff = None new_type = {'name': u'compressed_type', 'id': 'compressed'} host = {'host': 'HostA@BackendB#PoolB'} result = self.adapter.retype(ctxt, volume, new_type, diff, host) self.assertTrue(result) @patch_for_unity_adapter def test_retype_volume_to_qos(self): volume = MockOSResource(name='thin_volume', size=5, host='HostA@BackendB#PoolB') ctxt = None diff = None new_type = {'name': u'qos_type', 'id': 'qos'} host = {'host': 'HostA@BackendB#PoolB'} result = self.adapter.retype(ctxt, volume, new_type, diff, host) self.assertTrue(result) @patch_for_unity_adapter def test_retype_volume_revert_qos(self): volume = MockOSResource(name='qos_volume', size=5, host='HostA@BackendB#PoolB', volume_type_id='qos_2') ctxt = None diff = None new_type = {'name': u'no_qos_type', 'id': ''} host = {'host': 'HostA@BackendB#PoolB'} result = self.adapter.retype(ctxt, volume, new_type, diff, host) self.assertTrue(result) def test_get_pool_stats(self): stats_list = self.adapter.get_pools_stats() self.assertEqual(1, len(stats_list)) stats = stats_list[0] self.assertEqual('pool1', stats['pool_name']) self.assertEqual(5, stats['total_capacity_gb']) self.assertEqual('pool1|CLIENT_SERIAL', stats['location_info']) self.assertEqual(6, stats['provisioned_capacity_gb']) self.assertEqual(2, stats['free_capacity_gb']) self.assertEqual(300, stats['max_over_subscription_ratio']) self.assertEqual(5, stats['reserved_percentage']) self.assertTrue(stats['thick_provisioning_support']) self.assertTrue(stats['thin_provisioning_support']) self.assertTrue(stats['compression_support']) self.assertTrue(stats['consistent_group_snapshot_enabled']) self.assertFalse(stats['replication_enabled']) self.assertEqual(0, len(stats['replication_targets'])) self.assertTrue(stats['fast_support']) def test_update_volume_stats(self): stats = self.adapter.update_volume_stats() self.assertEqual('backend', stats['volume_backend_name']) self.assertEqual('unknown', stats['storage_protocol']) self.assertTrue(stats['thin_provisioning_support']) self.assertTrue(stats['thick_provisioning_support']) self.assertTrue(stats['consistent_group_snapshot_enabled']) self.assertFalse(stats['replication_enabled']) self.assertEqual(0, len(stats['replication_targets'])) self.assertTrue(stats['fast_support']) self.assertEqual(1, len(stats['pools'])) def test_get_replication_stats(self): self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { 'secondary_unity': None } stats = self.adapter.update_volume_stats() self.assertTrue(stats['replication_enabled']) self.assertEqual(['secondary_unity'], stats['replication_targets']) self.assertEqual(1, len(stats['pools'])) pool_stats = stats['pools'][0] self.assertTrue(pool_stats['replication_enabled']) self.assertEqual(['secondary_unity'], pool_stats['replication_targets']) def test_serial_number(self): self.assertEqual('CLIENT_SERIAL', self.adapter.serial_number) def test_do_setup(self): self.assertEqual('1.2.3.4', self.adapter.ip) self.assertEqual('user', self.adapter.username) self.assertEqual('pass', self.adapter.password) self.assertTrue(self.adapter.array_cert_verify) self.assertIsNone(self.adapter.array_ca_cert_path) def test_do_setup_version_before_4_1(self): def f(): with mock.patch('cinder.volume.drivers.dell_emc.unity.adapter.' 'CommonAdapter.validate_ports'): self.adapter._client.system.system_version = '4.0.0' self.adapter.do_setup(self.adapter.driver, MockConfig()) self.assertRaises(exception.VolumeBackendAPIException, f) def test_verify_cert_false_path_none(self): self.adapter.array_cert_verify = False self.adapter.array_ca_cert_path = None self.assertFalse(self.adapter.verify_cert) def test_verify_cert_false_path_not_none(self): self.adapter.array_cert_verify = False self.adapter.array_ca_cert_path = '/tmp/array_ca.crt' self.assertFalse(self.adapter.verify_cert) def test_verify_cert_true_path_none(self): self.adapter.array_cert_verify = True self.adapter.array_ca_cert_path = None self.assertTrue(self.adapter.verify_cert) def test_verify_cert_true_path_valide(self): self.adapter.array_cert_verify = True self.adapter.array_ca_cert_path = '/tmp/array_ca.crt' self.assertEqual(self.adapter.array_ca_cert_path, self.adapter.verify_cert) def test_terminate_connection_volume(self): def f(): volume = MockOSResource(provider_location='id^lun_43', id='id_43', volume_attachment=None) connector = {'host': 'host1'} self.adapter.terminate_connection(volume, connector) self.assertRaises(ex.DetachIsCalled, f) def test_terminate_connection_force_detach(self): def f(): volume = MockOSResource(provider_location='id^lun_44', id='id_44', volume_attachment=None) self.adapter.terminate_connection(volume, None) self.assertRaises(ex.DetachAllIsCalled, f) def test_terminate_connection_snapshot(self): def f(): connector = {'host': 'host1'} snap = MockOSResource(name='snap_0', id='snap_0', volume_attachment=None) self.adapter.terminate_connection_snapshot(snap, connector) self.assertRaises(ex.DetachIsCalled, f) def test_terminate_connection_remove_empty_host(self): self.adapter.remove_empty_host = True def f(): connector = {'host': 'empty-host'} vol = MockOSResource(provider_location='id^lun_45', id='id_45', volume_attachment=None) self.adapter.terminate_connection(vol, connector) self.assertRaises(ex.HostDeleteIsCalled, f) def test_terminate_connection_multiattached_volume(self): def f(): connector = {'host': 'host1'} attachments = [MockOSResource(id='id-1', attach_status='attached', attached_host='host1'), MockOSResource(id='id-2', attach_status='attached', attached_host='host1')] vol = MockOSResource(provider_location='id^lun_45', id='id_45', volume_attachment=attachments) self.adapter.terminate_connection(vol, connector) self.assertIsNone(f()) def test_manage_existing_by_name(self): ref = {'source-id': 12} volume = MockOSResource(name='lun1') ret = self.adapter.manage_existing(volume, ref) expected = get_lun_pl('12') self.assertEqual(expected, ret['provider_location']) def test_manage_existing_by_id(self): ref = {'source-name': 'lunx'} volume = MockOSResource(name='lun1') ret = self.adapter.manage_existing(volume, ref) expected = get_lun_pl('lun_4') self.assertEqual(expected, ret['provider_location']) def test_manage_existing_invalid_ref(self): def f(): ref = {} volume = MockOSResource(name='lun1') self.adapter.manage_existing(volume, ref) self.assertRaises(exception.ManageExistingInvalidReference, f) def test_manage_existing_lun_not_found(self): def f(): ref = {'source-name': 'not_exists'} volume = MockOSResource(name='lun1') self.adapter.manage_existing(volume, ref) self.assertRaises(exception.ManageExistingInvalidReference, f) @patch_for_unity_adapter def test_manage_existing_get_size_invalid_backend(self): def f(): volume = MockOSResource(volume_type_id='thin', host='host@backend#pool1') ref = {'source-id': 12} self.adapter.manage_existing_get_size(volume, ref) self.assertRaises(exception.ManageExistingInvalidReference, f) @patch_for_unity_adapter def test_manage_existing_get_size_success(self): volume = MockOSResource(volume_type_id='thin', host='host@backend#pool0') ref = {'source-id': 12} volume_size = self.adapter.manage_existing_get_size(volume, ref) self.assertEqual(5, volume_size) @patch_for_unity_adapter def test_create_volume_from_snapshot(self): lun_id = 'lun_50' volume = MockOSResource(name=lun_id, id=lun_id, host='unity#pool1') snap_id = 'snap_50' snap = MockOSResource(name=snap_id) with patch_thin_clone(test_client.MockResource(_id=lun_id)) as tc: ret = self.adapter.create_volume_from_snapshot(volume, snap) self.assertEqual(get_snap_lun_pl(lun_id), ret['provider_location']) tc.assert_called_with(adapter.VolumeParams(self.adapter, volume), snap_id) @patch_for_unity_adapter def test_create_cloned_volume_attached(self): lun_id = 'lun_51' src_lun_id = 'lun_53' volume = MockOSResource(name=lun_id, id=lun_id, host='unity#pool1') src_vref = MockOSResource(id=src_lun_id, name=src_lun_id, provider_location=get_lun_pl(src_lun_id), volume_attachment=['not_care']) with patch_dd_copy(test_client.MockResource(_id=lun_id)) as dd: ret = self.adapter.create_cloned_volume(volume, src_vref) dd.assert_called_with( adapter.VolumeParams(self.adapter, volume), IdMatcher(test_client.MockResource( _id='snap_clone_{}'.format(src_lun_id))), src_lun=IdMatcher(test_client.MockResource(_id=src_lun_id))) self.assertEqual(get_lun_pl(lun_id), ret['provider_location']) @patch_for_unity_adapter def test_create_cloned_volume_available(self): lun_id = 'lun_54' src_lun_id = 'lun_55' volume = MockOSResource(id=lun_id, host='unity#pool1', size=3, provider_location=get_lun_pl(lun_id)) src_vref = MockOSResource(id=src_lun_id, name=src_lun_id, provider_location=get_lun_pl(src_lun_id), volume_attachment=None) with patch_thin_clone(test_client.MockResource(_id=lun_id)) as tc: ret = self.adapter.create_cloned_volume(volume, src_vref) tc.assert_called_with( adapter.VolumeParams(self.adapter, volume), IdMatcher(test_client.MockResource( _id='snap_clone_{}'.format(src_lun_id))), src_lun=IdMatcher(test_client.MockResource(_id=src_lun_id))) self.assertEqual(get_snap_lun_pl(lun_id), ret['provider_location']) @patch_for_unity_adapter def test_dd_copy_with_src_lun(self): lun_id = 'lun_56' src_lun_id = 'lun_57' src_snap_id = 'snap_57' volume = MockOSResource(name=lun_id, id=lun_id, host='unity#pool1', provider_location=get_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) src_lun = test_client.MockResource(name=src_lun_id, _id=src_lun_id) src_lun.size_total = 6 * units.Gi with patch_copy_volume() as copy_volume: ret = self.adapter._dd_copy( adapter.VolumeParams(self.adapter, volume), src_snap, src_lun=src_lun) copy_volume.assert_called_with('dev', 'dev', 6144, '1M', sparse=True) self.assertEqual(IdMatcher(test_client.MockResource(_id=lun_id)), ret) @patch_for_unity_adapter def test_dd_copy_wo_src_lun(self): lun_id = 'lun_58' src_lun_id = 'lun_59' src_snap_id = 'snap_59' volume = MockOSResource(name=lun_id, id=lun_id, host='unity#pool1', provider_location=get_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) src_snap.size = 5 * units.Gi src_snap.storage_resource = test_client.MockResource(name=src_lun_id, _id=src_lun_id) with patch_copy_volume() as copy_volume: ret = self.adapter._dd_copy( adapter.VolumeParams(self.adapter, volume), src_snap) copy_volume.assert_called_with('dev', 'dev', 5120, '1M', sparse=True) self.assertEqual(IdMatcher(test_client.MockResource(_id=lun_id)), ret) @patch_for_unity_adapter def test_dd_copy_raise(self): lun_id = 'lun_58' src_snap_id = 'snap_59' volume = MockOSResource(name=lun_id, id=lun_id, host='unity#pool1', provider_location=get_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) with patch_copy_volume() as copy_volume: copy_volume.side_effect = AttributeError self.assertRaises(AttributeError, self.adapter._dd_copy, volume, src_snap) @patch_for_unity_adapter def test_thin_clone(self): lun_id = 'lun_60' src_snap_id = 'snap_61' volume = MockOSResource(name=lun_id, id=lun_id, size=1, provider_location=get_snap_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) ret = self.adapter._thin_clone(volume, src_snap) self.assertEqual(IdMatcher(test_client.MockResource(_id=lun_id)), ret) @patch_for_unity_adapter def test_thin_clone_downgraded_with_src_lun(self): lun_id = 'lun_60' src_snap_id = 'snap_62' src_lun_id = 'lun_62' volume = MockOSResource(name=lun_id, id=lun_id, size=1, provider_location=get_snap_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) src_lun = test_client.MockResource(name=src_lun_id, _id=src_lun_id) new_dd_lun = test_client.MockResource(name='lun_63') with patch_storops() as mocked_storops, \ patch_dd_copy(new_dd_lun) as dd: ret = self.adapter._thin_clone( adapter.VolumeParams(self.adapter, volume), src_snap, src_lun=src_lun) vol_params = adapter.VolumeParams(self.adapter, volume) vol_params.name = 'hidden-{}'.format(volume.name) vol_params.description = 'hidden-{}'.format(volume.description) dd.assert_called_with(vol_params, src_snap, src_lun=src_lun) mocked_storops.TCHelper.notify.assert_called_with(src_lun, 'DD_COPY', new_dd_lun) self.assertEqual(IdMatcher(test_client.MockResource(_id=lun_id)), ret) @patch_for_unity_adapter def test_thin_clone_downgraded_wo_src_lun(self): lun_id = 'lun_60' src_snap_id = 'snap_62' volume = MockOSResource(name=lun_id, id=lun_id, size=1, provider_location=get_snap_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) new_dd_lun = test_client.MockResource(name='lun_63') with patch_storops() as mocked_storops, \ patch_dd_copy(new_dd_lun) as dd: ret = self.adapter._thin_clone( adapter.VolumeParams(self.adapter, volume), src_snap) vol_params = adapter.VolumeParams(self.adapter, volume) vol_params.name = 'hidden-{}'.format(volume.name) vol_params.description = 'hidden-{}'.format(volume.description) dd.assert_called_with(vol_params, src_snap, src_lun=None) mocked_storops.TCHelper.notify.assert_called_with(src_snap, 'DD_COPY', new_dd_lun) self.assertEqual(IdMatcher(test_client.MockResource(_id=lun_id)), ret) @patch_for_unity_adapter def test_thin_clone_thick(self): lun_id = 'lun_70' src_snap_id = 'snap_71' volume = MockOSResource(name=lun_id, id=lun_id, size=1, provider_location=get_snap_lun_pl(lun_id)) src_snap = test_client.MockResource(name=src_snap_id, _id=src_snap_id) new_dd_lun = test_client.MockResource(name='lun_73') with patch_storops(), patch_dd_copy(new_dd_lun) as dd: vol_params = adapter.VolumeParams(self.adapter, volume) ret = self.adapter._thin_clone(vol_params, src_snap) dd.assert_called_with(vol_params, src_snap, src_lun=None) self.assertEqual(ret, new_dd_lun) def test_extend_volume_error(self): def f(): volume = MockOSResource(id='l56', provider_location=get_lun_pl('lun56')) self.adapter.extend_volume(volume, -1) self.assertRaises(ex.ExtendLunError, f) def test_extend_volume_no_id(self): def f(): volume = MockOSResource(provider_location='type^lun') self.adapter.extend_volume(volume, 5) self.assertRaises(exception.VolumeBackendAPIException, f) def test_normalize_config(self): config = MockConfig() config.unity_storage_pool_names = [' pool_1 ', '', ' '] config.unity_io_ports = [' spa_eth2 ', '', ' '] normalized = self.adapter.normalize_config(config) self.assertEqual(['pool_1'], normalized.unity_storage_pool_names) self.assertEqual(['spa_eth2'], normalized.unity_io_ports) def test_normalize_config_raise(self): with self.assertRaisesRegex(exception.InvalidConfigurationValue, 'unity_storage_pool_names'): config = MockConfig() config.unity_storage_pool_names = ['', ' '] self.adapter.normalize_config(config) with self.assertRaisesRegex(exception.InvalidConfigurationValue, 'unity_io_ports'): config = MockConfig() config.unity_io_ports = ['', ' '] self.adapter.normalize_config(config) def test_restore_snapshot(self): volume = MockOSResource(id='1', name='vol_1') snapshot = MockOSResource(id='2', name='snap_1') self.adapter.restore_snapshot(volume, snapshot) def test_get_pool_id_by_name(self): pool_name = 'PoolA' pool_id = self.adapter.get_pool_id_by_name(pool_name) self.assertEqual('pool_1', pool_id) def test_migrate_volume(self): provider_location = 'id^1|system^FNM001|type^lun|version^05.00' volume = MockOSResource(id='1', name='vol_1', host='HostA@BackendB#PoolA', provider_location=provider_location) host = {'host': 'HostA@BackendB#PoolB'} ret = self.adapter.migrate_volume(volume, host) self.assertEqual((True, {}), ret) def test_migrate_volume_failed(self): provider_location = 'id^1|system^FNM001|type^lun|version^05.00' volume = MockOSResource(id='1', name='vol_1', host='HostA@BackendB#PoolA', provider_location=provider_location) host = {'host': 'HostA@BackendB#PoolC'} ret = self.adapter.migrate_volume(volume, host) self.assertEqual((False, None), ret) def test_migrate_volume_cross_backends(self): provider_location = 'id^1|system^FNM001|type^lun|version^05.00' volume = MockOSResource(id='1', name='vol_1', host='HostA@BackendA#PoolA', provider_location=provider_location) host = {'host': 'HostA@BackendB#PoolB'} ret = self.adapter.migrate_volume(volume, host) self.assertEqual((False, None), ret) @ddt.unpack @ddt.data((('group-1', 'group-1_name', 'group-1_description'), ('group-1', 'group-1_description')), (('group-2', 'group-2_name', None), ('group-2', 'group-2_name')), (('group-3', 'group-3_name', ''), ('group-3', 'group-3_name'))) def test_create_group(self, inputs, expected): cg_id, cg_name, cg_description = inputs cg = MockOSResource(id=cg_id, name=cg_name, description=cg_description) with mock.patch.object(self.adapter.client, 'create_cg', create=True) as mocked: model_update = self.adapter.create_group(cg) self.assertEqual('available', model_update['status']) mocked.assert_called_once_with(expected[0], description=expected[1]) def test_delete_group(self): cg = MockOSResource(id='group-1') with mock.patch.object(self.adapter.client, 'delete_cg', create=True) as mocked: ret = self.adapter.delete_group(cg) self.assertIsNone(ret[0]) self.assertIsNone(ret[1]) mocked.assert_called_once_with('group-1') def test_update_group(self): cg = MockOSResource(id='group-1') add_volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-1', 'sv_1'), ('volume-2', 'sv_2'))] remove_volumes = [MockOSResource( id='volume-3', provider_location=get_lun_pl('sv_3'))] with mock.patch.object(self.adapter.client, 'update_cg', create=True) as mocked: ret = self.adapter.update_group(cg, add_volumes, remove_volumes) self.assertEqual('available', ret[0]['status']) self.assertIsNone(ret[1]) self.assertIsNone(ret[2]) mocked.assert_called_once_with('group-1', {'sv_1', 'sv_2'}, {'sv_3'}) def test_update_group_add_volumes_none(self): cg = MockOSResource(id='group-1') remove_volumes = [MockOSResource( id='volume-3', provider_location=get_lun_pl('sv_3'))] with mock.patch.object(self.adapter.client, 'update_cg', create=True) as mocked: ret = self.adapter.update_group(cg, None, remove_volumes) self.assertEqual('available', ret[0]['status']) self.assertIsNone(ret[1]) self.assertIsNone(ret[2]) mocked.assert_called_once_with('group-1', set(), {'sv_3'}) def test_update_group_remove_volumes_none(self): cg = MockOSResource(id='group-1') add_volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-1', 'sv_1'), ('volume-2', 'sv_2'))] with mock.patch.object(self.adapter.client, 'update_cg', create=True) as mocked: ret = self.adapter.update_group(cg, add_volumes, None) self.assertEqual('available', ret[0]['status']) self.assertIsNone(ret[1]) self.assertIsNone(ret[2]) mocked.assert_called_once_with('group-1', {'sv_1', 'sv_2'}, set()) def test_update_group_add_remove_volumes_none(self): cg = MockOSResource(id='group-1') with mock.patch.object(self.adapter.client, 'update_cg', create=True) as mocked: ret = self.adapter.update_group(cg, None, None) self.assertEqual('available', ret[0]['status']) self.assertIsNone(ret[1]) self.assertIsNone(ret[2]) mocked.assert_called_once_with('group-1', set(), set()) @patch_for_unity_adapter def test_copy_luns_in_group(self): cg = MockOSResource(id='group-1') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] src_cg_snap = test_client.MockResource(_id='id_src_cg_snap') src_volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-1', 'sv_1'), ('volume-2', 'sv_2'))] copied_luns = [test_client.MockResource(_id=lun_id) for lun_id in ('sv_3', 'sv_4')] def _prepare_lun_snaps(lun_id): lun_snap = test_client.MockResource(_id='snap_{}'.format(lun_id)) lun_snap.lun = test_client.MockResource(_id=lun_id) return lun_snap lun_snaps = list(map(_prepare_lun_snaps, ('sv_1', 'sv_2'))) with mock.patch.object(self.adapter.client, 'filter_snaps_in_cg_snap', create=True) as mocked_filter, \ mock.patch.object(self.adapter.client, 'create_cg', create=True) as mocked_create_cg, \ patch_dd_copy(None) as mocked_dd: mocked_filter.return_value = lun_snaps mocked_dd.side_effect = copied_luns ret = self.adapter.copy_luns_in_group(cg, volumes, src_cg_snap, src_volumes) mocked_filter.assert_called_once_with('id_src_cg_snap') dd_args = zip([adapter.VolumeParams(self.adapter, vol) for vol in volumes], lun_snaps) mocked_dd.assert_has_calls([mock.call(*args) for args in dd_args]) mocked_create_cg.assert_called_once_with('group-1', lun_add=copied_luns) self.assertEqual('available', ret[0]['status']) self.assertEqual(2, len(ret[1])) for vol_id in ('volume-3', 'volume-4'): self.assertIn({'id': vol_id, 'status': 'available'}, ret[1]) def test_create_group_from_snap(self): cg = MockOSResource(id='group-2') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] cg_snap = MockOSResource(id='snap-group-1') vol_1 = MockOSResource(id='volume-1') vol_2 = MockOSResource(id='volume-2') vol_snaps = [MockOSResource(id='snap-volume-1', volume=vol_1), MockOSResource(id='snap-volume-2', volume=vol_2)] src_cg_snap = test_client.MockResource(_id='id_src_cg_snap') with mock.patch.object(self.adapter.client, 'get_snap', create=True, return_value=src_cg_snap), \ mock.patch.object(self.adapter, 'copy_luns_in_group', create=True) as mocked_copy: mocked_copy.return_value = ({'status': 'available'}, [{'id': 'volume-3', 'status': 'available'}, {'id': 'volume-4', 'status': 'available'}]) ret = self.adapter.create_group_from_snap(cg, volumes, cg_snap, vol_snaps) mocked_copy.assert_called_once_with(cg, volumes, src_cg_snap, [vol_1, vol_2]) self.assertEqual('available', ret[0]['status']) self.assertEqual(2, len(ret[1])) for vol_id in ('volume-3', 'volume-4'): self.assertIn({'id': vol_id, 'status': 'available'}, ret[1]) def test_create_group_from_snap_none_snapshots(self): cg = MockOSResource(id='group-2') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] cg_snap = MockOSResource(id='snap-group-1') src_cg_snap = test_client.MockResource(_id='id_src_cg_snap') with mock.patch.object(self.adapter.client, 'get_snap', create=True, return_value=src_cg_snap), \ mock.patch.object(self.adapter, 'copy_luns_in_group', create=True) as mocked_copy: mocked_copy.return_value = ({'status': 'available'}, [{'id': 'volume-3', 'status': 'available'}, {'id': 'volume-4', 'status': 'available'}]) ret = self.adapter.create_group_from_snap(cg, volumes, cg_snap, None) mocked_copy.assert_called_once_with(cg, volumes, src_cg_snap, []) self.assertEqual('available', ret[0]['status']) self.assertEqual(2, len(ret[1])) for vol_id in ('volume-3', 'volume-4'): self.assertIn({'id': vol_id, 'status': 'available'}, ret[1]) def test_create_cloned_group(self): cg = MockOSResource(id='group-2') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] src_cg = MockOSResource(id='group-1') vol_1 = MockOSResource(id='volume-1') vol_2 = MockOSResource(id='volume-2') src_vols = [vol_1, vol_2] src_cg_snap = test_client.MockResource(_id='id_src_cg_snap') with mock.patch.object(self.adapter.client, 'create_cg_snap', create=True, return_value=src_cg_snap) as mocked_create, \ mock.patch.object(self.adapter, 'copy_luns_in_group', create=True) as mocked_copy: mocked_create.__name__ = 'create_cg_snap' mocked_copy.return_value = ({'status': 'available'}, [{'id': 'volume-3', 'status': 'available'}, {'id': 'volume-4', 'status': 'available'}]) ret = self.adapter.create_cloned_group(cg, volumes, src_cg, src_vols) mocked_create.assert_called_once_with('group-1', 'snap_clone_group_group-1') mocked_copy.assert_called_once_with(cg, volumes, src_cg_snap, [vol_1, vol_2]) self.assertEqual('available', ret[0]['status']) self.assertEqual(2, len(ret[1])) for vol_id in ('volume-3', 'volume-4'): self.assertIn({'id': vol_id, 'status': 'available'}, ret[1]) def test_create_cloned_group_none_source_vols(self): cg = MockOSResource(id='group-2') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] src_cg = MockOSResource(id='group-1') src_cg_snap = test_client.MockResource(_id='id_src_cg_snap') with mock.patch.object(self.adapter.client, 'create_cg_snap', create=True, return_value=src_cg_snap) as mocked_create, \ mock.patch.object(self.adapter, 'copy_luns_in_group', create=True) as mocked_copy: mocked_create.__name__ = 'create_cg_snap' mocked_copy.return_value = ({'status': 'available'}, [{'id': 'volume-3', 'status': 'available'}, {'id': 'volume-4', 'status': 'available'}]) ret = self.adapter.create_cloned_group(cg, volumes, src_cg, None) mocked_create.assert_called_once_with('group-1', 'snap_clone_group_group-1') mocked_copy.assert_called_once_with(cg, volumes, src_cg_snap, []) self.assertEqual('available', ret[0]['status']) self.assertEqual(2, len(ret[1])) for vol_id in ('volume-3', 'volume-4'): self.assertIn({'id': vol_id, 'status': 'available'}, ret[1]) def test_create_group_snapshot(self): cg_snap = MockOSResource(id='snap-group-1', group_id='group-1') vol_1 = MockOSResource(id='volume-1') vol_2 = MockOSResource(id='volume-2') vol_snaps = [MockOSResource(id='snap-volume-1', volume=vol_1), MockOSResource(id='snap-volume-2', volume=vol_2)] with mock.patch.object(self.adapter.client, 'create_cg_snap', create=True) as mocked_create: mocked_create.return_value = ({'status': 'available'}, [{'id': 'snap-volume-1', 'status': 'available'}, {'id': 'snap-volume-2', 'status': 'available'}]) ret = self.adapter.create_group_snapshot(cg_snap, vol_snaps) mocked_create.assert_called_once_with('group-1', snap_name='snap-group-1') self.assertEqual({'status': 'available'}, ret[0]) self.assertEqual(2, len(ret[1])) for snap_id in ('snap-volume-1', 'snap-volume-2'): self.assertIn({'id': snap_id, 'status': 'available'}, ret[1]) def test_delete_group_snapshot(self): group_snap = MockOSResource(id='snap-group-1') cg_snap = test_client.MockResource(_id='snap_cg_1') with mock.patch.object(self.adapter.client, 'get_snap', create=True, return_value=cg_snap) as mocked_get, \ mock.patch.object(self.adapter.client, 'delete_snap', create=True) as mocked_delete: ret = self.adapter.delete_group_snapshot(group_snap) mocked_get.assert_called_once_with('snap-group-1') mocked_delete.assert_called_once_with(cg_snap) self.assertEqual((None, None), ret) def test_setup_replications(self): secondary_device = mock_replication_device() self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { 'secondary_unity': secondary_device } model_update = self.adapter.setup_replications( test_client.MockResource(_id='sv_1'), {}) self.assertIn('replication_status', model_update) self.assertEqual('enabled', model_update['replication_status']) self.assertIn('replication_driver_data', model_update) self.assertEqual('{"secondary_unity": "rep_session_name_1"}', model_update['replication_driver_data']) def test_setup_replications_not_configured_replication(self): model_update = self.adapter.setup_replications( test_client.MockResource(_id='sv_1'), {}) self.assertEqual(0, len(model_update)) def test_setup_replications_raise(self): secondary_device = mock_replication_device( serial_number='not-found-remote-system') self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { 'secondary_unity': secondary_device } self.assertRaises(exception.VolumeBackendAPIException, self.adapter.setup_replications, test_client.MockResource(_id='sv_1'), {}) @ddt.data({'failover_to': 'secondary_unity'}, {'failover_to': None}) @ddt.unpack def test_failover(self, failover_to): secondary_id = 'secondary_unity' secondary_device = mock_replication_device() self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { secondary_id: secondary_device } volume = MockOSResource( id='volume-id-1', name='volume-name-1', replication_driver_data='{"secondary_unity":"rep_session_name_1"}') model_update = self.adapter.failover([volume], secondary_id=failover_to) self.assertEqual(3, len(model_update)) active_backend_id, volumes_update, groups_update = model_update self.assertEqual(secondary_id, active_backend_id) self.assertEqual([], groups_update) self.assertEqual(1, len(volumes_update)) model_update = volumes_update[0] self.assertIn('volume_id', model_update) self.assertEqual('volume-id-1', model_update['volume_id']) self.assertIn('updates', model_update) self.assertEqual( {'provider_id': 'sv_99', 'provider_location': 'id^sv_99|system^SECONDARY_UNITY_SN|type^lun|version^None'}, model_update['updates']) self.assertTrue( self.adapter.replication_manager.is_service_failed_over) def test_failover_raise(self): secondary_id = 'secondary_unity' secondary_device = mock_replication_device() self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { secondary_id: secondary_device } vol1 = MockOSResource( id='volume-id-1', name='volume-name-1', replication_driver_data='{"secondary_unity":"rep_session_name_1"}') vol2 = MockOSResource( id='volume-id-2', name='volume-name-2', replication_driver_data='{"secondary_unity":"rep_session_name_2"}') model_update = self.adapter.failover([vol1, vol2], secondary_id=secondary_id) active_backend_id, volumes_update, groups_update = model_update self.assertEqual(secondary_id, active_backend_id) self.assertEqual([], groups_update) self.assertEqual(2, len(volumes_update)) m = volumes_update[0] self.assertIn('volume_id', m) self.assertEqual('volume-id-1', m['volume_id']) self.assertIn('updates', m) self.assertEqual( {'provider_id': 'sv_99', 'provider_location': 'id^sv_99|system^SECONDARY_UNITY_SN|type^lun|version^None'}, m['updates']) m = volumes_update[1] self.assertIn('volume_id', m) self.assertEqual('volume-id-2', m['volume_id']) self.assertIn('updates', m) self.assertEqual({'replication_status': 'failover-error'}, m['updates']) self.assertTrue( self.adapter.replication_manager.is_service_failed_over) def test_failover_failback(self): secondary_id = 'secondary_unity' secondary_device = mock_replication_device() self.adapter.replication_manager.is_replication_configured = True self.adapter.replication_manager.replication_devices = { secondary_id: secondary_device } default_device = mock_replication_device( device_conf={ 'backend_id': 'default', 'san_ip': '10.10.10.10' }, serial_number='PRIMARY_UNITY_SN' ) self.adapter.replication_manager.default_device = default_device self.adapter.replication_manager.active_adapter = ( self.adapter.replication_manager.replication_devices[ secondary_id].adapter) self.adapter.replication_manager.active_backend_id = secondary_id volume = MockOSResource( id='volume-id-1', name='volume-name-1', replication_driver_data='{"secondary_unity":"rep_session_name_1"}') model_update = self.adapter.failover([volume], secondary_id='default') active_backend_id, volumes_update, groups_update = model_update self.assertEqual('default', active_backend_id) self.assertEqual([], groups_update) self.assertEqual(1, len(volumes_update)) model_update = volumes_update[0] self.assertIn('volume_id', model_update) self.assertEqual('volume-id-1', model_update['volume_id']) self.assertIn('updates', model_update) self.assertEqual( {'provider_id': 'sv_1', 'provider_location': 'id^sv_1|system^PRIMARY_UNITY_SN|type^lun|version^None'}, model_update['updates']) self.assertFalse( self.adapter.replication_manager.is_service_failed_over) @patch_for_unity_adapter def test_failed_enable_replication(self): cg = MockOSResource(id='not_cg', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] self.assertRaises(exception.InvalidGroupType, self.adapter.enable_replication, None, cg, volumes) @patch_for_unity_adapter def test_enable_replication(self): cg = MockOSResource(id='test_cg_1', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] secondary_device = mock_replication_device() self.adapter.replication_manager.replication_devices = { 'secondary_unity': secondary_device } result = self.adapter.enable_replication(None, cg, volumes) self.assertEqual(({'replication_status': 'enabled'}, None), result) @patch_for_unity_adapter def test_cannot_disable_replication_on_generic_group(self): cg = MockOSResource(id='not_cg', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] self.assertRaises(exception.InvalidGroupType, self.adapter.disable_replication, None, cg, volumes) @patch_for_unity_adapter def test_disable_replication(self): cg = MockOSResource(id='cg_is_replicated', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] result = self.adapter.disable_replication(None, cg, volumes) self.assertEqual(({'replication_status': 'disabled'}, None), result) @patch_for_unity_adapter def test_failover_replication(self): cg = MockOSResource(id='cg_is_replicated', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] real_secondary_id = 'secondary_unity' secondary_device = mock_replication_device() self.adapter.replication_manager.replication_devices = { real_secondary_id: secondary_device } result = self.adapter.failover_replication(None, cg, volumes, real_secondary_id) self.assertEqual(({'replication_status': 'failed-over'}, [{'id': 'volume-3', 'replication_status': 'failed-over'}, {'id': 'volume-4', 'replication_status': 'failed-over'}]), result) @patch_for_unity_adapter def test_failback_replication(self): cg = MockOSResource(id='cg_is_replicated', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] input_secondary_id = 'default' real_secondary_id = 'secondary_unity' secondary_device = mock_replication_device() self.adapter.replication_manager.replication_devices = { real_secondary_id: secondary_device } result = self.adapter.failover_replication(None, cg, volumes, input_secondary_id) self.assertEqual(({'replication_status': 'enabled'}, [{'id': 'volume-3', 'replication_status': 'enabled'}, {'id': 'volume-4', 'replication_status': 'enabled'}]), result) failed_cg = MockOSResource(id='cg_is_replicated_but_has_error', name='cg_name', description='cg_description') failed_result = self.adapter.failover_replication( None, failed_cg, volumes, real_secondary_id) self.assertEqual(({'replication_status': 'error'}, [{'id': 'volume-3', 'replication_status': 'error'}, {'id': 'volume-4', 'replication_status': 'error'}]), failed_result) @patch_for_unity_adapter def test_failover_replication_error(self): cg = MockOSResource(id='cg_is_replicated_but_has_error', name='cg_name', description='cg_description') volumes = [MockOSResource(id=vol_id, provider_location=get_lun_pl(lun_id)) for vol_id, lun_id in (('volume-3', 'sv_3'), ('volume-4', 'sv_4'))] real_secondary_id = 'default' secondary_device = mock_replication_device() self.adapter.replication_manager.replication_devices = { real_secondary_id: secondary_device } result = self.adapter.failover_replication( None, cg, volumes, real_secondary_id) self.assertEqual(({'replication_status': 'error'}, [{'id': 'volume-3', 'replication_status': 'error'}, {'id': 'volume-4', 'replication_status': 'error'}]), result) class FCAdapterTest(test.TestCase): def setUp(self): super(FCAdapterTest, self).setUp() self.adapter = mock_adapter(adapter.FCAdapter) def test_setup(self): self.assertIsNotNone(self.adapter.lookup_service) def test_auto_zone_enabled(self): self.assertTrue(self.adapter.auto_zone_enabled) def test_fc_protocol(self): stats = mock_adapter(adapter.FCAdapter).update_volume_stats() self.assertEqual('FC', stats['storage_protocol']) def test_get_connector_uids(self): connector = {'host': 'fake_host', 'wwnns': ['1111111111111111', '2222222222222222'], 'wwpns': ['3333333333333333', '4444444444444444'] } expected = ['11:11:11:11:11:11:11:11:33:33:33:33:33:33:33:33', '22:22:22:22:22:22:22:22:44:44:44:44:44:44:44:44'] ret = self.adapter.get_connector_uids(connector) self.assertListEqual(expected, ret) def test_get_connection_info_no_targets(self): def f(): host = test_client.MockResource('no_target') self.adapter.get_connection_info(12, host, {}) self.assertRaises(exception.VolumeBackendAPIException, f) def test_get_connection_info_auto_zone_enabled(self): host = test_client.MockResource('host1') connector = {'wwpns': 'abcdefg'} ret = self.adapter.get_connection_info(10, host, connector) target_wwns = ['100000051e55a100', '100000051e55a121'] self.assertListEqual(target_wwns, ret['target_wwn']) init_target_map = { '200000051e55a100': ('100000051e55a100', '100000051e55a121'), '200000051e55a121': ('100000051e55a100', '100000051e55a121')} self.assertDictEqual(init_target_map, ret['initiator_target_map']) self.assertEqual(10, ret['target_lun']) def test_get_connection_info_auto_zone_disabled(self): self.adapter.lookup_service = None host = test_client.MockResource('host1') connector = {'wwpns': 'abcdefg'} ret = self.adapter.get_connection_info(10, host, connector) self.assertEqual(10, ret['target_lun']) wwns = ['8899AABBCCDDEEFF', '8899AABBCCDDFFEE'] self.assertListEqual(wwns, ret['target_wwn']) @patch_for_fc_adapter def test_initialize_connection_volume(self): volume = MockOSResource(provider_location='id^lun_43', id='id_43') connector = {'host': 'host1'} conn_info = self.adapter.initialize_connection(volume, connector) self.assertEqual('fibre_channel', conn_info['driver_volume_type']) self.assertTrue(conn_info['data']['target_discovered']) self.assertEqual('id_43', conn_info['data']['volume_id']) @patch_for_fc_adapter def test_initialize_connection_snapshot(self): snap = MockOSResource(id='snap_1', name='snap_1') connector = {'host': 'host1'} conn_info = self.adapter.initialize_connection_snapshot( snap, connector) self.assertEqual('fibre_channel', conn_info['driver_volume_type']) self.assertTrue(conn_info['data']['target_discovered']) self.assertEqual('snap_1', conn_info['data']['volume_id']) def test_terminate_connection_auto_zone_enabled(self): connector = {'host': 'host1', 'wwpns': 'abcdefg'} volume = MockOSResource(provider_location='id^lun_41', id='id_41', volume_attachment=None) ret = self.adapter.terminate_connection(volume, connector) self.assertEqual('fibre_channel', ret['driver_volume_type']) data = ret['data'] target_map = { '200000051e55a100': ('100000051e55a100', '100000051e55a121'), '200000051e55a121': ('100000051e55a100', '100000051e55a121')} self.assertDictEqual(target_map, data['initiator_target_map']) target_wwn = ['100000051e55a100', '100000051e55a121'] self.assertListEqual(target_wwn, data['target_wwn']) def test_terminate_connection_auto_zone_enabled_none_host_luns(self): connector = {'host': 'host-no-host_luns', 'wwpns': 'abcdefg'} volume = MockOSResource(provider_location='id^lun_41', id='id_41', volume_attachment=None) ret = self.adapter.terminate_connection(volume, connector) self.assertEqual('fibre_channel', ret['driver_volume_type']) data = ret['data'] target_map = { '200000051e55a100': ('100000051e55a100', '100000051e55a121'), '200000051e55a121': ('100000051e55a100', '100000051e55a121')} self.assertDictEqual(target_map, data['initiator_target_map']) target_wwn = ['100000051e55a100', '100000051e55a121'] self.assertListEqual(target_wwn, data['target_wwn']) def test_terminate_connection_remove_empty_host_return_data(self): self.adapter.remove_empty_host = True connector = {'host': 'empty-host-return-data', 'wwpns': 'abcdefg'} volume = MockOSResource(provider_location='id^lun_41', id='id_41', volume_attachment=None) ret = self.adapter.terminate_connection(volume, connector) self.assertEqual('fibre_channel', ret['driver_volume_type']) data = ret['data'] target_map = { '200000051e55a100': ('100000051e55a100', '100000051e55a121'), '200000051e55a121': ('100000051e55a100', '100000051e55a121')} self.assertDictEqual(target_map, data['initiator_target_map']) target_wwn = ['100000051e55a100', '100000051e55a121'] self.assertListEqual(target_wwn, data['target_wwn']) def test_validate_ports_whitelist_none(self): ports = self.adapter.validate_ports(None) self.assertEqual(set(('spa_iom_0_fc0', 'spa_iom_0_fc1')), set(ports)) def test_validate_ports(self): ports = self.adapter.validate_ports(['spa_iom_0_fc0']) self.assertEqual(set(('spa_iom_0_fc0',)), set(ports)) def test_validate_ports_asterisk(self): ports = self.adapter.validate_ports(['spa*']) self.assertEqual(set(('spa_iom_0_fc0', 'spa_iom_0_fc1')), set(ports)) def test_validate_ports_question_mark(self): ports = self.adapter.validate_ports(['spa_iom_0_fc?']) self.assertEqual(set(('spa_iom_0_fc0', 'spa_iom_0_fc1')), set(ports)) def test_validate_ports_no_matched(self): with self.assertRaisesRegex(exception.InvalidConfigurationValue, 'unity_io_ports'): self.adapter.validate_ports(['spc_invalid']) def test_validate_ports_unmatched_whitelist(self): with self.assertRaisesRegex(exception.InvalidConfigurationValue, 'unity_io_ports'): self.adapter.validate_ports(['spa_iom*', 'spc_invalid']) class ISCSIAdapterTest(test.TestCase): def setUp(self): super(ISCSIAdapterTest, self).setUp() self.adapter = mock_adapter(adapter.ISCSIAdapter) def test_iscsi_protocol(self): stats = self.adapter.update_volume_stats() self.assertEqual('iSCSI', stats['storage_protocol']) def test_get_connector_uids(self): connector = {'host': 'fake_host', 'initiator': 'fake_iqn'} ret = self.adapter.get_connector_uids(connector) self.assertListEqual(['fake_iqn'], ret) def test_get_connection_info(self): connector = {'host': 'fake_host', 'initiator': 'fake_iqn'} hlu = 10 info = self.adapter.get_connection_info(hlu, None, connector) target_iqns = ['iqn.1-1.com.e:c.a.a0', 'iqn.1-1.com.e:c.a.a1'] target_portals = ['1.2.3.4:1234', '1.2.3.5:1234'] self.assertListEqual(target_iqns, info['target_iqns']) self.assertListEqual([hlu, hlu], info['target_luns']) self.assertListEqual(target_portals, info['target_portals']) self.assertEqual(hlu, info['target_lun']) self.assertIn(info['target_portal'], target_portals) self.assertIn(info['target_iqn'], target_iqns) @patch_for_iscsi_adapter def test_initialize_connection_volume(self): volume = MockOSResource(provider_location='id^lun_43', id='id_43') connector = {'host': 'host1'} conn_info = self.adapter.initialize_connection(volume, connector) self.assertEqual('iscsi', conn_info['driver_volume_type']) self.assertTrue(conn_info['data']['target_discovered']) self.assertEqual('id_43', conn_info['data']['volume_id']) @patch_for_iscsi_adapter def test_initialize_connection_snapshot(self): snap = MockOSResource(id='snap_1', name='snap_1') connector = {'host': 'host1'} conn_info = self.adapter.initialize_connection_snapshot( snap, connector) self.assertEqual('iscsi', conn_info['driver_volume_type']) self.assertTrue(conn_info['data']['target_discovered']) self.assertEqual('snap_1', conn_info['data']['volume_id'])
40,777
848
/* * Copyright 2019 Xilinx 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. */ /* * Filename: lanedetect.hpp * * Description: * This network is used to detecting road line * * Please refer to document "Xilnx_AI_SDK_User_Guide.pdf" for more details of *these APIs. */ #pragma once #include <memory> #include <opencv2/core.hpp> #include <vitis/ai/nnpp/lanedetect.hpp> namespace vitis { namespace ai { /** * @brief Base class for detecting lanedetect from an image (cv::Mat). * * Input is an image (cv::Mat). * * Output road line type and points marked road line. * * @note The input image size is 640x480 * * Sample code: * @code auto det = vitis::ai::RoadLine::create("vpgnet_pruned_0_99"); auto image = cv::imread("sample_lanedetect.jpg"); // Mat image; // resize(img, image, Size(640, 480)); if (image.empty()) { cerr << "cannot load " << argv[1] << endl; abort(); } vector<int> color1 = {0, 255, 0, 0, 100, 255}; vector<int> color2 = {0, 0, 255, 0, 100, 255}; vector<int> color3 = {0, 0, 0, 255, 100, 255}; RoadLineResult results = det->run(image); for (auto &line : results.lines) { vector<Point> points_poly = line.points_cluster; // for (auto &p : points_poly) { // std::cout << p.x << " " << (int)p.y << std::endl; //} int type = line.type < 5 ? line.type : 5; if (type == 2 && points_poly[0].x < image.rows * 0.5) continue; cv::polylines(image, points_poly, false, Scalar(color1[type], color2[type], color3[type]), 3, cv::LINE_AA, 0); } @endcode * * Display of the model results: * @image latex images/sample_lanedetect_result.jpg "result image" width=300px * */ class RoadLine { public: /** * @brief Factory function to get an instance of derived classes of class * RoadLine. * * @param model_name String of model name * @param need_preprocess normalize with mean/scale or not, default value is * true. * * @return An instance of RoadLine class. */ static std::unique_ptr<RoadLine> create(const std::string& model_name, bool need_preprocess = true); /** * @cond NOCOMMENTS */ protected: explicit RoadLine(); RoadLine(const RoadLine&) = delete; public: virtual ~RoadLine(); /** * @endcond */ public: /** * @brief Function to get InputWidth of the lanedetect network (input image * columns). * * @return InputWidth of the lanedetect network. */ virtual int getInputWidth() const = 0; /** * @brief Function to get InputHeight of the lanedetect network (input image * rows). * * @return InputHeight of the lanedetect network. */ virtual int getInputHeight() const = 0; /** * @brief Function to get the number of images processed by the DPU at one *time. * @note Different DPU core the batch size may be different. This depends on *the IP used. * *@return Batch size. */ virtual size_t get_input_batch() const = 0; /** * @brief Function to get running result of the RoadLine network. * * @param image Input data , input image (cv::Mat) need to resized as 640x480. * * @return The struct of RoadLineResult */ virtual RoadLineResult run(const cv::Mat& image) = 0; /** * @brief Function to get running result of the RoadLine network in * batch mode. * * @param images Input data of input images (vector<cv::Mat>).The size of * input images equals batch size obtained by get_input_batch. * * @return The vector of RoadLineResult */ virtual std::vector<RoadLineResult> run( const std::vector<cv::Mat>& images) = 0; }; } // namespace ai } // namespace vitis
1,501
2,453
<reponame>haozhiyu1990/XVim2 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <swiftCore/_TtCs12_SwiftObject.h> @class DVTDocumentLocation, MISSING_TYPE, NSDictionary, NSString, NSURL; @interface _TtCC6IDEKit13IDEEditorCore11HistoryItem : _TtCs12_SwiftObject { MISSING_TYPE *location; MISSING_TYPE *documentExtensionIdentifier; MISSING_TYPE *historyMenuItemTitle; MISSING_TYPE *documentDisplayName; MISSING_TYPE *documentURL; MISSING_TYPE *stateSavingStateDictionary; MISSING_TYPE *domainIdentifier; MISSING_TYPE *documentLocation; } - (BOOL)isEqualToHistoryControllerItem:(id)arg1; @property(nonatomic, retain) DVTDocumentLocation *documentLocation; // @synthesize documentLocation; @property(nonatomic, copy) NSString *domainIdentifier; @property(nonatomic, copy) NSDictionary *stateSavingStateDictionary; @property(nonatomic, copy) NSURL *documentURL; @property(nonatomic, copy) NSString *documentDisplayName; @property(nonatomic, copy) NSString *historyMenuItemTitle; @property(nonatomic, copy) NSString *documentExtensionIdentifier; @end
403
15,577
<gh_stars>1000+ #if __has_include(<mysql.h>) #include <mysql.h> #else #include <mysql/mysql.h> #endif #include <mysqlxx/Connection.h> #include <mysqlxx/ResultBase.h> namespace mysqlxx { ResultBase::ResultBase(MYSQL_RES * res_, Connection * conn_, const Query * query_) : res(res_), conn(conn_), query(query_) { fields = mysql_fetch_fields(res); num_fields = mysql_num_fields(res); } ResultBase::~ResultBase() { mysql_free_result(res); } std::string ResultBase::getFieldName(size_t n) const { if (num_fields <= n) throw Exception(std::string("Unknown column position ") + std::to_string(n)); return fields[n].name; } }
264
1,069
<gh_stars>1000+ # -*- coding: utf-8 -*- from django.db import models class Services(models.Model): """ Main class for Services """ name = models.CharField(max_length=255) status = models.BooleanField(default=False) description = models.CharField(max_length=255) class Meta: app_label = 'django_th' abstract = True verbose_name = 'Services' verbose_name_plural = 'Services'
182
763
package org.batfish.representation.juniper; import static org.junit.Assert.assertEquals; import org.batfish.datamodel.HeaderSpace; import org.batfish.datamodel.IpWildcard; import org.batfish.datamodel.TraceElement; import org.batfish.datamodel.acl.MatchHeaderSpace; import org.junit.Test; /** Test for {@link FwFromSourceAddressExcept} */ public class FwFromSourceAddressExceptTest { @Test public void testToAclLineMatchExpr() { IpWildcard ipWildcard = IpWildcard.parse("1.1.1.0/24"); FwFromSourceAddressExcept from = new FwFromSourceAddressExcept(ipWildcard, ipWildcard.toString()); assertEquals( from.toAclLineMatchExpr(null, null, null), new MatchHeaderSpace( HeaderSpace.builder().setNotSrcIps(ipWildcard.toIpSpace()).build(), TraceElement.of("Matched source-address 1.1.1.0/24 except"))); } }
338
5,169
<reponame>Gantios/Specs<filename>Specs/b/3/7/MOA-Swift/0.1.2/MOA-Swift.podspec.json { "name": "MOA-Swift", "version": "0.1.2", "summary": "Swift Boilerplate code and building blocks for Module Oriented Architecture (MOA)", "description": "Module Oriented Architecture (MOA) is a principle of building the client apps\nwith the logic of routed services, but local, within the bundle.\nThis repository contains all the building blocks to implement it in the apps", "homepage": "http://itnext.io/module-oriented-architecture-4b54c8976415", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/mladendes", "platforms": { "ios": "11.0" }, "swift_versions": "4.2", "source": { "git": "https://github.com/poksi592/MOA-Swift.git", "tag": "0.1.2" }, "source_files": [ "MOA-Swift/MOA-Swift/Helpers/*", "MOA-Swift/MOA-Swift/Application Services/*", "MOA-Swift/MOA-Swift/Routing/*" ], "exclude_files": "MOA-Swift/MOA-Swift/Application Services/Examples/*" }
419
372
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysds.test.component.matrix; import static org.junit.Assert.assertEquals; import org.apache.sysds.runtime.matrix.data.MatrixBlock; import org.junit.Test; public class ProdTest { private final MatrixBlock m; private final MatrixBlock mDense; public ProdTest() { m = new MatrixBlock(10, 10, true); m.allocateSparseRowsBlock(); for(int i = 0; i < 10; i++) m.setValue(0, i, 3); mDense = new MatrixBlock(10, 10, false); mDense.copy(m); mDense.sparseToDense(); } @Test public void testFullRowSparseProd() { // this test verifies that the prod call of a matrix where the sparse row is full, and the subsequent rows are // empty, returns 0. double ret = m.prod(); assertEquals(ret, 0.0, 0.0); } @Test public void testFullProdIsEqualToDense() { double ret = m.prod(); double retDense = mDense.prod(); assertEquals(ret, retDense, 0.0); } @Test public void testZeroDimMatrix() { MatrixBlock mz = new MatrixBlock(0, 0, false); assertEquals(1, mz.prod(), 0.0); } @Test public void testZeroDimMatrixAllocateDense() { MatrixBlock mz = new MatrixBlock(0, 0, false); mz.allocateDenseBlock(); assertEquals(1, mz.prod(), 0.0); } @Test public void testZeroDimMatrixAllocateSparse() { MatrixBlock mz = new MatrixBlock(0, 0, false); mz.allocateSparseRowsBlock(); assertEquals(1, mz.prod(), 0.0); } @Test public void testEmptyProd() { MatrixBlock empty = new MatrixBlock(10, 10, false); assertEquals(0, empty.prod(), 0.0); } }
797
1,125
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.composite; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.support.ValueType; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; import org.elasticsearch.search.internal.SearchContext; import java.io.IOException; import java.util.Objects; /** * A {@link CompositeValuesSourceBuilder} that builds a {@link HistogramValuesSource} from another numeric values source * using the provided interval. */ public class HistogramValuesSourceBuilder extends CompositeValuesSourceBuilder<HistogramValuesSourceBuilder> { static final String TYPE = "histogram"; private static final ObjectParser<HistogramValuesSourceBuilder, Void> PARSER; static { PARSER = new ObjectParser<>(HistogramValuesSourceBuilder.TYPE); PARSER.declareDouble(HistogramValuesSourceBuilder::interval, Histogram.INTERVAL_FIELD); CompositeValuesSourceParserHelper.declareValuesSourceFields(PARSER, ValueType.NUMERIC); } static HistogramValuesSourceBuilder parse(String name, XContentParser parser) throws IOException { return PARSER.parse(parser, new HistogramValuesSourceBuilder(name), null); } private double interval = 0; public HistogramValuesSourceBuilder(String name) { super(name, ValueType.DOUBLE); } protected HistogramValuesSourceBuilder(StreamInput in) throws IOException { super(in); this.interval = in.readDouble(); } @Override protected void innerWriteTo(StreamOutput out) throws IOException { out.writeDouble(interval); } @Override protected void doXContentBody(XContentBuilder builder, Params params) throws IOException { builder.field(Histogram.INTERVAL_FIELD.getPreferredName(), interval); } @Override protected int innerHashCode() { return Objects.hash(interval); } @Override protected boolean innerEquals(HistogramValuesSourceBuilder other) { return Objects.equals(interval, other.interval); } @Override public String type() { return TYPE; } /** * Returns the interval that is set on this source **/ public double interval() { return interval; } /** * Sets the interval on this source. **/ public HistogramValuesSourceBuilder interval(double interval) { if (interval <= 0) { throw new IllegalArgumentException("[interval] must be greater than 0 for [histogram] source"); } this.interval = interval; return this; } @Override protected CompositeValuesSourceConfig innerBuild(SearchContext context, ValuesSourceConfig<?> config) throws IOException { ValuesSource orig = config.toValuesSource(context.getQueryShardContext()); if (orig == null) { orig = ValuesSource.Numeric.EMPTY; } if (orig instanceof ValuesSource.Numeric) { ValuesSource.Numeric numeric = (ValuesSource.Numeric) orig; final HistogramValuesSource vs = new HistogramValuesSource(numeric, interval); final MappedFieldType fieldType = config.fieldContext() != null ? config.fieldContext().fieldType() : null; return new CompositeValuesSourceConfig(name, fieldType, vs, config.format(), order(), missingBucket(), missing()); } else { throw new IllegalArgumentException("invalid source, expected numeric, got " + orig.getClass().getSimpleName()); } } }
1,519
1,337
<filename>modules/web/src/com/haulmont/cuba/web/gui/components/WebSuggestionPickerField.java /* * Copyright (c) 2008-2017 Haulmont. * * 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.haulmont.cuba.web.gui.components; import com.haulmont.bali.events.Subscription; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.components.SecuredActionsHolder; import com.haulmont.cuba.gui.components.SuggestionPickerField; import com.haulmont.cuba.gui.executors.BackgroundTask; import com.haulmont.cuba.gui.executors.BackgroundTaskHandler; import com.haulmont.cuba.gui.executors.BackgroundWorker; import com.haulmont.cuba.gui.executors.TaskLifeCycle; import com.haulmont.cuba.gui.screen.FrameOwner; import com.haulmont.cuba.gui.screen.Screen; import com.haulmont.cuba.gui.screen.ScreenFragment; import com.haulmont.cuba.gui.screen.UiControllerUtils; import com.haulmont.cuba.web.widgets.CubaPickerField; import com.haulmont.cuba.web.widgets.CubaSuggestionPickerField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import static com.haulmont.cuba.web.gui.components.WebLookupField.NULL_STYLE_GENERATOR; public class WebSuggestionPickerField<V extends Entity> extends WebPickerField<V> implements SuggestionPickerField<V>, SecuredActionsHolder { private static final Logger log = LoggerFactory.getLogger(WebSuggestionPickerField.class); protected BackgroundWorker backgroundWorker; protected BackgroundTaskHandler<List<V>> handler; protected SearchExecutor<V> searchExecutor; protected EnterActionHandler enterActionHandler; protected ArrowDownActionHandler arrowDownActionHandler; protected Function<? super V, String> optionStyleProvider; protected Locale locale; public WebSuggestionPickerField() { } @Override protected CubaPickerField<V> createComponent() { return new CubaSuggestionPickerField<>(); } @Override public CubaSuggestionPickerField<V> getComponent() { return (CubaSuggestionPickerField<V>) super.getComponent(); } @Inject public void setBackgroundWorker(BackgroundWorker backgroundWorker) { this.backgroundWorker = backgroundWorker; } @Override protected void initComponent(CubaPickerField<V> component) { getComponent().setTextViewConverter(this::convertToTextView); getComponent().setSearchExecutor(query -> { cancelSearch(); searchSuggestions(query); }); getComponent().setCancelSearchHandler(this::cancelSearch); } @Inject public void setUserSessionSource(UserSessionSource userSessionSource) { this.locale = userSessionSource.getLocale(); } protected String convertToTextView(V value) { if (value == null) { return ""; } if (optionCaptionProvider != null) { return optionCaptionProvider.apply(value); } return metadataTools.getInstanceName(value); } protected void cancelSearch() { if (handler != null) { log.debug("Cancel previous search"); handler.cancel(); handler = null; } } protected void searchSuggestions(final String query) { BackgroundTask<Long, List<V>> task = getSearchSuggestionsTask(query); if (task != null) { handler = backgroundWorker.handle(task); handler.execute(); } } protected BackgroundTask<Long, List<V>> getSearchSuggestionsTask(final String query) { if (this.searchExecutor == null) return null; final SearchExecutor<V> currentSearchExecutor = this.searchExecutor; Map<String, Object> params; if (currentSearchExecutor instanceof ParametrizedSearchExecutor) { params = ((ParametrizedSearchExecutor<?>) currentSearchExecutor).getParams(); } else { params = Collections.emptyMap(); } return new BackgroundTask<Long, List<V>>(0) { @Override public List<V> run(TaskLifeCycle<Long> taskLifeCycle) throws Exception { List<V> result; try { result = asyncSearch(currentSearchExecutor, query, params); } catch (RuntimeException e) { log.error("Error in async search thread", e); result = Collections.emptyList(); } return result; } @Override public void done(List<V> result) { log.debug("Search results for '{}'", query); handleSearchResult(result); } @Override public void canceled() { } @Override public boolean handleException(Exception ex) { log.error("Error in async search thread", ex); return true; } }; } protected List<V> asyncSearch(SearchExecutor<V> searchExecutor, String searchString, Map<String, Object> params) throws Exception { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } log.debug("Search '{}'", searchString); List<V> searchResultItems; if (searchExecutor instanceof ParametrizedSearchExecutor) { ParametrizedSearchExecutor<V> pSearchExecutor = (ParametrizedSearchExecutor<V>) searchExecutor; searchResultItems = pSearchExecutor.search(searchString, params); } else { searchResultItems = searchExecutor.search(searchString, Collections.emptyMap()); } return searchResultItems; } protected void handleSearchResult(List<V> results) { showSuggestions(results, true); } @SuppressWarnings("unchecked") protected String generateItemStylename(Object item) { if (optionStyleProvider == null) { return null; } return this.optionStyleProvider.apply((V)item); } @Override public Subscription addFieldValueChangeListener(Consumer<FieldValueChangeEvent<V>> listener) { throw new UnsupportedOperationException(); } @Override public void setFieldEditable(boolean editable) { throw new UnsupportedOperationException(); } @Override public int getAsyncSearchDelayMs() { return getComponent().getAsyncSearchDelayMs(); } @Override public void setAsyncSearchDelayMs(int asyncSearchDelayMs) { getComponent().setAsyncSearchDelayMs(asyncSearchDelayMs); } @Override public SearchExecutor getSearchExecutor() { return searchExecutor; } @Override public void setSearchExecutor(SearchExecutor searchExecutor) { this.searchExecutor = searchExecutor; } @Override public EnterActionHandler getEnterActionHandler() { return enterActionHandler; } @Override public void setEnterActionHandler(EnterActionHandler enterActionHandler) { this.enterActionHandler = enterActionHandler; getComponent().setEnterActionHandler(enterActionHandler::onEnterKeyPressed); } @Override public ArrowDownActionHandler getArrowDownActionHandler() { return arrowDownActionHandler; } @Override public void setArrowDownActionHandler(ArrowDownActionHandler arrowDownActionHandler) { this.arrowDownActionHandler = arrowDownActionHandler; getComponent().setArrowDownActionHandler(arrowDownActionHandler::onArrowDownKeyPressed); } @Override public int getMinSearchStringLength() { return getComponent().getMinSearchStringLength(); } @Override public void setMinSearchStringLength(int minSearchStringLength) { getComponent().setMinSearchStringLength(minSearchStringLength); } @Override public int getSuggestionsLimit() { return getComponent().getSuggestionsLimit(); } @Override public void setSuggestionsLimit(int suggestionsLimit) { getComponent().setSuggestionsLimit(suggestionsLimit); } @Override public void showSuggestions(List<V> suggestions) { showSuggestions(suggestions, false); } protected void showSuggestions(List<V> suggestions, boolean userOriginated) { FrameOwner frameOwner = getFrame().getFrameOwner(); Collection<Screen> dialogScreens = UiControllerUtils.getScreenContext(frameOwner) .getScreens() .getOpenedScreens() .getDialogScreens(); Screen lastDialog = null; for (Screen dialogScreen : dialogScreens) { lastDialog = dialogScreen; } if(frameOwner instanceof ScreenFragment) { frameOwner = ComponentsHelper.getScreen((ScreenFragment) frameOwner); } if (lastDialog == null || Objects.equals(frameOwner, lastDialog)) { getComponent().showSuggestions(suggestions, userOriginated); } } @Override public void setPopupWidth(String popupWidth) { getComponent().setPopupWidth(popupWidth); } @Override public String getPopupWidth() { return getComponent().getPopupWidth(); } @Override public String getInputPrompt() { return getComponent().getInputPrompt(); } @Override public void setInputPrompt(String inputPrompt) { getComponent().setInputPrompt(inputPrompt); } @SuppressWarnings("unchecked") @Override public void setOptionStyleProvider(Function<? super V, String> optionStyleProvider) { if (this.optionStyleProvider != optionStyleProvider) { this.optionStyleProvider = optionStyleProvider; if (optionStyleProvider != null) { getComponent().setOptionsStyleProvider(this::generateItemStylename); } else { getComponent().setOptionsStyleProvider(NULL_STYLE_GENERATOR); } } } @Override public Function<? super V, String> getOptionStyleProvider() { return optionStyleProvider; } @Override public void setStyleName(String name) { super.setStyleName(name); getComponent().setPopupStyleName(name); } @Override public void addStyleName(String styleName) { super.addStyleName(styleName); getComponent().addPopupStyleName(styleName); } @Override public void removeStyleName(String styleName) { super.removeStyleName(styleName); getComponent().removePopupStyleName(styleName); } @Override protected void checkValueType(V value) { // do not check } }
4,374
434
<filename>gcc_bugs.cpp /* g++ --version: g++ (Ubuntu 10 - 20200416 - 0ubuntu1~18.04) 10.0.1 20200416 (experimental)[master revision 3c3f12e2a76:dcee354ce56:44b326839d864fc10c459916abcc97f35a9ac3de] Copyright(C) 2020 Free Software Foundation, Inc. This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #include <iostream> #include "librf.h" using namespace resumef; #define GCC_FIX_BUGS 1 static future_t<> gcc_bugs_if_await(event_t e) { #if GCC_FIX_BUGS auto result = co_await e.wait(); if (result == false) #else if (co_await e.wait() == false) //internal compiler error: in fold_convert_loc, at fold-const.c:2435 #endif std::cout << "time out!" << std::endl; else std::cout << "event signal!" << std::endl; } static future_t<> gcc_bugs_while_await(mutex_t lock) { #if GCC_FIX_BUGS for (;;) { auto result = co_await lock.try_lock(); if (result) break; } #else while (!co_await lock.try_lock()); //internal compiler error: in fold_convert_loc, at fold-const.c:2435 #endif std::cout << "OK." << std::endl; } #if GCC_FIX_BUGS static future_t<> gcc_bugs_lambda_coroutines_fixed(std::thread& other, channel_t<bool> c_done) { co_await c_done; std::cout << "other thread = " << other.get_id(); co_await c_done; } #endif static void gcc_bugs_lambda_coroutines() { channel_t<bool> c_done{ 1 }; std::thread other; #if GCC_FIX_BUGS go gcc_bugs_lambda_coroutines_fixed(other, c_done); #else go[&other, c_done]()->future_t<> { co_await c_done; std::cout << "other thread = " << other.get_id(); co_await c_done; }; //internal compiler error: in captures_temporary, at cp/coroutines.cc:2716 #endif } #if GCC_FIX_BUGS static future_t<> gcc_bugs_lambda_coroutines2_fixed(channel_t<intptr_t> head, channel_t<intptr_t> tail) { for (int i = 0; i < 100; ++i) { co_await(head << 0); co_await tail; } } #endif static void gcc_bugs_lambda_coroutines2() { channel_t<intptr_t> head{ 1 }; channel_t<intptr_t> tail{ 0 }; #if GCC_FIX_BUGS go gcc_bugs_lambda_coroutines2_fixed(head, tail); #else GO { for (int i = 0; i < 100; ++i) { co_await(head << 0); intptr_t value = co_await tail; (void)value; } }; //internal compiler error: in captures_temporary, at cp/coroutines.cc:2716 #endif } template<class... _Mtxs> static future_t<> gcc_bugs_nameless_args(adopt_manual_unlock_t #if GCC_FIX_BUGS nameless #endif , _Mtxs&... mtxs) { #if GCC_FIX_BUGS (void)nameless; #endif co_await mutex_t::lock(adopt_manual_unlock, mtxs...); } //internal compiler error: Segmentation fault void gcc_bugs() { event_t e; go gcc_bugs_if_await(e); mutex_t mtx; go gcc_bugs_while_await(mtx); mutex_t a, b, c; go gcc_bugs_nameless_args(adopt_manual_unlock, a, b, c); }
1,220
1,120
<filename>spec/fixtures/fixtures/more_files/Empty.h // // Empty.h // fixtures // // Created by <NAME> on 27.10.14. // Copyright (c) 2014 marklarr. All rights reserved. // #import <Foundation/Foundation.h> @interface Empty : NSObject @end
91
5,169
<gh_stars>1000+ { "name": "DZMemo", "version": "0.1.0", "summary": "backup a value for an instance, then recover it", "description": "backup a value for an instance, then recover it, using the memo design pattern", "homepage": "https://github.com/yishuiliunian/DZMemo", "license": "MIT", "authors": { "stonedong": "<EMAIL>" }, "source": { "git": "https://github.com/yishuiliunian/DZMemo.git", "tag": "0.1.0" }, "platforms": { "ios": "5.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "resource_bundles": { "DZMemo": [ "Pod/Assets/*.png" ] } }
273
310
{ "name": "AF-S VR Zoom-NIKKOR 24-120mm f/3.5-5.6G IF-ED", "description": "A zoom lens.", "url": "https://www.nikonusa.com/en/nikon-products/product/camera-lenses/af-s-vr-zoom-nikkor-24-120mm-f%252f3.5-5.6g-if-ed.html" }
113
4,389
<reponame>mcinp/Sequel-Ace<filename>complexity/2.2.0/models.json [{"Name":"C Header","Bytes":22057,"CodeBytes":0,"Lines":608,"Code":182,"Comment":356,"Blank":70,"Complexity":0,"Count":11,"WeightedComplexity":0,"Files":[]},{"Name":"Objective C","Bytes":83920,"CodeBytes":0,"Lines":2702,"Code":1783,"Comment":470,"Blank":449,"Complexity":445,"Count":10,"WeightedComplexity":0,"Files":[]}]
146
14,668
// 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. #include "content/browser/metrics/histograms_monitor.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/statistics_recorder.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { class HistogramsMonitorTest : public testing::Test { public: HistogramsMonitorTest() : task_environment_(BrowserTaskEnvironment::IO_MAINLOOP) {} content::BrowserTaskEnvironment task_environment_; }; TEST_F(HistogramsMonitorTest, StartMonitoringThenGetDiff) { base::StatisticsRecorder::ForgetHistogramForTesting("MonitorHistogram1"); base::StatisticsRecorder::ForgetHistogramForTesting("MonitorHistogram2"); base::HistogramBase* histogram1 = base::Histogram::FactoryGet( "MonitorHistogram1", 1, 1000, 10, base::HistogramBase::kNoFlags); histogram1->Add(30); HistogramsMonitor monitor; monitor.StartMonitoring(""); // Get diff immediately should return nothing. base::ListValue diff = monitor.GetDiff(); ASSERT_EQ(diff.GetList().size(), 0ull); // Add more data to histogram. histogram1->Add(30); histogram1->Add(40); diff = monitor.GetDiff(); ASSERT_EQ(diff.GetList().size(), 1ull); std::string* header1 = diff.GetList()[0].FindStringKey("header"); EXPECT_EQ(*header1, "Histogram: MonitorHistogram1 recorded 2 samples, mean = 35.0"); // Add another histogram base::HistogramBase* histogram2 = base::Histogram::FactoryGet( "MonitorHistogram2", 1, 1000, 10, base::HistogramBase::kNoFlags); histogram2->Add(50); diff = monitor.GetDiff(); ASSERT_EQ(diff.GetList().size(), 2ull); std::string* header2 = diff.GetList()[1].FindStringKey("header"); EXPECT_EQ(*header2, "Histogram: MonitorHistogram2 recorded 1 samples, mean = 50.0"); } TEST_F(HistogramsMonitorTest, StartMonitoringWithQueryThenGetDiff) { base::StatisticsRecorder::ForgetHistogramForTesting("MonitorHistogram1"); base::StatisticsRecorder::ForgetHistogramForTesting("MonitorHistogram2"); base::HistogramBase* histogram1 = base::Histogram::FactoryGet( "MonitorHistogram1", 1, 1000, 10, base::HistogramBase::kNoFlags); histogram1->Add(30); HistogramsMonitor monitor; monitor.StartMonitoring("MonitorHistogram1"); base::HistogramBase* histogram2 = base::Histogram::FactoryGet( "MonitorHistogram2", 1, 1000, 10, base::HistogramBase::kNoFlags); histogram2->Add(50); base::ListValue diff = monitor.GetDiff(); ASSERT_EQ(diff.GetList().size(), 0ull); } } // namespace content
909
2,023
<reponame>tdiprima/code<filename>recipes/Python/440477_Writes_logfiles_and_keep_backups/recipe-440477.py<gh_stars>1000+ """ logger.py This module is responsible for controlling the action logging for the application. """ """ Author: <NAME> """ ## #Imports ################################################################################ import os, time, threading #Constants ################################################################################ """ Tuple containing the backup filename extensions""" OLD_FILE_TUP = ('.1bak','.2bak','.3bak','.4bak') STR_TIME_FORMAT = '%d/%m/%Y %H:%M:%S' CR = '\n' TIMESTAMP = 'TIMESTAMP: ' SPACE = ' ' #Classes ################################################################################ class ActionLogManager (object): """ Script action log storage manager class """ ## #Constructor ############################################################################ def __init__ (self): """ LogStorageManager constructor Initialising the LogStorageManager class :Parameters: - :Returns: - None """ ## #Private Members ######################################################################## self._actionLogName = ('ActivityLogFile') self._logHandle = None self._maxEntries = 20 self._maxEntryCount = 0 self._logStr = None self._threadObject = None self._threadFlag = False """ check if the log file exists. If yes read the entries and update the entry counter.""" if os.path.exists(self._actionLogName): """ The log file exists already """ logFile = open(self._actionLogName, 'r') """ Read the number of entries from the log file""" self._maxEntryCount = len(logFile.readlines()) print('No. of entries in Action log file:%d' %\ self._maxEntryCount ) """ Close it""" logFile.close() """ Flag which will be usd to determine that the application is shutting down """ self._isRunning = True print('LogStorageManager Class Initialised..') ## #Methods ############################################################################ def writeActionLog(self): """ This method just logs the logStr into log-action-file and increments the entry-count :Parameters: - None :Returns: - None :Raises: -`FileHandlingException` : Raised when the script encounters an IOError. """ try: """ Opening the file in append mode and writing to it """ self._logHandle = open(self._actionLogName, 'a+') self._logHandle.write(self._logStr) """ Incrementing the entry count """ self._maxEntryCount += 1 print('The action log string written to the file') self._logHandle.close() except IOError: print('ActionLogFile could not be written to.') ############################################################################ def logMessage(self, msg): """ This method will log the data together with time stamp. The eventual checking, file transfer and backup will also be done by this method. :Parameters: - `msg` : Contains the text message. :Returns: - None. :Raises: - `FileHandlingException` : Raised when file operation fails. """ """ Getting the Time-Stamp """ timeStr = time.strftime(STR_TIME_FORMAT, time.localtime()) string = msg self._logStr = TIMESTAMP + timeStr + SPACE + string + CR print self._logStr """ Calling the writeActionLog method """ self.writeActionLog() """ Checking for Maximum entries """ if( self._maxEntryCount >= self._maxEntries): """ If the maximum entries is reached start the thread""" try: if self._threadFlag is not True: """ Creating a new thread object """ self._threadObject = WriteThread(self) """ Starting the new thread """ self._threadObject.start() """ Sleeping so that the thread runs """ time.sleep(1) else: print('Log file already resized, Write thread active !!') except Exception : printException() ############################################################################ def threadRun (self): """run method of the thread This method will run as a separate thread which will handle the file overwrite function. :Parameters: - None :Returns: - None Setting the threadFlag so that any accidental duplicate spawning doesnt occur. """ self._threadFlag = True print('Maximum entry count exceeded. Starting the '\ + 'Write thread..') try: try: """ Checks whether the files exist """ if(os.path.exists(self._actionLogName)): """ if 4th bak file exists remove it """ if(os.path.exists(self._actionLogName + OLD_FILE_TUP[3])): os.remove(self._actionLogName + OLD_FILE_TUP[3]) print('Removing %s file' \ %self._actionLogName + OLD_FILE_TUP[3]) """ Renaming the bak files to accomodate the new file """ for index in range(2, -1, -1): if(os.path.exists(self._actionLogName \ + OLD_FILE_TUP[index])): os.rename(self._actionLogName + OLD_FILE_TUP[index], self._actionLogName + OLD_FILE_TUP[index + 1]) os.rename(self._actionLogName, self._actionLogName \ + OLD_FILE_TUP[0]) except IOError: printException() """ Making the entry count to 0 """ self._maxEntryCount = 0 finally: """ Clearing the threadFlag when the thread ends """ self._threadFlag = False ############################################################################ def stop (self): """ method for stopping the WriteThread :Parameters: - None :Returns: - None """ """ Calling the stop method of the thread """ print('Stopping ActionLogManager ..') if (self._threadFlag == True): """ Notify the Write thread that it needs to be stopped """ self._isRunning = False self._threadObject.join() ################################################################################ class WriteThread (threading.Thread): """ WriteThread class This class will overwrite old backup files and rename the other files in separate threads. """ ## #Constructor ############################################################################ def __init__ (self , caller): """ WriteThread constructor :Paramters: - `caller` : Reference to the calling object :Returns: - None """ """ Calling the constructor of the base class """ threading.Thread.__init__ (self) self._caller = caller print('Initialising the WriteThread class ..') ############################################################################ def run (self): """ run method of the WriteThread class :Parameters: - None :Returns: - None """ print('Inside the run method of the WriteThread') """ Calling the threadRun method of the LogStorageManager class """ self._caller.threadRun() ################################################################################
4,168
397
// // Storage.h // sample-custom_objects // // Created by Quickblox Team on 6/10/15. // Copyright (c) 2015 QuickBlox. All rights reserved. // #import <Foundation/Foundation.h> #define kMovieClassName @"Movie" @interface Storage : NSObject @property (nonatomic, strong) NSMutableArray *moviesList; + (instancetype)instance; @end
119
301
''' /****************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ ''' import os from ite.config import * from ite.tc.analyzer import TCAnalyzer from ite.tc.robot_analyzer import RobotTCAnalyzer class TestSpecContainer: def __init__(self): self.data = dict() for platform in TEST_PLATFORM: self.data[platform] = dict() for build_type in BUILD_TYPE: self.data[platform][build_type] = dict() for transport in TEST_TRANSPORT: self.data[platform][build_type][transport] = dict() for network in TEST_NETWORK: self.data[platform][build_type][transport][network] = dict() for tctype in TESTCASE_TYPES: self.data[platform][build_type][transport][network][tctype] = dict() for module in TESTSUITE_MODULES: self.data[platform][build_type][transport][network][tctype][module] = dict() def extract_api_testspec_bysuite(self, tctype, module, testfw, path): analyzer = TCAnalyzer(testfw) rootpath = os.path.normcase(path) api_valid_convention = True for path, dir, files in os.walk(rootpath): for fname in files: filepath = os.path.join(path, fname) if (os.path.isfile(filepath) == False): continue if not (filepath.endswith('.cpp') or filepath.endswith('.c') or filepath.endswith('.java')): continue testspec_dict, invalid_list = analyzer.analyze_tc_file(filepath, module) for invalid in invalid_list: print("=> Invalid Test Case : %s(%d), %s.%s, message:%s" % (filepath, invalid[0], invalid[1], invalid[2], invalid[3])) api_valid_convention = False for platform in testspec_dict.keys(): if not platform in self.data.keys(): print("=> Invalid Platform: " + platform) continue for build_type in testspec_dict[platform]: for transport in testspec_dict[platform][build_type].keys(): #print (testspec_dict[platform][build_type][transport].items()) for network, testspec_list in testspec_dict[platform][build_type][transport].items(): #print('line 77:', len(testspec_list), testspec_list) for testspec in testspec_list: #print (self.data[platform][build_type][transport][network][tctype][module]) if (not testspec.suite in self.data[platform][build_type][transport][network][tctype][module]): self.data[platform][build_type][transport][network][tctype][module][testspec.suite] = dict() self.data[platform][build_type][transport][network][tctype][module][testspec.suite][testspec.name] = testspec return api_valid_convention def extract_api_testspec_bytypes(self, module, testfw, path): rootpath = os.path.normcase(path) api_valid_convention = True # rootpath = os.path.join(rootpath, "src") for tctype in TESTCASE_TYPES: type_dir = os.path.join(rootpath, tctype.lower()) if (os.path.isdir(type_dir)): valid = self.extract_api_testspec_bysuite(tctype, module, testfw, type_dir) api_valid_convention = api_valid_convention and valid return api_valid_convention def extract_api_testspec_bytestfw(self, module, path): rootpath = os.path.normcase(path) api_valid_convention = True for testfw in TESTFW_TYPES: fw_dir = os.path.join(rootpath, testfw.lower()) tmp_dir = fw_dir if (os.path.isdir(fw_dir)): if (testfw.lower() == "gtest"): for sdk_type in SDK_TYPES: sdk_fw_dir = os.path.join(tmp_dir, sdk_type.lower()) if (os.path.isdir(sdk_fw_dir)): sdk_fw_dir = os.path.join(sdk_fw_dir, "src") valid = self.extract_api_testspec_bytypes(module, testfw, sdk_fw_dir) api_valid_convention = api_valid_convention and valid fw_dir = os.path.join(tmp_dir, "src") if (os.path.isdir(fw_dir)): valid = self.extract_api_testspec_bytypes(module, testfw, fw_dir) api_valid_convention = api_valid_convention and valid else: fw_dir = os.path.join(tmp_dir, "src") if (testfw.lower() == "junit"): fw_dir = os.path.join(fw_dir, "org") fw_dir = os.path.join(fw_dir, "iotivity") fw_dir = os.path.join(fw_dir, "test") fw_dir = os.path.join(fw_dir, module.lower()) fw_dir = os.path.join(fw_dir, "tc") valid = self.extract_api_testspec_bytypes(module, testfw, fw_dir) api_valid_convention = api_valid_convention and valid return api_valid_convention def extract_api_testspec_bymodule(self, path, module_filter): rootpath = os.path.normcase(path) api_valid_convention = True for module in TESTSUITE_MODULES: if not module_filter == '' and module.lower() != module_filter.lower(): continue module_dir = os.path.join(rootpath, module.lower()) if (os.path.isdir(module_dir)): valid = self.extract_api_testspec_bytestfw(module, module_dir) api_valid_convention = api_valid_convention and valid return api_valid_convention def extract_api_testspec(self, path, module_filter): rootpath = os.path.normcase(path) api_valid_convention = True if (os.path.isdir(rootpath)): valid = self.extract_api_testspec_bymodule(rootpath, module_filter) # valid = self.extract_api_testspec_bymodule(tctype, type_dir, module_filter) api_valid_convention = api_valid_convention and valid # for tctype in TESTCASE_TYPES: # type_dir = os.path.join(rootpath, tctype.lower()) # if (os.path.isdir(type_dir)): # valid = self.extract_api_testspec_bymodule(tctype, type_dir, module_filter) # api_valid_convention = api_valid_convention and valid return api_valid_convention def extract_sampleapp_testspec(self, path, module_filter): rootpath = os.path.normcase(path) analyzer = RobotTCAnalyzer() api_valid_convention = True for path, dir, files in os.walk(rootpath): for fname in files: filepath = os.path.join(path, fname) if (os.path.isfile(filepath) == False): continue if not 'Iotivity_ComponentSampleApp' in fname: continue if not filepath.endswith('.txt'): continue test_data, invalid_list = analyzer.analyze_tc_file(filepath) for invalid in invalid_list: print("=> Invalid Test Case : %s(%d), %s.%s, message:%s" % (filepath, invalid[0], invalid[1], invalid[2], invalid[3])) api_valid_convention = False for platform, module, testspec in test_data: if not platform in self.data: print("=> Invalid Platform: " + platform) continue for build_type in self.data[platform]: if (not testspec.suite in self.data[platform][build_type][NO_TRANSPORT][NO_NETWORK]['STC'][module]): self.data[platform][build_type][NO_TRANSPORT][NO_NETWORK]['STC'][module][testspec.suite] = dict() self.data[platform][build_type][NO_TRANSPORT][NO_NETWORK]['STC'][module][testspec.suite][testspec.name] = testspec return api_valid_convention
4,492
382
<gh_stars>100-1000 // // Created by 安炳旭 on 2020-01-26. // #include <vector> #include <iostream> #include <map> using namespace std; int MoreThanHalfNum_Solution(vector<int> numbers) { int size = numbers.size() / 2; sort(numbers.begin(), numbers.end());//排序 for (int i = 0; i + size < numbers.size(); i++) { if (numbers[i] == numbers[i + size]) return numbers[i]; } return 0; } //或者使用map int MoreThanHalfNum_Solution2(vector<int> numbers) { map<int,int> numbersMap; for(int i=0;i<numbers.size();i++){ numbersMap[numbers[i]]+=1; } int max =numbers.size()/2; int number=0; for (map<int, int>::iterator it = numbersMap.begin(); it != numbersMap.end(); it++) { if(max<(it->second)){ number=it->first; } } return number; }
388
335
{ "word": "Oversimplify", "definitions": [ "Simplify (something) so much that a distorted impression of it is given." ], "parts-of-speech": "Verb" }
71
734
<reponame>adamnemecek/tracktion_engine /* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { MidiNoteDispatcher::MidiNoteDispatcher() { } MidiNoteDispatcher::~MidiNoteDispatcher() { stopTimer(); } void MidiNoteDispatcher::dispatchPendingMessagesForDevices (double editTime) { ScopedLock s (deviceLock); for (auto state : devices) dispatchPendingMessages (*state, editTime); } void MidiNoteDispatcher::masterTimeUpdate (double editTime) { const ScopedLock s (timeLock); masterTime = editTime; hiResClockOfMasterTime = Time::getMillisecondCounterHiRes(); } void MidiNoteDispatcher::prepareToPlay (double editTime) { masterTimeUpdate (editTime); } double MidiNoteDispatcher::getCurrentTime() const { const ScopedLock s (timeLock); return masterTime + (Time::getMillisecondCounterHiRes() - hiResClockOfMasterTime) * 0.001; } void MidiNoteDispatcher::dispatchPendingMessages (DeviceState& state, double editTime) { // N.B. This should only be called under a deviceLock auto& pendingBuffer = state.device.getPendingMessages(); state.device.context.masterLevels.processMidi (pendingBuffer, nullptr); const double delay = state.device.getMidiOutput().getDeviceDelay(); if (! state.device.sendMessages (pendingBuffer, editTime - delay)) state.buffer.mergeFromAndClear (pendingBuffer); } void MidiNoteDispatcher::setMidiDeviceList (const OwnedArray<MidiOutputDeviceInstance>& newList) { CRASH_TRACER OwnedArray<DeviceState> newDevices; for (auto d : newList) newDevices.add (new DeviceState (*d)); if (newList.isEmpty()) stopTimer(); bool startTimerFlag = false; { const ScopedLock sl (deviceLock); newDevices.swapWith (devices); startTimerFlag = ! devices.isEmpty(); } if (startTimerFlag) startTimer (1); } void MidiNoteDispatcher::hiResTimerCallback() { struct MessageToSend { MidiOutputDeviceInstance* device; MidiMessage message; }; Array<MessageToSend> messagesToSend; messagesToSend.ensureStorageAllocated (32); { const ScopedLock sl (deviceLock); for (auto d : devices) { auto& device = d->device; auto& buffer = d->buffer; auto& midiOut = device.getMidiOutput(); if (buffer.isAllNotesOff) { buffer.clear(); midiOut.sendNoteOffMessages(); } else { while (buffer.isNotEmpty()) { auto& message = buffer[0]; auto noteTime = message.getTimeStamp(); auto currentTime = getCurrentTime(); if (noteTime > currentTime + 0.25) { buffer.remove (0); } else if (noteTime <= currentTime) { messagesToSend.add ({ &device, message }); buffer.remove (0); } else { break; } } } } } for (auto& m : messagesToSend) m.device->getMidiOutput().fireMessage (m.message); } }
1,809
534
package rb.popview; import android.graphics.Bitmap; import android.graphics.Rect; import java.util.Random; /** * Created by rb on 20/6/16. */ public class Particle { int color; Random random; float radius; float randSpeed; float initialX; float initialY; float x; float y; float alpha; public void advance (float factor, Rect bound, Bitmap bitmap, int moveFactor) { radius = (1f-(factor/40f))*radius; alpha = 1f-factor; x = x+randSpeed*((initialX - (bound.left+bitmap.getWidth()/2))/(bitmap.getWidth()/2))*(moveFactor); y = y+randSpeed*((initialY - (bound.top+bitmap.getHeight()/2))/(bitmap.getHeight()/2))*(moveFactor); } public void followUp (float factor, Rect bound, Bitmap bitmap, int moveFactor, float startX, float startY) { radius = radius/(1f-(factor/40f)); alpha = factor; if(startX>initialX && x>initialX || startX<initialX && x<initialX) x = x-randSpeed*((initialX - (bound.left+bitmap.getWidth()/2))/(bitmap.getWidth()/2))*(moveFactor); if(startY>initialY && y>initialY || startY<initialY && y<initialY) y = y-randSpeed*((initialY - (bound.top+bitmap.getHeight()/2))/(bitmap.getHeight()/2))*(moveFactor); } }
446
462
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2005-2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #ifndef GEOS_OPOVERLAY_H #define GEOS_OPOVERLAY_H namespace geos { namespace operation { /** \brief * Contains classes that perform a topological overlay to compute boolean * spatial functions. * * The Overlay Algorithm is used in spatial analysis methods for computing * set-theoretic operations (boolean combinations) of input {@link Geometry}s. * The algorithm for computing the overlay uses the intersection operations * supported by topology graphs. * To compute an overlay it is necessary to explicitly compute the resultant * graph formed by the computed intersections. * * The algorithm to compute a set-theoretic spatial analysis method has the * following steps: * * - Build topology graphs of the two input geometries. For each geometry all * self-intersection nodes are computed and added to the graph. * - Compute nodes for all intersections between edges and nodes of the graphs. * - Compute the labeling for the computed nodes by merging the labels from * the input graphs. * - Compute new edges between the compute intersection nodes. * Label the edges appropriately. * - Build the resultant graph from the new nodes and edges. * - Compute the labeling for isolated components of the graph. Add the * isolated components to the resultant graph. * - Compute the result of the boolean combination by selecting the node * and edges with the appropriate labels. Polygonize areas and sew linear * geometries together. * * <h2>Package Specification</h2> * * - Java Topology Suite Technical Specifications * - <A HREF="http://www.opengis.org/techno/specs.htm"> * OpenGIS Simple Features Specification for SQL</A> * */ namespace overlay { // geos.operation.overlay } // namespace geos.operation.overlay } // namespace geos.operation } // namespace geos #include <geos/operation/overlay/OverlayOp.h> //#include <geos/operation/overlay/PolygonBuilder.h> //#include <geos/operation/overlay/PointBuilder.h> //#include <geos/operation/overlay/LineBuilder.h> //#include <geos/operation/overlay/MinimalEdgeRing.h> //#include <geos/operation/overlay/MaximalEdgeRing.h> //#include <geos/operation/overlay/OverlayNodeFactory.h> //#include <geos/operation/overlay/EdgeSetNoder.h> //#include <geos/operation/overlay/ElevationMatrix.h> #endif
788
316
package com.mapbox.mapboxsdk.http; import android.util.Log; import com.mapbox.mapboxsdk.log.Logger; import static com.mapbox.mapboxsdk.http.HttpRequest.CONNECTION_ERROR; import static com.mapbox.mapboxsdk.http.HttpRequest.TEMPORARY_ERROR; public class HttpLogger { private static final String TAG = "Mbgl-HttpRequest"; public static boolean logRequestUrl; public static boolean logEnabled = true; private HttpLogger(){ } public static void logFailure(int type, String errorMessage, String requestUrl) { log(type == TEMPORARY_ERROR ? Log.DEBUG : type == CONNECTION_ERROR ? Log.INFO : Log.WARN, String.format( "Request failed due to a %s error: %s %s", type == TEMPORARY_ERROR ? "temporary" : type == CONNECTION_ERROR ? "connection" : "permanent", errorMessage, logRequestUrl ? requestUrl : "" ) ); } public static void log(int type, String errorMessage) { if (logEnabled) { Logger.log(type, TAG, errorMessage); } } }
367
5,169
{ "name": "AYRegistry", "version": "0.1.2", "summary": "DI in 100 lines of code!", "description": "Simple dependency injection container for your needs", "homepage": "https://github.com/andjash/AYRegistry", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "andjash": "<EMAIL>" }, "source": { "git": "https://github.com/andjash/AYRegistry.git", "tag": "0.1.2" }, "platforms": { "ios": "8.0" }, "source_files": "AYRegistry/Classes/**/*", "pushed_with_swift_version": "4" }
229
5,169
{ "name": "Esolang", "version": "0.0.1", "license": "MIT", "summary": "Esoteric programming language interpreter writen in swift", "homepage": "https://github.com/nutcrack/esolang", "authors": { "nutcrack": "<EMAIL>" }, "source": { "git": "https://github.com/nutcrack/esolang.git", "tag": "0.0.1" }, "source_files": "Sources/*.swift", "platforms": { "ios": "9.0" } }
176
1,444
<gh_stars>1000+ package mage.cards.w; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.BeginningOfUpkeepTriggeredAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.dynamicvalue.common.CountersSourceCount; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.TargetController; import mage.constants.Zone; import mage.counters.CounterType; import mage.target.common.TargetCreaturePermanent; /** * * @author TheElk801 */ public final class WarDance extends CardImpl { public WarDance(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{G}"); // At the beginning of your upkeep, you may put a verse counter on War Dance. this.addAbility(new BeginningOfUpkeepTriggeredAbility(Zone.BATTLEFIELD, new AddCountersSourceEffect(CounterType.VERSE.createInstance(), true), TargetController.YOU, true)); // Sacrifice War Dance: Target creature gets +X/+X until end of turn, where X is the number of verse counters on War Dance. Ability ability = new SimpleActivatedAbility( Zone.BATTLEFIELD, new BoostTargetEffect( new CountersSourceCount(CounterType.VERSE), new CountersSourceCount(CounterType.VERSE), Duration.EndOfTurn ), new SacrificeSourceCost() ); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); } private WarDance(final WarDance card) { super(card); } @Override public WarDance copy() { return new WarDance(this); } }
748
410
#ifndef CARYLL_INCLUDE_TABLE_VHEA_H #define CARYLL_INCLUDE_TABLE_VHEA_H #include "table-common.h" typedef struct { f16dot16 version; int16_t ascent; int16_t descent; int16_t lineGap; int16_t advanceHeightMax; int16_t minTop; int16_t minBottom; int16_t yMaxExtent; int16_t caretSlopeRise; int16_t caretSlopeRun; int16_t caretOffset; int16_t dummy0; int16_t dummy1; int16_t dummy2; int16_t dummy3; int16_t metricDataFormat; uint16_t numOfLongVerMetrics; } table_vhea; extern caryll_RefElementInterface(table_vhea) table_iVhea; #endif
259
538
<reponame>e16din/AndroidBucket<filename>src/com/wangjie/androidbucket/customviews/horizontialmenu/OnHoriMenuItemListener.java package com.wangjie.androidbucket.customviews.horizontialmenu; import android.view.View; /** * Created by wangjie on 14-5-5. */ public interface OnHoriMenuItemListener{ public abstract void onItemClick(View view, int position); }
123
1,708
#pragma once #include "pe32_64.h" inline bool load_imports(BYTE* image, PIMAGE_NT_HEADERS nt) { IMAGE_DATA_DIRECTORY importsDirectory = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; if (importsDirectory.VirtualAddress == 0) { return false; } PIMAGE_IMPORT_DESCRIPTOR importDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(importsDirectory.VirtualAddress + (FIELD_PTR)image); while (importDescriptor->Name != NULL) { LPCSTR libraryName = (LPCSTR)importDescriptor->Name + (FIELD_PTR)image; HMODULE library = LoadLibraryA(libraryName); #ifdef _DEBUG std::cout << "Loading: " << libraryName << "\n"; #endif if (library) { PIMAGE_THUNK_DATA thunk = NULL; thunk = (PIMAGE_THUNK_DATA)((FIELD_PTR)image + importDescriptor->FirstThunk); while (thunk->u1.AddressOfData != NULL) { FIELD_PTR functionAddress = NULL; if (IMAGE_SNAP_BY_ORDINAL(thunk->u1.Ordinal)) { LPCSTR functionOrdinal = (LPCSTR)IMAGE_ORDINAL(thunk->u1.Ordinal); functionAddress = (FIELD_PTR)GetProcAddress(library, functionOrdinal); } else { PIMAGE_IMPORT_BY_NAME functionName = (PIMAGE_IMPORT_BY_NAME)((FIELD_PTR)image + thunk->u1.AddressOfData); functionAddress = (FIELD_PTR)GetProcAddress(library, functionName->Name); } thunk->u1.Function = functionAddress; ++thunk; } } importDescriptor++; } return true; }
831
539
/* * Copyright (c) 2015, EURECOM (www.eurecom.fr) * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * 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 the FreeBSD Project. */ /*! \file common_defs.h \brief \author <NAME>, <NAME> \company Eurecom \email: <EMAIL> */ #ifndef FILE_COMMON_DEFS_SEEN #define FILE_COMMON_DEFS_SEEN #include <string.h> // memcpy #include <arpa/inet.h> #define GNB_GTP_TEID_FMT "%08x" //------------------------------------------------------------------------------ #define STOLEN_REF #define CLONE_REF #define OFFSET_OF(TyPe, MeMBeR) ((size_t) & ((TyPe*)0)->MeMBeR) // https://stackoverflow.com/questions/4415524/common-array-length-macro-for-c #define COUNT_OF(x) \ ((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x]))))) #ifndef __cplusplus #define PARENT_STRUCT(cOnTaiNeD, TyPe, MeMBeR) \ ({ \ const typeof(((TyPe*)0)->MeMBeR)* __MemBeR_ptr = (cOnTaiNeD); \ (TyPe*)((char*)__MemBeR_ptr - OFFSET_OF(TyPe, MeMBeR)); \ }) #endif #ifdef __cplusplus #define PARENT_STRUCT(cOnTaiNeD, TyPe, MeMBeR) \ ({ \ const decltype(((TyPe*)0)->MeMBeR)* __MemBeR_ptr = (cOnTaiNeD); \ (TyPe*)((char*)__MemBeR_ptr - OFFSET_OF(TyPe, MeMBeR)); \ }) #endif #define OAI_MAX(a, b) \ ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _a > _b ? _a : _b; \ }) #define OAI_MIN(a, b) \ ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _a < _b ? _a : _b; \ }) //------------------------------------------------------------------------------ #define INTERNAL_FLAG_NULL (0) #define INTERNAL_FLAG_X2_HANDOVER (1 << 0) #define INTERNAL_FLAG_SKIP_RESPONSE (1 << 2) #define INTERNAL_FLAG_TRIGGERED_ACK (1 << 3) #define INTERNAL_LATE_RESPONS_IND (1 << 4) //------------------------------------------------------------------------------ typedef enum { /* Fatal errors - received message should not be processed */ TLV_MAC_MISMATCH = -14, TLV_BUFFER_NULL = -13, TLV_BUFFER_TOO_SHORT = -12, TLV_PROTOCOL_NOT_SUPPORTED = -11, TLV_WRONG_MESSAGE_TYPE = -10, TLV_OCTET_STRING_TOO_LONG_FOR_IEI = -9, TLV_VALUE_DOESNT_MATCH = -4, TLV_MANDATORY_FIELD_NOT_PRESENT = -3, TLV_UNEXPECTED_IEI = -2, TLV_ERROR_OK = 0, /* Defines error code limit below which received message should be discarded * because it cannot be further processed */ TLV_FATAL_ERROR = TLV_VALUE_DOESNT_MATCH } tlv_error_code_e; /* Intended to be the primary mechanism to gracefully handle errors across * API boundaries. * Most functions which can produce a recoverable error should be designed to * return this. * Inspired by Google's absl::Status */ typedef enum { RETURNerror = -1, // An internal invariant is broken RETURNok = 0, // Ok } status_code_e; /* This enum should match with the ModeMapItem_FederatedMode enum * defined in mconfigs.proto */ typedef enum { SPGW_SUBSCRIBER = 0, // default mode is HSS + spgw_task LOCAL_SUBSCRIBER = 1, // will use subscriberDb + spgw_task S8_SUBSCRIBER = 2, // will use federated HSS + s8_task } mode_map; //------------------------------------------------------------------------------ #define DECODE_U8(bUFFER, vALUE, sIZE) \ vALUE = *(uint8_t*)(bUFFER); \ sIZE += sizeof(uint8_t) #define DECODE_U16(bUFFER, vALUE, sIZE) \ memcpy((unsigned char*)&vALUE, bUFFER, sizeof(uint16_t)); \ vALUE = ntohs(vALUE); \ sIZE += sizeof(uint16_t) // vALUE is uint32_t; the most significant byte after decoding will be zero #define DECODE_U24(bUFFER, vALUE, sIZE) \ vALUE = 0; \ memcpy((unsigned char*)&vALUE, bUFFER, 3); \ vALUE = ntohl(vALUE); \ vALUE = vALUE >> 8; \ sIZE += 3 #define DECODE_U32(bUFFER, vALUE, sIZE) \ memcpy((unsigned char*)&vALUE, bUFFER, sizeof(uint32_t)); \ vALUE = ntohl(vALUE); \ sIZE += sizeof(uint32_t) #define DESERIALIZE_N2HBO_U32(bUFFER, vALUE) \ memcpy((unsigned char*)&vALUE, bUFFER, sizeof(uint32_t)); \ vALUE = ntohl(vALUE); #if (BYTE_ORDER == LITTLE_ENDIAN) #define DECODE_LENGTH_U16(bUFFER, vALUE, sIZE) \ vALUE = ((*(bUFFER)) << 8) | (*((bUFFER) + 1)); \ sIZE += sizeof(uint16_t) #else #define DECODE_LENGTH_U16(bUFFER, vALUE, sIZE) \ vALUE = (*(bUFFER)) | (*((bUFFER) + 1) << 8); \ sIZE += sizeof(uint16_t) #endif #define ENCODE_U8(buffer, value, size) \ *(uint8_t*)(buffer) = value; \ size += sizeof(uint8_t) #define ENCODE_U16(buffer, value, size) \ do { \ uint16_t n_value = htons(value); \ memcpy(buffer, (unsigned char*)&n_value, sizeof(uint16_t)); \ size += sizeof(uint16_t); \ } while (0) // value is 24bits, so the most significant byte should be discarded. #define ENCODE_U24(buffer, value, size) \ do { \ uint32_t n_value = value << 8; \ n_value = htonl(n_value); \ memcpy(buffer, (unsigned char*)&n_value, 3); \ size += 3; \ } while (0) #define ENCODE_U32(buffer, value, size) \ do { \ uint32_t n_value = htonl(value); \ memcpy(buffer, (unsigned char*)&n_value, sizeof(uint32_t)); \ size += sizeof(uint32_t); \ } while (0) #define SERIALIZE_H2NBO_U32(buffer, value) \ do { \ uint32_t n_value = htonl(value); \ memcpy(buffer, (unsigned char*)&n_value, sizeof(uint32_t)); \ } while (0) #define SERIALIZE_U32(buffer, value) \ do { \ memcpy(buffer, (unsigned char*)&value, sizeof(uint32_t)); \ } while (0) #define IPV4_STR_ADDR_TO_INADDR(AdDr_StR, InAdDr, MeSsAgE) \ do { \ if (inet_aton(AdDr_StR, &InAdDr) <= 0) { \ Fatal(MeSsAgE); \ } \ } while (0) #define IPV6_STR_ADDR_TO_INADDR(AdDr_StR, InAdDr, MeSsAgE) \ do { \ if (inet_pton(AF_INET6, AdDr_StR, &InAdDr) <= 0) { \ Fatal(MeSsAgE); \ } \ } while (0) #define NIPADDR(addr) \ (uint8_t)(addr & 0x000000FF), (uint8_t)((addr & 0x0000FF00) >> 8), \ (uint8_t)((addr & 0x00FF0000) >> 16), \ (uint8_t)((addr & 0xFF000000) >> 24) #define HIPADDR(addr) \ (uint8_t)((addr & 0xFF000000) >> 24), (uint8_t)((addr & 0x00FF0000) >> 16), \ (uint8_t)((addr & 0x0000FF00) >> 8), (uint8_t)(addr & 0x000000FF) #define NIP6ADDR(addr) \ ntohs((addr)->s6_addr16[0]), ntohs((addr)->s6_addr16[1]), \ ntohs((addr)->s6_addr16[2]), ntohs((addr)->s6_addr16[3]), \ ntohs((addr)->s6_addr16[4]), ntohs((addr)->s6_addr16[5]), \ ntohs((addr)->s6_addr16[6]), ntohs((addr)->s6_addr16[7]) #define IN6_ARE_ADDR_MASKED_EQUAL(a, b, m) \ (((((__const uint32_t*)(a))[0] & (((__const uint32_t*)(m))[0])) == \ (((__const uint32_t*)(b))[0] & (((__const uint32_t*)(m))[0]))) && \ ((((__const uint32_t*)(a))[1] & (((__const uint32_t*)(m))[1])) == \ (((__const uint32_t*)(b))[1] & (((__const uint32_t*)(m))[1]))) && \ ((((__const uint32_t*)(a))[2] & (((__const uint32_t*)(m))[2])) == \ (((__const uint32_t*)(b))[2] & (((__const uint32_t*)(m))[2]))) && \ ((((__const uint32_t*)(a))[3] & (((__const uint32_t*)(m))[3])) == \ (((__const uint32_t*)(b))[3] & (((__const uint32_t*)(m))[3])))) #define EBI_TO_INDEX(eBi) (eBi - 5) #define INDEX_TO_EBI(iNdEx) (iNdEx + 5) #ifndef UNUSED #define UNUSED(x) (void)(x) #endif #endif /* FILE_COMMON_DEFS_SEEN */
5,152
523
package com.dalimao.verificationcodeinput; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.dalimao.corelibrary.VerificationCodeInput; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); VerificationCodeInput input = (VerificationCodeInput) findViewById(R.id.verificationCodeInput); input.setOnCompleteListener(new VerificationCodeInput.Listener() { @Override public void onComplete(String content) { Log.d(TAG, "完成输入:" + content); } }); } }
309
335
<reponame>tsbohc/ProjectE package moze_intel.projecte.api.nbt; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Represents that this class should be loaded as an {@link INBTProcessor)} */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface NBTProcessor { /** * Gets the priority of this {@link NBTProcessor}. This is used when loading the list of processors. The higher this number is the earlier it gets ran. * * @return Sort priority of this {@link NBTProcessor} */ int priority() default 0; /** * Array of modids that are required for this {@link NBTProcessor} to be loaded, empty String or array for no dependencies. * * @return array of modids. */ String[] requiredMods() default ""; /** * Used to on a static field of a class annotated with {@link NBTProcessor} to represent the field is an instance of an {@link NBTProcessor}. This instance will then * be used instead of attempting to create a new instance of the class. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Instance {} }
364
460
#ifndef WebCore_FWD_TypeTraits_h #define WebCore_FWD_TypeTraits_h #include <JavaScriptCore/TypeTraits.h> #endif
51
3,181
/* * SPDX-FileCopyrightText: 2016, microG Project Team * SPDX-License-Identifier: Apache-2.0 AND CC-BY-4.0 * Notice: Portions of this file are reproduced from work created and shared by Google and used * according to terms described in the Creative Commons 4.0 Attribution License. * See https://developers.google.com/readme/policies for details. */ package com.google.android.gms.tasks; import org.microg.gms.common.PublicApi; /** * Listener called when a {@link Task} fails with an exception. * * @see Task#addOnFailureListener(OnFailureListener) */ @PublicApi public interface OnFailureListener { /** * Called when the Task fails with an exception. * * @param e the exception that caused the Task to fail. Never null */ void onFailure(Exception e); }
263
474
<gh_stars>100-1000 // // TuSDKMediaAssetExtractorAudioSync.h // TuSDKVideo // // Created by sprint on 21/08/2018. // Copyright © 2018 TuSDK. All rights reserved. // #import <AVFoundation/AVFoundation.h> #import "TuSDKMediaExtractorSync.h" #import "TuSDKMediaTimelineAssetExtractor.h" #import "TuSDKMediaAssetTimeline.h" /** 音频分离器同步器 @since v3.0 */ @interface TuSDKMediaAssetExtractorAudioSync : NSObject <TuSDKMediaExtractorSync> /** 初始化 TuSDKMediaAssetExtractorAudioSync @param audioExtractor 音频数据分离器 @return TuSDKMediaAssetExtractorAudioSync */ - (instancetype)initExtractor:(id<TuSDKMediaTimelineExtractor>)audioExtractor; /** 视频数据分离器 @since v3.0 */ @property (nonatomic,readonly) id<TuSDKMediaTimelineExtractor> audioExtractor; /** 当前已播放时长 @since v3.0 */ @property (nonatomic,readonly) CMTime outputTime; @end
385
311
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeScope; import datadog.trace.api.Trace; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.stream.IntStream; import java.util.stream.Stream; public class Fanout { private final Executor executor; private final int tasks; private final boolean traceChild; public Fanout(Executor executor, int tasks, boolean traceChild) { this.executor = executor; this.tasks = tasks; this.traceChild = traceChild; } public void execute() { try { Stream<CompletableFuture<?>> futures = IntStream.range(0, tasks) .mapToObj( i -> CompletableFuture.runAsync( traceChild ? this::tracedWork : this::untracedWork, executor)); // Wait for those threads to finish work CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } public void executeTwoLevels() { try { Stream<CompletableFuture<?>> futures = IntStream.range(0, tasks) .mapToObj( i -> CompletableFuture.runAsync( traceChild ? this::tracedWork : this::untracedWork, executor) .thenRunAsync( traceChild ? this::tracedWork : this::untracedWork, executor)); // Wait for those threads to finish work CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void untracedWork() { assert null != activeScope(); } @Trace private void tracedWork() { assert null != activeScope(); } }
813
7,482
/** ****************************************************************************** * @file tae32f53xx_ll_sysctrl.h * @author MCD Application Team * @brief Header file for SYSCTRL LL module. * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 Tai-Action. * All rights reserved.</center></h2> * * This software is licensed by Tai-Action under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef _TAE32F53XX_LL_SYSCTRL_H_ #define _TAE32F53XX_LL_SYSCTRL_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "tae32f53xx_ll_def.h" /** @addtogroup TAE32F53xx_LL_Driver * @{ */ /** @addtogroup SYSCTRL_LL * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SYSCTRL_LL_Exported_Macros SYSCTRL LL Exported Macros * @brief SYSCTRL LL Exported Macros * @{ */ /** * @brief PLL0 Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_EN_Msk) /** * @brief PLL0 Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_EN_Msk) /** * @brief Judge PLL0 has Locked or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 PLL0 hasn't Locked * @retval 1 PLL0 has Locked */ #define __LL_SYSCTRL_PLL0_IsLocked(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_LOCKED_Msk) >> SYSCTRL_PLL0_LOCKED_Pos) /** * @brief PLL0 LPF Select 8M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_LPF_8M(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_LPF_Msk) /** * @brief PLL0 LPF Select 26M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_LPF_26M(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_LPF_Msk) /** * @brief PLL0 Band Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param band PLL0 Band * @return None */ #define __LL_SYSCTRL_PLL0_Band_Set(__SYSCTRL__, band) \ MODIFY_REG((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_BAND_Msk, band) /** * @brief PLL0 GVCO Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vco PLL0 GVCO * @return None */ #define __LL_SYSCTRL_PLL0_GVCO_Set(__SYSCTRL__, vco) \ MODIFY_REG((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_GVCO_Msk, vco) /** * @brief PLL0 DIV Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div PLL0 Div * @return None */ #define __LL_SYSCTRL_PLL0_DIV_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_DIV_Msk, (((div-1) & 0xfUL) << SYSCTRL_PLL0_DIV_Pos)) /** * @brief PLL0 Pre Div Set to 2 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_PreDiv_2(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_PREDIV_Msk) /** * @brief PLL0 Pre Div Set to 1 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL0_PreDiv_1(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_PREDIV_Msk) /** * @brief PLL0 Ref CLK Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param ref_clk PLL0 Ref CLK * @return None */ #define __LL_SYSCTRL_PLL0_RefClk_Set(__SYSCTRL__, ref_clk) \ MODIFY_REG((__SYSCTRL__)->PLL0CR, SYSCTRL_PLL0_REFCLK_Msk, ref_clk) /** * @brief PLL1 Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_EN_Msk) /** * @brief PLL1 Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_EN_Msk) /** * @brief Judge PLL1 has Locked or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 PLL1 hasn't Locked * @retval 1 PLL1 has Locked */ #define __LL_SYSCTRL_PLL1_IsLocked(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_LOCKED_Msk) >> SYSCTRL_PLL1_LOCKED_Pos) /** * @brief PLL1 LPF Select 8M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_LPF_8M(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_LPF_Msk) /** * @brief PLL1 LPF Select 26M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_LPF_26M(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_LPF_Msk) /** * @brief PLL1 Band Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param band PLL1 Band * @return None */ #define __LL_SYSCTRL_PLL1_Band_Set(__SYSCTRL__, band) \ MODIFY_REG((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_BAND_Msk, band) /** * @brief PLL1 GVCO Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vco PLL1 GVCO * @return None */ #define __LL_SYSCTRL_PLL1_GVCO_Set(__SYSCTRL__, vco) \ MODIFY_REG((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_GVCO_Msk, vco) /** * @brief PLL1 DIV Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div PLL1 Div * @return None */ #define __LL_SYSCTRL_PLL1_DIV_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_DIV_Msk, (((div-1) & 0xfUL) << SYSCTRL_PLL1_DIV_Pos)) /** * @brief PLL1 Pre Div Set to 2 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_PreDiv_2(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_PREDIV_Msk) /** * @brief PLL1 Pre Div Set to None * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL1_PreDiv_1(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_PREDIV_Msk) /** * @brief PLL1 Ref CLK Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param ref_clk PLL1 Ref CLK * @return None */ #define __LL_SYSCTRL_PLL1_RefClk_Set(__SYSCTRL__, ref_clk) \ MODIFY_REG((__SYSCTRL__)->PLL1CR, SYSCTRL_PLL1_REFCLK_Msk, ref_clk) /** * @brief PLL2 Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_EN_Msk) /** * @brief PLL2 Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_EN_Msk) /** * @brief Judge PLL2 has Locked or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 PLL2 hasn't Locked * @retval 1 PLL2 has Locked */ #define __LL_SYSCTRL_PLL2_IsLocked(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_LOCKED_Msk) >> SYSCTRL_PLL2_LOCKED_Pos) /** * @brief PLL2 LPF Select 8M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_LPF_8M(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_LPF_Msk) /** * @brief PLL2 LPF Select 26M * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_LPF_26M(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_LPF_Msk) /** * @brief PLL2 Band Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param band PLL2 Band * @return None */ #define __LL_SYSCTRL_PLL2_Band_Set(__SYSCTRL__, band) \ MODIFY_REG((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_BAND_Msk, band) /** * @brief PLL2 GVCO Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vco PLL2 GVCO * @return None */ #define __LL_SYSCTRL_PLL2_GVCO_Set(__SYSCTRL__, vco) \ MODIFY_REG((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_GVCO_Msk, vco) /** * @brief PLL2 DIV Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div PLL2 Div * @return None */ #define __LL_SYSCTRL_PLL2_DIV_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_DIV_Msk, (((div-1) & 0xfUL) << SYSCTRL_PLL2_DIV_Pos)) /** * @brief PLL2 Pre Div Set to 2 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_PreDiv_2(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_PREDIV_Msk) /** * @brief PLL2 Pre Div Set to None * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PLL2_PreDiv_1(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_PREDIV_Msk) /** * @brief PLL2 Ref CLK Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param ref_clk PLL2 Ref CLK * @return None */ #define __LL_SYSCTRL_PLL2_RefClk_Set(__SYSCTRL__, ref_clk) \ MODIFY_REG((__SYSCTRL__)->PLL2CR, SYSCTRL_PLL2_REFCLK_Msk, ref_clk) /** * @brief SYSCLK Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div SYSCLK Div * @return None */ #define __LL_SYSCTRL_SysClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->SCLKCR, SYSCTRL_SYSCLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_SYSCLK_DIV_Pos)) /** * @brief SYSCLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src SYSCLK Source * @return None */ #define __LL_SYSCTRL_SysClkSrc_Set(__SYSCTRL__, src) \ MODIFY_REG((__SYSCTRL__)->SCLKCR, SYSCTRL_SYSCLK_SRC_Msk, src) /** * @brief APB1 CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1Clk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB1CLK_EN_Msk) /** * @brief APB1 CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1Clk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB1CLK_EN_Msk) /** * @brief APB0 CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0Clk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB0CLK_EN_Msk) /** * @brief APB0 CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0Clk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB0CLK_EN_Msk) /** * @brief AHB CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_AHBCLK_EN_Msk) /** * @brief AHB CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_AHBCLK_EN_Msk) /** * @brief APB1 CLK Div SET * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div APB1 Div * @return None */ #define __LL_SYSCTRL_APB1ClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->BCLKCR, SYSCTRL_APB1CLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_APB1CLK_DIV_Pos)) /** * @brief APB1 CLK Div GET * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return APB1 Div */ #define __LL_SYSCTRL_APB1ClkDiv_Get(__SYSCTRL__) \ ((READ_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB1CLK_DIV_Msk) >> SYSCTRL_APB1CLK_DIV_Pos) + 1) /** * @brief APB0 CLK Div SET * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div APB0 Div * @return None */ #define __LL_SYSCTRL_APB0ClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->BCLKCR, SYSCTRL_APB0CLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_APB0CLK_DIV_Pos)) /** * @brief APB0 CLK Div GET * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return APB0 Div */ #define __LL_SYSCTRL_APB0ClkDiv_Get(__SYSCTRL__) \ ((READ_BIT((__SYSCTRL__)->BCLKCR, SYSCTRL_APB0CLK_DIV_Msk) >> SYSCTRL_APB0CLK_DIV_Pos) + 1) /** * @brief GPIOD Debounce CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src GPIOD Debounce CLK Source * @return None */ #define __LL_SYSCTRL_GPIODDbcSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_GPIOD_DBCCLK_SRC_Msk, src) /** * @brief GPIOC Debounce CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src GPIOC Debounce CLK Source * @return None */ #define __LL_SYSCTRL_GPIOCDbcSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_GPIOC_DBCCLK_SRC_Msk, src) /** * @brief GPIOB Debounce CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src GPIOB Debounce CLK Source * @return None */ #define __LL_SYSCTRL_GPIOBDbcSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_GPIOB_DBCCLK_SRC_Msk, src) /** * @brief GPIOA Debounce CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src GPIOA Debounce CLK Source * @return None */ #define __LL_SYSCTRL_GPIOADbcSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_GPIOA_DBCCLK_SRC_Msk, src) /** * @brief DFLASH Memory CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src DFLASH Memory CLK Source * @return None */ #define __LL_SYSCTRL_DFLASHMemClkSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_DFLASH_MEMCLK_SRC_Msk, src) /** * @brief EFLASH Memory CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src EFLASH Memory CLK Source * @return None */ #define __LL_SYSCTRL_EFLASHMemClkSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_EFLASH_MEMCLK_SRC_Msk, src) /** * @brief ADC Function CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src ADC Function CLK Source * @return None */ #define __LL_SYSCTRL_ADCFunClkSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_ADC_FUNCLK_SRC_Msk, src) /** * @brief HRPWM Function CLK Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src HRPWM Function CLK Source * @return None */ #define __LL_SYSCTRL_HRPWMFunClkSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->FSRCCR, SYSCTRL_HRPWM_FUNCLK_SRC_Msk, src) /** * @brief DFLASH Memory Clk Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div DFLASH Memory Clk Div * @return None */ #define __LL_SYSCTRL_DFLASHMemClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD0CR, SYSCTRL_DFLASH_MEMCLK_DIV_Msk, (((div-1) & 0xfUL) << SYSCTRL_DFLASH_MEMCLK_DIV_Pos)) /** * @brief EFLASH Memory Clk Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div EFLASH Memory Clk Div * @return None */ #define __LL_SYSCTRL_EFLASHMemClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD0CR, SYSCTRL_EFLASH_MEMCLK_DIV_Msk, (((div-1) & 0xfUL) << SYSCTRL_EFLASH_MEMCLK_DIV_Pos)) /** * @brief ADC Function Clk Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div ADC Function Clk Div * @return None */ #define __LL_SYSCTRL_ADCFunClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD0CR, SYSCTRL_ADC_FUNCLK_DIV_Msk, (((div-1) & 0x3UL) << SYSCTRL_ADC_FUNCLK_DIV_Pos)) /** * @brief HRPWM Function Clk Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div HRPWM Function Clk Div * @return None */ #define __LL_SYSCTRL_HRPWMFunClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD0CR, SYSCTRL_HRPWM_FUNCLK_DIV_Msk, (((div-1) & 0x3UL) << SYSCTRL_HRPWM_FUNCLK_DIV_Pos)) /** * @brief GPIOD Debounce CLK Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div GPIOD Debounce CLK Div * @return None */ #define __LL_SYSCTRL_GPIODDbcClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD1CR, SYSCTRL_GPIOD_DBCCLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_GPIOD_DBCCLK_DIV_Pos)) /** * @brief GPIOC Debounce CLK Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div GPIOC Debounce CLK Div * @return None */ #define __LL_SYSCTRL_GPIOCDbcClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD1CR, SYSCTRL_GPIOC_DBCCLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_GPIOC_DBCCLK_DIV_Pos)) /** * @brief GPIOB Debounce CLK Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div GPIOB Debounce CLK Div * @return None */ #define __LL_SYSCTRL_GPIOBDbcClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD1CR, SYSCTRL_GPIOB_DBCCLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_GPIOB_DBCCLK_DIV_Pos)) /** * @brief GPIOA Debounce CLK Div Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param div GPIOA Debounce CLK Div * @return None */ #define __LL_SYSCTRL_GPIOADbcClkDiv_Set(__SYSCTRL__, div) \ MODIFY_REG((__SYSCTRL__)->FCD1CR, SYSCTRL_GPIOA_DBCCLK_DIV_Msk, (((div-1) & 0xffUL) << SYSCTRL_GPIOA_DBCCLK_DIV_Pos)) /** * @brief LSTIMER Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTIMERBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_LSTIMER_BUSCLK_EN_Msk) /** * @brief LSTIMER Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTIMERBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_LSTIMER_BUSCLK_EN_Msk) /** * @brief UART1 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART1BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_UART1_BUSCLK_EN_Msk) /** * @brief UART1 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART1BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_UART1_BUSCLK_EN_Msk) /** * @brief UART0 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART0BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_UART0_BUSCLK_EN_Msk) /** * @brief UART0 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART0BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_UART0_BUSCLK_EN_Msk) /** * @brief I2C1 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_I2C1_BUSCLK_EN_Msk) /** * @brief I2C1 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_I2C1_BUSCLK_EN_Msk) /** * @brief I2C0 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_I2C0_BUSCLK_EN_Msk) /** * @brief I2C0 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0CCR, SYSCTRL_I2C0_BUSCLK_EN_Msk) /** * @brief ECU Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_ECU_BUSCLK_EN_Msk) /** * @brief ECU Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_ECU_BUSCLK_EN_Msk) /** * @brief IIR4 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR4_BUSCLK_EN_Msk) /** * @brief IIR4 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR4_BUSCLK_EN_Msk) /** * @brief IIR3 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR3_BUSCLK_EN_Msk) /** * @brief IIR3 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR3_BUSCLK_EN_Msk) /** * @brief IIR2 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR2_BUSCLK_EN_Msk) /** * @brief IIR2 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR2_BUSCLK_EN_Msk) /** * @brief IIR1 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR1_BUSCLK_EN_Msk) /** * @brief IIR1 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR1_BUSCLK_EN_Msk) /** * @brief IIR0 Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR0_BUSCLK_EN_Msk) /** * @brief IIR0 Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_IIR0_BUSCLK_EN_Msk) /** * @brief DALI Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DALIBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_DALI_BUSCLK_EN_Msk) /** * @brief DALI Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DALIBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1CCR, SYSCTRL_DALI_BUSCLK_EN_Msk) /** * @brief RAM2 Bus Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM2BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM2_BUSCLK_EN_Msk) /** * @brief RAM2 Bus Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM2BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM2_BUSCLK_EN_Msk) /** * @brief RAM1 Bus Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM1BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM1_BUSCLK_EN_Msk) /** * @brief RAM1 Bus Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM1BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM1_BUSCLK_EN_Msk) /** * @brief RAM0 Bus Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM0BusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM0_BUSCLK_EN_Msk) /** * @brief RAM0 Bus Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RAM0BusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_RAM0_BUSCLK_EN_Msk) /** * @brief USB Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_USB_BUSCLK_EN_Msk) /** * @brief USB Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_USB_BUSCLK_EN_Msk) /** * @brief DFLASH Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DFLASH_BUSCLK_EN_Msk) /** * @brief DFLASH Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DFLASH_BUSCLK_EN_Msk) /** * @brief EFLASH Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_EFLASH_BUSCLK_EN_Msk) /** * @brief EFLASH Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_EFLASH_BUSCLK_EN_Msk) /** * @brief HRPWM Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_HRPWM_BUSCLK_EN_Msk) /** * @brief HRPWM Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_HRPWM_BUSCLK_EN_Msk) /** * @brief ADC Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_ADC_BUSCLK_EN_Msk) /** * @brief ADC Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_ADC_BUSCLK_EN_Msk) /** * @brief DAC Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DACBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DAC_BUSCLK_EN_Msk) /** * @brief DAC Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DACBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DAC_BUSCLK_EN_Msk) /** * @brief CMP Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CMPBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_CMP_BUSCLK_EN_Msk) /** * @brief CMP Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CMPBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_CMP_BUSCLK_EN_Msk) /** * @brief GPIOD Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOD_BUSCLK_EN_Msk) /** * @brief GPIOD Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOD_BUSCLK_EN_Msk) /** * @brief GPIOC Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOC_BUSCLK_EN_Msk) /** * @brief GPIOC Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOC_BUSCLK_EN_Msk) /** * @brief GPIOB Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOB_BUSCLK_EN_Msk) /** * @brief GPIOB Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOB_BUSCLK_EN_Msk) /** * @brief GPIOA Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOABusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOA_BUSCLK_EN_Msk) /** * @brief GPIOA Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOABusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_GPIOA_BUSCLK_EN_Msk) /** * @brief HSTIMER Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTIMERBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_HSTIMER_BUSCLK_EN_Msk) /** * @brief HSTIMER Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTIMERBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_HSTIMER_BUSCLK_EN_Msk) /** * @brief CAN Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANBusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_CAN_BUSCLK_EN_Msk) /** * @brief CAN Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANBusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_CAN_BUSCLK_EN_Msk) /** * @brief DMA Bus CLK Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DMABusClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DMA_BUSCLK_EN_Msk) /** * @brief DMA Bus CLK Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DMABusClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBCCR, SYSCTRL_DMA_BUSCLK_EN_Msk) /** * @brief HRPWM Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMFunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_HRPWM_FUNCLK_EN_Msk) /** * @brief HRPWM Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMFunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_HRPWM_FUNCLK_EN_Msk) /** * @brief ADC Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCFunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_ADC_FUNCLK_EN_Msk) /** * @brief ADC Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCFunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_ADC_FUNCLK_EN_Msk) /** * @brief CAN Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANFunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_CAN_FUNCLK_EN_Msk) /** * @brief CAN Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANFunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_CAN_FUNCLK_EN_Msk) /** * @brief ECU Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUFunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_ECU_FUNCLK_EN_Msk) /** * @brief ECU Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUFunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_ECU_FUNCLK_EN_Msk) /** * @brief IIR4 Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4FunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR4_FUNCLK_EN_Msk) /** * @brief IIR4 Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4FunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR4_FUNCLK_EN_Msk) /** * @brief IIR3 Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3FunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR3_FUNCLK_EN_Msk) /** * @brief IIR3 Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3FunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR3_FUNCLK_EN_Msk) /** * @brief IIR2 Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2FunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR2_FUNCLK_EN_Msk) /** * @brief IIR2 Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2FunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR2_FUNCLK_EN_Msk) /** * @brief IIR1 Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1FunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR1_FUNCLK_EN_Msk) /** * @brief IIR1 Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1FunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR1_FUNCLK_EN_Msk) /** * @brief IIR0 Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0FunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR0_FUNCLK_EN_Msk) /** * @brief IIR0 Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0FunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_IIR0_FUNCLK_EN_Msk) /** * @brief USB Function Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBFunClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_USB_FUNCLK_EN_Msk) /** * @brief USB Function Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBFunClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_USB_FUNCLK_EN_Msk) /** * @brief DFLASH Memory Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHMemClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_DFLASH_MEMCLK_EN_Msk) /** * @brief DFLASH Memory Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHMemClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_DFLASH_MEMCLK_EN_Msk) /** * @brief EFLASH Memory Clk Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHMemClk_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_EFLASH_MEMCLK_EN_Msk) /** * @brief EFLASH Memory Clk Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHMemClk_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->FUNCCR, SYSCTRL_EFLASH_MEMCLK_EN_Msk) /** * @brief GPIOD Debounce Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODDbcSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOD_DBC_SOFTRST_Msk) /** * @brief GPIOD Debounce Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODDbcSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOD_DBC_SOFTRST_Msk) /** * @brief GPIOC Debounce Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCDbcSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOC_DBC_SOFTRST_Msk) /** * @brief GPIOC Debounce Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCDbcSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOC_DBC_SOFTRST_Msk) /** * @brief GPIOB Debounce Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBDbcSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOB_DBC_SOFTRST_Msk) /** * @brief GPIOB Debounce Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBDbcSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOB_DBC_SOFTRST_Msk) /** * @brief GPIOA Debounce Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOADbcSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOA_DBC_SOFTRST_Msk) /** * @brief GPIOA Debounce Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOADbcSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_GPIOA_DBC_SOFTRST_Msk) /** * @brief APB1 Bus Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1BusSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_APB1BUS_SOFTRST_Msk) /** * @brief APB1 Bus Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1BusSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_APB1BUS_SOFTRST_Msk) /** * @brief APB0 Bus Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0BusSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_APB0BUS_SOFTRST_Msk) /** * @brief APB0 Bus Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0BusSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_APB0BUS_SOFTRST_Msk) /** * @brief AHB Bus Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBBusSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_AHBBUS_SOFTRST_Msk) /** * @brief AHB Bus Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBBusSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSRCR, SYSCTRL_AHBBUS_SOFTRST_Msk) /** * @brief System Soft Reset all Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_SysSoftRstAll_Assert(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->SYSRCR, 0x0) /** * @brief System Soft Reset all Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_SysSoftRstAll_Release(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->SYSRCR, 0xffffffffUL) /** * @brief LSTIMER Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTIMERSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_LSTIMER_SOFTRST_Msk) /** * @brief LSTIMER Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTIMERSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_LSTIMER_SOFTRST_Msk) /** * @brief UART1 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART1SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_UART1_SOFTRST_Msk) /** * @brief UART1 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART1SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_UART1_SOFTRST_Msk) /** * @brief UART0 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART0SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_UART0_SOFTRST_Msk) /** * @brief UART0 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_UART0SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_UART0_SOFTRST_Msk) /** * @brief I2C1 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_I2C1_SOFTRST_Msk) /** * @brief I2C1 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_I2C1_SOFTRST_Msk) /** * @brief I2C0 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_I2C0_SOFTRST_Msk) /** * @brief I2C0 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB0RCR, SYSCTRL_I2C0_SOFTRST_Msk) /** * @brief APB0 Soft Reset all Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0SoftRstAll_Assert(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->APB0RCR, 0x0) /** * @brief APB0 Soft Reset all Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB0SoftRstAll_Release(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->APB0RCR, 0xffffffffUL) /** * @brief ECU Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_ECU_SOFTRST_Msk) /** * @brief ECU Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ECUSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_ECU_SOFTRST_Msk) /** * @brief IIR4 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR4_SOFTRST_Msk) /** * @brief IIR4 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR4SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR4_SOFTRST_Msk) /** * @brief IIR3 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR3_SOFTRST_Msk) /** * @brief IIR3 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR3SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR3_SOFTRST_Msk) /** * @brief IIR2 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR2_SOFTRST_Msk) /** * @brief IIR2 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR2SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR2_SOFTRST_Msk) /** * @brief IIR1 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR1_SOFTRST_Msk) /** * @brief IIR1 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR1SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR1_SOFTRST_Msk) /** * @brief IIR0 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR0_SOFTRST_Msk) /** * @brief IIR0 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IIR0SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_IIR0_SOFTRST_Msk) /** * @brief FPLL2 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL2SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL2_SOFTRST_Msk) /** * @brief FPLL2 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL2SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL2_SOFTRST_Msk) /** * @brief FPLL1 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL1SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL1_SOFTRST_Msk) /** * @brief FPLL1 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL1SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL1_SOFTRST_Msk) /** * @brief FPLL0 Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL0SoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL0_SOFTRST_Msk) /** * @brief FPLL0 Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FPLL0SoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_FPLL0_SOFTRST_Msk) /** * @brief DALI Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DALISoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_DALI_SOFTRST_Msk) /** * @brief DALI Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DALISoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->APB1RCR, SYSCTRL_DALI_SOFTRST_Msk) /** * @brief APB1 Soft Reset all Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1SoftRstAll_Assert(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->APB1RCR, 0x0) /** * @brief APB1 Soft Reset all Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_APB1SoftRstAll_Release(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->APB1RCR, 0xffffffffUL) /** * @brief DFLASH Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DFLASH_SOFTRST_Msk) /** * @brief DFLASH Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DFLASHSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DFLASH_SOFTRST_Msk) /** * @brief HSTIMER Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTIMERSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_HSTIMER_SOFTRST_Msk) /** * @brief HSTIMER Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTIMERSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_HSTIMER_SOFTRST_Msk) /** * @brief GPIOD Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOD_SOFTRST_Msk) /** * @brief GPIOD Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIODSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOD_SOFTRST_Msk) /** * @brief GPIOC Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOC_SOFTRST_Msk) /** * @brief GPIOC Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOCSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOC_SOFTRST_Msk) /** * @brief GPIOB Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOB_SOFTRST_Msk) /** * @brief GPIOB Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOBSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOB_SOFTRST_Msk) /** * @brief GPIOA Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOASoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOA_SOFTRST_Msk) /** * @brief GPIOA Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIOASoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_GPIOA_SOFTRST_Msk) /** * @brief USB Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_USB_SOFTRST_Msk) /** * @brief USB Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_USBSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_USB_SOFTRST_Msk) /** * @brief HRPWM Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_HRPWM_SOFTRST_Msk) /** * @brief HRPWM Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HRPWMSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_HRPWM_SOFTRST_Msk) /** * @brief DAC Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DACSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DAC_SOFTRST_Msk) /** * @brief DAC Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DACSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DAC_SOFTRST_Msk) /** * @brief ADC Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_ADC_SOFTRST_Msk) /** * @brief ADC Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_ADC_SOFTRST_Msk) /** * @brief CMP Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CMPSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_CMP_SOFTRST_Msk) /** * @brief CMP Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CMPSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_CMP_SOFTRST_Msk) /** * @brief EFLASH Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_EFLASH_SOFTRST_Msk) /** * @brief EFLASH Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_EFLASHSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_EFLASH_SOFTRST_Msk) /** * @brief CAN Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANSoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_CAN_SOFTRST_Msk) /** * @brief CAN Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CANSoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_CAN_SOFTRST_Msk) /** * @brief DMA Soft Reset Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DMASoftRst_Assert(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DMA_SOFTRST_Msk) /** * @brief DMA Soft Reset Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_DMASoftRst_Release(__SYSCTRL__) SET_BIT((__SYSCTRL__)->AHBRCR, SYSCTRL_DMA_SOFTRST_Msk) /** * @brief AHB Soft Reset all Assert * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBSoftRstAll_Assert(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->AHBRCR, 0x0) /** * @brief AHB Soft Reset all Release * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AHBSoftRstAll_Release(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->AHBRCR, 0xffffffffUL) /** * @brief RC8M Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RC8M_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_RC8M_EN_Msk) /** * @brief RC8M Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_RC8M_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_RC8M_EN_Msk) /** * @brief XOSC Loss IRQ Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSCLossIRQ_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSCLOSS_IRQEN_Msk) /** * @brief XOSC Loss IRQ Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSCLossIRQ_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSCLOSS_IRQEN_Msk) /** * @brief XOSC HY Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_HY_EN(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_HYEN_Msk) /** * @brief XOSC HY Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_HY_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_HYEN_Msk) /** * @brief XOSC DR Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param cur Current * @return None */ #define __LL_SYSCTRL_XOSC_DR_Set(__SYSCTRL__, cur) MODIFY_REG((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_DR_Msk, cur) /** * @brief XOSC CTO Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param cap capacitance Register Value * @return None */ #define __LL_SYSCTRL_XOSC_CTO_Set(__SYSCTRL__, cap) \ MODIFY_REG((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_CTO_Msk, ((cap & 0xfUL) << SYSCTRL_XOSC_CTO_Pos)) /** * @brief XOSC CTI Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param cap capacitance Register Value * @return None */ #define __LL_SYSCTRL_XOSC_CTI_Set(__SYSCTRL__, cap) \ MODIFY_REG((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_CTI_Msk, ((cap & 0xfUL) << SYSCTRL_XOSC_CTI_Pos)) /** * @brief XOSC CS Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param cap capacitance * @return None */ #define __LL_SYSCTRL_XOSC_CS_Set(__SYSCTRL__, cap) MODIFY_REG((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_CS_Msk, cap) /** * @brief XOSC Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_EN_Msk) /** * @brief XOSC Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XOSCCR, SYSCTRL_XOSC_EN_Msk) /** * @brief Judge XOSC Loss or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 XOSC hasn't loss * @retval 1 XOSC has loss */ #define __LL_SYSCTRL_IsXOSCLossPending(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_LOSS_PENDING_Msk) >> SYSCTRL_XOSC_LOSS_PENDING_Pos) /** * @brief Clear XOSC Loss Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSCLossPending_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_LOSS_PENDING_Msk) /** * @brief Enable SYSCLK Auto Switch to RC8M When XOSC Fault * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_SysclkSw_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_SYSCLK_SWEN_Msk) /** * @brief Disable SYSCLK Auto Switch to RC8M When XOSC Fault * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_SysclkSw_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_SYSCLK_SWEN_Msk) /** * @brief Enable PLL Ref Clk Auto Switch to RC8M When XOSC Fault * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_PLLRefClkSw_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_REFCLK_SWEN_Msk) /** * @brief Disable PLL Ref Clk Auto Switch to RC8M When XOSC Fault * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_PLLRefClkSw_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_REFCLK_SWEN_Msk) /** * @brief XOSC MNT Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_MNT_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_MNTEN_Msk) /** * @brief XOSC MNT Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_XOSC_MNT_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_MNTEN_Msk) /** * @brief XOSC AutoSwitch Window Width Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param width Auto Switch Window Width Register Value * @return None */ #define __LL_SYSCTRL_XOSC_Width_Set(__SYSCTRL__, width) \ MODIFY_REG((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_WIDTH_Msk, ((width & 0xfUL) << SYSCTRL_XOSC_WIDTH_Pos)) /** * @brief XOSC AutoSwitch Function High Limit Value Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param limit High Limit Register Value * @return None */ #define __LL_SYSCTRL_XOSC_HighLimit_Set(__SYSCTRL__, limit) \ MODIFY_REG((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_HIGH_LIMIT_Msk, ((limit & 0x3ffUL) << SYSCTRL_XOSC_HIGH_LIMIT_Pos)) /** * @brief XOSC AutoSwitch Function Low Limit Value Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param limit Low Limit Register Value * @return None */ #define __LL_SYSCTRL_XOSC_LowLimit_Set(__SYSCTRL__, limit) \ MODIFY_REG((__SYSCTRL__)->XASWCR, SYSCTRL_XOSC_LOW_LIMIT_Msk, ((limit & 0x3ffUL) << SYSCTRL_XOSC_LOW_LIMIT_Pos)) /** * @brief ADC Buffer Source Select * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src ADC Buffer Source * @return None */ #define __LL_SYSCTRL_ADCBufSrc_Sel(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->BUFCR, SYSCTRL_ADCBUF_SRCSEL_Msk, src) /** * @brief ADC Buffer Bypass Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBufBypass_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->BUFCR, SYSCTRL_ADCBUF_BYPASS_Msk) /** * @brief ADC Buffer Bypass Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBufBypass_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->BUFCR, SYSCTRL_ADCBUF_BYPASS_Msk) /** * @brief ADC Buffer Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBuf_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->BUFCR, SYSCTRL_ADCBUF_EN_Msk) /** * @brief ADC Buffer Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCBuf_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->BUFCR, SYSCTRL_ADCBUF_EN_Msk) /** * @brief TOUT Source Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src TOUT Source * @return None */ #define __LL_SYSCTRL_TOUTSrc_Set(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->BUFCR, SYSCTRL_TOUT_SRC_Msk, src) /** * @brief ADC Fan Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADC_Fan_Dis(__SYSCTRL__) \ MODIFY_REG((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCCTRL_FANOUT_EN_Msk, (0x0 << SYSCTRL_ADCCTRL_FANOUT_EN_Pos)) /** * @brief ADC Fan Out Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADC_FanOut_En(__SYSCTRL__) \ MODIFY_REG((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCCTRL_FANOUT_EN_Msk, (0x1 << SYSCTRL_ADCCTRL_FANOUT_EN_Pos)) /** * @brief ADC Fan In Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADC_FanIn_En(__SYSCTRL__) \ MODIFY_REG((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCCTRL_FANOUT_EN_Msk, (0x2 << SYSCTRL_ADCCTRL_FANOUT_EN_Pos)) /** * @brief ADC Data Fan Out Source Select ADC0 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCDataFanOutSrc_ADC0(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCDATA_FANOUT_SRC_Msk) /** * @brief ADC Data Fan Out Source Select ADC1 * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCDataFanOutSrc_ADC1(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCDATA_FANOUT_SRC_Msk) /** * @brief ADC Data Fan Out Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCDataFanOut_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCDATA_FANOUT_EN_Msk) /** * @brief ADC Data Fan Out Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_ADCDataFanOut_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_ADCDATA_FANOUT_EN_Msk) /** * @brief I2C1 SMBUS Output Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1_SMBUSOutput_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_I2C1_SMBUS_OE_Msk) /** * @brief I2C1 SMBUS Output Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C1_SMBUSOutput_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_I2C1_SMBUS_OE_Msk) /** * @brief I2C0 SMBUS Output Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0_SMBUSOutput_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_I2C0_SMBUS_OE_Msk) /** * @brief I2C0 SMBUS Output Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_I2C0_SMBUSOutput_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_I2C0_SMBUS_OE_Msk) /** * @brief JTAG Bug Fix Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_JTAG_BugFix_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_JTAG_BUGFIX_EN_Msk) /** * @brief JTAG Bug Fix Diaable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_JTAG_BugFix_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_JTAG_BUGFIX_EN_Msk) /** * @brief CAN FD Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CAN_FD_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CANFD_EN_Msk) /** * @brief CAN FD Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CAN_FD_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CANFD_EN_Msk) /** * @brief CPU Lockup Reset Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CPU_LockupRst_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CPU_LOCKUPRST_EN_Msk) /** * @brief CPU Lockup Reset Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CPU_LockupRst_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CPU_LOCKUPRST_EN_Msk) /** * @brief WWDG Debug Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_WWDG_Debug_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_WWDG_DEBUG_EN_Msk) /** * @brief WWDG Debug Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_WWDG_Debug_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_WWDG_DEBUG_EN_Msk) /** * @brief WWDG Timeout Reset Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_WWDG_TimeoutRst_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_WWDG_TIMEOUTRST_EN_Msk) /** * @brief WWDG Timeout Reset Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_WWDG_TimeoutRst_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_WWDG_TIMEOUTRST_EN_Msk) /** * @brief IWDG Debug Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IWDG_Debug_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_IWDG_DEBUG_EN_Msk) /** * @brief IWDG Debug Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IWDG_Debug_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_IWDG_DEBUG_EN_Msk) /** * @brief IWDG Timeout Reset Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IWDG_TimeoutRst_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_IWDG_TIMEOUTRST_EN_Msk) /** * @brief IWDG Timeout Reset Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IWDG_TimeoutRst_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_IWDG_TIMEOUTRST_EN_Msk) /** * @brief HSTMR Debug Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTMR_Debug_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_HSTMR_DEBUG_EN_Msk) /** * @brief HSTMR Debug Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_HSTMR_Debug_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_HSTMR_DEBUG_EN_Msk) /** * @brief LSTMR Debug Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTMR_Debug_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_LSTMR_DEBUG_EN_Msk) /** * @brief LSTMR Debug Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LSTMR_Debug_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_LSTMR_DEBUG_EN_Msk) /** * @brief GPIO Input NMI Interrupt Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIO_InputNMI_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_GPIO_NMIEN_Msk) /** * @brief GPIO Input NMI Interrupt Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_GPIO_InputNMI_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_GPIO_NMIEN_Msk) /** * @brief CLK Test Source Select * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param src CLK Test Source * @return None */ #define __LL_SYSCTRL_CLK_TestSrc_Sel(__SYSCTRL__, src) MODIFY_REG((__SYSCTRL__)->SYSCCR, SYSCTRL_CLK_TEST_SRC_Msk, src) /** * @brief CLK Fan Out Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CLK_FanOut_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CLK_FANOUT_EN_Msk) /** * @brief CLK Fan Out Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CLK_FanOut_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_CLK_FANOUT_EN_Msk) /** * @brief PMU Debug1 Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PMU_Debug1_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_PMU_DEBUG1_EN_Msk) /** * @brief PMU Debug1 Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PMU_Debug1_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_PMU_DEBUG1_EN_Msk) /** * @brief PMU Debug0 Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PMU_Debug0_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_PMU_DEBUG0_EN_Msk) /** * @brief PMU Debug0 Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_PMU_Debug0_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_PMU_DEBUG0_EN_Msk) /** * @brief TEST CLK In Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_TESTClkIn_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_TEST_CLKIN_EN_Msk) /** * @brief TEST CLK In Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_TESTClkIn_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->SYSCCR, SYSCTRL_TEST_CLKIN_EN_Msk) /** * @brief Judge SysReq Reset or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 Isn't SysReq Reset * @retval 1 Is SysReq Reset */ #define __LL_SYSCTRL_IsSysReqRst(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_SYSREQ_RST_ST_Msk) >> SYSCTRL_SYSREQ_RST_ST_Pos) /** * @brief Clear SysReq Reset Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_SysReqRst_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_SYSREQ_RST_ST_Msk) /** * @brief Judge MCLR Reset or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 Isn't MCLR Reset * @retval 1 Is MCLR Reset */ #define __LL_SYSCTRL_IsMCLRRst(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_MCLR_RST_ST_Msk) >> SYSCTRL_MCLR_RST_ST_Pos) /** * @brief Clear MCLR Reset Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_MCLRRst_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_MCLR_RST_ST_Msk) /** * @brief Judge LVD Reset or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 Isn't LVD Reset * @retval 1 Is LVD Reset */ #define __LL_SYSCTRL_IsLVDRst(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_LVD_RST_ST_Msk) >> SYSCTRL_LVD_RST_ST_Pos) /** * @brief Clear LVD Reset Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_LVDRst_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_LVD_RST_ST_Msk) /** * @brief Judge WWDG Reset or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 Isn't WWDG Reset * @retval 1 Is WWDG Reset */ #define __LL_SYSCTRL_IsWWDGRst(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_WWDG_RST_ST_Msk) >> SYSCTRL_WWDG_RST_ST_Pos) /** * @brief Clear WWDG Reset Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_WWDGRst_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_WWDG_RST_ST_Msk) /** * @brief Judge IWDG Reset or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 Isn't IWDG Reset * @retval 1 Is IWDG Reset */ #define __LL_SYSCTRL_IsIWDGRst(__SYSCTRL__) \ (READ_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_IWDG_RST_ST_Msk) >> SYSCTRL_IWDG_RST_ST_Pos) /** * @brief Clear IWDG Reset Pending * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_IWDGRst_Clr(__SYSCTRL__) SET_BIT((__SYSCTRL__)->SRSTSR, SYSCTRL_IWDG_RST_ST_Msk) /** * @brief SYSCTRL Control Register Unlock * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CTRLReg_Unlock(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->KEY, 0x3fac87e4) /** * @brief SYSCTRL FLS Register Unlock * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_FLSReg_Unlock(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->KEY, 0x1f2e3c4a) /** * @brief SYSCTRL Reg Lock * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_Reg_Lock(__SYSCTRL__) WRITE_REG((__SYSCTRL__)->KEY, 0x00) /** * @brief Judge SYSCTRL CTRL Register is unlock or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 SYSCTRL CTRL Register is lock * @retval 1 SYSCTRL CTRL Register is unlock */ #define __LL_SYSCTRL_IsCTRLRegUnlock(__SYSCTRL__) (READ_REG((__SYSCTRL__)->KEY) == 0x3fac87e4) /** * @brief Judge SYSCTRL FLS Register is unlock or not * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @retval 0 SYSCTRL FLS Register is lock * @retval 1 SYSCTRL FLS Register is unlock */ #define __LL_SYSCTRL_IsFLSRegUnlock(__SYSCTRL__) (READ_REG((__SYSCTRL__)->KEY) == 0x1f2e3c4a) /** * @brief PMU In Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param val Register Value * @return None */ #define __LL_SYSCTRL_PMU_In_Set(__SYSCTRL__, val) \ MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_PMU_IN_Msk, ((val & 0x3fUL) << SYSCTRL_PMU_IN_Pos)) /** * @brief CUR Resistance Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param res Resistance Register Value * @return None */ #define __LL_SYSCTRL_CUR_RES_Set(__SYSCTRL__, res) \ MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_CUR_RES_Msk, ((res & 0x3fUL) << SYSCTRL_CUR_RES_Pos)) /** * @brief CUR CAL Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param val Register Value * @return None */ #define __LL_SYSCTRL_CUR_CAL_Set(__SYSCTRL__, val) \ MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_CUR_CAL_Msk, ((val & 0x3UL) << SYSCTRL_CUR_CAL_Pos)) /** * @brief AVDD DRD Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AVDD_DRD_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_AVDD_DRD_Msk) /** * @brief AVDD DRD Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AVDD_DRD_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_AVDD_DRD_Msk) /** * @brief AVDD Voltage Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vol AVDD Voltage * @return None */ #define __LL_SYSCTRL_AVDD_VOL_Sel(__SYSCTRL__, vol) MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_AVDD_SET_Msk, vol) /** * @brief VDD Voltage Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vol VDD Voltage * @return None */ #define __LL_SYSCTRL_VDD_VOL_Sel(__SYSCTRL__, vol) MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_VDD_SET_Msk, vol) /** * @brief CUR Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CUR_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_CUR_ENABLE_Msk) /** * @brief CUR Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_CUR_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_CUR_ENABLE_Msk) /** * @brief AVDDLDO Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AVDDLDO_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_AVDDLDO_ENABLE_Msk) /** * @brief AVDDLDO Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_AVDDLDO_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_AVDDLDO_ENABLE_Msk) /** * @brief Temperature Sensor Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_TempSensor_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_TEMPSENSOR_ENABLE_Msk) /** * @brief Temperature Sensor Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_TempSensor_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_TEMPSENSOR_ENABLE_Msk) /** * @brief Band Gap Voltage Set * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @param vol Voltage Register Value * @return None */ #define __LL_SYSCTRL_BandGapVol_Set(__SYSCTRL__, vol) \ MODIFY_REG((__SYSCTRL__)->PMUCR, SYSCTRL_BGR_VOL_Msk, ((vol & 0x1fUL) << SYSCTRL_BGR_VOL_Pos)) /** * @brief BGR DRD Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_BGR_DRD_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_BGR_DRD_Msk) /** * @brief BGR DRD Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_BGR_DRD_Dis(__SYSCTRL__) CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_BGR_DRD_Msk) /** * @brief BGR Filter Enable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_BGR_Filter_En(__SYSCTRL__) SET_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_BGR_FILTER_Msk) /** * @brief BGR Filter Disable * @param __SYSCTRL__ Specifies SYSCTRL peripheral * @return None */ #define __LL_SYSCTRL_BGR_Filter_Dis(__SYSCTRL__) \ __LL_SYSCTRL_CtrlREG_OPT(CLEAR_BIT((__SYSCTRL__)->PMUCR, SYSCTRL_BGR_FILTER_Msk)) /** * @brief SYSCTRL CTRL Register Operation * @param expression SYSCTRL CTRL Register Read/Write Operation * @note Only Write Operation need Unlock before Operation * @return None */ #define __LL_SYSCTRL_CtrlREG_OPT(expression) \ do { \ __LL_SYSCTRL_CTRLReg_Unlock(SYSCTRL); \ expression; \ __LL_SYSCTRL_Reg_Lock(SYSCTRL); \ } while(0) /** * @brief SYSCTRL FLS Register Operation * @param expression SYSCTRL FLS Register Read/Write Operation * @note Only Write Operation need Unlock before Operation * @return None */ #define __LL_SYSCTRL_FlsREG_OPT(expression) \ do { \ __LL_SYSCTRL_FLSReg_Unlock(SYSCTRL); \ expression; \ __LL_SYSCTRL_Reg_Lock(SYSCTRL); \ } while(0) /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SYSCTRL_LL_Exported_Types SYSCTRL LL Exported Types * @brief SYSCTRL LL Exported Types * @{ */ /** * @brief SYSCTRL CLK Div Definition */ typedef enum { SYSCTRL_CLK_DIV_IVD = 0,/*!< SYSCTRL CLK DIV IND */ SYSCTRL_CLK_DIV_1, /*!< SYSCTRL CLK DIV 1 */ SYSCTRL_CLK_DIV_2, /*!< SYSCTRL CLK DIV 2 */ SYSCTRL_CLK_DIV_3, /*!< SYSCTRL CLK DIV 3 */ SYSCTRL_CLK_DIV_4, /*!< SYSCTRL CLK DIV 4 */ SYSCTRL_CLK_DIV_5, /*!< SYSCTRL CLK DIV 5 */ SYSCTRL_CLK_DIV_6, /*!< SYSCTRL CLK DIV 6 */ SYSCTRL_CLK_DIV_7, /*!< SYSCTRL CLK DIV 7 */ SYSCTRL_CLK_DIV_8, /*!< SYSCTRL CLK DIV 8 */ SYSCTRL_CLK_DIV_9, /*!< SYSCTRL CLK DIV 9 */ SYSCTRL_CLK_DIV_10, /*!< SYSCTRL CLK DIV 10 */ SYSCTRL_CLK_DIV_11, /*!< SYSCTRL CLK DIV 11 */ SYSCTRL_CLK_DIV_12, /*!< SYSCTRL CLK DIV 12 */ SYSCTRL_CLK_DIV_13, /*!< SYSCTRL CLK DIV 13 */ SYSCTRL_CLK_DIV_14, /*!< SYSCTRL CLK DIV 14 */ SYSCTRL_CLK_DIV_15, /*!< SYSCTRL CLK DIV 15 */ SYSCTRL_CLK_DIV_16, /*!< SYSCTRL CLK DIV 16 */ SYSCTRL_CLK_DIV_17, /*!< SYSCTRL CLK DIV 17 */ SYSCTRL_CLK_DIV_18, /*!< SYSCTRL CLK DIV 18 */ SYSCTRL_CLK_DIV_19, /*!< SYSCTRL CLK DIV 19 */ SYSCTRL_CLK_DIV_20, /*!< SYSCTRL CLK DIV 20 */ SYSCTRL_CLK_DIV_21, /*!< SYSCTRL CLK DIV 21 */ SYSCTRL_CLK_DIV_22, /*!< SYSCTRL CLK DIV 22 */ SYSCTRL_CLK_DIV_23, /*!< SYSCTRL CLK DIV 23 */ SYSCTRL_CLK_DIV_24, /*!< SYSCTRL CLK DIV 24 */ SYSCTRL_CLK_DIV_25, /*!< SYSCTRL CLK DIV 25 */ SYSCTRL_CLK_DIV_26, /*!< SYSCTRL CLK DIV 26 */ SYSCTRL_CLK_DIV_27, /*!< SYSCTRL CLK DIV 27 */ SYSCTRL_CLK_DIV_28, /*!< SYSCTRL CLK DIV 28 */ SYSCTRL_CLK_DIV_29, /*!< SYSCTRL CLK DIV 29 */ SYSCTRL_CLK_DIV_30, /*!< SYSCTRL CLK DIV 30 */ SYSCTRL_CLK_DIV_31, /*!< SYSCTRL CLK DIV 31 */ SYSCTRL_CLK_DIV_32, /*!< SYSCTRL CLK DIV 32 */ SYSCTRL_CLK_DIV_33, /*!< SYSCTRL CLK DIV 33 */ SYSCTRL_CLK_DIV_34, /*!< SYSCTRL CLK DIV 34 */ SYSCTRL_CLK_DIV_35, /*!< SYSCTRL CLK DIV 35 */ SYSCTRL_CLK_DIV_36, /*!< SYSCTRL CLK DIV 36 */ SYSCTRL_CLK_DIV_37, /*!< SYSCTRL CLK DIV 37 */ SYSCTRL_CLK_DIV_38, /*!< SYSCTRL CLK DIV 38 */ SYSCTRL_CLK_DIV_39, /*!< SYSCTRL CLK DIV 39 */ SYSCTRL_CLK_DIV_40, /*!< SYSCTRL CLK DIV 40 */ SYSCTRL_CLK_DIV_41, /*!< SYSCTRL CLK DIV 41 */ SYSCTRL_CLK_DIV_42, /*!< SYSCTRL CLK DIV 42 */ SYSCTRL_CLK_DIV_43, /*!< SYSCTRL CLK DIV 43 */ SYSCTRL_CLK_DIV_44, /*!< SYSCTRL CLK DIV 44 */ SYSCTRL_CLK_DIV_45, /*!< SYSCTRL CLK DIV 45 */ SYSCTRL_CLK_DIV_46, /*!< SYSCTRL CLK DIV 46 */ SYSCTRL_CLK_DIV_47, /*!< SYSCTRL CLK DIV 47 */ SYSCTRL_CLK_DIV_48, /*!< SYSCTRL CLK DIV 48 */ SYSCTRL_CLK_DIV_49, /*!< SYSCTRL CLK DIV 49 */ SYSCTRL_CLK_DIV_50, /*!< SYSCTRL CLK DIV 50 */ SYSCTRL_CLK_DIV_51, /*!< SYSCTRL CLK DIV 51 */ SYSCTRL_CLK_DIV_52, /*!< SYSCTRL CLK DIV 52 */ SYSCTRL_CLK_DIV_53, /*!< SYSCTRL CLK DIV 53 */ SYSCTRL_CLK_DIV_54, /*!< SYSCTRL CLK DIV 54 */ SYSCTRL_CLK_DIV_55, /*!< SYSCTRL CLK DIV 55 */ SYSCTRL_CLK_DIV_56, /*!< SYSCTRL CLK DIV 56 */ SYSCTRL_CLK_DIV_57, /*!< SYSCTRL CLK DIV 57 */ SYSCTRL_CLK_DIV_58, /*!< SYSCTRL CLK DIV 58 */ SYSCTRL_CLK_DIV_59, /*!< SYSCTRL CLK DIV 59 */ SYSCTRL_CLK_DIV_60, /*!< SYSCTRL CLK DIV 60 */ SYSCTRL_CLK_DIV_61, /*!< SYSCTRL CLK DIV 61 */ SYSCTRL_CLK_DIV_62, /*!< SYSCTRL CLK DIV 62 */ SYSCTRL_CLK_DIV_63, /*!< SYSCTRL CLK DIV 63 */ SYSCTRL_CLK_DIV_64, /*!< SYSCTRL CLK DIV 64 */ SYSCTRL_CLK_DIV_65, /*!< SYSCTRL CLK DIV 65 */ SYSCTRL_CLK_DIV_66, /*!< SYSCTRL CLK DIV 66 */ SYSCTRL_CLK_DIV_67, /*!< SYSCTRL CLK DIV 67 */ SYSCTRL_CLK_DIV_68, /*!< SYSCTRL CLK DIV 68 */ SYSCTRL_CLK_DIV_69, /*!< SYSCTRL CLK DIV 69 */ SYSCTRL_CLK_DIV_70, /*!< SYSCTRL CLK DIV 70 */ SYSCTRL_CLK_DIV_71, /*!< SYSCTRL CLK DIV 71 */ SYSCTRL_CLK_DIV_72, /*!< SYSCTRL CLK DIV 72 */ SYSCTRL_CLK_DIV_73, /*!< SYSCTRL CLK DIV 73 */ SYSCTRL_CLK_DIV_74, /*!< SYSCTRL CLK DIV 74 */ SYSCTRL_CLK_DIV_75, /*!< SYSCTRL CLK DIV 75 */ SYSCTRL_CLK_DIV_76, /*!< SYSCTRL CLK DIV 76 */ SYSCTRL_CLK_DIV_77, /*!< SYSCTRL CLK DIV 77 */ SYSCTRL_CLK_DIV_78, /*!< SYSCTRL CLK DIV 78 */ SYSCTRL_CLK_DIV_79, /*!< SYSCTRL CLK DIV 79 */ SYSCTRL_CLK_DIV_80, /*!< SYSCTRL CLK DIV 80 */ SYSCTRL_CLK_DIV_81, /*!< SYSCTRL CLK DIV 81 */ SYSCTRL_CLK_DIV_82, /*!< SYSCTRL CLK DIV 82 */ SYSCTRL_CLK_DIV_83, /*!< SYSCTRL CLK DIV 83 */ SYSCTRL_CLK_DIV_84, /*!< SYSCTRL CLK DIV 84 */ SYSCTRL_CLK_DIV_85, /*!< SYSCTRL CLK DIV 85 */ SYSCTRL_CLK_DIV_86, /*!< SYSCTRL CLK DIV 86 */ SYSCTRL_CLK_DIV_87, /*!< SYSCTRL CLK DIV 87 */ SYSCTRL_CLK_DIV_88, /*!< SYSCTRL CLK DIV 88 */ SYSCTRL_CLK_DIV_89, /*!< SYSCTRL CLK DIV 89 */ SYSCTRL_CLK_DIV_90, /*!< SYSCTRL CLK DIV 90 */ SYSCTRL_CLK_DIV_91, /*!< SYSCTRL CLK DIV 91 */ SYSCTRL_CLK_DIV_92, /*!< SYSCTRL CLK DIV 92 */ SYSCTRL_CLK_DIV_93, /*!< SYSCTRL CLK DIV 93 */ SYSCTRL_CLK_DIV_94, /*!< SYSCTRL CLK DIV 94 */ SYSCTRL_CLK_DIV_95, /*!< SYSCTRL CLK DIV 95 */ SYSCTRL_CLK_DIV_96, /*!< SYSCTRL CLK DIV 96 */ SYSCTRL_CLK_DIV_97, /*!< SYSCTRL CLK DIV 97 */ SYSCTRL_CLK_DIV_98, /*!< SYSCTRL CLK DIV 98 */ SYSCTRL_CLK_DIV_99, /*!< SYSCTRL CLK DIV 99 */ SYSCTRL_CLK_DIV_100, /*!< SYSCTRL CLK DIV 100 */ SYSCTRL_CLK_DIV_101, /*!< SYSCTRL CLK DIV 101 */ SYSCTRL_CLK_DIV_102, /*!< SYSCTRL CLK DIV 102 */ SYSCTRL_CLK_DIV_103, /*!< SYSCTRL CLK DIV 103 */ SYSCTRL_CLK_DIV_104, /*!< SYSCTRL CLK DIV 104 */ SYSCTRL_CLK_DIV_105, /*!< SYSCTRL CLK DIV 105 */ SYSCTRL_CLK_DIV_106, /*!< SYSCTRL CLK DIV 106 */ SYSCTRL_CLK_DIV_107, /*!< SYSCTRL CLK DIV 107 */ SYSCTRL_CLK_DIV_108, /*!< SYSCTRL CLK DIV 108 */ SYSCTRL_CLK_DIV_109, /*!< SYSCTRL CLK DIV 109 */ SYSCTRL_CLK_DIV_110, /*!< SYSCTRL CLK DIV 110 */ SYSCTRL_CLK_DIV_111, /*!< SYSCTRL CLK DIV 111 */ SYSCTRL_CLK_DIV_112, /*!< SYSCTRL CLK DIV 112 */ SYSCTRL_CLK_DIV_113, /*!< SYSCTRL CLK DIV 113 */ SYSCTRL_CLK_DIV_114, /*!< SYSCTRL CLK DIV 114 */ SYSCTRL_CLK_DIV_115, /*!< SYSCTRL CLK DIV 115 */ SYSCTRL_CLK_DIV_116, /*!< SYSCTRL CLK DIV 116 */ SYSCTRL_CLK_DIV_117, /*!< SYSCTRL CLK DIV 117 */ SYSCTRL_CLK_DIV_118, /*!< SYSCTRL CLK DIV 118 */ SYSCTRL_CLK_DIV_119, /*!< SYSCTRL CLK DIV 119 */ SYSCTRL_CLK_DIV_120, /*!< SYSCTRL CLK DIV 120 */ SYSCTRL_CLK_DIV_121, /*!< SYSCTRL CLK DIV 121 */ SYSCTRL_CLK_DIV_122, /*!< SYSCTRL CLK DIV 122 */ SYSCTRL_CLK_DIV_123, /*!< SYSCTRL CLK DIV 123 */ SYSCTRL_CLK_DIV_124, /*!< SYSCTRL CLK DIV 124 */ SYSCTRL_CLK_DIV_125, /*!< SYSCTRL CLK DIV 125 */ SYSCTRL_CLK_DIV_126, /*!< SYSCTRL CLK DIV 126 */ SYSCTRL_CLK_DIV_127, /*!< SYSCTRL CLK DIV 127 */ SYSCTRL_CLK_DIV_128, /*!< SYSCTRL CLK DIV 128 */ SYSCTRL_CLK_DIV_129, /*!< SYSCTRL CLK DIV 129 */ SYSCTRL_CLK_DIV_130, /*!< SYSCTRL CLK DIV 130 */ SYSCTRL_CLK_DIV_131, /*!< SYSCTRL CLK DIV 131 */ SYSCTRL_CLK_DIV_132, /*!< SYSCTRL CLK DIV 132 */ SYSCTRL_CLK_DIV_133, /*!< SYSCTRL CLK DIV 133 */ SYSCTRL_CLK_DIV_134, /*!< SYSCTRL CLK DIV 134 */ SYSCTRL_CLK_DIV_135, /*!< SYSCTRL CLK DIV 135 */ SYSCTRL_CLK_DIV_136, /*!< SYSCTRL CLK DIV 136 */ SYSCTRL_CLK_DIV_137, /*!< SYSCTRL CLK DIV 137 */ SYSCTRL_CLK_DIV_138, /*!< SYSCTRL CLK DIV 138 */ SYSCTRL_CLK_DIV_139, /*!< SYSCTRL CLK DIV 139 */ SYSCTRL_CLK_DIV_140, /*!< SYSCTRL CLK DIV 140 */ SYSCTRL_CLK_DIV_141, /*!< SYSCTRL CLK DIV 141 */ SYSCTRL_CLK_DIV_142, /*!< SYSCTRL CLK DIV 142 */ SYSCTRL_CLK_DIV_143, /*!< SYSCTRL CLK DIV 143 */ SYSCTRL_CLK_DIV_144, /*!< SYSCTRL CLK DIV 144 */ SYSCTRL_CLK_DIV_145, /*!< SYSCTRL CLK DIV 145 */ SYSCTRL_CLK_DIV_146, /*!< SYSCTRL CLK DIV 146 */ SYSCTRL_CLK_DIV_147, /*!< SYSCTRL CLK DIV 147 */ SYSCTRL_CLK_DIV_148, /*!< SYSCTRL CLK DIV 148 */ SYSCTRL_CLK_DIV_149, /*!< SYSCTRL CLK DIV 149 */ SYSCTRL_CLK_DIV_150, /*!< SYSCTRL CLK DIV 150 */ SYSCTRL_CLK_DIV_151, /*!< SYSCTRL CLK DIV 151 */ SYSCTRL_CLK_DIV_152, /*!< SYSCTRL CLK DIV 152 */ SYSCTRL_CLK_DIV_153, /*!< SYSCTRL CLK DIV 153 */ SYSCTRL_CLK_DIV_154, /*!< SYSCTRL CLK DIV 154 */ SYSCTRL_CLK_DIV_155, /*!< SYSCTRL CLK DIV 155 */ SYSCTRL_CLK_DIV_156, /*!< SYSCTRL CLK DIV 156 */ SYSCTRL_CLK_DIV_157, /*!< SYSCTRL CLK DIV 157 */ SYSCTRL_CLK_DIV_158, /*!< SYSCTRL CLK DIV 158 */ SYSCTRL_CLK_DIV_159, /*!< SYSCTRL CLK DIV 159 */ SYSCTRL_CLK_DIV_160, /*!< SYSCTRL CLK DIV 160 */ SYSCTRL_CLK_DIV_161, /*!< SYSCTRL CLK DIV 161 */ SYSCTRL_CLK_DIV_162, /*!< SYSCTRL CLK DIV 162 */ SYSCTRL_CLK_DIV_163, /*!< SYSCTRL CLK DIV 163 */ SYSCTRL_CLK_DIV_164, /*!< SYSCTRL CLK DIV 164 */ SYSCTRL_CLK_DIV_165, /*!< SYSCTRL CLK DIV 165 */ SYSCTRL_CLK_DIV_166, /*!< SYSCTRL CLK DIV 166 */ SYSCTRL_CLK_DIV_167, /*!< SYSCTRL CLK DIV 167 */ SYSCTRL_CLK_DIV_168, /*!< SYSCTRL CLK DIV 168 */ SYSCTRL_CLK_DIV_169, /*!< SYSCTRL CLK DIV 169 */ SYSCTRL_CLK_DIV_170, /*!< SYSCTRL CLK DIV 170 */ SYSCTRL_CLK_DIV_171, /*!< SYSCTRL CLK DIV 171 */ SYSCTRL_CLK_DIV_172, /*!< SYSCTRL CLK DIV 172 */ SYSCTRL_CLK_DIV_173, /*!< SYSCTRL CLK DIV 173 */ SYSCTRL_CLK_DIV_174, /*!< SYSCTRL CLK DIV 174 */ SYSCTRL_CLK_DIV_175, /*!< SYSCTRL CLK DIV 175 */ SYSCTRL_CLK_DIV_176, /*!< SYSCTRL CLK DIV 176 */ SYSCTRL_CLK_DIV_177, /*!< SYSCTRL CLK DIV 177 */ SYSCTRL_CLK_DIV_178, /*!< SYSCTRL CLK DIV 178 */ SYSCTRL_CLK_DIV_179, /*!< SYSCTRL CLK DIV 179 */ SYSCTRL_CLK_DIV_180, /*!< SYSCTRL CLK DIV 180 */ SYSCTRL_CLK_DIV_181, /*!< SYSCTRL CLK DIV 181 */ SYSCTRL_CLK_DIV_182, /*!< SYSCTRL CLK DIV 182 */ SYSCTRL_CLK_DIV_183, /*!< SYSCTRL CLK DIV 183 */ SYSCTRL_CLK_DIV_184, /*!< SYSCTRL CLK DIV 184 */ SYSCTRL_CLK_DIV_185, /*!< SYSCTRL CLK DIV 185 */ SYSCTRL_CLK_DIV_186, /*!< SYSCTRL CLK DIV 186 */ SYSCTRL_CLK_DIV_187, /*!< SYSCTRL CLK DIV 187 */ SYSCTRL_CLK_DIV_188, /*!< SYSCTRL CLK DIV 188 */ SYSCTRL_CLK_DIV_189, /*!< SYSCTRL CLK DIV 189 */ SYSCTRL_CLK_DIV_190, /*!< SYSCTRL CLK DIV 190 */ SYSCTRL_CLK_DIV_191, /*!< SYSCTRL CLK DIV 191 */ SYSCTRL_CLK_DIV_192, /*!< SYSCTRL CLK DIV 192 */ SYSCTRL_CLK_DIV_193, /*!< SYSCTRL CLK DIV 193 */ SYSCTRL_CLK_DIV_194, /*!< SYSCTRL CLK DIV 194 */ SYSCTRL_CLK_DIV_195, /*!< SYSCTRL CLK DIV 195 */ SYSCTRL_CLK_DIV_196, /*!< SYSCTRL CLK DIV 196 */ SYSCTRL_CLK_DIV_197, /*!< SYSCTRL CLK DIV 197 */ SYSCTRL_CLK_DIV_198, /*!< SYSCTRL CLK DIV 198 */ SYSCTRL_CLK_DIV_199, /*!< SYSCTRL CLK DIV 199 */ SYSCTRL_CLK_DIV_200, /*!< SYSCTRL CLK DIV 200 */ SYSCTRL_CLK_DIV_201, /*!< SYSCTRL CLK DIV 201 */ SYSCTRL_CLK_DIV_202, /*!< SYSCTRL CLK DIV 202 */ SYSCTRL_CLK_DIV_203, /*!< SYSCTRL CLK DIV 203 */ SYSCTRL_CLK_DIV_204, /*!< SYSCTRL CLK DIV 204 */ SYSCTRL_CLK_DIV_205, /*!< SYSCTRL CLK DIV 205 */ SYSCTRL_CLK_DIV_206, /*!< SYSCTRL CLK DIV 206 */ SYSCTRL_CLK_DIV_207, /*!< SYSCTRL CLK DIV 207 */ SYSCTRL_CLK_DIV_208, /*!< SYSCTRL CLK DIV 208 */ SYSCTRL_CLK_DIV_209, /*!< SYSCTRL CLK DIV 209 */ SYSCTRL_CLK_DIV_210, /*!< SYSCTRL CLK DIV 210 */ SYSCTRL_CLK_DIV_211, /*!< SYSCTRL CLK DIV 211 */ SYSCTRL_CLK_DIV_212, /*!< SYSCTRL CLK DIV 212 */ SYSCTRL_CLK_DIV_213, /*!< SYSCTRL CLK DIV 213 */ SYSCTRL_CLK_DIV_214, /*!< SYSCTRL CLK DIV 214 */ SYSCTRL_CLK_DIV_215, /*!< SYSCTRL CLK DIV 215 */ SYSCTRL_CLK_DIV_216, /*!< SYSCTRL CLK DIV 216 */ SYSCTRL_CLK_DIV_217, /*!< SYSCTRL CLK DIV 217 */ SYSCTRL_CLK_DIV_218, /*!< SYSCTRL CLK DIV 218 */ SYSCTRL_CLK_DIV_219, /*!< SYSCTRL CLK DIV 219 */ SYSCTRL_CLK_DIV_220, /*!< SYSCTRL CLK DIV 220 */ SYSCTRL_CLK_DIV_221, /*!< SYSCTRL CLK DIV 221 */ SYSCTRL_CLK_DIV_222, /*!< SYSCTRL CLK DIV 222 */ SYSCTRL_CLK_DIV_223, /*!< SYSCTRL CLK DIV 223 */ SYSCTRL_CLK_DIV_224, /*!< SYSCTRL CLK DIV 224 */ SYSCTRL_CLK_DIV_225, /*!< SYSCTRL CLK DIV 225 */ SYSCTRL_CLK_DIV_226, /*!< SYSCTRL CLK DIV 226 */ SYSCTRL_CLK_DIV_227, /*!< SYSCTRL CLK DIV 227 */ SYSCTRL_CLK_DIV_228, /*!< SYSCTRL CLK DIV 228 */ SYSCTRL_CLK_DIV_229, /*!< SYSCTRL CLK DIV 229 */ SYSCTRL_CLK_DIV_230, /*!< SYSCTRL CLK DIV 230 */ SYSCTRL_CLK_DIV_231, /*!< SYSCTRL CLK DIV 231 */ SYSCTRL_CLK_DIV_232, /*!< SYSCTRL CLK DIV 232 */ SYSCTRL_CLK_DIV_233, /*!< SYSCTRL CLK DIV 233 */ SYSCTRL_CLK_DIV_234, /*!< SYSCTRL CLK DIV 234 */ SYSCTRL_CLK_DIV_235, /*!< SYSCTRL CLK DIV 235 */ SYSCTRL_CLK_DIV_236, /*!< SYSCTRL CLK DIV 236 */ SYSCTRL_CLK_DIV_237, /*!< SYSCTRL CLK DIV 237 */ SYSCTRL_CLK_DIV_238, /*!< SYSCTRL CLK DIV 238 */ SYSCTRL_CLK_DIV_239, /*!< SYSCTRL CLK DIV 239 */ SYSCTRL_CLK_DIV_240, /*!< SYSCTRL CLK DIV 240 */ SYSCTRL_CLK_DIV_241, /*!< SYSCTRL CLK DIV 241 */ SYSCTRL_CLK_DIV_242, /*!< SYSCTRL CLK DIV 242 */ SYSCTRL_CLK_DIV_243, /*!< SYSCTRL CLK DIV 243 */ SYSCTRL_CLK_DIV_244, /*!< SYSCTRL CLK DIV 244 */ SYSCTRL_CLK_DIV_245, /*!< SYSCTRL CLK DIV 245 */ SYSCTRL_CLK_DIV_246, /*!< SYSCTRL CLK DIV 246 */ SYSCTRL_CLK_DIV_247, /*!< SYSCTRL CLK DIV 247 */ SYSCTRL_CLK_DIV_248, /*!< SYSCTRL CLK DIV 248 */ SYSCTRL_CLK_DIV_249, /*!< SYSCTRL CLK DIV 249 */ SYSCTRL_CLK_DIV_250, /*!< SYSCTRL CLK DIV 250 */ SYSCTRL_CLK_DIV_251, /*!< SYSCTRL CLK DIV 251 */ SYSCTRL_CLK_DIV_252, /*!< SYSCTRL CLK DIV 252 */ SYSCTRL_CLK_DIV_253, /*!< SYSCTRL CLK DIV 253 */ SYSCTRL_CLK_DIV_254, /*!< SYSCTRL CLK DIV 254 */ SYSCTRL_CLK_DIV_255, /*!< SYSCTRL CLK DIV 255 */ SYSCTRL_CLK_DIV_256, /*!< SYSCTRL CLK DIV 256 */ } SYSCTRL_ClkDivETypeDef; /** * @brief SYSCTRL SYSCLK Source Definition */ typedef enum { SYSCLK_SRC_RC32K = 0, /*!< SYSCLK Source RC32K */ SYSCLK_SRC_RC8M = 1, /*!< SYSCLK Source RC8M */ SYSCLK_SRC_PLL0DivClk = 2, /*!< SYSCLK Source PLL0 Div Clk */ SYSCLK_SRC_HOSC = 3, /*!< SYSCLK Source HOSC */ } SYSCTRL_SysclkSrcETypeDef; /** * @brief SYSCTRL GPIOA Debounce Clock Source Definition */ typedef enum { GPIOA_DBC_CLK_SRC_RC8M = SYSCTRL_GPIOA_DBCCLK_SRC_RC8M, /*!< GPIOA DBC CLK Source RC8M */ GPIOA_DBC_CLK_SRC_XOSC = SYSCTRL_GPIOA_DBCCLK_SRC_XOSC, /*!< GPIOA DBC CLK Source XOSC */ GPIOA_DBC_CLK_SRC_SYSCLK = SYSCTRL_GPIOA_DBCCLK_SRC_SYSCLK, /*!< GPIOA DBC CLK Source SYSCLK */ GPIOA_DBC_CLK_SRC_RC32K = SYSCTRL_GPIOA_DBCCLK_SRC_RC32K, /*!< GPIOA DBC CLK Source RC32K */ } SYSCTRL_GPIOADbcClkSrcETypeDef; /** * @brief SYSCTRL GPIOB Debounce Clock Source Definition */ typedef enum { GPIOB_DBC_CLK_SRC_RC8M = SYSCTRL_GPIOB_DBCCLK_SRC_RC8M, /*!< GPIOB DBC CLK Source RC8M */ GPIOB_DBC_CLK_SRC_XOSC = SYSCTRL_GPIOB_DBCCLK_SRC_XOSC, /*!< GPIOB DBC CLK Source XOSC */ GPIOB_DBC_CLK_SRC_SYSCLK = SYSCTRL_GPIOB_DBCCLK_SRC_SYSCLK, /*!< GPIOB DBC CLK Source SYSCLK */ GPIOB_DBC_CLK_SRC_RC32K = SYSCTRL_GPIOB_DBCCLK_SRC_RC32K, /*!< GPIOB DBC CLK Source RC32K */ } SYSCTRL_GPIOBDbcClkSrcETypeDef; /** * @brief SYSCTRL GPIOC Debounce Clock Source Definition */ typedef enum { GPIOC_DBC_CLK_SRC_RC8M = SYSCTRL_GPIOC_DBCCLK_SRC_RC8M, /*!< GPIOC DBC CLK Source RC8M */ GPIOC_DBC_CLK_SRC_XOSC = SYSCTRL_GPIOC_DBCCLK_SRC_XOSC, /*!< GPIOC DBC CLK Source XOSC */ GPIOC_DBC_CLK_SRC_SYSCLK = SYSCTRL_GPIOC_DBCCLK_SRC_SYSCLK, /*!< GPIOC DBC CLK Source SYSCLK */ GPIOC_DBC_CLK_SRC_RC32K = SYSCTRL_GPIOC_DBCCLK_SRC_RC32K, /*!< GPIOC DBC CLK Source RC32K */ } SYSCTRL_GPIOCDbcClkSrcETypeDef; /** * @brief SYSCTRL GPIOD Debounce Clock Source Definition */ typedef enum { GPIOD_DBC_CLK_SRC_RC8M = SYSCTRL_GPIOD_DBCCLK_SRC_RC8M, /*!< GPIOD DBC CLK Source RC8M */ GPIOD_DBC_CLK_SRC_XOSC = SYSCTRL_GPIOD_DBCCLK_SRC_XOSC, /*!< GPIOD DBC CLK Source XOSC */ GPIOD_DBC_CLK_SRC_SYSCLK = SYSCTRL_GPIOD_DBCCLK_SRC_SYSCLK, /*!< GPIOD DBC CLK Source SYSCLK */ GPIOD_DBC_CLK_SRC_RC32K = SYSCTRL_GPIOD_DBCCLK_SRC_RC32K, /*!< GPIOD DBC CLK Source RC32K */ } SYSCTRL_GPIODDbcClkSrcETypeDef; /** * @brief SYSCTRL Dflash Clock Source Definition */ typedef enum { DFLASH_CLK_SRC_RC8M = SYSCTRL_DFLASH_MEMCLK_SRC_RC8M, /*!< Dflash CLK Source RC8M */ DFLASH_CLK_SRC_PLL0DivClk = SYSCTRL_DFLASH_MEMCLK_SRC_PLL0DivClk, /*!< Dflash CLK Source PLL0 Div Clk */ DFLASH_CLK_SRC_PLL1DivClk = SYSCTRL_DFLASH_MEMCLK_SRC_PLL1DivClk, /*!< Dflash CLK Source PLL1 Div Clk */ DFLASH_CLK_SRC_PLL2DivClk = SYSCTRL_DFLASH_MEMCLK_SRC_PLL2DivClk, /*!< Dflash CLK Source PLL2 Div Clk */ } SYSCTRL_DflashClkSrcETypeDef; /** * @brief SYSCTRL Eflash Clock Source Definition */ typedef enum { EFLASH_CLK_SRC_RC8M = SYSCTRL_EFLASH_MEMCLK_SRC_RC8M, /*!< Eflash CLK Source RC8M */ EFLASH_CLK_SRC_PLL0DivClk = SYSCTRL_EFLASH_MEMCLK_SRC_PLL0DivClk, /*!< Eflash CLK Source PLL0 Div Clk */ EFLASH_CLK_SRC_PLL1DivClk = SYSCTRL_EFLASH_MEMCLK_SRC_PLL1DivClk, /*!< Eflash CLK Source PLL1 Div Clk */ EFLASH_CLK_SRC_PLL2DivClk = SYSCTRL_EFLASH_MEMCLK_SRC_PLL2DivClk, /*!< Eflash CLK Source PLL2 Div Clk */ } SYSCTRL_EflashClkSrcETypeDef; /** * @brief SYSCTRL ADC Function Clock Source Definition */ typedef enum { ADC_FUNC_CLK_SRC_RC8M = SYSCTRL_ADC_FUNCLK_SRC_RC8M, /*!< ADC Function CLK Source RC8M */ ADC_FUNC_CLK_SRC_HOSC = SYSCTRL_ADC_FUNCLK_SRC_HOSC, /*!< ADC Function CLK Source HOSC */ ADC_FUNC_CLK_SRC_PLL0 = SYSCTRL_ADC_FUNCLK_SRC_PLL0, /*!< ADC Function CLK Source PLL0 */ ADC_FUNC_CLK_SRC_PLL1 = SYSCTRL_ADC_FUNCLK_SRC_PLL1, /*!< ADC Function CLK Source PLL1 */ } SYSCTRL_ADCFuncClkSrcETypeDef; /** * @brief SYSCTRL HRPWM Function Clock Source Definition */ typedef enum { HRPWM_FUNC_CLK_SRC_RC8M = SYSCTRL_HRPWM_FUNCLK_SRC_RC8M, /*!< HRPWM Function CLK Source RC8M */ HRPWM_FUNC_CLK_SRC_HOSC = SYSCTRL_HRPWM_FUNCLK_SRC_HOSC, /*!< HRPWM Function CLK Source HOSC */ HRPWM_FUNC_CLK_SRC_PLL0 = SYSCTRL_HRPWM_FUNCLK_SRC_PLL0, /*!< HRPWM Function CLK Source PLL0 */ HRPWM_FUNC_CLK_SRC_PLL1 = SYSCTRL_HRPWM_FUNCLK_SRC_PLL1, /*!< HRPWM Function CLK Source PLL1 */ } SYSCTRL_HRPWMFuncClkSrcETypeDef; /** * @brief SYSCTRL PLLCLK Source Definition */ typedef enum { PLLCLK_SRC_XOSC = 0, /*!< PLLCLK Source XOSC */ PLLCLK_SRC_RC8M = 1, /*!< PLLCLK Source RC8M */ PLLCLK_SRC_DFT = 3, /*!< PLLCLK Source DFT */ } SYSCTRL_PllClkSrcETypeDef; /** * @brief SYSCTRL SYSCLK Config Definition */ typedef struct __SYSCTRL_SysclkUserCfgTypeDef { SYSCTRL_SysclkSrcETypeDef sysclk_src; /*!< SYSCLK Source */ SYSCTRL_PllClkSrcETypeDef pll0clk_src; /*!< PLLCLK Source */ uint32_t sysclk_src_freq; /*!< SYSCLK Source Freq */ uint32_t pll0clk_src_freq; /*!< PLLCLK Source Freq */ uint32_t sysclk_freq; /*!< SYSCLK Freq */ SYSCTRL_ClkDivETypeDef apb0_clk_div; /*!< APB0 clock Div */ SYSCTRL_ClkDivETypeDef apb1_clk_div; /*!< APB1 clock Div */ } SYSCTRL_SysclkUserCfgTypeDef; /** * @brief SYSCTRL PLL1/2 Config Definition */ typedef struct __SYSCTRL_PLLUserCfgTypeDef { SYSCTRL_PllClkSrcETypeDef pll_clk_src; /*!< PLLCLK Source */ uint32_t pll_in_freq; /*!< PLLCLK Input Freq */ uint32_t pll_user_freq; /*!< PLLCLK User Freq */ } SYSCTRL_PLLUserCfgTypeDef; /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup SYSCTRL_LL_Exported_Functions SYSCTRL LL Exported Functions * @brief SYSCTRL LL Exported Functions * @{ */ /** @addtogroup SYSCTRL_LL_Exported_Functions_Group1 * @{ */ LL_StatusETypeDef LL_SYSCTRL_SysclkInit(SYSCTRL_TypeDef *Instance, SYSCTRL_SysclkUserCfgTypeDef *sysclk_cfg); LL_StatusETypeDef LL_SYSCTRL_GPIOA_DbcClkCfg(SYSCTRL_GPIOADbcClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_GPIOB_DbcClkCfg(SYSCTRL_GPIOBDbcClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_GPIOC_DbcClkCfg(SYSCTRL_GPIOCDbcClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_GPIOD_DbcClkCfg(SYSCTRL_GPIODDbcClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_DFLASH_ClkCfg(SYSCTRL_DflashClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_EFLASH_ClkCfg(SYSCTRL_EflashClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_ADC_FuncClkCfg(SYSCTRL_ADCFuncClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); LL_StatusETypeDef LL_SYSCTRL_HRPWM_FuncClkCfg(SYSCTRL_HRPWMFuncClkSrcETypeDef src, SYSCTRL_ClkDivETypeDef div); uint32_t LL_SYSCTRL_SysclkGet(void); uint32_t LL_SYSCTRL_AHBClkGet(void); uint32_t LL_SYSCTRL_APB0ClkGet(void); uint32_t LL_SYSCTRL_APB1ClkGet(void); /** * @} */ /** @addtogroup SYSCTRL_LL_Exported_Functions_Group2 * @{ */ LL_StatusETypeDef LL_SYSCTRL_Pll0Cfg(SYSCTRL_TypeDef *Instance, SYSCTRL_PLLUserCfgTypeDef *pll0_cfg); LL_StatusETypeDef LL_SYSCTRL_Pll1Cfg(SYSCTRL_TypeDef *Instance, SYSCTRL_PLLUserCfgTypeDef *pll1_cfg); LL_StatusETypeDef LL_SYSCTRL_Pll2Cfg(SYSCTRL_TypeDef *Instance, SYSCTRL_PLLUserCfgTypeDef *pll2_cfg); /** * @} */ /** @addtogroup SYSCTRL_LL_Exported_Functions_Group3 * @{ */ void LL_SYSCTRL_LSTMR_ClkEnRstRelease(void); void LL_SYSCTRL_LSTMR_ClkDisRstAssert(void); void LL_SYSCTRL_UART1_ClkEnRstRelease(void); void LL_SYSCTRL_UART1_ClkDisRstAssert(void); void LL_SYSCTRL_UART0_ClkEnRstRelease(void); void LL_SYSCTRL_UART0_ClkDisRstAssert(void); void LL_SYSCTRL_I2C1_ClkEnRstRelease(void); void LL_SYSCTRL_I2C1_ClkDisRstAssert(void); void LL_SYSCTRL_I2C0_ClkEnRstRelease(void); void LL_SYSCTRL_I2C0_ClkDisRstAssert(void); void LL_SYSCTRL_ECU_ClkEnRstRelease(void); void LL_SYSCTRL_ECU_ClkDisRstAssert(void); void LL_SYSCTRL_IIR4_ClkEnRstRelease(void); void LL_SYSCTRL_IIR4_ClkDisRstAssert(void); void LL_SYSCTRL_IIR3_ClkEnRstRelease(void); void LL_SYSCTRL_IIR3_ClkDisRstAssert(void); void LL_SYSCTRL_IIR2_ClkEnRstRelease(void); void LL_SYSCTRL_IIR2_ClkDisRstAssert(void); void LL_SYSCTRL_IIR1_ClkEnRstRelease(void); void LL_SYSCTRL_IIR1_ClkDisRstAssert(void); void LL_SYSCTRL_IIR0_ClkEnRstRelease(void); void LL_SYSCTRL_IIR0_ClkDisRstAssert(void); void LL_SYSCTRL_DALI_ClkEnRstRelease(void); void LL_SYSCTRL_DALI_ClkDisRstAssert(void); void LL_SYSCTRL_FPLL2_RstRelease(void); void LL_SYSCTRL_FPLL2_RstAssert(void); void LL_SYSCTRL_FPLL1_RstRelease(void); void LL_SYSCTRL_FPLL1_RstAssert(void); void LL_SYSCTRL_FPLL0_RstRelease(void); void LL_SYSCTRL_FPLL0_RstAssert(void); void LL_SYSCTRL_USB_ClkEnRstRelease(void); void LL_SYSCTRL_USB_ClkDisRstAssert(void); void LL_SYSCTRL_DFLASH_ClkEnRstRelease(void); void LL_SYSCTRL_DFLASH_ClkDisRstAssert(void); void LL_SYSCTRL_EFLASH_ClkEnRstRelease(void); void LL_SYSCTRL_EFLASH_ClkDisRstAssert(void); void LL_SYSCTRL_HRPWM_ClkEnRstRelease(void); void LL_SYSCTRL_HRPWM_ClkDisRstAssert(void); void LL_SYSCTRL_ADC_ClkEnRstRelease(void); void LL_SYSCTRL_ADC_ClkDisRstAssert(void); void LL_SYSCTRL_DAC_ClkEnRstRelease(void); void LL_SYSCTRL_DAC_ClkDisRstAssert(void); void LL_SYSCTRL_CMP_ClkEnRstRelease(void); void LL_SYSCTRL_CMP_ClkDisRstAssert(void); void LL_SYSCTRL_GPIOD_ClkEnRstRelease(void); void LL_SYSCTRL_GPIOD_ClkDisRstAssert(void); void LL_SYSCTRL_GPIOC_ClkEnRstRelease(void); void LL_SYSCTRL_GPIOC_ClkDisRstAssert(void); void LL_SYSCTRL_GPIOB_ClkEnRstRelease(void); void LL_SYSCTRL_GPIOB_ClkDisRstAssert(void); void LL_SYSCTRL_GPIOA_ClkEnRstRelease(void); void LL_SYSCTRL_GPIOA_ClkDisRstAssert(void); void LL_SYSCTRL_HSTMR_ClkEnRstRelease(void); void LL_SYSCTRL_HSTMR_ClkDisRstAssert(void); void LL_SYSCTRL_CAN_ClkEnRstRelease(void); void LL_SYSCTRL_CAN_ClkDisRstAssert(void); void LL_SYSCTRL_DMA_ClkEnRstRelease(void); void LL_SYSCTRL_DMA_ClkDisRstAssert(void); void LL_SYSCTRL_AllPeriphRstAssert(void); void LL_SYSCTRL_AllPeriphRstRelease(void); /** * @} */ /** @addtogroup SYSCTRL_LL_Exported_Functions_Group4 * @{ */ void LL_SYSCTRL_PMUCfg(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _TAE32F53XX_LL_SYSCTRL_H_ */ /************************* (C) COPYRIGHT Tai-Action *****END OF FILE***********/
53,908
348
{"nom":"Aumeville-Lestre","dpt":"Manche","inscrits":96,"abs":18,"votants":78,"blancs":9,"nuls":2,"exp":67,"res":[{"panneau":"2","voix":36},{"panneau":"1","voix":31}]}
72
513
<reponame>dumpmemory/state-spaces<gh_stars>100-1000 """ The core RNN cell architecture of the HiPPO-RNN from the original HiPPO paper. """ import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np from scipy import signal from scipy import linalg as la from src.models.sequence.rnns.cells.basic import RNNCell from src.models.nn.components import LinearActivation, Activation # , get_initializer from src.models.nn.gate import Gate forward_aliases = ['euler', 'forward_euler', 'forward', 'forward_diff'] backward_aliases = ['backward', 'backward_diff', 'backward_euler'] bilinear_aliases = ['bilinear', 'tustin', 'trapezoidal', 'trapezoid'] zoh_aliases = ['zoh'] class MemoryCell(RNNCell): """ This class handles the general architectural wiring of the HiPPO-RNN, in particular the interaction between the hidden state and the linear memory state. Specific variants can be instantiated by subclassing this with an appropriately defined update_memory() method. """ name = None valid_keys = ['<KEY> 'uh', 'um', 'hxm', 'hx', 'hm', 'hh', 'bias', ] @property def default_initializers(self): return { 'uxh': 'uniform', 'hxm': 'xavier', 'um': 'zero', 'hh': 'xavier', } @property def default_architecture(self): return { 'ux': True, 'hx': True, 'hm': True, 'hh': False, 'bias': True, } def __init__( self, d_input, d_model, memory_size, memory_order, memory_activation='id', gate='G', # 'N' | 'G' | UR' **kwargs ): self.memory_size = memory_size self.memory_order = memory_order self.memory_activation = memory_activation self.gate = gate super(MemoryCell, self).__init__(d_input, d_model, **kwargs) self.input_to_d_model = self.d_input if self.architecture['hx'] else 0 self.input_to_memory_size = self.d_input if self.architecture['ux'] else 0 # Hidden to memory self.W_uxh = LinearActivation( self.input_to_memory_size + self.d_model, self.memory_size, bias=self.architecture['bias'], initializer=self.initializers['uxh'], activation=self.memory_activation, activate=True, ) self.memory_to_d_model = self.memory_size * self.memory_order if self.architecture['hm'] else 0 # Memory to hidden self.W_hxm = LinearActivation( self.input_to_d_model + self.memory_to_d_model, self.d_model, self.architecture['bias'], initializer=self.initializers['hxm'], activation=self.hidden_activation, activate=False, ) if self.architecture['hh']: self.reset_hidden_to_hidden() else: self.W_hh = None # Construct gate with options if self.gate is not None: preact_ctor = LinearActivation preact_args = [ self.input_to_d_model + self.memory_to_d_model, self.d_model, self.architecture['bias'], ] if self.architecture['hh']: print("input to hidden size, memory to hidden size, hidden size:", self.input_to_d_model, self.memory_to_d_model, self.d_model) preact_args[0] += self.d_model self.W_gxm = Gate(self.d_model, preact_ctor, preact_args, mechanism=self.gate) def reset_parameters(self): # super().reset_parameters() # TODO find a way to refactor to call super() self.activate = Activation(self.hidden_activation, self.d_model) def forward(self, input, state): h, m, time_step = state # Update the memory u = self.forward_memory(input, h, m) m = self.update_memory(m, u, time_step) # (batch, memory_size, memory_order) # Update hidden h = self.forward_hidden(input, h, m) next_state = (h, m, time_step + 1) output = self.state_to_tensor(next_state) return output, next_state def forward_memory(self, input, h, m): """ First part of forward pass to construct the memory state update """ input_to_memory = input if self.architecture['ux'] else input.new_empty((0,)) xh = torch.cat((input_to_memory, h), dim=-1) # Construct the update features u = self.W_uxh(xh) # (batch, memory_size) return u def forward_hidden(self, input, h, m): input_to_hidden = input if self.architecture['hx'] else input.new_empty((0,)) # Update hidden state from memory memory_to_hidden = m.view(input.shape[0], self.memory_size*self.memory_order) xm = torch.cat((input_to_hidden, memory_to_hidden), dim=-1) hidden_preact = self.W_hxm(xm) if self.architecture['hh']: hidden_preact = hidden_preact + self.W_hh(h) hidden = self.activate(hidden_preact) # Construct gate if necessary if self.gate is None: h = hidden else: if self.architecture['hh']: xm = torch.cat((xm, h), dim=-1) g = self.W_gxm(xm) h = (1.-g) * h + g * hidden return h def update_memory(self, m, u, time_step): """ m: (B, M, N) [batch size, memory size, memory order] u: (B, M) Output: (B, M, N) """ raise NotImplementedError def default_state(self, *batch_shape, device=None): return ( torch.zeros(*batch_shape, self.d_model, device=device, requires_grad=False), torch.zeros(*batch_shape, self.memory_size, self.memory_order, device=device, requires_grad=False), 0, ) @property def state_to_tensor(self): """ Converts a state into a single output (tensor) """ def fn(state): h, m, time_step = state return h return fn @property def d_state(self): return self.d_model @property def d_output(self): return self.d_model class LTICell(MemoryCell): """ A cell where the memory state follows Linear Time Invariant dynamics: c' = Ac + Bf. """ def __init__( self, d_input, d_model, memory_size, memory_order, A, B, dt=0.01, discretization='zoh', **kwargs ): super().__init__(d_input, d_model, memory_size, memory_order, **kwargs) C = np.ones((1, memory_order)) D = np.zeros((1,)) dA, dB, _, _, _ = signal.cont2discrete((A, B, C, D), dt=dt, method=discretization) dA = dA - np.eye(memory_order) # puts into form: x += Ax self.register_buffer('A', torch.Tensor(dA)) self.register_buffer('B', torch.Tensor(dB)) def update_memory(self, m, u, time_step): u = u.unsqueeze(-1) # (B, M, 1) return m + F.linear(m, self.A) + F.linear(u, self.B) class LSICell(MemoryCell): """ A cell where the memory state Linear 'Scale' Invariant dynamics: c' = 1/t (Ac + Bf). """ def __init__( self, d_input, d_model, memory_size, memory_order, A, B, init_t = 0, # 0 for special case at t=0 (new code), else old code without special case l_max=1024, discretization='bilinear', **kwargs ): """ # TODO: make init_t start at arbitrary time (instead of 0 or 1) """ # B should have shape (N, 1) assert len(B.shape) == 2 and B.shape[1] == 1 super().__init__(d_input, d_model, memory_size, memory_order, **kwargs) assert isinstance(init_t, int) self.init_t = init_t self.l_max = l_max A_stacked = np.empty((l_max, memory_order, memory_order), dtype=A.dtype) B_stacked = np.empty((l_max, memory_order), dtype=B.dtype) B = B[:,0] N = memory_order for t in range(1, l_max + 1): At = A / t Bt = B / t if discretization in forward_aliases: A_stacked[t - 1] = np.eye(N) + At B_stacked[t - 1] = Bt elif discretization in backward_aliases: A_stacked[t - 1] = la.solve_triangular(np.eye(N) - At, np.eye(N), lower=True) B_stacked[t - 1] = la.solve_triangular(np.eye(N) - At, Bt, lower=True) elif discretization in bilinear_aliases: A_stacked[t - 1] = la.solve_triangular(np.eye(N) - At / 2, np.eye(N) + At / 2, lower=True) B_stacked[t - 1] = la.solve_triangular(np.eye(N) - At / 2, Bt, lower=True) elif discretization in zoh_aliases: A_stacked[t - 1] = la.expm(A * (math.log(t + 1) - math.log(t))) B_stacked[t - 1] = la.solve_triangular(A, A_stacked[t - 1] @ B - B, lower=True) B_stacked = B_stacked[:, :, None] A_stacked -= np.eye(memory_order) # puts into form: x += Ax self.register_buffer('A', torch.Tensor(A_stacked)) self.register_buffer('B', torch.Tensor(B_stacked)) def update_memory(self, m, u, time_step): u = u.unsqueeze(-1) # (B, M, 1) t = time_step - 1 + self.init_t if t < 0: return F.pad(u, (0, self.memory_order - 1)) else: if t >= self.l_max: t = self.l_max - 1 return m + F.linear(m, self.A[t]) + F.linear(u, self.B[t])
4,611
333
// // MCFireworksButton.h // MCFireworksButton // // Created by <NAME> on 17/3/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface MCFireworksButton : UIButton @property (strong, nonatomic) UIImage *particleImage; @property (assign, nonatomic) CGFloat particleScale; @property (assign, nonatomic) CGFloat particleScaleRange; - (void)animate; - (void)popOutsideWithDuration:(NSTimeInterval)duration; - (void)popInsideWithDuration:(NSTimeInterval)duration; @end
176
403
#ifndef VKPP_APPEND_HH #define VKPP_APPEND_HH #include <vector> namespace vkpp { template<typename T> // Super simple way to append values to vector void append(const std::vector<T>& values, std::vector<T>& target) { target.insert(target.end(), values.begin(), values.end()); } template<typename T> void append(const T& value, std::vector<T>& target) { target.push_back(value); } } #endif
173
463
<gh_stars>100-1000 /* * Copyright (c) 2006 JMockit developers * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package mockit.internal.reflection; import java.lang.reflect.*; import javax.annotation.*; import static mockit.internal.util.Utilities.ensureThatMemberIsAccessible; public final class FieldReflection { private FieldReflection() {} @Nullable public static <T> T getFieldValue(@Nonnull Field field, @Nullable Object targetObject) { ensureThatMemberIsAccessible(field); try { if (targetObject != null && !field.getDeclaringClass().isInstance(targetObject)) { Field outerInstanceField = targetObject.getClass().getDeclaredField("this$0"); targetObject = getFieldValue(outerInstanceField, targetObject); } //noinspection unchecked return (T) field.get(targetObject); } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); } } public static void setFieldValue(@Nonnull Field field, @Nullable Object targetObject, @Nullable Object value) { ensureThatMemberIsAccessible(field); try { if (targetObject != null && !field.getDeclaringClass().isInstance(targetObject)) { Field outerInstanceField = targetObject.getClass().getDeclaredField("this$0"); targetObject = getFieldValue(outerInstanceField, targetObject); } field.set(targetObject, value); } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); } } }
554
1,223
/* Copyright 2016 Nidium Inc. All rights reserved. Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ #include "Binding/JSAudioContext.h" #include "Binding/JSAudioNode.h" #include "Binding/JSConsole.h" #include "Core/Utils.h" #include "AV/Audio.h" #include "Frontend/Context.h" using namespace Nidium::AV; using namespace Nidium::Core; namespace Nidium { namespace Binding { JSAudioContext *JSAudioContext::m_Ctx = nullptr; extern void reportError(JSContext *cx, const char *message, JSErrorReport *report); static JSClass Global_AudioThread_class = { "_GLOBALAudioThread", JSCLASS_GLOBAL_FLAGS | JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(1), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; JSAudioContext::JSAudioContext(JSContext *cx, Audio *audio) : m_Audio(audio), m_JsGlobalObj(nullptr) { JSAudioContext::m_Ctx = this; JSAudioContext::CreateObject(cx, this); this->root(); NIDIUM_PTHREAD_VAR_INIT(&m_ShutdownWait) m_Audio->postMessage(JSAudioContext::CtxCallback, static_cast<void *>(this), true); } JSAudioContext *JSAudioContext::GetContext() { return JSAudioContext::m_Ctx; } JSAudioContext *JSAudioContext::GetContext(JSContext *cx, unsigned int bufferSize, unsigned int channels, unsigned int sampleRate) { ape_global *net = static_cast<ape_global *>(JS_GetContextPrivate(cx)); Audio *audio; try { audio = new Audio(net, bufferSize, channels, sampleRate); } catch (...) { return NULL; } return new JSAudioContext(cx, audio); } void JSAudioContext::RunCallback(void *custom) { JSAudioContext *audio = JSAudioContext::GetContext(); if (!audio) return; char *str = static_cast<char *>(custom); audio->run(str); JS_free(audio->getJSContext(), custom); } bool JSAudioContext::JS_run(JSContext *cx, JS::CallArgs &args) { JS::RootedString fn(cx); JS::RootedFunction nfn(cx); if ((nfn = JS_ValueToFunction(cx, args[0])) == NULL || (fn = JS_DecompileFunction(cx, nfn, 0)) == NULL) { JS_ReportError(cx, "Failed to read callback function\n"); return false; } char *funStr = JS_EncodeString(cx, fn); if (!funStr) { JS_ReportError(cx, "Failed to convert callback function to source string"); return false; } m_Audio->postMessage(JSAudioContext::RunCallback, static_cast<void *>(funStr)); return true; } bool JSAudioContext::JS_load(JSContext *cx, JS::CallArgs &args) { JS_ReportError(cx, "Not implemented"); return false; } bool JSAudioContext::JS_createNode(JSContext *cx, JS::CallArgs &args) { int in, out; JS::RootedString name(cx); JSAudioNode *node = nullptr; JS::RootedObject nodeObj(cx); if (!JS_ConvertArguments(cx, args, "Suu", name.address(), &in, &out)) { return false; } if (in == 0 && out == 0) { JS_ReportError(cx, "Node must have at least one input or output"); return false; } else if (in < 0 || out < 0) { JS_ReportError(cx, "Wrong channel count (Must be greater or equal to 0)"); return false; } else if (in > 32 || out > 32) { JS_ReportError(cx, "Wrong channel count (Must be lower or equal to 32)"); return false; } JSAutoByteString cname(cx, name); try { if (strcmp("source", cname.ptr()) == 0) { JSAudioNodeSource *tmp = new JSAudioNodeSource(cx, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("custom-source", cname.ptr()) == 0) { JSAudioNodeCustomSource *tmp = new JSAudioNodeCustomSource(cx, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("custom", cname.ptr()) == 0) { JSAudioNodeCustom *tmp = new JSAudioNodeCustom(cx, in, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("reverb", cname.ptr()) == 0) { JSAudioNodeReverb *tmp = new JSAudioNodeReverb(cx, in, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("delay", cname.ptr()) == 0) { JSAudioNodeDelay *tmp = new JSAudioNodeDelay(cx, in, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("gain", cname.ptr()) == 0) { JSAudioNodeGain *tmp = new JSAudioNodeGain(cx, in, out); node = tmp; nodeObj = tmp->getJSObject(); } else if (strcmp("target", cname.ptr()) == 0) { if (m_Target != nullptr) { node = m_Target; nodeObj = m_Target->getJSObject(); } else { JSAudioNodeTarget *tmp = new JSAudioNodeTarget(cx, in); node = tmp; nodeObj = tmp->getJSObject(); m_Target = tmp; } } else if (strcmp("stereo-enhancer", cname.ptr()) == 0) { JSAudioNodeStereoEnhancer *tmp = new JSAudioNodeStereoEnhancer(cx, in, out); node = tmp; nodeObj = tmp->getJSObject(); } else { JS_ReportError(cx, "Unknown node : %s\n", cname.ptr()); return false; } } catch (AudioNodeException *e) { delete node; JS_ReportError(cx, "Error while creating node : %s\n", e->what()); return false; } args.rval().setObjectOrNull(nodeObj); return true; } bool JSAudioContext::JS_connect(JSContext *cx, JS::CallArgs &args) { JSAudioNodeLink *jlink1 = nullptr; JSAudioNodeLink *jlink2 = nullptr; NodeLink *link1 = nullptr; NodeLink *link2 = nullptr; Audio *audio = this->m_Audio; JS::RootedObject arg0(cx, args[0].isObject() ? args[0].toObjectOrNull() : nullptr); JS::RootedObject arg1(cx, args[1].isObject() ? args[1].toObjectOrNull() : nullptr); if (!arg0 || !(jlink1 = JSAudioNodeLink::GetInstance(arg0))) { JS_ReportError(cx, "First argument must be an AudioNodeLink"); return false; } if (!arg1 || !(jlink2 = JSAudioNodeLink::GetInstance(arg1))) { JS_ReportError(cx, "Second argument must be an AudioNodeLink"); return false; } link1 = jlink1->get(); link2 = jlink2->get(); if (!link1 || !link2) { JS_ReportError(cx, "Invalid AudioNodeLink"); return false; } if (link1->isInput() && link2->isOutput()) { if (!audio->connect(link2, link1)) { JS_ReportError(cx, "connect() failed (max connection reached)\n"); return false; } } else if (link1->isOutput() && link2->isInput()) { if (!audio->connect(link1, link2)) { JS_ReportError(cx, "connect() failed (max connection reached)\n"); return false; } } else { JS_ReportError(cx, "connect() expect one input and one output.\n"); return false; } return true; } bool JSAudioContext::JS_disconnect(JSContext *cx, JS::CallArgs &args) { JSAudioNodeLink *jlink1; JSAudioNodeLink *jlink2; NodeLink *link1; NodeLink *link2; Audio *audio = this->m_Audio; JS::RootedObject arg0(cx, args[0].isObject() ? args[0].toObjectOrNull() : nullptr); JS::RootedObject arg1(cx, args[1].isObject() ? args[1].toObjectOrNull() : nullptr); if (!(arg0 || (jlink1 = JSAudioNodeLink::GetInstance(arg0)))) { JS_ReportError(cx, "First argument must be an AudioNodeLink"); return false; } if (!(arg1 || (jlink2 = JSAudioNodeLink::GetInstance(arg1)))) { JS_ReportError(cx, "Second argument must be an AudioNodeLink"); return false; } link1 = jlink1->get(); link2 = jlink2->get(); if (!link1 || !link2) { JS_ReportError(cx, "Invalid AudioNodeLink"); return false; } if (link1->isInput() && link2->isOutput()) { audio->disconnect(link2, link1); } else if (link1->isOutput() && link2->isInput()) { audio->disconnect(link1, link2); } else { JS_ReportError(cx, "disconnect() expect one input and one output\n"); return false; } return true; } bool JSAudioContext::JS_pFFT(JSContext *cx, JS::CallArgs &args) { int dir, n; double *dx, *dy; uint32_t dlenx, dleny; JS::RootedObject x(cx); JS::RootedObject y(cx); if (!JS_ConvertArguments(cx, args, "ooii", x.address(), y.address(), &n, &dir)) { return false; } if (!JS_IsTypedArrayObject(x) || !JS_IsTypedArrayObject(y)) { JS_ReportError(cx, "Bad argument"); return false; } bool shared; if (JS_GetObjectAsFloat64Array(x, &dlenx, &shared, &dx) == NULL) { JS_ReportError(cx, "Can't convert typed array (expected Float64Array)"); return false; } if (JS_GetObjectAsFloat64Array(y, &dleny, &shared, &dy) == NULL) { JS_ReportError(cx, "Can't convert typed array (expected Float64Array)"); return false; } if (dlenx != dleny) { JS_ReportError(cx, "Buffers size must match"); return false; } if ((n & (n - 1)) != 0 || n < 32 || n > 4096) { JS_ReportError(cx, "Invalid frame size"); return false; } if (n > dlenx) { JS_ReportError(cx, "Buffer is too small"); return false; } Utils::FFT(dir, n, dx, dy); return true; } bool JSAudioContext::JSGetter_bufferSize(JSContext *cx, JS::MutableHandleValue vp) { vp.setInt32(m_Audio->m_OutputParameters->m_FramesPerBuffer); return true; } bool JSAudioContext::JSGetter_channels(JSContext *cx, JS::MutableHandleValue vp) { AudioParameters *params = m_Audio->m_OutputParameters; vp.setInt32(params->m_Channels); return true; } bool JSAudioContext::JSGetter_sampleRate(JSContext *cx, JS::MutableHandleValue vp) { AudioParameters *params = m_Audio->m_OutputParameters; vp.setInt32(params->m_SampleRate); return true; } bool JSAudioContext::JSGetter_volume(JSContext *cx, JS::MutableHandleValue vp) { vp.setNumber(m_Audio->getVolume()); return true; } bool JSAudioContext::JSSetter_volume(JSContext *cx, JS::MutableHandleValue vp) { if (vp.isNumber()) { m_Audio->setVolume((float)vp.toNumber()); } return true; } bool JSAudioContext::createContext() { if (m_JsRt != NULL) return false; if ((m_JsRt = JS_NewRuntime(JS::DefaultHeapMaxBytes, JS::DefaultNurseryBytes)) == NULL) { fprintf(stderr, "Failed to init JS runtime"); return false; } NidiumJS::SetJSRuntimeOptions(m_JsRt); JS_SetGCParameter(m_JsRt, JSGC_MAX_BYTES, 0xffffffff); JS_SetGCParameter(m_JsRt, JSGC_SLICE_TIME_BUDGET, 15); if ((m_JsTcx = JS_NewContext(m_JsRt, 8192)) == NULL) { fprintf(stderr, "Failed to init JS context"); return false; } NidiumLocalContext::InitJSThread(m_JsRt, m_JsTcx); JSAutoRequest ar(m_JsTcx); // JS_SetGCParameterForThread(this->tcx, JSGC_MAX_CODE_CACHE_BYTES, 16 * // 1024 * 1024); JS::CompartmentOptions options; options.setVersion(JSVERSION_LATEST); JS::RootedObject global( m_JsTcx, JS_NewGlobalObject(m_JsTcx, &Global_AudioThread_class, nullptr, JS::DontFireOnNewGlobalHook, options)); JSAutoCompartment ac(m_JsTcx, global); m_JsGlobalObj = global; // We don't actually needs to root a global object, but we // need to store a reference to the global object in a // JS::Heap and this reference needs to be traced. NidiumLocalContext::RootObjectUntilShutdown(m_JsGlobalObj); if (!JS_InitStandardClasses(m_JsTcx, global)) { fprintf(stderr, "Failed to init std class"); return false; } JS_SetErrorReporter(m_JsRt, reportError); JS_FireOnNewGlobalObject(m_JsTcx, global); JSConsole::RegisterObject(m_JsTcx); JSAudioNodeThreaded::RegisterObject(m_JsTcx); return true; } bool JSAudioContext::run(char *str) { if (!m_JsTcx) { fprintf(stderr, "No JS context for audio thread"); return false; } JSAutoRequest ar(m_JsTcx); JSAutoCompartment ac(m_JsTcx, m_JsGlobalObj); JS::CompileOptions options(m_JsTcx); JS::RootedObject globalObj(m_JsTcx, JS::CurrentGlobalOrNull(m_JsTcx)); options.setIntroductionType("audio Thread").setUTF8(true); JS::RootedFunction fun(m_JsTcx); JS::AutoObjectVector scopeChain(m_JsTcx); bool state = JS::CompileFunction(m_JsTcx, scopeChain, options, "Audio_run", 0, nullptr, str, strlen(str), &fun); if (!state) { JS_ReportError(m_JsTcx, "Failed to compile script on audio thread\n"); return false; } JS::RootedValue rval(m_JsTcx); JS_CallFunction(m_JsTcx, globalObj, fun, JS::HandleValueArray::empty(), &rval); return true; } void JSAudioContext::addNode(JSAudioNode *node) { JSAudioContext::NodeListItem *item = new JSAudioContext::NodeListItem(node, nullptr, m_Nodes); if (m_Nodes != nullptr) { m_Nodes->prev = item; } m_Nodes = item; } void JSAudioContext::removeNode(JSAudioNode *node) { JSAudioContext::NodeListItem *item = m_Nodes; while (item != NULL) { if (item->curr == node) { if (item->prev != NULL) { item->prev->next = item->next; } else { m_Nodes = item->next; } if (item->next != NULL) { item->next->prev = item->prev; } delete item; break; } item = item->next; } } void JSAudioContext::ShutdownCallback(void *custom) { JSAudioContext *audio = static_cast<JSAudioContext *>(custom); #ifdef DEBUG JSAudioContext::NodeListItem *node = audio->m_Nodes; while (node != NULL) { ndm_log(NDM_LOG_DEBUG, "JSAudioContext", "All nodes should have been destroyed"); assert(false); } #endif NidiumLocalContext::UnrootObject(audio->m_JsGlobalObj); audio->m_JsGlobalObj = nullptr; NidiumLocalContext *nlc = NidiumLocalContext::Get(); nlc->shutdown(); if (audio->m_JsTcx != NULL) { JSRuntime *rt = JS_GetRuntime(audio->m_JsTcx); JS_DestroyContext(audio->m_JsTcx); JS_DestroyRuntime(rt); audio->m_JsTcx = NULL; } NIDIUM_PTHREAD_SIGNAL(&audio->m_ShutdownWait) } JSAudioContext::~JSAudioContext() { m_Audio->lockSources(); m_Audio->lockQueue(); // Delete all nodes JSAudioContext::NodeListItem *node = m_Nodes; JSAudioContext::NodeListItem *next = nullptr; while (node != nullptr) { next = node->next; // Node destructor will remove the node // from the nodes linked list delete node->curr; node = next; } // Clear threaded js context m_Audio->postMessage(JSAudioContext::ShutdownCallback, this, true); NIDIUM_PTHREAD_WAIT(&m_ShutdownWait) // Unlock the sources thread, so the decode thread can exit // when we call Audio::shutdown() m_Audio->unlockSources(); // Shutdown the audio m_Audio->shutdown(); m_Audio->unlockQueue(); // And delete the audio delete m_Audio; JSAudioContext::m_Ctx = NULL; } void JSAudioContext::CtxCallback(void *custom) { JSAudioContext *audio = static_cast<JSAudioContext *>(custom); if (!audio->createContext()) { fprintf(stderr, "Failed to create audio thread context"); // JS_ReportError(jsNode->audio->cx, "Failed to create audio thread // context\n"); // XXX : Can't report error from another thread? } } JSFunctionSpec *JSAudioContext::ListMethods() { static JSFunctionSpec funcs[] = { CLASSMAPPER_FN(JSAudioContext, run, 1), CLASSMAPPER_FN(JSAudioContext, load, 1), CLASSMAPPER_FN(JSAudioContext, createNode, 3), CLASSMAPPER_FN(JSAudioContext, connect, 2), CLASSMAPPER_FN(JSAudioContext, disconnect, 2), CLASSMAPPER_FN(JSAudioContext, pFFT, 2), JS_FS_END }; return funcs; } JSPropertySpec *JSAudioContext::ListProperties() { static JSPropertySpec props[] = { CLASSMAPPER_PROP_GS(JSAudioContext, volume), CLASSMAPPER_PROP_G(JSAudioContext, bufferSize), CLASSMAPPER_PROP_G(JSAudioContext, channels), CLASSMAPPER_PROP_G(JSAudioContext, sampleRate), JS_PS_END }; return props; } void JSAudioContext::RegisterObject(JSContext *cx) { JSAudioContext::ExposeClass<0>(cx, "AudioContext"); } } // namespace Binding } // namespace Nidium
8,263
1,162
<gh_stars>1000+ package org.nesc.ec.bigdata.cache; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author lg99 * expire map */ public class ExpireMap { private static final Map<String, Object> CACHE_MAP = new ConcurrentHashMap<>(); /** expire time for Maps.key or Maps.values*/ public static final long CACHE_HOLD_TIME_5MIN = 5*60*1000L; /** A single key is used to store the expiration time of the key */ public static final String EXPIRE_ = "_expire"; public ExpireMap() { } /** put key,value to CacheMap */ public static void put(String key, Object value){ put(key,value,CACHE_HOLD_TIME_5MIN); } /** * put key,value,expire time to cacheMap * */ public static void put(String key,Object value,long expireTime){ //check key whether exits in cacheMap if(checkCacheName(key)){ return; } CACHE_MAP.put(key,value); CACHE_MAP.put(key+ EXPIRE_,System.currentTimeMillis()+expireTime); } /** check key whether exits in cacheMap, * 1.if not exits,return false * 2.if exits,the expireTime less than the current Time,remove the key and the expire key in cacheMap,return false * 3.else return true * */ public static boolean checkCacheName(String key){ long expireTime = (long) CACHE_MAP.getOrDefault(key+ EXPIRE_,0L); if(expireTime==0L){ return false; } if(expireTime < System.currentTimeMillis()){ remove(key); remove(key+ EXPIRE_); return false; } return true; } /** * get the key from the cacheMap * if key exits in cacheMap,return map.value * else return null * */ public static Object get(String key){ if(checkCacheName(key)){ return CACHE_MAP.get(key); } return null; } /** * remove the key and the expire key in cacheMap * */ public static void remove(String key){ CACHE_MAP.remove(key); CACHE_MAP.remove(key+ EXPIRE_); } /** clear the cacheMap */ public static void removeAll(){ CACHE_MAP.clear(); } }
939
346
<reponame>rhyep/Python_tutorials def is_prime(x): n = 2 Prime = False if x <2: Prime = False else: while n < x: if x % n == 0: Prime = False break else: n +=1 Prime = True else: Prime = True return Prime
215
1,731
<reponame>frafra/pdm import re from typing import Any, Tuple, Union, cast, overload from pdm._types import Literal from pdm.exceptions import InvalidPyVersion VersionBit = Union[int, Literal["*"]] class Version: """A loosely semantic version implementation that allows '*' in version part. This class is designed for Python specifier set merging only, hence up to 3 version parts are kept, plus prereleases or postreleases are not supported. """ MIN: "Version" MAX: "Version" def __init__(self, version: Union[Tuple[VersionBit, ...], str]) -> None: if isinstance(version, str): version_str = re.sub(r"(?<!\.)\*", ".*", version) try: version = cast( Tuple[VersionBit, ...], tuple(int(v) if v != "*" else v for v in version_str.split("."))[ :3 ], ) except ValueError: raise InvalidPyVersion( f"{version_str}: Prereleases or postreleases are not supported " "for python version specifers." ) self._version: Tuple[VersionBit, ...] = version def complete(self, complete_with: VersionBit = 0, max_bits: int = 3) -> "Version": """ Complete the version with the given bit if the version has less than max parts """ assert len(self._version) <= max_bits, self new_tuple = self._version + (max_bits - len(self._version)) * (complete_with,) return type(self)(new_tuple) def bump(self, idx: int = -1) -> "Version": """Bump version by incrementing 1 on the given index of version part. Increment the last version bit by default. """ version = self._version head, value = version[:idx], int(version[idx]) return type(self)((*head, value + 1)).complete() def startswith(self, other: "Version") -> bool: """Check if the version begins with another version.""" return self._version[: len(other._version)] == other._version @property def is_wildcard(self) -> bool: """Check if the version ends with a '*'""" return self._version[-1] == "*" def __str__(self) -> str: return ".".join(map(str, self._version)) def __repr__(self) -> str: return f"<Version({self})>" def __eq__(self, other: Any) -> bool: if not isinstance(other, Version): return NotImplemented return self._version == other._version def __lt__(self, other: Any) -> bool: if not isinstance(other, Version): return NotImplemented def comp_key(version: Version) -> Tuple[int, ...]: return tuple(-1 if v == "*" else v for v in version._version) return comp_key(self) < comp_key(other) def __gt__(self, other: Any) -> bool: return not (self.__lt__(other) or self.__eq__(other)) def __le__(self, other: Any) -> bool: return self.__lt__(other) or self.__eq__(other) def __ge__(self, other: Any) -> bool: return self.__gt__(other) or self.__eq__(other) @overload def __getitem__(self, idx: int) -> VersionBit: ... @overload def __getitem__(self, idx: slice) -> "Version": ... def __getitem__(self, idx: Union[int, slice]) -> Union[VersionBit, "Version"]: if isinstance(idx, slice): return type(self)(self._version[idx]) else: return self._version[idx] def __setitem__(self, idx: int, value: VersionBit) -> None: if not isinstance(idx, int): raise TypeError("Slice assignment is not supported") version = list(self._version) version[idx] = value self._version = tuple(version) def __hash__(self) -> int: return hash(self._version) @property def is_py2(self) -> bool: return self._version[0] == 2 Version.MIN = Version((-1, -1, -1)) Version.MAX = Version((99, 99, 99))
1,730
2,151
<reponame>zipated/src /* * Copyright (C) 2000 <NAME> (<EMAIL>) * (C) 2000 <NAME> (<EMAIL>) * (C) 2000 <NAME> <EMAIL>) * (C) 2004 <NAME> (<EMAIL>) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights * reserved. * Copyright (C) 2009 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_INFO_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_INFO_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/layout_object.h" // TODO(jchaffraix): Once we unify PaintBehavior and PaintLayerFlags, we should // move PaintLayerFlags to PaintPhase and rename it. Thus removing the need for // this #include // "third_party/blink/renderer/core/paint/paint_layer_painting_info.h" #include "third_party/blink/renderer/core/paint/paint_layer_painting_info.h" #include "third_party/blink/renderer/core/paint/paint_phase.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item.h" #include "third_party/blink/renderer/platform/transforms/affine_transform.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include <limits> namespace blink { class LayoutBoxModelObject; struct CORE_EXPORT PaintInfo { USING_FAST_MALLOC(PaintInfo); public: PaintInfo(GraphicsContext& context, const IntRect& cull_rect, PaintPhase phase, GlobalPaintFlags global_paint_flags, PaintLayerFlags paint_flags, const LayoutBoxModelObject* paint_container = nullptr, LayoutUnit fragment_logical_top_in_flow_thread = LayoutUnit(), bool suppress_painting_descendants = false) : context(context), phase(phase), cull_rect_(cull_rect), paint_container_(paint_container), fragment_logical_top_in_flow_thread_( fragment_logical_top_in_flow_thread), paint_flags_(paint_flags), global_paint_flags_(global_paint_flags), suppress_painting_descendants_(suppress_painting_descendants) {} PaintInfo(GraphicsContext& new_context, const PaintInfo& copy_other_fields_from) : context(new_context), phase(copy_other_fields_from.phase), cull_rect_(copy_other_fields_from.cull_rect_), paint_container_(copy_other_fields_from.paint_container_), fragment_logical_top_in_flow_thread_( copy_other_fields_from.fragment_logical_top_in_flow_thread_), paint_flags_(copy_other_fields_from.paint_flags_), global_paint_flags_(copy_other_fields_from.global_paint_flags_), suppress_painting_descendants_( copy_other_fields_from.suppress_painting_descendants_) {} // Creates a PaintInfo for painting descendants. See comments about the paint // phases in PaintPhase.h for details. PaintInfo ForDescendants() const { PaintInfo result(*this); if (phase == PaintPhase::kDescendantOutlinesOnly) result.phase = PaintPhase::kOutline; else if (phase == PaintPhase::kDescendantBlockBackgroundsOnly) result.phase = PaintPhase::kBlockBackground; return result; } bool IsRenderingClipPathAsMaskImage() const { return paint_flags_ & kPaintLayerPaintingRenderingClipPathAsMask; } bool IsRenderingResourceSubtree() const { return paint_flags_ & kPaintLayerPaintingRenderingResourceSubtree; } bool SkipRootBackground() const { return paint_flags_ & kPaintLayerPaintingSkipRootBackground; } bool IsPrinting() const { return global_paint_flags_ & kGlobalPaintPrinting; } bool SuppressPaintingDescendants() const { return suppress_painting_descendants_; } DisplayItem::Type DisplayItemTypeForClipping() const { return DisplayItem::PaintPhaseToClipBoxType(phase); } const LayoutBoxModelObject* PaintContainer() const { return paint_container_; } GlobalPaintFlags GetGlobalPaintFlags() const { return global_paint_flags_; } PaintLayerFlags PaintFlags() const { return paint_flags_; } const CullRect& GetCullRect() const { return cull_rect_; } void UpdateCullRect(const AffineTransform& local_to_parent_transform) { cull_rect_.UpdateCullRect(local_to_parent_transform); } void UpdateCullRectForScrollingContents( const IntRect& overflow_clip_rect, const AffineTransform& local_to_parent_transform) { cull_rect_.UpdateForScrollingContents(overflow_clip_rect, local_to_parent_transform); } // Returns the fragment of the current painting object matching the current // layer fragment. const FragmentData* FragmentToPaint(const LayoutObject& object) const { for (const auto* fragment = &object.FirstFragment(); fragment; fragment = fragment->NextFragment()) { if (fragment->LogicalTopInFlowThread() == fragment_logical_top_in_flow_thread_) return fragment; } // No fragment of the current painting object matches the layer fragment, // which means the object should not paint in this fragment. return nullptr; } // FIXME: Introduce setters/getters at some point. Requires a lot of changes // throughout layout/. GraphicsContext& context; PaintPhase phase; private: CullRect cull_rect_; // The box model object that originates the current painting. const LayoutBoxModelObject* paint_container_; // The logical top of the current fragment of the self-painting PaintLayer // which initiated the current painting, in the containing flow thread. LayoutUnit fragment_logical_top_in_flow_thread_; const PaintLayerFlags paint_flags_; const GlobalPaintFlags global_paint_flags_; const bool suppress_painting_descendants_; // TODO(chrishtr): temporary while we implement CullRect everywhere. friend class SVGPaintContext; friend class SVGShapePainter; }; Image::ImageDecodingMode GetImageDecodingMode(Node*); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_INFO_H_
2,517
26,879
<filename>butterknife-integration-test/src/androidTest/java/com/example/butterknife/functional/OnItemClickTest.java package com.example.butterknife.functional; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.AbsSpinner; import android.widget.AdapterView; import android.widget.FrameLayout; import androidx.test.InstrumentationRegistry; import androidx.test.annotation.UiThreadTest; import butterknife.ButterKnife; import butterknife.OnItemClick; import butterknife.Optional; import butterknife.Unbinder; import com.example.butterknife.BuildConfig; import com.example.butterknife.library.SimpleAdapter; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assume.assumeFalse; @SuppressWarnings("unused") // Used reflectively / by code gen. public final class OnItemClickTest { static class TestSpinner extends AbsSpinner { public TestSpinner(Context context) { super(context); setAdapter(new SimpleAdapter(context)); } void performItemClick(int position) { if (position < 0) { return; } AdapterView.OnItemClickListener listener = getOnItemClickListener(); if (listener != null) { listener.onItemClick(this, null, position, NO_ID); } } } static final class Simple { int clickedPosition = -1; @OnItemClick(1) void itemClick(int position) { clickedPosition = position; } } @UiThreadTest @Test public void simple() { View tree = ViewTree.create(TestSpinner.class, 1); TestSpinner spinner = tree.findViewById(1); Simple target = new Simple(); Unbinder unbinder = ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition); spinner.performItemClick(0); assertEquals(0, target.clickedPosition); unbinder.unbind(); spinner.performItemClick(1); assertEquals(0, target.clickedPosition); } static final class MultipleBindings { int clickedPosition1 = -1; int clickedPosition2 = -1; @OnItemClick(1) void itemClick1(int position) { clickedPosition1 = position; } @OnItemClick(1) void itemClick2(int position) { clickedPosition2 = position; } } @UiThreadTest @Test public void multipleBindings() { assumeFalse("Not implemented", BuildConfig.FLAVOR.equals("reflect")); // TODO View tree = ViewTree.create(TestSpinner.class, 1); TestSpinner spinner = tree.findViewById(1); MultipleBindings target = new MultipleBindings(); Unbinder unbinder = ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition1); assertEquals(-1, target.clickedPosition2); spinner.performItemClick(0); assertEquals(0, target.clickedPosition1); assertEquals(0, target.clickedPosition2); unbinder.unbind(); spinner.performItemClick(1); assertEquals(0, target.clickedPosition1); assertEquals(0, target.clickedPosition2); } static final class Visibilities { int clickedPosition = -1; @OnItemClick(1) public void publicItemClick(int position) { clickedPosition = position; } @OnItemClick(2) void packageItemClick(int position) { clickedPosition = position; } @OnItemClick(3) protected void protectedItemClick(int position) { clickedPosition = position; } } @UiThreadTest @Test public void visibilities() { View tree = ViewTree.create(TestSpinner.class, 1, 2, 3); TestSpinner spinner1 = tree.findViewById(1); TestSpinner spinner2 = tree.findViewById(2); TestSpinner spinner3 = tree.findViewById(3); Visibilities target = new Visibilities(); ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition); spinner1.performItemClick(0); assertEquals(0, target.clickedPosition); spinner2.performItemClick(1); assertEquals(1, target.clickedPosition); spinner3.performItemClick(2); assertEquals(2, target.clickedPosition); } static final class MultipleIds { int clickedPosition = -1; @OnItemClick({1, 2}) void itemClick(int position) { clickedPosition = position; } } @UiThreadTest @Test public void multipleIds() { View tree = ViewTree.create(TestSpinner.class, 1, 2); TestSpinner spinner1 = tree.findViewById(1); TestSpinner spinner2 = tree.findViewById(2); MultipleIds target = new MultipleIds(); Unbinder unbinder = ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition); spinner1.performItemClick(0); assertEquals(0, target.clickedPosition); spinner2.performItemClick(1); assertEquals(1, target.clickedPosition); unbinder.unbind(); spinner1.performItemClick(2); assertEquals(1, target.clickedPosition); spinner2.performItemClick(2); assertEquals(1, target.clickedPosition); } static final class OptionalId { int clickedPosition = -1; @Optional @OnItemClick(1) void itemClick(int position) { clickedPosition = position; } } @UiThreadTest @Test public void optionalIdPresent() { View tree = ViewTree.create(TestSpinner.class, 1); TestSpinner spinner = tree.findViewById(1); OptionalId target = new OptionalId(); Unbinder unbinder = ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition); spinner.performItemClick(0); assertEquals(0, target.clickedPosition); unbinder.unbind(); spinner.performItemClick(1); assertEquals(0, target.clickedPosition); } @UiThreadTest @Test public void optionalIdAbsent() { View tree = ViewTree.create(TestSpinner.class, 2); TestSpinner spinner = tree.findViewById(2); OptionalId target = new OptionalId(); Unbinder unbinder = ButterKnife.bind(target, tree); assertEquals(-1, target.clickedPosition); spinner.performItemClick(0); assertEquals(-1, target.clickedPosition); unbinder.unbind(); spinner.performItemClick(0); assertEquals(-1, target.clickedPosition); } static final class ArgumentCast { interface MyInterface {} View last; @OnItemClick(1) void itemClickAdapterView(AdapterView<?> view) { last = view; } @OnItemClick(2) void itemClickAbsSpinner(AbsSpinner view) { last = view; } @OnItemClick(3) void itemClickMyInterface(ArgumentCast.MyInterface view) { last = (View) view; } } @UiThreadTest @Test public void argumentCast() { class MySpinner extends TestSpinner implements ArgumentCast.MyInterface { MySpinner(Context context) { super(context); } } Context context = InstrumentationRegistry.getContext(); TestSpinner spinner1 = new MySpinner(context); spinner1.setId(1); TestSpinner spinner2 = new MySpinner(context); spinner2.setId(2); TestSpinner spinner3 = new MySpinner(context); spinner3.setId(3); ViewGroup tree = new FrameLayout(context); tree.addView(spinner1); tree.addView(spinner2); tree.addView(spinner3); ArgumentCast target = new ArgumentCast(); ButterKnife.bind(target, tree); spinner1.performItemClick(0); assertSame(spinner1, target.last); spinner2.performItemClick(0); assertSame(spinner2, target.last); spinner3.performItemClick(0); assertSame(spinner3, target.last); } }
3,382
3,428
<reponame>ghalimi/stdlib {"id":"00899","group":"easy-ham-2","checksum":{"type":"MD5","value":"ebda16f739e9e222b56d0c71ca51b82f"},"text":"From <EMAIL> Fri Jul 26 04:42:10 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy@<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id C58BF440E7\n\tfor <jm@localhost>; Thu, 25 Jul 2002 23:42:08 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Fri, 26 Jul 2002 04:42:08 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g6Q3hd421655 for <<EMAIL>>;\n Fri, 26 Jul 2002 04:43:39 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id D9CCA2940FC; Thu, 25 Jul 2002 20:42:06 -0700 (PDT)\nDelivered-To: <EMAIL>int.<EMAIL>\nReceived: from relay.pair.com (relay1.pair.com [192.168.3.11]) by xent.com\n (Postfix) with SMTP id 6644F2940A2 for <<EMAIL>>; Thu,\n 25 Jul 2002 20:41:44 -0700 (PDT)\nReceived: (qmail 48331 invoked from network); 26 Jul 2002 03:41:47 -0000\nReceived: from dsl-64-195-248-145.telocity.com (HELO golden)\n (172.16.31.10) by relay1.pair.com with SMTP; 26 Jul 2002 03:41:47 -0000\nX-Pair-Authenticated: 172.16.31.10\nMessage-Id: <01fe01c23456$5d862760$640a000a@golden>\nFrom: \"<NAME>\" <<EMAIL>>\nTo: <<EMAIL>>\nReferences: <001301c23359$d8208130$0100a8c0@PETER>\n <<EMAIL>>\n <2784.192.216.194.113.1027554358.<EMAIL>>\n <<EMAIL>>\n <<EMAIL>>\nSubject: Re: Asteroids anyone ?\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook Express 6.00.2600.0000\nX-Mimeole: Produced By Microsoft MimeOLE V6.00.2600.0000\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Thu, 25 Jul 2002 20:41:45 -0700\n\n<NAME> writes:\n> 20,000 years ago, one of them the size of Mt Everest just ever so\n> slightly grazed us and left a scar 400km long in the side of South\n> America before it scooted out into space. First nations people would\n> have been there then, and it would have seriously ruined their day.\n\nDo you have any further information about this incident that\nwould me find more details on the web?\n\n- Gordon\n\n\nhttp://xent.com/mailman/listinfo/fork\n\n\n"}
1,186
333
{ "name": "com.dukechiang.dcet.numeric", "displayName": "DCET.Numeric", "version": "6.0.1", "unity": "2018.1", "description": "DCET的介绍:\nDCET是一个开源的游戏客户端(基于unity3d)服务端双端框架,服务端是使用C# .net core开发的分布式游戏服务端,其特点是开发效率高,性能强,双端共享逻辑代码,客户端服务端热更机制完善,同时支持可靠udp tcp websocket协议,支持服务端3D recast寻路等等\n\nDCET的功能:\n1.可用VS单步调试的分布式服务端,N变1\n一般来说,分布式服务端要启动很多进程,一旦进程多了,单步调试就变得非常困难,导致服务端开发基本上靠打log来查找问题。平常开发游戏逻辑也得开启一大堆进程,不仅启动慢,而且查找问题及其不方便,要在一堆堆日志里面查问题,这感觉非常糟糕,这么多年也没人解决这个问题。DCET框架使用了类似守望先锋的组件设计,所有服务端内容都拆成了一个个组件,启动时根据服务器类型挂载自己所需要的组件。这有点类似电脑,电脑都模块化的拆成了内存,CPU,主板等等零件,搭配不同的零件就能组装成一台不同的电脑,例如家用台式机需要内存,CPU,主板,显卡,显示器,硬盘。而公司用的服务器却不需要显示器和显卡,网吧的电脑可能不需要硬盘等。正因为这样的设计,DCET框架可以将所有的服务器组件都挂在一个服务器进程上,那么这个服务器进程就有了所有服务器的功能,一个进程就可以作为整组分布式服务器使用。这也类似电脑,台式机有所有的电脑组件,那它也完全可以当作公司服务器使用,也可以当作网吧电脑。\n\n2.随意可拆分功能的分布式服务端,1变N\n分布式服务端要开发多种类型的服务器进程,比如Login server,gate server,battle server,chat server friend server等等一大堆各种server,传统开发方式需要预先知道当前的功能要放在哪个服务器上,当功能越来越多的时候,比如聊天功能之前在一个中心服务器上,之后需要拆出来单独做成一个服务器,这时会牵扯到大量迁移代码的工作,烦不胜烦。DCET框架在平常开发的时候根本不太需要关心当前开发的这个功能会放在什么server上,只用一个进程进行开发,功能开发成组件的形式。发布的时候使用一份多进程的配置即可发布成多进程的形式,是不是很方便呢?随便你怎么拆分服务器。只需要修改极少的代码就可以进行拆分。不同的server挂上不同的组件就行了嘛!\n\n3.跨平台的分布式服务端\nDCET框架使用C#做服务端,现在C#是完全可以跨平台的,在linux上安装.netcore,即可,不需要修改任何代码,就能跑起来。性能方面,现在.netcore的性能非常强,比lua,python,js什么快的多了。做游戏服务端完全不在话下。平常我们开发的时候用VS在windows上开发调试,发布的时候发布到linux上即可。DCET框架还提供了一键同步工具,打开unity->tools->rsync同步,即可同步代码到linux上\n\n./Run.sh Config/StartConfig/192.168.12.188.txt \n即可编译启动服务器。\n\n4.提供协程支持\nC#天生支持异步变同步语法 async和await,比lua,python的协程强大的多,新版python以及javascript语言甚至照搬了C#的协程语法。分布式服务端大量服务器之间的远程调用,没有异步语法的支持,开发将非常麻烦。所以java没有异步语法,做单服还行,不适合做大型分布式游戏服务端。例如:\n\n// 发送C2R_Ping并且等待响应消息R2C_Ping\nR2C_Ping pong = await session.Call(new C2R_Ping()) as R2C_Ping;\nLog.Debug(\"收到R2C_Ping\");\n\n// 向mongodb查询一个id为1的Player,并且等待返回\nPlayer player = await Game.Scene.GetComponent<DBProxyComponent>().Query<Player>(1);\nLog.Debug($\"打印player name: {player.Name}\")\n可以看出,有了async await,所有的服务器间的异步操作将变得非常连贯,不用再拆成多段逻辑。大大简化了分布式服务器开发\n\n5.提供类似erlang的actor消息机制\nerlang语言一大优势就是位置透明的消息机制,用户完全不用关心对象在哪个进程,拿到id就可以对对象发送消息。DCET框架也提供了actor消息机制,实体对象只需要挂上MailBoxComponent组件,这个实体对象就成了一个Actor,任何服务器只需要知道这个实体对象的id就可以向其发送消息,完全不用关心这个实体对象在哪个server,在哪台物理机器上。其实现原理也很简单,DCET框架提供了一个位置服务器,所有挂载MailBoxComponent的实体对象都会将自己的id跟位置注册到这个位置服务器,其它服务器向这个实体对象发送消息的时候如果不知道这个实体对象的位置,会先去位置服务器查询,查询到位置再进行发送。\n\n6.提供服务器不停服动态更新逻辑功能\n热更是游戏服务器不可缺少的功能,DCET框架使用的组件设计,可以做成守望先锋的设计,组件只有成员,无方法,将所有方法做成扩展方法放到热更dll中,运行时重新加载dll即可热更所有逻辑。\n\n7.客户端使用C#热更新,热更新一键切换\n因为ios的限制,之前unity热更新一般使用lua,导致unity3d开发人员要写两种代码,麻烦的要死。之后幸好出了ILRuntime库,利用ILRuntime库,unity3d可以利用C#语言加载热更新dll进行热更新。ILRuntime一个缺陷就是开发时候不支持VS debug,这有点不爽。DCET框架使用了一个预编译指令ILRuntime,可以无缝切换。平常开发的时候不使用ILRuntime,而是使用Assembly.Load加载热更新动态库,这样可以方便用VS单步调试。在发布的时候,定义预编译指令ILRuntime就可以无缝切换成使用ILRuntime加载热更新动态库。这样开发起来及其方便,再也不用使用狗屎lua了\n\n8.客户端全热更新\n客户端可以实现所有逻辑热更新,包括协议,config,ui等等\n\n9.客户端服务端用同一种语言,并且共享代码\n下载DCET框架,打开服务端工程,可以看到服务端引用了客户端很多代码,通过引用客户端代码的方式实现了双端共享代码。例如客户端服务端之间的网络消息两边完全共用一个文件即可,添加一个消息只需要修改一遍。\n\n10.KCP TCP Websocket协议无缝切换\nDCET框架不但支持TCP,而且支持可靠的UDP协议(KCP),KCP是可靠UDP协议,使用kcp请注意,需要自己加心跳机制,否则20秒没收到包,服务端将断开连接。协议可以无缝切换。\n\n11. 3D Recast寻路功能\n可以Unity导出场景数据,给服务端做recast寻路。做MMO非常方便,demo演示了服务端3d寻路功能\n\n12. 服务端支持repl,也可以动态执行一段新代码\n这样就可以打印出进程中任何数据,大大简化了服务端查找问题的难度,开启repl方法,直接在console中输入repl回车即可进入repl模式\n\n13.打包工具\nDCET框架带有一整套打包工具,完全傻瓜式。一键打包,自动分析共享资源。对比md5更新\n\n14.还有很多很多功能,我就不详细介绍了\na.及其方便检查CPU占用和内存泄漏检查,vs自带分析工具,不用再为性能和内存泄漏检查而烦恼\nb.使用NLog库,打log及其方便,平常开发时,可以将所有服务器log打到一个文件中,再也不用一个个文件搜索log了\nc.统一使用Mongodb的bson做序列化,消息和配置文件全部都是bson或者json,并且以后使用mongodb做数据库,再也不用做格式转换了。\nd.提供一个强大的ai行为树工具\ne.提供一个同步工具\nf.提供命令行配置工具,配置分布式非常简单\n\nDCET框架的服务端是一个强大灵活的分布式服务端架构,完全可以满足绝大部分大型游戏需求。使用这套框架,客户端开发者就可以自己完成双端开发,节省大量人力物力,节省大量沟通时间。", "keywords": ["DCET", "ET", "Framework"], "category": "Script", "dependencies": { } }
5,719
415
<filename>todoapp/todos/tests.py import json from django.contrib.auth.models import User from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from todos.models import Todo from todos.serializers import TodoSerializer class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todos:list") def setUp(self): self.username = "john" self.email = "<EMAIL>" self.password = "<PASSWORD>" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_create_todo(self): response = self.client.post(self.url, {"name": "Clean the room!"}) self.assertEqual(201, response.status_code) def test_user_todos(self): """ Test to verify user todos list """ Todo.objects.create(user=self.user, name="Clean the car!") response = self.client.get(self.url) self.assertTrue(len(json.loads(response.content)) == Todo.objects.count()) class TodoDetailAPIViewTestCase(APITestCase): def setUp(self): self.username = "john" self.email = "<EMAIL>" self.password = "<PASSWORD>" self.user = User.objects.create_user(self.username, self.email, self.password) self.todo = Todo.objects.create(user=self.user, name="Call Mom!") self.url = reverse("todos:detail", kwargs={"pk": self.todo.pk}) self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_todo_object_bundle(self): """ Test to verify todo object bundle """ response = self.client.get(self.url) self.assertEqual(200, response.status_code) todo_serializer_data = TodoSerializer(instance=self.todo).data response_data = json.loads(response.content) self.assertEqual(todo_serializer_data, response_data) def test_todo_object_update_authorization(self): """ Test to verify that put call with different user token """ new_user = User.objects.create_user("newuser", "<EMAIL>", "<PASSWORD>") new_token = Token.objects.create(user=new_user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + new_token.key) # HTTP PUT response = self.client.put(self.url, {"name", "Hacked by new user"}) self.assertEqual(403, response.status_code) # HTTP PATCH response = self.client.patch(self.url, {"name", "Hacked by new user"}) self.assertEqual(403, response.status_code) def test_todo_object_update(self): response = self.client.put(self.url, {"name": "Call Dad!"}) response_data = json.loads(response.content) todo = Todo.objects.get(id=self.todo.id) self.assertEqual(response_data.get("name"), todo.name) def test_todo_object_partial_update(self): response = self.client.patch(self.url, {"done": True}) response_data = json.loads(response.content) todo = Todo.objects.get(id=self.todo.id) self.assertEqual(response_data.get("done"), todo.done) def test_todo_object_delete_authorization(self): """ Test to verify that put call with different user token """ new_user = User.objects.create_user("newuser", "<EMAIL>", "<PASSWORD>") new_token = Token.objects.create(user=new_user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + new_token.key) response = self.client.delete(self.url) self.assertEqual(403, response.status_code) def test_todo_object_delete(self): response = self.client.delete(self.url) self.assertEqual(204, response.status_code)
1,676
4,054
<filename>eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "constant_value.h" #include <vespa/vespalib/stllike/string.h> namespace vespalib { namespace eval { /** * A ConstantValueFactory that will load constant tensor values from * file. The file is expected to be in json format with the same * structure used when feeding. **/ class ConstantTensorLoader : public ConstantValueFactory { private: const ValueBuilderFactory &_factory; public: ConstantTensorLoader(const ValueBuilderFactory &factory) : _factory(factory) {} ConstantValue::UP create(const vespalib::string &path, const vespalib::string &type) const override; }; } // namespace vespalib::eval } // namespace vespalib
260