text
stringlengths
1
1.05M
<gh_stars>0 package benchmarks import agni.RowDecoder import agni.generic.semiauto._ package object inMem { type S5 = (String, String, String, String, String) type S22 = (String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String) } package inMem { final case class C5(s1: String, s2: String, s3: String, s4: String, s5: String) object C5 { implicit val e: RowDecoder[C5] = derivedRowDecoder[C5] } final case class C22(s1: String, s2: String, s3: String, s4: String, s5: String, s6: String, s7: String, s8: String, s9: String, s10: String, s11: String, s12: String, s13: String, s14: String, s15: String, s16: String, s17: String, s18: String, s19: String, s20: String, s21: String, s22: String) object C22 { implicit val e: RowDecoder[C22] = derivedRowDecoder[C22] } final case class C30(s1: String, s2: String, s3: String, s4: String, s5: String, s6: String, s7: String, s8: String, s9: String, s10: String, s11: String, s12: String, s13: String, s14: String, s15: String, s16: String, s17: String, s18: String, s19: String, s20: String, s21: String, s22: String, s23: String, s24: String, s25: String, s26: String, s27: String, s28: String, s29: String, s30: String) object C30 { implicit val e: RowDecoder[C30] = derivedRowDecoder[C30] } }
/* * Copyright (c) 2010, <NAME> * All rights reserved. * * Made available under the BSD license - see the LICENSE file */ package sim.routing; //import java.util.ArrayList; //import java.util.Arrays; /* * Floyd-Warshall all-pairs shortest path algorithm * Modified implementation from http://algowiki.net/wiki/index.php/Floyd-Warshall%27s_algorithm */ public class ShortestPath { /*private int[][] dist; private Vertex[][] P; public ShortestPath(Vertex[] vertices, Edge[] edges) { calcShortestPaths(vertices, edges); } private void calcShortestPaths(Vertex[] vertices, Edge[] edges) { dist = initializeWeight(vertices.length, edges); P = new Vertex[vertices.length][vertices.length]; for(int k=0; k<vertices.length; k++){ for(int i=0; i<vertices.length; i++){ for(int j=0; j<vertices.length; j++){ if(dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE && dist[i][k]+dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k]+dist[k][j]; P[i][j] = vertices[k]; } } } } } public int getOutputPort(Vertex source, Vertex target) { ArrayList<Vertex> path = getShortestPath(source, target); return source.getOutputPort(path.get(1).getId()); } public int getShortestDistance(Vertex source, Vertex target){ return dist[source.getId()][target.getId()]; } public ArrayList<Vertex> getShortestPath(Vertex source, Vertex target){ if(dist[source.getId()][target.getId()] == Integer.MAX_VALUE) return new ArrayList<Vertex>(); ArrayList<Vertex> path = getIntermediatePath(source, target); path.add(0, source); path.add(target); return path; } private ArrayList<Vertex> getIntermediatePath(Vertex source, Vertex target){ if(dist == null) throw new IllegalArgumentException("Must call calcShortestPaths(...) before attempting to obtain a path."); if(P[source.getId()][target.getId()] == null) return new ArrayList<Vertex>(); ArrayList<Vertex> path = new ArrayList<Vertex>(); path.addAll(getIntermediatePath(source, P[source.getId()][target.getId()])); path.add(P[source.getId()][target.getId()]); path.addAll(getIntermediatePath(P[source.getId()][target.getId()], target)); return path; } private int[][] initializeWeight(int numNodes, Edge[] edges){ int[][] Weight = new int[numNodes][numNodes]; for(int i=0; i<numNodes; i++) Arrays.fill(Weight[i], Integer.MAX_VALUE); for(Edge e : edges) Weight[e.getFromId()][e.getToId()] = e.getWeight(); return Weight; }*/ }
import { rxIP4 } from '../regex'; import { testFind, testReplace, testVerify } from './_'; const valid: string[] = ['127.0.0.1', '0.0.0.0', '255.255.255.255']; const invalid: string[] = ['a.0.0.0', '0.a.0.0', '0.0.a.0', '0.0.0.a', '0.256.0.0', '0.0.256.0']; testVerify('IP4', rxIP4, valid, invalid); testFind('IP4', rxIP4, valid, invalid); testReplace('IP4', rxIP4, valid, invalid);
import React from "react" import './imageModal.sass' import { Modal, Button } from 'react-bootstrap' export default function ImageModal(props) { const viewImage = props.Root("READ", "lastViewedImage") return ( <div> <div> <Modal size="xl" show={viewImage.show} onHide={props.handleClose} className="image-modal" > <Modal.Header closeButton> <Modal.Title> Image ID# {viewImage.id} </Modal.Title> </Modal.Header> <Modal.Body> <img src={viewImage.img_src} className="image" alt="mars"/> <h5> Camera: <span className="right"> {viewImage.cameraName} </span> </h5> <hr /> <h5> Martian days from landing(sol): <span className="right"> {viewImage.sol} </span> </h5> <hr /> <h5> Date taken: <span className="right"> {viewImage.earth_date} </span> </h5> </Modal.Body> {!props.noSaveButton && <Modal.Footer className="d-flex justify-content-center"> <Button variant="primary" className="save-button" onClick={props.saveImage} > Save Image </Button> </Modal.Footer> } </Modal> </div> </div> ) }
RELEASE_VERSION="8.1.0-2" DISTRIBUTION_FILE_DATE="20181019-0952" TARGET_OS="linux" TARGET_BITS="32" HOST_UNAME="Linux" GROUP_ID="1000" USER_ID="1000" HOST_WORK_FOLDER_PATH="/home/ilg/Work/riscv-none-gcc-8.1.0-2" CONTAINER_WORK_FOLDER_PATH="/Host/Work/riscv-none-gcc-8.1.0-2" HOST_CACHE_FOLDER_PATH="/home/ilg/.caches/XBB" CONTAINER_CACHE_FOLDER_PATH="/Host/Caches/XBB" DEPLOY_FOLDER_NAME="deploy"
roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=none results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_shotgun_all_none.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=random results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_shotgun_all_random.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=local results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_shotgun_all_local.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=none shotgun:=false results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_simple_none.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=none shotgun_path:=false results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_shotgun_nopath_none.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=random shotgun_path:=false shotgun:=false results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_simple_random.csv roslaunch mav_planning_benchmark local_planning_benchmark.launch exit_at_end:=true num_trials:=1000 strategy:=local shotgun_path:=false shotgun:=false results_path:=/home/helen/data/jfr_2018/local_benchmark/local_11_05_2019_script_simple_local.csv
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package inventory scans the current inventory (patches and package installed and available) // and writes them to Guest Attributes. package inventory import ( "fmt" "reflect" "strings" "time" "github.com/GoogleCloudPlatform/guest-logging-go/logger" "github.com/GoogleCloudPlatform/osconfig/attributes" "github.com/GoogleCloudPlatform/osconfig/config" "github.com/GoogleCloudPlatform/osconfig/osinfo" "github.com/GoogleCloudPlatform/osconfig/packages" "github.com/GoogleCloudPlatform/osconfig/tasker" ) const ( inventoryURL = config.ReportURL + "/guestInventory" ) // InstanceInventory is an instances inventory data. type InstanceInventory struct { Hostname string LongName string ShortName string Version string Architecture string KernelVersion string KernelRelease string OSConfigAgentVersion string InstalledPackages packages.Packages PackageUpdates packages.Packages LastUpdated string } func write(state *InstanceInventory, url string) { logger.Debugf("Writing instance inventory.") e := reflect.ValueOf(state).Elem() t := e.Type() for i := 0; i < e.NumField(); i++ { f := e.Field(i) u := fmt.Sprintf("%s/%s", url, t.Field(i).Name) switch f.Kind() { case reflect.String: logger.Debugf("postAttribute %s: %+v", u, f) if err := attributes.PostAttribute(u, strings.NewReader(f.String())); err != nil { logger.Errorf("postAttribute error: %v", err) } case reflect.Struct: logger.Debugf("postAttributeCompressed %s: %+v", u, f) if err := attributes.PostAttributeCompressed(u, f.Interface()); err != nil { logger.Errorf("postAttributeCompressed error: %v", err) } } } } // Get generates inventory data. func Get() *InstanceInventory { logger.Debugf("Gathering instance inventory.") hs := &InstanceInventory{} installedPackages, err := packages.GetInstalledPackages() if err != nil { logger.Errorf("packages.GetInstalledPackages() error: %v", err) } packageUpdates, err := packages.GetPackageUpdates() if err != nil { logger.Errorf("packages.GetPackageUpdates() error: %v", err) } oi, err := osinfo.Get() if err != nil { logger.Errorf("osinfo.Get() error: %v", err) } hs.Hostname = oi.Hostname hs.LongName = oi.LongName hs.ShortName = oi.ShortName hs.Version = oi.Version hs.KernelVersion = oi.KernelVersion hs.KernelRelease = oi.KernelRelease hs.Architecture = oi.Architecture hs.OSConfigAgentVersion = config.Version() hs.InstalledPackages = installedPackages hs.PackageUpdates = packageUpdates hs.LastUpdated = time.Now().UTC().Format(time.RFC3339) return hs } // Run gathers and records inventory information using tasker.Enqueue. func Run() { tasker.Enqueue("Run OSInventory", func() { write(Get(), inventoryURL) }) }
package io.opensphere.core.util.swing.table; import java.util.List; /** * A provider of row values. * * @param <T> the type of the data object */ @FunctionalInterface public interface RowValuesProvider<T> { /** * Gets the row values for the given row and data object. * * @param rowIndex the row index * @param dataObject the data object * @return the row values */ List<?> getValues(int rowIndex, T dataObject); }
#!/bin/bash aws cloudformation update-stack --stack-name lambda-function \ --template-body file://lambda-function.yaml \ --capabilities CAPABILITY_NAMED_IAM \ --parameters file://lambda-function-parameters.json \ --region us-east-1
package servicecentral import ( "testing" "github.com/atlassian/voyager" "github.com/stretchr/testify/assert" ) func TestParsesTagsFromServiceCentralCorrectly(t *testing.T) { t.Parallel() testCases := []struct { name string inputTags []string expectedTags map[voyager.Tag]string }{ { "nothing mapped", []string{"not", "mapped"}, map[voyager.Tag]string{}}, { "mix of tags", []string{"skipthis", "micros2:foo=bar"}, map[voyager.Tag]string{"foo": "bar"}, }, { "valid and invalid", []string{"micros2:blah=something", "micros:notvalid=skipme"}, map[voyager.Tag]string{"blah": "something"}, }, { "skip invalid", []string{"micros2:=nokey", "micros2:novalue="}, map[voyager.Tag]string{}, }, { "special chars", []string{"micros2:some_key-other====this+works/but_is-silly"}, map[voyager.Tag]string{"some_key-other": "===this+works/but_is-silly"}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actual := parsePlatformTags(tc.inputTags) assert.Equal(t, tc.expectedTags, actual) }) } } func TestConvertsTagsToServiceCentralFormatCorrectly(t *testing.T) { t.Parallel() testCases := []struct { name string inputTags map[voyager.Tag]string expected []string }{ { "Single value", map[voyager.Tag]string{ "foo": "bar", }, []string{"micros2:foo=bar"}, }, { "Multiple values", map[voyager.Tag]string{ "foo": "bar", "other": "baz", "something": "else", }, []string{"micros2:foo=bar", "micros2:other=baz", "micros2:something=else"}, }, { "Empty map", map[voyager.Tag]string{}, []string{}, }, { "nil map", nil, []string{}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actual := convertPlatformTags(tc.inputTags) assert.ElementsMatch(t, tc.expected, actual) }) } } func TestFiltersNonPlatformTagsCorrectly(t *testing.T) { t.Parallel() testCases := []struct { name string inputTags []string expected []string }{ { "Only SC", []string{"random", "things"}, []string{"random", "things"}, }, { "Mix of values", []string{"sc entry", "micros2:foo=bar"}, []string{"sc entry"}, }, { "Platform only", []string{"micros2:foo=bar", "micros2:blah=something"}, []string{}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actual := nonPlatformTags(tc.inputTags) assert.Equal(t, tc.expected, actual) }) } }
const fs = require('fs'); const path = require('path'); const saveStyleModule = ({ srcDir, moduleNameSuffix }) => { return (cssFileName, json) => { const cssDir = path.dirname(cssFileName); const cssName = path.basename(cssFileName, '.css'); const baseModuleNames = path.relative(srcDir, cssDir).split(path.sep); if (baseModuleNames.length > 0 && baseModuleNames[0] === '..') return; const moduleName = cssName + moduleNameSuffix; const pursFilePath = path.resolve(cssDir, moduleName + '.purs'); const entries = Object .keys(json) .sort() .map((key) => ({ key, value: json[key] })) .map(({ key, value }) => { return { key: key.replace(/-(.)/, (_, c) => c.toUpperCase()), value }; }); const purs = [ 'module ' + baseModuleNames.concat([moduleName]).join('.') ].concat( ' ( ' + entries.map((i) => i.key).join('\n , ') + '\n ) where' ).concat( entries.map(({ key, value }) => { return [ '', key + ' :: String', key + ' = "' + value + '"' ].join('\n'); }) ).join('\n'); fs.writeFileSync(pursFilePath, purs, { encoding: 'utf-8' }); }; }; const mySaveStyleModule = saveStyleModule({ srcDir: path.resolve('./src'), moduleNameSuffix: 'Style' }); module.exports = { plugins: [ require('postcss-modules')({ getJSON: (cssFileName, json, _outputFileName) => { return mySaveStyleModule(cssFileName, json); } }) ] };
function extractJavaFileInfo(filePath) { const fs = require('fs'); const fileContent = fs.readFileSync(filePath, 'utf8'); const packageRegex = /package\s+([\w.]+);/; const interfaceRegex = /interface\s+(\w+)\s+extends\s+(\w+)<.*>/; const packageMatch = fileContent.match(packageRegex); const interfaceMatch = fileContent.match(interfaceRegex); if (packageMatch && interfaceMatch) { const packageName = packageMatch[1]; const interfaceName = interfaceMatch[1]; const superclassName = interfaceMatch[2]; return { packageName, interfaceName, superclassName }; } else { throw new Error('Invalid Java file format'); } } // Test the function const filePath = "server/src/main/java/com/ninjamind/confman/repository/ParameterValueGenericRepository.java"; const fileInfo = extractJavaFileInfo(filePath); console.log(fileInfo);
<gh_stars>0 /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import { v1 as uuidv1 } from 'uuid'; import { useMemo } from 'react'; /** * This function returns a function to generate ids. * This can be used to generate unique, but predictable ids to pair labels * with their inputs. It takes an optional prefix as a parameter. If you don't * specify it, it generates a random id prefix. If you specify a custom prefix * it should begin with an letter to be HTML4 compliant. */ export function htmlIdGenerator(idPrefix: string = '') { const staticUuid = uuidv1(); return (idSuffix: string = '') => { const prefix = `${idPrefix}${idPrefix !== '' ? '_' : 'i'}`; const suffix = idSuffix ? `_${idSuffix}` : ''; return `${prefix}${suffix ? staticUuid : uuidv1()}${suffix}`; }; } /** * Generates a memoized ID that remains static until component unmount. * This prevents IDs from being re-randomized on every component update. */ export type UseGeneratedHtmlIdOptions = { /** * Optional prefix to prepend to the generated ID */ prefix?: string; /** * Optional suffix to append to the generated ID */ suffix?: string; /** * Optional conditional ID to use instead of a randomly generated ID. * Typically used by EUI components where IDs can be passed in as custom props */ conditionalId?: string; }; export const useGeneratedHtmlId = ({ prefix, suffix, conditionalId, }: UseGeneratedHtmlIdOptions = {}) => { return useMemo<string>(() => { return conditionalId || htmlIdGenerator(prefix)(suffix); }, [conditionalId, prefix, suffix]); };
export const getScreenWidth = () => { return window.innerWidth; }; export const setBodyColor = (color) => { document.body.style.background = color; }; export const navigateTo = (url) => { window.open(url); };
import React from "react" import Header from "../components/header" import Footer from "../components/footer" import CardAnderson from "../components/card_professor/card_anderson" import CardCarla from "../components/card_professor/card_carla" import CardLuciana from "../components/card_professor/card_luciana" import SEO from "../components/seo" const Professors = () => { return ( <div> <Header /> <SEO title="Professors" /> <div className="section"> <div className="container"> <div className="columns"> <div className="column"> <CardAnderson /> </div> <div className="column"> <CardCarla /> </div> <div className="column"> <CardLuciana /> </div> </div> </div> </div> <Footer /> </div> ) } export default Professors
#!/bin/sh BASE_DIR=$(dirname "$(readlink -f "$0")") if [ "$1" != "test" ]; then psql -h localhost -U restimageserver -d restimageserver < $BASE_DIR/restimageserver.sql fi psql -h localhost -U restimageserver -d restimageserver_test < $BASE_DIR/restimageserver.sql
<gh_stars>100-1000 // Copyright 2021 The BladeDISC Authors. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "compiler/mlir/runtime/ral_context.h" #include <dlfcn.h> #include <c10/core/CPUAllocator.h> #if PYTORCH_MAJOR_VERSION == 1 && PYTORCH_MINOR_VERSION >= 11 #include <c10/core/impl/alloc_cpu.h> #endif #ifdef TORCH_BLADE_BUILD_WITH_CUDA #ifdef TORCH_BLADE_USE_ROCM #include <c10/hip/HIPCachingAllocator.h> #include <c10/hip/HIPFunctions.h> #else // TORCH_BLADE_USE_ROCM #include <c10/cuda/CUDACachingAllocator.h> #include <c10/cuda/CUDAFunctions.h> #endif // TORCH_BLADE_USE_ROCM #endif // TORCH_BLADE_BUILD_WITH_CUDA #include "tensorflow/compiler/mlir/xla/ral/ral_api.h" #include "common_utils/utils.h" #ifdef TORCH_BLADE_USE_ROCM namespace c10 { namespace cuda { const auto& current_device = ::c10::hip::current_device; const auto& getCurrentCUDAStream = ::c10::hip::getCurrentHIPStream; namespace CUDACachingAllocator = ::c10::hip::HIPCachingAllocator; } // namespace cuda } // namespace c10 #endif // TORCH_BLADE_USE_ROCM namespace torch { namespace blade { class RalAllocator : public tao::ral::Allocator { public: using buffer_t = tao::ral::buffer_t; using alloc_t = tao::ral::alloc_t; using dealloc_t = tao::ral::dealloc_t; RalAllocator(alloc_t alloc_func, dealloc_t dealloc_func) : alloc_func_(alloc_func), dealloc_func_(dealloc_func) {} buffer_t alloc(size_t bytes) { return alloc_func_(bytes); } void dealloc(buffer_t buffer) { dealloc_func_(buffer); } private: alloc_t alloc_func_; dealloc_t dealloc_func_; }; // Check if every tensor in a list of tensors matches the current // device. bool RalContext::CheckCurrentDevice(const at::List<at::Tensor>& inputs) const { #ifdef TORCH_BLADE_BUILD_WITH_CUDA TORCH_CHECK(gpu_device_ == c10::cuda::current_device()); // TODO(gty): Refactor this function together with the one defined in TensorRT // Engine Context if (inputs.empty()) { return true; } // TODO: to support cpu only torch torch::Device cur_cuda_device = torch::Device(torch::kCUDA, c10::cuda::current_device()); auto& inputs_info = engine_state_->inputs; TORCH_CHECK(inputs_info.size() == inputs.size()); for (size_t k = 0; k < inputs.size(); ++k) { at::Tensor inp = inputs[k]; auto device = inputs_info[k].device; if (device == "cuda" && inp.device() != cur_cuda_device) { return false; } } return true; #endif // TORCH_BLADE_BUILD_WITH_CUDA return true; } std::tuple<void*, void*> RalContext::LoadEngine( const std::string& ral_engine_bytes) { // Also had tried with shm_fs, however, dlopen tao_lib is not always // successful. auto is_ok = lib_tmpf_.WriteBytesToFile(ral_engine_bytes); TORCH_CHECK(is_ok, "Failed to dump RAL engine to file"); std::string filename = lib_tmpf_.GetFilename(); void* tao_lib = dlopen(filename.c_str(), RTLD_NOW | RTLD_LOCAL); TORCH_CHECK(tao_lib, "Fail to open ral engine"); void* func_handle = dlsym(tao_lib, kMlirLoweredEntry); TORCH_CHECK(func_handle, "Fail to find kMlirLoweredEntry"); return std::make_tuple(tao_lib, func_handle); } RalContext::~RalContext() { if (tao_lib_ != nullptr) { dlclose(tao_lib_); } } RalContext::RalContext(std::shared_ptr<backends::EngineState> state) : engine_state_(state) { auto is_ok = meta_tmpf_.WriteBytesToFile(state->model_proto); TORCH_CHECK(is_ok, "FAiled to dump model proto to file."); default_opt_.metadata_file_path = meta_tmpf_.GetFilename(); default_opt_.cache_workspace_mem_across_execution = true; auto torch_allocator = c10::GetAllocator(torch::kCPU); TORCH_CHECK(torch_allocator != nullptr); auto cpu_alloc = [torch_allocator](size_t n) { return torch_allocator->raw_allocate(n); }; auto cpu_delete = [torch_allocator](void* ptr) { torch_allocator->raw_deallocate(ptr); }; cpu_opt_.cpu_allocator.reset(new RalAllocator(cpu_alloc, cpu_delete)); #ifdef TORCH_BLADE_BUILD_WITH_CUDA at::globalContext().lazyInitCUDA(); gpu_device_ = c10::cuda::current_device(); #else ral_ctx_ = tao::ral::cpu::MakeBaseCpuContext(default_opt_, cpu_opt_); #endif // TORCH_BLADE_BUILD_WITH_CUDA void* func_handle = nullptr; std::tie(tao_lib_, func_handle) = LoadEngine(state->engine_bytes); using func_t = void (*)(void**); entry_func_ = (func_t)func_handle; CHECK_NOTNULL(entry_func_); } at::List<at::Tensor> RalContext::PreProcessInputs( const at::List<at::Tensor>& inputs) const { // TODO: we currently only support inputs on the same device as tensorrt TORCH_CHECK(CheckCurrentDevice(inputs)); at::List<at::Tensor> contiguous_inputs; for (at::Tensor inp_tensor : inputs) { // make sure the input is in contiguous layout auto contiguous_tensor = inp_tensor.contiguous(); contiguous_inputs.push_back(contiguous_tensor); } return contiguous_inputs; } void RalContext::BindingInputs( const at::List<at::Tensor>& inputs, tao::ral::ExecutionContext& exec_ctx) const { for (size_t idx = 0; idx < inputs.size(); ++idx) { at::Tensor inp = inputs[idx]; const auto& shape = inp.sizes(); exec_ctx.bindInput(idx, inp.data_ptr(), shape.vec()); } } inline bool IsEmptyTensor(const tao::ral::buffer_shape_t& shape) { return shape.size() > 0 && std::any_of( shape.begin(), shape.end(), [](int64_t dim) { return dim == 0; }); } at::List<at::Tensor> RalContext::CreateAndBindingOutputs( tao::ral::ExecutionContext& exec_ctx) const { at::List<at::Tensor> outputs; auto num_outputs = engine_state_->outputs.size(); outputs.reserve(num_outputs); std::vector<std::unique_ptr<tao::ral::OutputBufferWrapper>> out_bufs( num_outputs); for (size_t idx = 0; idx < num_outputs; ++idx) { auto& out_buf = out_bufs[idx]; // Note: Ral has memory allocator that allocate memory each time forward. // So it's thread-safe to reuse the underline memory. exec_ctx.bindOutput(idx, &out_buf); const auto& output_info = engine_state_->outputs[idx]; auto scalar_type = output_info.scalar_type; #ifdef TORCH_BLADE_BUILD_WITH_CUDA torch::DeviceType dev_type = torch::kCUDA; dev_type = (output_info.device == "cuda") ? torch::kCUDA : torch::kCPU; #else torch::DeviceType dev_type = torch::kCPU; #endif // TORCH_BLADE_BUILD_WITH_CUDA auto option = torch::device(dev_type) .dtype(scalar_type) .memory_format(torch::MemoryFormat::Contiguous); at::Tensor out_tensor; if (IsEmptyTensor(out_buf->shape())) { out_tensor = torch::zeros(out_buf->shape(), option); } else if (out_buf->owned()) { auto cpu_allocator = c10::GetAllocator(torch::kCPU); TORCH_CHECK(cpu_allocator != nullptr); std::function<void(void*)> deleter = [cpu_allocator](void* ptr) { cpu_allocator->raw_deallocate(ptr); }; #ifdef TORCH_BLADE_BUILD_WITH_CUDA if (output_info.device == "cuda") { deleter = c10::cuda::CUDACachingAllocator::raw_delete; } #endif out_tensor = torch::from_blob( const_cast<void*>(out_buf->data()), out_buf->shape(), deleter, option); out_buf->release(); } else { out_tensor = torch::from_blob( const_cast<void*>(out_buf->data()), out_buf->shape(), option) .clone(); } outputs.push_back(out_tensor); } return outputs; } #ifdef TORCH_BLADE_BUILD_WITH_CUDA tao::ral::BaseContext* RalContext::LoadCache() { TORCH_CHECK(gpu_device_ == c10::cuda::current_device()) c10::cuda::CUDAStream stream = c10::cuda::getCurrentCUDAStream(gpu_device_); // TODO: take care of the duplicated const // which currently is managed per context tao::ral::gpu::BaseCudaContextOption gpu_opt; gpu_opt.device_ordinal = gpu_device_; gpu_opt.use_stream_executor = true; gpu_opt.gpu_allocator.reset(new RalAllocator( c10::cuda::CUDACachingAllocator::raw_alloc, c10::cuda::CUDACachingAllocator::raw_delete)); std::lock_guard<std::mutex> guard(mtx_); tao::ral::BaseContext* ral_ctx_ptr; auto it = ral_ctx_map_.find(stream); if (it == ral_ctx_map_.end()) { gpu_opt.stream = stream.stream(); auto ral_ctx = tao::ral::gpu::MakeBaseCudaContext(default_opt_, cpu_opt_, gpu_opt); ral_ctx_ptr = ral_ctx.get(); ral_ctx_map_[stream].reset(ral_ctx.release()); } else { ral_ctx_ptr = it->second.get(); } return ral_ctx_ptr; } #endif // TORCH_BLADE_BUILD_WITH_CUDA at::List<at::Tensor> RalContext::Execute(const at::List<at::Tensor>& inputs) { #ifdef TORCH_BLADE_BUILD_WITH_CUDA auto ral_ctx = LoadCache(); // execution context is per-inference context and thread-safe auto exec_ctx = tao::ral::MakeExecutionContext<tao::ral::gpu::BaseCudaExecutionContext>( ral_ctx); #else auto exec_ctx = tao::ral::MakeExecutionContext<tao::ral::cpu::BaseCpuExecutionContext>( ral_ctx_.get()); #endif // TORCH_BLADE_BUILD_WITH_CUDA auto contiguous_inputs = PreProcessInputs(inputs); BindingInputs(contiguous_inputs, *exec_ctx.get()); auto tao_ral_func_ptr = reinterpret_cast<void*>(&tao_ral_call_impl); // execute void* ctx_struct[] = {exec_ctx.get(), tao_ral_func_ptr}; try { entry_func_(ctx_struct); } catch (std::exception& ex) { LOG(ERROR) << ex.what(); throw ex; } auto outputs = CreateAndBindingOutputs(*exec_ctx.get()); return outputs; } } // namespace blade } // namespace torch
package com.abubusoft.kripton.benchmark.serializetasks; public class SerializeResult { public long runDuration; public int objectsParsed; public SerializeResult(long runDuration, int objectsSerialized) { this.runDuration = runDuration; this.objectsParsed = objectsSerialized; } }
/** * * ListHeader * */ import React from 'react'; import PropTypes from 'prop-types'; import { ListHeader as StyledListHeader } from '@buffetjs/styles'; import Button from '../Button'; import Flex from '../Flex'; import Padded from '../Padded'; import Text from '../Text'; import BaselineAlignement from './BaselineAlignement'; function ListHeader({ button, title, subtitle }) { return ( <StyledListHeader> <Flex justifyContent="space-between"> <Padded top bottom size="smd"> <Text fontSize="lg" fontWeight="bold" lineHeight="18px"> {title} </Text> {subtitle && ( <Padded top size="xs"> <Text fontSize="md" color="grey" lineHeight="13px"> {subtitle} </Text> </Padded> )} </Padded> {button && ( <BaselineAlignement> <Button {...button} /> </BaselineAlignement> )} </Flex> </StyledListHeader> ); } ListHeader.defaultProps = { button: null, title: null, subtitle: null, }; ListHeader.propTypes = { button: PropTypes.shape({ color: PropTypes.string, icon: PropTypes.bool, type: PropTypes.string, }), subtitle: PropTypes.string, title: PropTypes.string, }; export default ListHeader;
## Settings # Filename of the dotenv file to look for : ${ZSH_DOTENV_FILE:=.env} # Path to the file containing allowed paths : ${ZSH_DOTENV_ALLOWED_LIST:="${ZSH_CACHE_DIR:-$ZSH/cache}/dotenv-allowed.list"} ## Functions source_env() { if [[ -f $ZSH_DOTENV_FILE ]]; then if [[ "$ZSH_DOTENV_PROMPT" != false ]]; then local confirmation dirpath="${PWD:A}" # make sure there is an allowed file touch "$ZSH_DOTENV_ALLOWED_LIST" # check if current directory's .env file is allowed or ask for confirmation if ! grep -q "$dirpath" "$ZSH_DOTENV_ALLOWED_LIST" &>/dev/null; then # print same-line prompt and output newline character if necessary echo -n "dotenv: found '$ZSH_DOTENV_FILE' file. Source it? ([Y]es/[n]o/[a]lways) " read -k 1 confirmation; [[ "$confirmation" != $'\n' ]] && echo # check input case "$confirmation" in [nN]) return ;; [aA]) echo "$dirpath" >> "$ZSH_DOTENV_ALLOWED_LIST" ;; *) ;; # interpret anything else as a yes esac fi fi # test .env syntax zsh -fn $ZSH_DOTENV_FILE || echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2 setopt localoptions allexport source $ZSH_DOTENV_FILE fi } autoload -U add-zsh-hook add-zsh-hook chpwd source_env source_env
<gh_stars>0 import * as clientType from '@sourcegraph/extension-api-types' import { from } from 'rxjs' import { distinctUntilChanged, first, switchMap, take, toArray } from 'rxjs/operators' import * as sourcegraph from 'sourcegraph' import { isDefined } from '../../util/types' import { Range } from '../extension/types/range' import { Selection } from '../extension/types/selection' import { assertToJSON } from '../extension/types/testHelpers' import { integrationTestContext } from './testHelpers' describe('CodeEditor (integration)', () => { describe('selection', () => { test('observe changes', async () => { const { services: { editor: editorService }, extensionAPI, } = await integrationTestContext() const editors = await from(editorService.editors) .pipe(first()) .toPromise() editorService.setSelections(editors[0], [new Selection(1, 2, 3, 4)]) editorService.setSelections(editors[0], []) const values = await from(extensionAPI.app.windows[0].activeViewComponentChanges) .pipe( switchMap(c => (c ? c.selectionsChanges : [])), distinctUntilChanged(), take(3), toArray() ) .toPromise() assertToJSON(values.map(v => v.map(v => Selection.fromPlain(v).toPlain())), [ [], [new Selection(1, 2, 3, 4).toPlain()], [], ]) }) }) describe('setDecorations', () => { test('adds decorations', async () => { const { services, extensionAPI } = await integrationTestContext() const dt = extensionAPI.app.createDecorationType() // Set some decorations and check they are present on the client. const editor = await getFirstCodeEditor(extensionAPI) editor.setDecorations(dt, [ { range: new Range(1, 2, 3, 4), backgroundColor: 'red', }, ]) await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual([ { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, backgroundColor: 'red', }, ] as clientType.TextDocumentDecoration[]) // Clear the decorations and ensure they are removed. editor.setDecorations(dt, []) await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual(null) }) it('merges decorations from several types', async () => { const { services, extensionAPI } = await integrationTestContext() const [dt1, dt2] = [extensionAPI.app.createDecorationType(), extensionAPI.app.createDecorationType()] const editor = await getFirstCodeEditor(extensionAPI) editor.setDecorations(dt1, [ { range: new Range(1, 2, 3, 4), after: { hoverMessage: 'foo', }, }, ]) editor.setDecorations(dt2, [ { range: new Range(1, 2, 3, 4), after: { hoverMessage: 'bar', }, }, ]) await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual([ { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'foo', }, }, { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'bar', }, }, ] as clientType.TextDocumentDecoration[]) // Change decorations only for dt1, and check that merged decorations are coherent editor.setDecorations(dt1, [ { range: new Range(1, 2, 3, 4), after: { hoverMessage: 'baz', }, }, ]) await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual([ { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'baz', }, }, { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'bar', }, }, ] as clientType.TextDocumentDecoration[]) // remove decorations for dt2, and verify that decorations for dt1 are still present editor.setDecorations(dt2, []) await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual([ { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'baz', }, }, ] as clientType.TextDocumentDecoration[]) }) it('is backwards compatible with extensions that do not provide a decoration type', async () => { const { services, extensionAPI } = await integrationTestContext() const dt = extensionAPI.app.createDecorationType() // Set some decorations and check they are present on the client. const editor = await getFirstCodeEditor(extensionAPI) editor.setDecorations(dt, [ { range: new Range(1, 2, 3, 4), backgroundColor: 'red', }, ]) // This call to setDecorations does not supply a type, mimicking extensions // that may have been developed against an older version of the API editor.setDecorations(null as any, [ { range: new Range(1, 2, 3, 4), after: { hoverMessage: 'foo', }, }, ]) // Both sets of decorations should be displayed await extensionAPI.internal.sync() expect( await services.textDocumentDecoration .getDecorations({ uri: 'file:///f' }) .pipe(take(1)) .toPromise() ).toEqual([ { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, backgroundColor: 'red', }, { range: { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }, after: { hoverMessage: 'foo', }, }, ] as clientType.TextDocumentDecoration[]) }) }) }) async function getFirstCodeEditor(extensionAPI: typeof sourcegraph): Promise<sourcegraph.CodeEditor> { return from(extensionAPI.app.activeWindowChanges) .pipe( first(isDefined), switchMap(win => win.activeViewComponentChanges), first(isDefined) ) .toPromise() }
<reponame>aasiyahf/programs<gh_stars>0 package edu.ncsu.csc316.hub_manager.priority_queue; import static org.junit.Assert.*; import org.junit.Test; import edu.ncsu.csc316.hub_manager.flight.Airport; import edu.ncsu.csc316.hub_manager.flight.FlightLeg; /** * Tests the MinHeap class * @author <NAME> * * @param <E> allows for abstract elements to be used */ public class MinHeapTest<E> { /** * Tests methods within MinHeap */ @Test public void test() { MinHeap<FlightLeg> heap = new MinHeap<FlightLeg>(6); Airport origin = new Airport("DFW", 32.89680099487305, -97.03800201416016); Airport destination = new Airport("MIA", 25.79319953918457, -80.29060363769531); FlightLeg flightLeg = new FlightLeg(origin, destination); heap.insert(10, flightLeg); heap.insert(100, flightLeg); heap.insert(7, flightLeg); heap.insert(30, flightLeg); heap.insert(50, flightLeg); heap.insert(60, flightLeg); assertEquals(6, heap.size()); heap.deleteMin(); heap.deleteMin(); heap.deleteMin(); heap.deleteMin(); heap.deleteMin(); heap.deleteMin(); try { heap.deleteMin(); fail(); } catch (ArrayIndexOutOfBoundsException e) { //catches exception } } }
from sklearn.ensemble import RandomForestClassifier features = [[2, 6, 9], [5, 3, 1], [7, 8, 4], [1, 4, 2]] labels = [0, 1, 1, 0] model = RandomForestClassifier(random_state=0).fit(features, labels)
#ifndef __SAY_HELLO #define __SAY_HELLO extern int say_hello(void); #endif
<filename>src/main/java/com/dmitrievanthony/tree/ui/classification/LocalClassificationUIApplication.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dmitrievanthony.tree.ui.classification; import com.dmitrievanthony.tree.core.Node; import com.dmitrievanthony.tree.core.local.LocalDecisionTreeClassifier; import com.dmitrievanthony.tree.ui.util.ControlPanel; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JFrame; import javax.swing.WindowConstants; public class LocalClassificationUIApplication extends ClassificationUIApplication { public static void main(String... args) { JFrame f = new JFrame(); f.setSize(500, 620); f.setBackground(Color.decode("#2B2B2B")); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ControlPanel ctrlPanel = new ControlPanel(); LocalClassificationUIApplication application = new LocalClassificationUIApplication(); ctrlPanel.addListener(application); f.add(ctrlPanel, BorderLayout.NORTH); f.add(application, BorderLayout.SOUTH); f.setVisible(true); } @Override Node classify(double[][] x, double[] y, int maxDeep, double minImpurityDecrease) { return new LocalDecisionTreeClassifier(maxDeep, minImpurityDecrease).fit(x, y); } }
#!/usr/bin/env bash # # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. export LC_ALL=C.UTF-8 DIAZ_CONFIG_ALL="--disable-dependency-tracking --prefix=$DEPENDS_DIR/$HOST --bindir=$BASE_OUTDIR/bin --libdir=$BASE_OUTDIR/lib" if [ -z "$NO_DEPENDS" ]; then DOCKER_EXEC ccache --max-size=$CCACHE_SIZE fi BEGIN_FOLD autogen if [ -n "$CONFIG_SHELL" ]; then DOCKER_EXEC "$CONFIG_SHELL" -c "./autogen.sh" else DOCKER_EXEC ./autogen.sh fi END_FOLD DOCKER_EXEC mkdir -p build export P_CI_DIR="$P_CI_DIR/build" BEGIN_FOLD configure DOCKER_EXEC ../configure --cache-file=config.cache $DIAZ_CONFIG_ALL $DIAZ_CONFIG || ( (DOCKER_EXEC cat config.log) && false) END_FOLD BEGIN_FOLD distdir # Create folder on host and docker, so that `cd` works mkdir -p "diaz-$HOST" DOCKER_EXEC make distdir VERSION=$HOST END_FOLD export P_CI_DIR="$P_CI_DIR/diaz-$HOST" BEGIN_FOLD configure DOCKER_EXEC ./configure --cache-file=../config.cache $DIAZ_CONFIG_ALL $DIAZ_CONFIG || ( (DOCKER_EXEC cat config.log) && false) END_FOLD set -o errtrace trap 'DOCKER_EXEC "cat ${BASE_SCRATCH_DIR}/sanitizer-output/* 2> /dev/null"' ERR BEGIN_FOLD build DOCKER_EXEC make $MAKEJOBS $GOAL || ( echo "Build failure. Verbose build follows." && DOCKER_EXEC make $GOAL V=1 ; false ) END_FOLD
<gh_stars>0 class NotificationsController < ApplicationController layout 'adminlte' def index @notifications = Notification.where(user: current_user).order(:created_at).reverse unread = @notifications.where(read: false) unread.each do |note| note.read = true note.save end end end
# https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-item zdesk_dynamic_content_item_delete () { method=DELETE url="$(echo "/api/v2/dynamic_content/items/{id}.json" | sed \ -e "s/{id}"/"$1"/ \ )" shift }
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
#! /usr/local/bin/ksh93 -p # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # $FreeBSD$ # # ident "@(#)zvol_swap_001_pos.ksh 1.3 08/05/14 SMI" # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # . $STF_SUITE/include/libtest.kshlib . $STF_SUITE/tests/zvol/zvol_common.kshlib ############################################################################### # # __stc_assertion_start # # ID: zvol_swap_001_pos # # DESCRIPTION: # Verify that a zvol can be used as a swap device # # STRATEGY: # 1. Create a pool # 2. Create a zvol volume # 3. Use zvol as swap space # 4. Create a file under $TMPDIR # # TESTABILITY: explicit # # TEST_AUTOMATION_LEVEL: automated # # CODING_STATUS: COMPLETED (2005-07-04) # # __stc_assertion_end # ################################################################################ verify_runnable "global" function cleanup { $RM -rf $TMPDIR/$TESTFILE if is_swap_inuse $voldev ; then log_must $SWAP -d $voldev fi } log_assert "Verify that a zvol can be used as a swap device" log_onexit cleanup test_requires SWAP voldev=/dev/zvol/$TESTPOOL/$TESTVOL log_note "Add zvol volume as swap space" log_must $SWAP -a $voldev log_note "Create a file under $TMPDIR" log_must $FILE_WRITE -o create -f $TMPDIR/$TESTFILE \ -b $BLOCKSZ -c $NUM_WRITES -d $DATA [[ ! -f $TMPDIR/$TESTFILE ]] && log_fail "Unable to create file under $TMPDIR" filesize=`$LS -l $TMPDIR/$TESTFILE | $AWK '{print $5}'` tf_size=$(( BLOCKSZ * NUM_WRITES )) (( $tf_size != $filesize )) && log_fail "testfile is ($filesize bytes), expected ($tf_size bytes)" log_pass "Successfully added a zvol to swap area."
import { render } from '@testing-library/react' import Header from './index' describe('Test Header.tsx', () => { it('Renderizando header', () => { const { container } = render(<Header />) const header = container.querySelector('header') expect(!!header).toBe(true) }) })
<filename>src/main/java/mastermind/models/server/SessionImplServer.java package mastermind.models.server; import java.util.List; import mastermind.models.Game; import mastermind.models.Session; import mastermind.models.StateValue; import mastermind.types.Color; import mastermind.types.FrameType; import santaTecla.utils.TCPIP; public class SessionImplServer implements Session { private TCPIP tcpip; public SessionImplServer(TCPIP tcpip) { this.tcpip = tcpip; } @Override public StateValue getValueState() { tcpip.send(FrameType.GET_VALUE_STATE); return tcpip.receiveStateValue(); } @Override public void redo() { tcpip.send(FrameType.REDO); } @Override public boolean isRedoable() { tcpip.send(FrameType.IS_REDOABLE); return tcpip.receiveBoolean(); } @Override public void undo() { tcpip.send(FrameType.UNDO); } @Override public boolean isUndoable() { tcpip.send(FrameType.IS_UNDOABLE); return tcpip.receiveBoolean(); } @Override public boolean isWinner() { tcpip.send(FrameType.IS_WINNER); return tcpip.receiveBoolean(); } @Override public boolean isLooser() { tcpip.send(FrameType.IS_LOOSER); return tcpip.receiveBoolean(); } @Override public int getAttempts() { tcpip.send(FrameType.GET_ATTEMPTS); return tcpip.receiveInt(); } @Override public List<Color> getColors(int position) { tcpip.send(FrameType.GET_COLORS); tcpip.send(position); return tcpip.receiveColors(); } @Override public int getBlacks(int position) { tcpip.send(FrameType.GET_BLACKS); return tcpip.receiveInt(); } @Override public int getWhites(int position) { tcpip.send(FrameType.GET_WHITES); return tcpip.receiveInt(); } @Override public int getWidth() { tcpip.send(FrameType.GET_WIDTH); return tcpip.receiveInt(); } @Override public void nextState() { tcpip.send(FrameType.NEXT_STATE); } @Override public void addProposedCombination(List<Color> colors) { tcpip.send(FrameType.ADD_PROPOSED_COMBINATION); tcpip.send(colors); tcpip.receiveError(); } @Override public void clear() { tcpip.send(FrameType.CLEAR); } @Override public void resetState() { tcpip.send(FrameType.RESET_STATE); } @Override public Game getGame() { return null; } @Override public void setStateValue(StateValue stateValue) { tcpip.send(FrameType.SET_STATE_VALUE); tcpip.send(stateValue); } @Override public boolean isGameFinished() { tcpip.send(FrameType.IS_GAME_FINISHED); return tcpip.receiveBoolean(); } @Override public void setGame(Game game) { } }
#!/bin/bash mkdir -p ${PREFIX}/bin #index pushd src/BWT_Index make CC=$CC FLAGS="$CFLAGS" LIBS="$LDFLAGS -lm -lz" cp bwt_index $PREFIX/bin popd #htslib pushd src/htslib make CC=$CC CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" libhts.a popd #dart pushd src make CXX=$CXX FLAGS="$CXXFLAGS -Wall -D NDEBUG -O3 -m64 -msse4.1 -fPIC" LIB="$LDFLAGS -lz -lm -lbz2 -llzma -lpthread" cp dart $PREFIX/bin
#!/bin/sh # OrientDB init script # You have to SET the OrientDB installation directory here ORIENTDB_DIR="YOUR_ORIENTDB_INSTALLATION_PATH" ORIENTDB_USER="USER_YOU_WANT_ORIENTDB_RUN_WITH" usage() { echo "Usage: `basename $0`: <start|stop|status>" exit 1 } start() { status if [ $PID -gt 0 ] then echo "OrientDB server daemon was already started. PID: $PID" return $PID fi echo "Starting OrientDB server daemon..." cd "$ORIENTDB_DIR/bin" su $ORIENTDB_USER -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./server.sh 1>../log/orientdb.log 2>../log/orientdb.err &" } stop() { status if [ $PID -eq 0 ] then echo "OrientDB server daemon is already not running" return 0 fi echo "Stopping OrientDB server daemon..." cd "$ORIENTDB_DIR/bin" su $ORIENTDB_USER -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./shutdown.sh 1>>../log/orientdb.log 2>>../log/orientdb.err &" } status() { PID=`ps -ef | grep 'orientdb.www.path' | grep java | grep -v grep | awk '{print $2}'` if [ "x$PID" = "x" ] then PID=0 fi # if PID is greater than 0 then OrientDB is running, else it is not return $PID } if [ "x$1" = "xstart" ] then start exit 0 fi if [ "x$1" = "xstop" ] then stop exit 0 fi if [ "x$1" = "xstatus" ] then status if [ $PID -gt 0 ] then echo "OrientDB server daemon is running with PID: $PID" else echo "OrientDB server daemon is NOT running" fi exit $PID fi usage
// style dependencies import '../../icon/style'; import './button.scss'; import './buttonGroup.scss';
<reponame>JamesParkinSonos/okta-auth-js /*! * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 type { Selector } from 'webdriverio'; type WaitForCommands = 'waitForClickable' | 'waitForDisplayed' | 'waitForEnabled' | 'waitForExist'; /** * Wait for the given element to be enabled, displayed, or to exist * @param {String} selector Element selector * @param {String} ms Wait duration (optional) * @param {String} falseState Check for opposite state * @param {String} state State to check for (default * existence) */ export default ( selector: Selector, ms: string, falseState: boolean, state: string ) => { /** * Maximum number of milliseconds to wait, default 3000 * @type {Int} */ const intMs = parseInt(ms, 10) || 3000; /** * Command to perform on the browser object * @type {String} */ let command: WaitForCommands = 'waitForExist'; /** * Boolean interpretation of the false state * @type {Boolean} */ let boolFalseState = !!falseState; /** * Parsed interpretation of the state * @type {String} */ let parsedState = ''; if (falseState || state) { parsedState = state.indexOf(' ') > -1 ? state.split(/\s/)[state.split(/\s/).length - 1] : state; if (parsedState) { command = `waitFor${parsedState[0].toUpperCase()}` + `${parsedState.slice(1)}` as WaitForCommands; } } if (typeof falseState === 'undefined') { boolFalseState = false; } $(selector)[command]({ timeout: intMs, reverse: boolFalseState, }); };
conda create --name docsenv python=3.7 source activate docsenv conda install -y pytorch=1.8 torchvision cpuonly -c pytorch conda install scipy pip install pymanopt conda install autograd pip install lie_learn pip install joblib pip install torch-geometric pip install sphinx pip install sphinx-rtd-theme pip install sphinx-autodoc-typehints
package cn.icepear.dandelion.upm.biz.mapper; import cn.icepear.dandelion.upm.api.domain.dto.DeptTree; import cn.icepear.dandelion.upm.api.domain.entity.SysDept; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author rim-wood * @description 部门管理 Mapper 接口 * @date Created on 2019-04-18. */ @Mapper public interface SysDeptMapper extends BaseMapper<SysDept> { /** * 所有的机构部门列表 * * @return 数据列表 */ List<DeptTree> listDeptsTrees(); /** * 所有的机构部门列表 * * @return 数据列表 */ List<SysDept> listDeptsTreesList(); /** * 查询父级机构列表 * * @return 部门父级数据列表 */ List<SysDept> parentListDepts(@Param("deptId") Long deptId, @Param("delFlag") Integer delFlag); /** * 查询子级机构列表 * * @param * @return 部门父级数据列表 */ List<SysDept> sonListDepts(Long deptId); }
def sum_first_100_natural_numbers(): total = 0 for i in range(1,101): total += i return total # example print(sum_first_100_natural_numbers()) # output: 5050
<reponame>Mitko-Kerezov/Friends var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var dependencyObservable = require("ui/core/dependency-observable"); var proxy = require("ui/core/proxy"); var textBase = require("ui/text-base"); var Label = (function (_super) { __extends(Label, _super); function Label(options) { _super.call(this, options); } Object.defineProperty(Label.prototype, "textWrap", { get: function () { return this._getValue(Label.textWrapProperty); }, set: function (value) { this._setValue(Label.textWrapProperty, value); }, enumerable: true, configurable: true }); Label.textWrapProperty = new dependencyObservable.Property("textWrap", "Label", new proxy.PropertyMetadata(false, dependencyObservable.PropertyMetadataSettings.AffectsLayout)); return Label; })(textBase.TextBase); exports.Label = Label;
<reponame>15292137182/era package com.went.core.erabatis.phantom; /** * <p>Title: Alias</p> * <p>Description: 别名列</p> * <p>Copyright: Shanghai era Information of management platform 2017</p> * * @author <NAME> * @version 1.0 * <pre>History: 2017/10/21 W<NAME> Create </pre> */ public interface Alias { /** * 获取字段信息 * * @return String * @Author wenTieHu * @date 2017/11/2 */ String getAlias(); }
export * from './utils'; export * from './annotation'; export * from './jsonrpc'; export * from './application'; export * from './logger'; export * from './container'; export * from './aop'; export * from './resolver'; export * from './constants'; export * from './config';
export enum RabbitMQ{ PassengerQueue = 'passengers' } export enum PassengerMSG{ CREATE = 'CREATE_PASSENGER', FIND_ALL='FIND_PASSENGERS', FIND_ONE= 'FIND_PASSENGER', UPDATE='UPDATE_PASSENGER', DELETE='DELETE_PASSENGER', }
#!/bin/bash #cd ../../ #make clean #make #cd scripts/parallel/ input_path="../../../workloads/scan/" #array-dram for file in $input_path*.spec; do n_threads=1 while [ $n_threads -le 16 ] do counter=1 echo "[Benchmark] array-dram, #of_threads: " $n_threads ", workload: ${file##*/}" while [ $counter -le 10 ] do ./../../../ycsbc -db storeds -threads $n_threads -dbpath /pmem/array.pmem -type array-dram-conc-lock -P $input_path${file##*/} ((counter++)) done echo "*****************<>*****************" ((n_threads*=2)) done echo "~~~~~~~~~~~~~~~~~~~~~~~~~<>~~~~~~~~~~~~~~~~~~~~~~~~~" done #array-pmem for file in $input_path*.spec; do n_threads=1 while [ $n_threads -le 16 ] do counter=1 echo "[Benchmark] array-pmem, #of_threads: " $n_threads ", workload: ${file##*/}" while [ $counter -le 10 ] do ./../../../ycsbc -db storeds -threads $n_threads -dbpath /pmem/array.pmem -type array-pmem-conc-lock -P $input_path${file##*/} ((counter++)) rm /pmem/array.pmem done echo "*****************<>*****************" ((n_threads*=2)) done echo "~~~~~~~~~~~~~~~~~~~~~~~~~<>~~~~~~~~~~~~~~~~~~~~~~~~~" done #array-pmem-tx for file in $input_path*.spec; do n_threads=1 while [ $n_threads -le 16 ] do counter=1 echo "[Benchmark] array-pmem-tx, #of_threads: " $n_threads ", workload: ${file##*/}" while [ $counter -le 10 ] do ./../../../ycsbc -db storeds -threads $n_threads -dbpath /pmem/array.pmem -type array-pmem-tx-conc-lock -P $input_path${file##*/} ((counter++)) rm /pmem/array.pmem done echo "*****************<>*****************" ((n_threads*=2)) done echo "~~~~~~~~~~~~~~~~~~~~~~~~~<>~~~~~~~~~~~~~~~~~~~~~~~~~" done
<reponame>tadhondup/xmltoldmigration<filename>src/main/java/io/bdrc/xmltoldmigration/xml2files/PlaceMigration.java package io.bdrc.xmltoldmigration.xml2files; import static io.bdrc.libraries.Models.ADM; import static io.bdrc.libraries.Models.BDA; import static io.bdrc.libraries.Models.BDO; import static io.bdrc.libraries.Models.BDR; import static io.bdrc.libraries.Models.VCARD; import static io.bdrc.libraries.Models.addStatus; import static io.bdrc.libraries.Models.createAdminRoot; import static io.bdrc.libraries.Models.createRoot; import static io.bdrc.libraries.Models.getAdminData; import static io.bdrc.libraries.Models.getFacetNode; import static io.bdrc.libraries.Models.setPrefixes; import static io.bdrc.libraries.Models.FacetType.EVENT; import static io.bdrc.libraries.Models.FacetType.VCARD_ADDR; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.bdrc.xmltoldmigration.MigrationHelpers; import io.bdrc.xmltoldmigration.helpers.ExceptionHelper; import io.bdrc.xmltoldmigration.helpers.SymetricNormalization; public class PlaceMigration { public static final String PLXSDNS = "http://www.tbrc.org/models/place#"; private static String getUriFromTypeSubtype(String type, String subtype) { switch (type) { case "tradition": return BDR+"Tradition"+subtype.substring(0, 1).toUpperCase() + subtype.substring(1); case "simple": return BDO+"place"+subtype.substring(0, 1).toUpperCase() + subtype.substring(1); case "eventType": return BDO+"Place"+subtype.substring(0, 1).toUpperCase() + subtype.substring(1); default: return ""; } } private static String normalizePlaceType(String val) { switch(val) { case "khul": return "khul"; case "placeTypes:townshipSeats": return "shang"; case "placeTypes:srolRgyunSaMing": return "srolRgyunGyiSaMing"; case "placeTypes:tshoPa": return "tshoBa"; case "placeTypes:rgyalKhams": return "rgyalKhab"; case "placeTypes:traditionalPlaceName": return "srolRgyunGyiSaMing"; case "placeTypes:residentialHouse": return "gzimsKhang"; case "placeTypes:notSpecified": return "notSpecified"; } // starts with "placeTypes:" val = val.substring(11); // val = CommonMigration.normalizePropName(val, "Class"); return val; } private static Map<String,String> typeToLocalName = new HashMap<>(); static { typeToLocalName.put("yulSde", "PT0001"); typeToLocalName.put("rangSkyongKhul", "PT0002"); typeToLocalName.put("rangSkyongLjongs", "PT0003"); typeToLocalName.put("zamPa", "PT0004"); typeToLocalName.put("rong", "PT0005"); typeToLocalName.put("durKhrod", "PT0006"); typeToLocalName.put("skor", "PT0007"); typeToLocalName.put("grongKhyer", "PT0008"); typeToLocalName.put("dengRabsSaGnas", "PT0009"); typeToLocalName.put("rgyalKhab", "PT0010"); typeToLocalName.put("rdzong", "PT0011"); typeToLocalName.put("chus", "PT0012"); typeToLocalName.put("cholKha", "PT0013"); typeToLocalName.put("saKhul", "PT0014"); typeToLocalName.put("gzhisKa", "PT0015"); typeToLocalName.put("gruKha", "PT0016"); typeToLocalName.put("nagsTshal", "PT0017"); typeToLocalName.put("mkharRnying", "PT0018"); typeToLocalName.put("beHu", "PT0019"); typeToLocalName.put("sdeTsho", "PT0020"); typeToLocalName.put("riKhrod", "PT0021"); typeToLocalName.put("sbasYul", "PT0022"); typeToLocalName.put("smanKhang", "PT0023"); typeToLocalName.put("gzimsKhang", "PT0024"); typeToLocalName.put("khyimTshang", "PT0025"); typeToLocalName.put("gling", "PT0026"); typeToLocalName.put("rgyalPhran", "PT0027"); typeToLocalName.put("mtsho", "PT0028"); typeToLocalName.put("yulChen", "PT0029"); typeToLocalName.put("dpeMdzodKhang", "PT0030"); typeToLocalName.put("mda'", "PT0031"); typeToLocalName.put("khriSde", "PT0032"); typeToLocalName.put("maNiRdoPhung", "PT0033"); typeToLocalName.put("gzimsShag", "PT0034"); typeToLocalName.put("tshong'Dus", "PT0035"); typeToLocalName.put("sgrubPhug", "PT0036"); typeToLocalName.put("dgonPa", "PT0037"); typeToLocalName.put("bshadGrwa", "PT0038"); typeToLocalName.put("khamsTshan", "PT0039"); typeToLocalName.put("grwaTshang", "PT0040"); typeToLocalName.put("blaBrang", "PT0041"); typeToLocalName.put("riBo", "PT0042"); typeToLocalName.put("laKha", "PT0043"); typeToLocalName.put("riRgyud", "PT0044"); typeToLocalName.put("grongRdal", "PT0045"); typeToLocalName.put("khriSkor", "PT0046"); typeToLocalName.put("rangByung'KhorYug", "PT0047"); typeToLocalName.put("'brogSde", "PT0048"); typeToLocalName.put("btsunDgon", "PT0050"); typeToLocalName.put("phoBrang", "PT0051"); typeToLocalName.put("glingKha", "PT0052"); typeToLocalName.put("gnasChen", "PT0053"); typeToLocalName.put("rdoRing", "PT0054"); typeToLocalName.put("thang", "PT0055"); typeToLocalName.put("sngarGyiRdzong", "PT0056"); typeToLocalName.put("khul", "PT0057"); typeToLocalName.put("sdeDponMnga'Ris", "PT0058"); typeToLocalName.put("parKhang", "PT0059"); typeToLocalName.put("zhingChen", "PT0060"); typeToLocalName.put("ru", "PT0061"); typeToLocalName.put("sgang", "PT0062"); typeToLocalName.put("rtenGzhiYulLung", "PT0063"); typeToLocalName.put("sgrubGrwa", "PT0064"); typeToLocalName.put("chuBo", "PT0065"); typeToLocalName.put("chuRgyud", "PT0066"); typeToLocalName.put("slobGrwa", "PT0067"); typeToLocalName.put("tshoBa", "PT0068"); typeToLocalName.put("brtenPaGnasKhang", "PT0069"); typeToLocalName.put("yulPhran", "PT0070"); typeToLocalName.put("chuMig", "PT0071"); typeToLocalName.put("mchodRten", "PT0072"); typeToLocalName.put("stongSde", "PT0073"); typeToLocalName.put("lhaKhang", "PT0074"); typeToLocalName.put("gtsugLagKhang", "PT0075"); typeToLocalName.put("bangSo", "PT0076"); typeToLocalName.put("shang", "PT0077"); typeToLocalName.put("srolRgyunGyiSaMing", "PT0078"); typeToLocalName.put("srolRgyunSaKhul", "PT0079"); typeToLocalName.put("gterGnas", "PT0080"); typeToLocalName.put("ruSde", "PT0081"); typeToLocalName.put("phu", "PT0082"); typeToLocalName.put("lungPa", "PT0083"); typeToLocalName.put("grongTsho", "PT0084"); typeToLocalName.put("grongSde", "PT0085"); typeToLocalName.put("rdzongSridGzhungGnasSa", "PT0086"); } private static Resource getPlaceType(Element root, Model model, Resource main) { NodeList nodeList = root.getElementsByTagNameNS(PLXSDNS, "info"); String typeValue = ""; for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); typeValue = current.getAttribute("type").trim(); if (typeValue.isEmpty()) { continue; } else { break; } } if (typeValue.isEmpty()) { ExceptionHelper.logException(ExceptionHelper.ET_GEN, main.getLocalName(), main.getLocalName(), "info/type", "missing place type"); return null; } else if (typeValue.equals("notSpecified")) { ExceptionHelper.logException(ExceptionHelper.ET_GEN, main.getLocalName(), main.getLocalName(), "info/type", "original type: notSpecified"); return null; } typeValue = normalizePlaceType(typeValue); String localName = typeToLocalName.get(typeValue); if (localName == null) return null; return model.createResource(BDR+localName); } public static Model MigratePlace(Document xmlDocument) { Model model = ModelFactory.createDefaultModel(); MigrationHelpers.setPrefixes(model, "place"); Element root = xmlDocument.getDocumentElement(); Element current; Resource main = createRoot(model, BDR+root.getAttribute("RID"), BDO+"Place"); Resource admMain = createAdminRoot(main); if (MigrationHelpers.ricrid.containsKey(root.getAttribute("RID"))) { admMain.addLiteral(admMain.getModel().createProperty(ADM, "restrictedInChina"), true); } Resource placeType = getPlaceType(root, model, main); if (placeType != null) model.add(main, model.getProperty(BDO, "placeType"), placeType); addStatus(model, admMain, root.getAttribute("status")); admMain.addProperty(model.getProperty(ADM, "metadataLegal"), model.createResource(BDA+"LD_BDRC_CC0")); CommonMigration.addNames(model, root, main, PLXSDNS); CommonMigration.addNotes(model, root, main, PLXSDNS); CommonMigration.addExternals(model, root, main, PLXSDNS); CommonMigration.addDescriptions(model, root, main, PLXSDNS); addEvents(model, root, main); CommonMigration.addLog(model, root, admMain, PLXSDNS, false); NodeList nodeList = root.getElementsByTagNameNS(PLXSDNS, "gis"); for (int i = 0; i < nodeList.getLength(); i++) { current = (Element) nodeList.item(i); addGis(model, current, main); } addSimpleObjectProp("isLocatedIn", "placeLocatedIn", model, main, root); addSimpleObjectProp("near", "placeIsNear", model, main, root); addSimpleObjectProp("contains", "placeContains", model, main, root); // address nodeList = root.getElementsByTagNameNS(PLXSDNS, "address"); for (int i = 0; i < nodeList.getLength(); i++) { current = (Element) nodeList.item(i); Resource address = getFacetNode(VCARD_ADDR, VCARD, main, VCARD_ADDR.getNodeType()); model.add(main, model.getProperty(BDO+"placeAddress"), address); addSimpleAttr(current.getAttribute("city"), "city", VCARD+"locality", model, address); addSimpleAttr(current.getAttribute("country"), "country", VCARD+"country-name", model, address); addSimpleAttr(current.getAttribute("postal"), "postal", VCARD+"postal-code", model, address); addSimpleAttr(current.getAttribute("state"), "state", VCARD+"region", model, address); String streetAddress = current.getAttribute("number").trim()+" "+current.getAttribute("street").trim(); address.addProperty(model.getProperty(VCARD, "street-address"), model.createLiteral(streetAddress)); } // tlm nodeList = root.getElementsByTagNameNS(PLXSDNS, "tlm"); for (int i = 0; i < nodeList.getLength(); i++) { current = (Element) nodeList.item(i); addTlm(model, admMain, current); } // adding monastery foundation events from persons (should be merged with the current founding event if present) PersonMigration.FoundingEvent fe = PersonMigration.placeEvents.get(main.getLocalName()); if (fe != null) { Resource event = getFacetNode(EVENT, main, model.getResource(BDO+"PlaceFounded")); CommonMigration.addDates(fe.circa, event, main); model.add(event, model.createProperty(BDO, "eventWho"), model.createResource(BDR+fe.person)); Property prop = model.getProperty(BDO+"placeEvent"); model.add(main, prop, event); } SymetricNormalization.insertMissingTriplesInModel(model, root.getAttribute("RID")); return model; } public static void addTlm(Model m, Resource main, Element tlmEl) { addSimpleAttr(tlmEl.getAttribute("accession"), "hasTLM_accession", ADM+"place_TLM_accession", m, main); addSimpleAttr(tlmEl.getAttribute("code"), "hasTLM_code", ADM+"place_TLM_code", m, main); addSimpleAttr(tlmEl.getAttribute("num"), "hasTLM_num", ADM+"place_TLM_num", m, main); NodeList nodeList = tlmEl.getElementsByTagNameNS(PLXSDNS, "taxonomy"); for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); Resource tax = m.createResource(BDR+current.getAttribute("rid")); m.add(main, m.getProperty(ADM+"place_TLM_taxonomy"), tax); } nodeList = tlmEl.getElementsByTagNameNS(PLXSDNS, "groups"); for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); addSimpleAttr(current.getAttribute("admin"), "hasTLM_admin", ADM+"place_TLM_admin", m, main); addSimpleAttr(current.getAttribute("adminEmail"), "hasTLM_adminEmail", ADM+"place_TLM_adminEmail", m, main); addSimpleAttr(current.getAttribute("librarian"), "hasTLM_librarian", ADM+"place_TLM_librarian", m, main); addSimpleAttr(current.getAttribute("librarianEmail"), "hasTLM_librarianEmail", ADM+"place_TLM_librarianEmail", m, main); } } public static void addSimpleAttr(String attrValue, String attrName, String ontoProp, Model m, Resource r) { if (attrValue.isEmpty()) return; Property prop = m.getProperty(ontoProp); m.add(r, prop, m.createLiteral(attrValue)); } public static void addSimpleObjectProp(String propName, String ontoPropName, Model m, Resource main, Element root) { NodeList nodeList = root.getElementsByTagNameNS(PLXSDNS, propName); for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); String value = current.getAttribute("place").trim(); if (value.isEmpty() || value.equals("NONE")) return; value = MigrationHelpers.sanitizeRID(main.getLocalName(), propName, value); if (!MigrationHelpers.isDisconnected(value)) SymetricNormalization.addSymetricProperty(m, ontoPropName, main.getLocalName(), value, null); } } public static String gisIdToUri(String gisId) { switch (gisId) { case "fromLex": return ADM+"place_id_lex"; case "fromTBRC": return ADM+"place_id_TBRC"; case "chgis_id": return BDO+"placeChgisId"; case "gb2260-2013": return BDO+"placeGB2260-2013"; case "WB_area_sq_km": return BDO+"placeWBArea"; case "WB_pop_2000": return BDO+"placeWB2000"; case "WB_pop_2010": return BDO+"placeWB2010"; default: return ""; } } public static void addGis(Model m, Element gis, Resource main) { NodeList nodeList = gis.getElementsByTagNameNS(PLXSDNS, "id"); String value = null; Property prop; Literal lit; for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); value = current.getAttribute("type"); if (value.equals("chgis_id")) { // The CHGIS Ids in our database are not the actual ones, so we // compute the correct ones instead: CommonMigration.addIdentifier(main, BDR+"CHGISId", "TBRC_"+main.getLocalName()); continue; } value = gisIdToUri(value); if (value.isEmpty()) continue; prop = m.getProperty(value); value = current.getAttribute("value").trim(); lit = m.createLiteral(value); if (prop.getNameSpace().contains("admin")) { m.add(getAdminData(main), prop, lit); } else { m.add(main, prop, lit); } } nodeList = gis.getElementsByTagNameNS(PLXSDNS, "coords"); for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); value = current.getAttribute("lat").trim(); if (!value.isEmpty()) { prop = m.getProperty(BDO+"placeLat"); lit = m.createLiteral(value); m.add(main, prop, lit); } value = current.getAttribute("long").trim(); if (!value.isEmpty()) { prop = m.getProperty(BDO+"placeLong"); lit = m.createLiteral(value); m.add(main, prop, lit); } prop = m.getProperty(BDO+"placeAccuracy"); value = current.getAttribute("accuracy").trim(); if(!value.isEmpty()) { lit = m.createLiteral(value); m.add(main, prop, lit); } prop = m.getProperty(BDO+"placeRegionPoly"); value = current.getTextContent().trim(); if(!value.isEmpty()) { try { new ObjectMapper().readTree(value); lit = m.createLiteral(value); m.add(main, prop, lit); } catch (JsonProcessingException e) { System.err.println("invalid json for "+main.getLocalName()); } catch (IOException e) { e.printStackTrace(); } } } } public static void addEvents(Model m, Element root, Resource main) { NodeList nodeList = root.getElementsByTagNameNS(PLXSDNS, "event"); String value = null; for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); value = current.getAttribute("type"); if (value.isEmpty()) { value = BDO+"PlaceEventNotSpecified"; ExceptionHelper.logException(ExceptionHelper.ET_GEN, main.getLocalName(), main.getLocalName(), "event", "missing type for an event"); } else { // should start with "placeEventTypes:" value = value.substring(16); value = getUriFromTypeSubtype("eventType", value); } Resource event = getFacetNode(EVENT, BDR, main, m.createResource(value)); CommonMigration.addDates(current.getAttribute("circa"), event, main); value = current.getAttribute("circa").trim(); Property prop = m.getProperty(BDO+"placeEvent"); m.add(main, prop, event); addAffiliations(m, current, event, main); CommonMigration.addNotes(m, current, event, PLXSDNS); CommonMigration.addDescriptions(m, current, event, PLXSDNS); } } public static void addAffiliations(Model m, Element eventElement, Resource event, Resource main) throws IllegalArgumentException { NodeList nodeList = eventElement.getElementsByTagNameNS(PLXSDNS, "affiliation"); for (int i = 0; i < nodeList.getLength(); i++) { Element current = (Element) nodeList.item(i); String type = current.getAttribute("type"); Resource target = null; Property prop = null; String value = current.getAttribute("rid"); if (value.isEmpty()) continue; if (!type.equals("placeEventAffiliationTypes:lineage")) { ExceptionHelper.logException(ExceptionHelper.ET_GEN, main.getLocalName(), main.getLocalName(), "event/affiliation", "invalid affiliation type value: `"+type+"` (should be `placeEventAffiliationTypes:lineage`)"); } if (!value.startsWith("lineage:")) { ExceptionHelper.logException(ExceptionHelper.ET_GEN, main.getLocalName(), main.getLocalName(), "event/affiliation", "invalid affiliation rid value: `"+value+"` (should be `lineage:`)"); } else { if (value.equals("lineage:Kadampa")) value = "lineage:Kadam"; if (value.equals("lineage:Shije")) value = "lineage:Zhije"; value = value.substring(8); String url = getUriFromTypeSubtype("tradition", value); target = m.createResource(url); prop = m.getProperty(BDO+"associatedTradition"); m.add(event, prop, target); } } } }
rsync -r --exclude-from rsync_data_excludes.txt data $1:~/static-data-sign-detection/data
<reponame>coboyoshi/uvicore import uvicore from uvicore.support.dumper import dump, dd from uvicore.support.module import location, load from uvicore.typing import List, Dict, OrderedDict from uvicore.contracts import Provider from uvicore.console import command_is class Http(Provider): """Http Service Provider Mixin""" def web_routes(self, module: str, prefix: str, name_prefix: str = ''): # Default registration self.package.registers.defaults({'web_routes': True}) # We do NOT check if package can registers.web_routes here as we always want # the package definition to contain the routes. Instead we simply don't load # the routes in http/bootstrap.py merge_routes() if registers is False # Add routes to package definition self.package.web.routes_module = module self.package.web.prefix = prefix self.package.web.name_prefix = name_prefix def api_routes(self, module: str, prefix: str, name_prefix: str = 'api'): # Default registration self.package.registers.defaults({'api_routes': True}) # We do NOT check if package can registers.api_routes here as we always want # the package definition to contain the routes. Instead we simply don't load # the routes in http/bootstrap.py merge_routes() if registers is False # Add routes to package definition self.package.api.routes_module = module self.package.api.prefix = prefix self.package.api.name_prefix = name_prefix def middlewareNO(self, items: OrderedDict): # Don't think this should be here. middleware is app global # not per package. I add apps middleware in http service.py # Default registration self.package.registers.defaults({'middleware': True}) # Register middleware only if allowed #if self.package.registers.middleware: #self._add_http_definition('middleware', items) def views(self, items: List): # Default registration self.package.registers.defaults({'views': True}) # Register views only if allowed if self.package.registers.views: self.package.web.view_paths = items def assets(self, items: List): # Default registration self.package.registers.defaults({'assets': True}) # Register assets only if allowed if self.package.registers.assets: self.package.web.asset_paths = items def public(self, items: List): self.package.web.public_paths = items def template(self, items: Dict): # Default registration - template obeys view registration self.package.registers.defaults({'views': True}) # Register templates only if [views] allowed if self.package.registers.views: self.package.web.template_options = Dict(items)
#include "Checker.hpp" Checker::Checker() {} Checker::Checker(std::shared_ptr<Texture> t0, std::shared_ptr<Texture> t1) : even(t0), odd(t1) {} Checker::Checker(Color3 c1, Color3 c2) : even(std::make_shared<SolidColor>(c1)), odd(std::make_shared<SolidColor>(c1)) {} Color3 Checker::value(float u, float v, const Vector3 &p) const { auto sines = sin(10 * p.x()) * sin(10 * p.y()) * sin(10 * p.z()); if (sines < 0) return odd->value(u, v, p); else return even->value(u, v, p); }
<reponame>turururu/Programming-Language-Benchmarks<gh_stars>10-100 'use strict'; const fs = require('fs'); const { WASI } = require('wasi'); const wasi = new WASI({ args: process.argv.slice(1), env: process.env, }); const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; (async () => { const wasm = await WebAssembly.compile(fs.readFileSync('./_app.wasm')); const instance = await WebAssembly.instantiate(wasm, importObject); wasi.start(instance); })();
/* E5 **Para o seguinte exercício** considere o array de objetos: [ {id: 1, first_name: ‘Juca’, last_name: ‘<NAME>’, age: 42}, {id: 2, first_name: ‘Daniel’, last_name: ‘Gonçalves’, age: 21}, {id: 3, first_name: ‘Matheus’, last_name: ‘Garcia’, age: 28}, {id: 4, first_name: ‘Gabriel’, last_name: ‘Dorneles’, age: 21} ] Imprima uma mensagem de saudação com o nome completo para cada um dos objetos. Ex.: Olá, Fulano de tal! Olá, Juca da silva! ... */ var exemploPessoas = [ {id: 1, first_name: 'Juca', last_name: '<NAME>', age: 42}, {id: 2, first_name: 'Daniel', last_name: 'Gonçalves', age: 21}, {id: 3, first_name: 'Matheus', last_name: 'Garcia', age: 28}, {id: 4, first_name: 'Gabriel', last_name: 'Dorneles', age: 21} ] function saudacoes() { let res = document.getElementById('res5') res.innerHTML = '' let arrayObj = [] // for percorrendo o array do objeto e inserindo as frases personalizadas no documento html for (let pessoas of exemploPessoas) { res.innerHTML += `Olá, ${pessoas.first_name} ${pessoas.last_name}!<br>` arrayObj += `Olá, ${pessoas.first_name} ${pessoas.last_name}! ` } return arrayObj } window.exercise05 = function() { console.log("resultado ex5: "+saudacoes()); };
#!/bin/bash #SBATCH --job-name="sample" #SBATCH --nodes=2 #SBATCH --exclusive #SBATCH --export=ALL #SBATCH --time=00:10:00 #SBATCH --out=%J.out #SBATCH --error=%J.err :<<++++ Author: Tim Kaiser Script that runs a MPI program "purempi" on the specified number of --nodes=2. This can be changed in the script or specifying a different number on the command line. We first run specifying the number of tasks on the srun line. Note that we have not specified an output file on the command line. In the script header we have the line: #SBATCH --out=%J.out This indicates that the output will go to a file %J.out where %J is replaced with the job number. Any error report will go to %J.err as specified in the header. In our second run we do not specify the numger of tasks. It defaults to 1. We do however, pipe data into a file $SLURM_JOBID.stdout where SLURM_JOBID is again the job number. purempi run with the options -t 10 -T will run for 10 seconds and print a list of nodes on which it is run and its start and stop time. Note the date command output will go into %J.out and %J.err should be empty. USAGE: sbatch -A hpcapps --partition=debug simple.sh ++++ # load our version of MPI module load mpt # Go to the directory from which our job was launched cd $SLURM_SUBMIT_DIR echo running glorified hello world date +"starting %y-%m-%d %H:%M:%S" echo "first run" #srun --ntasks=4 --cpus-per-task=2 ./purempi -t 10 -T -F srun --ntasks=4 ./purempi -t 10 -T -F date +"starting %y-%m-%d %H:%M:%S" echo "second run" srun ./purempi -t 10 -T -F > $SLURM_JOBID.stdout date +"finished %y-%m-%d %H:%M:%S" :<<++++ Example Output: el1:collect> sbatch -A hpcapps --partition=debug simple.sh Submitted batch job 5361993 el1:collect> el1:collect> ls -l 5361993* -rw-rw----. 1 tkaiser2 tkaiser2 0 Dec 17 10:21 5361993.err -rw-rw----. 1 tkaiser2 tkaiser2 236 Dec 17 10:21 5361993.out -rw-rw----. 1 tkaiser2 tkaiser2 88 Dec 17 10:21 5361993.stdout el1:collect> cat 5361993.out running glorified hello world starting 20-12-17 10:21:04 first run Thu Dec 17 10:21:05 2020 r105u37 r105u33 r105u33 r105u37 total time 10.005 Thu Dec 17 10:21:15 2020 starting 20-12-17 10:21:15 second run finished 20-12-17 10:21:27 el1:collect> el1:collect> el1:collect> cat 5361993.stdout Thu Dec 17 10:21:17 2020 r105u37 r105u33 total time 10.007 Thu Dec 17 10:21:27 2020 el1:collect> ++++
<reponame>richardmarston/cim4j package cim4j; import java.util.List; import java.util.Map; import java.util.HashMap; import cim4j.ExcitationSystemDynamics; import java.lang.ArrayIndexOutOfBoundsException; import java.lang.IllegalArgumentException; import cim4j.PU; import cim4j.Seconds; /* The class represents IEEE Std 421.5-2005 type AC4A model. The model represents type AC4A alternator-supplied controlled-rectifier excitation system which is quite different from the other type ac systems. This high initial response excitation system utilizes a full thyristor bridge in the exciter output circuit. The voltage regulator controls the firing of the thyristor bridges. The exciter alternator uses an independent voltage regulator to control its output voltage to a constant value. These effects are not modeled; however, transient loading effects on the exciter alternator are included. Reference: IEEE Standard 421.5-2005 Section 6.4. */ public class ExcIEEEAC4A extends ExcitationSystemDynamics { private BaseClass[] ExcIEEEAC4A_class_attributes; private BaseClass[] ExcIEEEAC4A_primitive_attributes; private java.lang.String rdfid; public void setRdfid(java.lang.String id) { rdfid = id; } private abstract interface PrimitiveBuilder { public abstract BaseClass construct(java.lang.String value); }; private enum ExcIEEEAC4A_primitive_builder implements PrimitiveBuilder { vimax(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, vimin(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, tc(){ public BaseClass construct (java.lang.String value) { return new Seconds(value); } }, tb(){ public BaseClass construct (java.lang.String value) { return new Seconds(value); } }, ka(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, ta(){ public BaseClass construct (java.lang.String value) { return new Seconds(value); } }, vrmax(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, vrmin(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, kc(){ public BaseClass construct (java.lang.String value) { return new PU(value); } }, LAST_ENUM() { public BaseClass construct (java.lang.String value) { return new cim4j.Integer("0"); } }; } private enum ExcIEEEAC4A_class_attributes_enum { vimax, vimin, tc, tb, ka, ta, vrmax, vrmin, kc, LAST_ENUM; } public ExcIEEEAC4A() { ExcIEEEAC4A_primitive_attributes = new BaseClass[ExcIEEEAC4A_primitive_builder.values().length]; ExcIEEEAC4A_class_attributes = new BaseClass[ExcIEEEAC4A_class_attributes_enum.values().length]; } public void updateAttributeInArray(ExcIEEEAC4A_class_attributes_enum attrEnum, BaseClass value) { try { ExcIEEEAC4A_class_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void updateAttributeInArray(ExcIEEEAC4A_primitive_builder attrEnum, BaseClass value) { try { ExcIEEEAC4A_primitive_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void setAttribute(java.lang.String attrName, BaseClass value) { try { ExcIEEEAC4A_class_attributes_enum attrEnum = ExcIEEEAC4A_class_attributes_enum.valueOf(attrName); updateAttributeInArray(attrEnum, value); System.out.println("Updated ExcIEEEAC4A, setting " + attrName); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } /* If the attribute is a String, it is a primitive and we will make it into a BaseClass */ public void setAttribute(java.lang.String attrName, java.lang.String value) { try { ExcIEEEAC4A_primitive_builder attrEnum = ExcIEEEAC4A_primitive_builder.valueOf(attrName); updateAttributeInArray(attrEnum, attrEnum.construct(value)); System.out.println("Updated ExcIEEEAC4A, setting " + attrName + " to: " + value); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } public java.lang.String toString(boolean topClass) { java.lang.String result = ""; java.lang.String indent = ""; if (topClass) { for (ExcIEEEAC4A_primitive_builder attrEnum: ExcIEEEAC4A_primitive_builder.values()) { BaseClass bc = ExcIEEEAC4A_primitive_attributes[attrEnum.ordinal()]; if (bc != null) { result += " ExcIEEEAC4A." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } for (ExcIEEEAC4A_class_attributes_enum attrEnum: ExcIEEEAC4A_class_attributes_enum.values()) { BaseClass bc = ExcIEEEAC4A_class_attributes[attrEnum.ordinal()]; if (bc != null) { result += " ExcIEEEAC4A." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } result += super.toString(true); } else { result += "(ExcIEEEAC4A) RDFID: " + rdfid; } return result; } public final java.lang.String debugName = "ExcIEEEAC4A"; public java.lang.String debugString() { return debugName; } public void setValue(java.lang.String s) { System.out.println(debugString() + " is not sure what to do with " + s); } public BaseClass construct() { return new ExcIEEEAC4A(); } };
size_t moveToStartOfCharSequence(size_t currentIndex, const char* str) { // Abort if already at the start of the string if (currentIndex == 0) return 0; // Move back one char to ensure we're in the middle of a char sequence const unsigned char* currentChar = (const unsigned char*)&str[currentIndex - 1]; while ((*currentChar >= 0x80) && (*currentChar < 0xC0)) { currentChar--; } return currentChar - (const unsigned char*)str; }
<reponame>stridders/horsleyparish package security.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import model.User; import play.mvc.Http; import security.UserAuthenticator; import java.io.IOException; import java.util.List; /** * Created by js on 23/06/2016. */ public class UserProfile { private static final String UNKNOWN = "UNKNOWN"; @JsonProperty("firstName") private String firstName; @JsonProperty("surname") private String surname; @JsonProperty("email") private String email; @JsonProperty("userid") private Long userid; @JsonProperty("roles") private List<String> roles; @JsonCreator public UserProfile() {} public UserProfile(User user) { this.setFirstName(user.getFirstname()); this.setSurname(user.getSurname()); this.setEmail(user.getEmail()); this.setUserid(user.getUser_id()); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getUserid() { return userid; } public void setUserid(Long userid) { this.userid = userid; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } public boolean hasRole(String role) { return this.roles.contains(role); } @Override public String toString() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch(IOException ioe) { return null; } } /** * Returns the UserProfile stored in the current HTTP context session (if present) * @return */ public static UserProfile getUserProfileFromHttpContext() { Http.Context context = Http.Context.current(); ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode json = objectMapper.readTree(context.session().get(UserAuthenticator.USER_PROFILE_KEY)); return transformFrom(json); } catch (IOException ioe) { return null; } } /** * Converts a JSON node into a UserProfile POJO * @param json * @return */ public static UserProfile transformFrom(JsonNode json) { UserProfile userProfile = new UserProfile(); userProfile.setEmail(json.findPath("email").asText()); userProfile.setSurname(json.findPath("surname").asText()); userProfile.setFirstName(json.findPath("firstname").asText()); userProfile.setUserid(json.findPath("userId").asLong()); userProfile.setRoles(json.findValuesAsText("roles")); return userProfile; } }
#!/bin/bash NODE_VER=16.13.2 if ! node --version | grep -q ${NODE_VER}; then if cat /proc/cpuinfo | grep -q "Pi Zero"; then if [ ! -d node-v${NODE_VER}-linux-armv6l ]; then echo "Installing nodejs ${NODE_VER} for armv6 from unofficial builds..." curl -O https://unofficial-builds.nodejs.org/download/release/v${NODE_VER}/node-v${NODE_VER}-linux-armv6l.tar.xz tar -xf node-v${NODE_VER}-linux-armv6l.tar.xz fi echo "Adding node to the PATH" export PATH="~/node-v${NODE_VER}-linux-armv6l/bin:${PATH}" echo "Adding path to ~/.bashrc" echo "export PATH=~/node-v${NODE_VER}-linux-armv6l/bin:\$PATH" >> ~/.bashrc else echo "This script is intended for Raspberry Pi Zero only." fi else echo "Node.js version ${NODE_VER} is already installed." fi
<gh_stars>10-100 var _neodroid_manager_8cs = [ [ "NeodroidManager", "classdroid_1_1_runtime_1_1_managers_1_1_neodroid_manager.html", "classdroid_1_1_runtime_1_1_managers_1_1_neodroid_manager" ], [ "Object", "_neodroid_manager_8cs.html#a5b2c8b05b9a357906d7f9e5b2c1e154d", null ] ];
package de.rieckpil.blog; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import javax.json.Json; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @MessageDriven public class JmsMessageReader implements MessageListener { @PersistenceContext private EntityManager entityManager; @Override public void onMessage(Message message) { TextMessage textMessage = (TextMessage) message; try { String incomingText = textMessage.getText(); System.out.println("-- a new message arrived: " + incomingText); Jsonb jsonb = JsonbBuilder.create(); CustomMessage parsedMessage = jsonb.fromJson(incomingText, CustomMessage.class); entityManager.persist(parsedMessage); } catch (JMSException e) { System.err.println(e.getMessage()); } } }
<filename>src/singleton/treadsafe/DoubleCheckLockedSingleton.java<gh_stars>0 package singleton.treadsafe; public class DoubleCheckLockedSingleton { private static volatile DoubleCheckLockedSingleton singleton; private DoubleCheckLockedSingleton() {} public static DoubleCheckLockedSingleton getInstance() { if (singleton == null) { synchronized (DoubleCheckLockedSingleton.class) { if (singleton == null) { singleton = new DoubleCheckLockedSingleton(); } } } return singleton; } }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-STWS/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-STWS/1024+0+512-N-IP-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function replace_all_but_nouns_first_two_thirds_sixth --eval_function last_sixth_eval
package cn.ben.tvdemo.data; import cn.ben.tvdemo.data.tvchannel.source.TVChannelsRepository; import cn.ben.tvdemo.data.tvchannel.source.local.TVChannelsLocalDataSource; import cn.ben.tvdemo.data.tvchannel.source.remote.TVChannelsRemoteDataSource; import cn.ben.tvdemo.data.tvshow.source.TVShowsRepository; import cn.ben.tvdemo.data.tvshow.source.local.TVShowsLocalDataSource; import cn.ben.tvdemo.data.tvshow.source.remote.TVShowsRemoteDataSource; import cn.ben.tvdemo.data.tvtype.source.TVTypesRepository; import cn.ben.tvdemo.data.tvtype.source.local.TVTypesLocalDataSource; import cn.ben.tvdemo.data.tvtype.source.remote.TVTypesRemoteDataSource; import cn.ben.tvdemo.util.schedulers.BaseSchedulerProvider; import cn.ben.tvdemo.util.schedulers.SchedulerProvider; public class Injection { public static TVTypesRepository provideTVTypesRepository() { return TVTypesRepository.getInstance( TVTypesRemoteDataSource.getInstance(), TVTypesLocalDataSource.getInstance() ); } public static BaseSchedulerProvider provideSchedulerProvider() { return SchedulerProvider.getInstance(); } public static TVChannelsRepository provideTVChannelsRepository() { return TVChannelsRepository.getInstance( TVChannelsRemoteDataSource.getInstance(), TVChannelsLocalDataSource.getInstance() ); } public static TVShowsRepository provideTVShowsRepository() { return TVShowsRepository.getInstance( TVShowsRemoteDataSource.getInstance(), TVShowsLocalDataSource.getInstance() ); } }
<gh_stars>0 /**************************************************************************** * Copyright (C) from 2009 to Present EPAM Systems. * * This file is part of Indigo toolkit. * * 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. ***************************************************************************/ #ifndef __bingo_storage__ #define __bingo_storage__ #include "base_cpp/array.h" #include "base_cpp/ptr_array.h" #include "base_cpp/shmem.h" namespace indigo { class OracleEnv; class OracleLOB; class SharedMemory; class BingoStorage { public: explicit BingoStorage(OracleEnv& env, int context_id); virtual ~BingoStorage(); void validateForInsert(OracleEnv& env); void add(OracleEnv& env, const Array<char>& data, int& blockno, int& offset); void create(OracleEnv& env); void drop(OracleEnv& env); void truncate(OracleEnv& env); void validate(OracleEnv& env); void flush(OracleEnv& env); void finish(OracleEnv& env); void lock(OracleEnv& env); void markRemoved(OracleEnv& env, int blockno, int offset); int count(); void get(int n, Array<char>& out); DECL_ERROR; protected: enum { _STATE_EMPTY = 0, _STATE_BULDING = 1, _STATE_LOADING = 2, _STATE_READY = 3 }; enum { _MAX_BLOCK_SIZE = 5 * 1024 * 1024 }; struct _Block { int size; }; struct _State { int state; // see STATE_*** int age; int age_loaded; }; struct _Addr { short blockno; short length; int offset; }; SharedMemory* _shmem_state; Array<_Block> _blocks; int _n_added; int _age_loaded; PtrArray<SharedMemory> _shmem_array; void* _getShared(SharedMemory*& sh_mem, char* name, int shared_size, bool allow_first); _State* _getState(bool allow_first); void _insertLOB(OracleEnv& env, int no); OracleLOB* _getLob(OracleEnv& env, int no); void _finishTopLob(OracleEnv& env); void _finishIndexLob(OracleEnv& env); Array<char> _shmem_id; Array<char> _table_name; Array<_Addr> _index; Array<char> _top_lob_pending_data; Array<char> _index_lob_pending_data; int _top_lob_pending_mark; int _index_lob_pending_mark; }; } // namespace indigo #endif
package proptics.law.discipline import cats.Eq import cats.laws.discipline._ import org.scalacheck.Arbitrary import org.scalacheck.Prop.forAll import org.typelevel.discipline._ import proptics.Traversal import proptics.law.TraversalLaws trait TraversalTests[S, A] extends Laws { def laws: TraversalLaws[S, A] def traversal(implicit eqS: Eq[S], eqA: Eq[A], arbS: Arbitrary[S], arbA: Arbitrary[A], arbAA: Arbitrary[A => A]): RuleSet = new SimpleRuleSet( "Traversal", "respectPurity" -> forAll(laws.respectPurity[Option] _), "consistentFoci" -> forAll((s: S, f: A => A, g: A => A) => laws.consistentFoci(s, f, g)), "preview" -> forAll(laws.preview _), "getGet" -> forAll((s: S, f: A => A) => laws.getSet(s, f)), "setSet" -> forAll((s: S, a: A) => laws.setSet(s, a)), "overIdentity" -> forAll(laws.overIdentity _), "composeOver" -> forAll((s: S, f: A => A, g: A => A) => laws.composeOver(s)(f)(g)) ) } object TraversalTests { def apply[S, A](_traversal: Traversal[S, A]): TraversalTests[S, A] = new TraversalTests[S, A] { def laws: TraversalLaws[S, A] = TraversalLaws[S, A](_traversal) } }
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Object3D } from "three/src/core/Object3D.js"; import { PerspectiveCamera } from "three/src/cameras/PerspectiveCamera.js"; import { Renderable } from "./renderable.js"; import { Scene as ThreeScene } from "three/src/scenes/Scene.js"; import { WebGLRenderTarget } from "three/src/renderers/WebGLRenderTarget.js"; /* All MathBox renderables sit inside this root, to keep things tidy. */ class MathBox extends Object3D { constructor() { super(); this.rotationAutoUpdate = false; this.frustumCulled = false; this.matrixAutoUpdate = false; } } /* Holds the root and binds to a THREE.Scene Will hold objects and inject them a few at a time to avoid long UI blocks. Will render injected objects to a 1x1 scratch buffer to ensure availability */ export class Scene extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders, options); this.root = new MathBox(); if ((options != null ? options.scene : undefined) != null) { this.scene = options.scene; } if (this.scene == null) { this.scene = new ThreeScene(); } this.pending = []; this.async = 0; this.scratch = new WebGLRenderTarget(1, 1); this.camera = new PerspectiveCamera(); } inject(scene) { if (scene != null) { this.scene = scene; } return this.scene.add(this.root); } unject() { return this.scene != null ? this.scene.remove(this.root) : undefined; } add(object) { if (this.async) { return this.pending.push(object); } else { return this._add(object); } } remove(object) { this.pending = this.pending.filter((o) => o !== object); if (object.parent != null) { return this._remove(object); } } _add(object) { return this.root.add(object); } _remove(object) { return this.root.remove(object); } dispose() { if (this.root.parent != null) { return this.unject(); } } warmup(n) { return (this.async = +n || 0); } render() { if (!this.pending.length) { return; } const { children } = this.root; // Insert up to @async children const added = []; for (let i = 0, end = this.async, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i--) { const pending = this.pending.shift(); if (!pending) { break; } // Insert new child this._add(pending); added.push(added); } // Remember current visibility const visible = children.map(function (o) { return o.visible; }); // Force only this child visible children.map((o) => (o.visible = !Array.from(added).includes(o))); // Render and throw away const currentTarget = this.renderer.getRenderTarget(); this.renderer.setRenderTarget(this.scratch); this.renderer.render(this.scene, this.camera); this.renderer.setRenderTarget(currentTarget); // Restore visibility return children.map((o, i) => (o.visible = visible[i])); } toJSON() { return this.root.toJSON(); } }
#!/bin/bash set -e sudo apt-get update && sudo apt-get install -y \ ros-crystal-example-interfaces \ ros-crystal-rclcpp-action
#!/bin/bash FILE_LIST=(quota.sh) COUNT=1 for file_name in ${FILE_LIST[@]} do cp yaml_template_quota ${file_name}.yaml sed -i "s/yaml_template.sh/${file_name}/g" ${file_name}.yaml echo ${COUNT} COUNT=$((${COUNT}+1)) done
<filename>src/main/java/org/nhindirect/config/manager/printers/TrustBundleRecordPrinter.java package org.nhindirect.config.manager.printers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import org.nhindirect.config.model.TrustBundle; public class TrustBundleRecordPrinter extends AbstractRecordPrinter<TrustBundle> { protected static final Collection<ReportColumn> REPORT_COLS; protected static final String BUNDLE_ID_COL = "ID"; protected static final String BUNDLE_NAME_COL = "Bundle Name"; protected static final String BUNDLE_URL_COL = "Bundle URL"; protected static final String BUNDLE_REFRESH_COL = "Refresh Interval"; protected static final String BUNDLE_LAST_CHECKED_COL = "Last Checked"; protected static final String BUNDLE_LAST_UPDATED_COL = "Last Updated"; static { REPORT_COLS = new ArrayList<ReportColumn>(); REPORT_COLS.add(new ReportColumn(BUNDLE_ID_COL, 10, "Id")); REPORT_COLS.add(new ReportColumn(BUNDLE_NAME_COL, 40, "BundleName")); REPORT_COLS.add(new ReportColumn(BUNDLE_URL_COL, 80, "BundleURL")); REPORT_COLS.add(new ReportColumn(BUNDLE_REFRESH_COL, 20, "RefreshInterval")); REPORT_COLS.add(new ReportColumn(BUNDLE_LAST_CHECKED_COL, 30, "LastChecked")); REPORT_COLS.add(new ReportColumn(BUNDLE_LAST_UPDATED_COL, 30, "Last Updated")); } protected final DateFormat dtFormat; public TrustBundleRecordPrinter() { super(200, REPORT_COLS); dtFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); } @Override protected String getColumnValue(ReportColumn column, TrustBundle bundle) { try { if (column.header.equals(BUNDLE_LAST_CHECKED_COL)) { return (bundle.getLastRefreshAttempt() == null) ? "N/A" : dtFormat.format(bundle.getLastRefreshAttempt().getTime()); } else if (column.header.equals(BUNDLE_LAST_UPDATED_COL)) { return (bundle.getLastSuccessfulRefresh() == null) ? "N/A" : dtFormat.format(bundle.getLastSuccessfulRefresh().getTime()); } else if (column.header.equals(BUNDLE_REFRESH_COL)) { return bundle.getRefreshInterval() + " sec"; } else return super.getColumnValue(column, bundle); } catch (Exception e) { return "ERROR: " + e.getMessage(); } } }
<filename>internal/padder/no/no.go package no import ( "gitee.com/ddkwork/libraryGo/internal/padder/padderApi" "gitee.com/ddkwork/libraryGo/stream" ) type ( No interface { padderApi.ApiPadder } _No struct { } ) func (n *_No) Padding(src []byte) stream.Interface { panic("implement me") } func (n *_No) UnPadding(dst []byte) stream.Interface { panic("implement me") } func (n *_No) Size() int { panic("implement me") } func (n *_No) SetSize(size int) { panic("implement me") } func New() No { return &_No{} }
class Indicator { protected $name; protected $value; public function __construct(string $name, float $value) { $this->name = $name; $this->value = $value; } public function getName(): string { return $this->name; } public function getValue(): float { return $this->value; } } class IndicatorRepository { private $indicators = []; public function addIndicator(Indicator $indicator): void { $this->indicators[$indicator->getName()] = $indicator; } public function removeIndicator(string $name): void { if (isset($this->indicators[$name])) { unset($this->indicators[$name]); } } public function getIndicator(string $name): ?Indicator { return $this->indicators[$name] ?? null; } public function calculateAverageValue(): float { $totalValue = 0; $count = count($this->indicators); if ($count === 0) { return 0; } foreach ($this->indicators as $indicator) { $totalValue += $indicator->getValue(); } return $totalValue / $count; } }
public required init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let color = aDecoder.decodeObject(forKey: "color") as? String, let area = aDecoder.decodeDouble(forKey: "area") else { return nil } self.name = name self.color = color self.area = area }
import { Component, OnInit, Input, Output, OnChanges, SimpleChanges, EventEmitter, ChangeDetectionStrategy, ViewChild, TemplateRef, } from '@angular/core'; import { Subject } from 'rxjs'; import { CalendarEventAction, CalendarView, CalendarEventTimesChangedEvent, } from 'angular-calendar'; import { MatDialog } from '@angular/material/dialog'; import { UserModel } from 'src/app/model/user-model'; import { ReservationModel, CalendarEventWithReservation } from 'src/app/model/reservation-model'; import { ReservationColorEnum } from 'src/app/enums/reservation-color-enum'; import { ReservationNewDialogComponent } from 'src/app/components/container/reservation-new-dialog/reservation-new-dialog.component'; import { UserService } from 'src/app/shared/services/user.service'; import { AdmissionYearService } from 'src/app/shared/services/admission-year.service'; @Component({ selector: 'app-reservations-calendar', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './reservations-calendar.component.html', styleUrls: ['./reservations-calendar.component.css'], }) export class ReservationsCalendarComponent implements OnInit, OnChanges { @Input() reservations!: ReservationModel[]; @Input() loginUser!: UserModel; @Output() reservationEdit: EventEmitter<any> = new EventEmitter<any>(); @Output() reservationDelete: EventEmitter<any> = new EventEmitter<any>(); @ViewChild('modalContent', { static: true }) modalContent!: TemplateRef<any>; view: CalendarView = CalendarView.Week; viewDate: Date = new Date(); events!: CalendarEventWithReservation[]; userNames: string[] = []; admissionYears!: number[]; searchName!: string; searchAdmissionYear!: number; actions: CalendarEventAction[] = [ { label: '<i class="fas fa-fw fa-trash-alt"></i>', a11yLabel: 'Delete', onClick: ({ event }: { event: any }): void => { this.deleteEvent(event); }, }, ]; constructor( private matDialog: MatDialog, private userService: UserService, private admissionYearService: AdmissionYearService ) {} ngOnInit(): void { // イベントを取得 this.buildEvents(); // ユーザ一覧を保管 let users: UserModel[] = this.reservations.map((reservation: ReservationModel) => { return reservation.user; }); // 予約者のユーザ名リストを取得 users = this.userService.sortUsers(users); this.userNames = users.map((user) => { return this.userService.getUserName(user); }); this.userNames = [...new Set(this.userNames)]; // 入学年度一覧 this.admissionYears = this.admissionYearService.getAdmissionYears(); } refresh: Subject<any> = new Subject(); activeDayIsOpen: boolean = true; buildEvents(): void { this.events = []; const pushEvent = (reservation: ReservationModel) => { const editable = this.loginUser.id === reservation.user.id || this.userService.checkAdmin(this.loginUser); this.events.push({ reservation: reservation, start: new Date(reservation.startAt), end: new Date(reservation.finishAt), title: this.userService.getUserName(reservation.user), color: this.loginUser.id === reservation.user.id ? ReservationColorEnum.BLUE : ReservationColorEnum.YELLOW, actions: this.actions, resizable: { beforeStart: editable, afterEnd: editable, }, draggable: editable, }); }; // イベント一覧 this.reservations.map((reservation: ReservationModel) => { if (this.searchName === undefined && this.searchAdmissionYear === undefined) { pushEvent(reservation); } // ユーザ名&入学年度で絞り込み検索 else if (this.searchName !== undefined && this.searchAdmissionYear !== undefined) { if ( this.searchName === this.userService.getUserName(reservation.user) && this.searchAdmissionYear === reservation.user.admissionYear ) { pushEvent(reservation); } } // ユーザ名で絞り込み検索 else if (this.searchName === this.userService.getUserName(reservation.user)) { pushEvent(reservation); } // 入学年度で絞り込み検索 else if (this.searchAdmissionYear === reservation.user.admissionYear) { pushEvent(reservation); } }); } eventTimesChanged(changedEvent: CalendarEventTimesChangedEvent): void { this.events.map((event) => { if (event === changedEvent.event) { const reservation = event.reservation; reservation.startAt = changedEvent.newStart as Date; reservation.finishAt = changedEvent.newEnd as Date; this.reservationEdit.emit(reservation); } }); } deleteEvent(eventToDelete: CalendarEventWithReservation) { this.reservationDelete.emit(eventToDelete.reservation); } onClickCreateButton(): void { this.matDialog.open(ReservationNewDialogComponent, { disableClose: true, }); } ngOnChanges(changes: SimpleChanges) { if (changes.reservations !== undefined) { this.reservations = changes.reservations.currentValue; this.ngOnInit(); } } }
import json import queue from concurrent.futures import ThreadPoolExecutor def process_task(task): result = {"id": task["id"], "result": task["data"] * 2} return result def process_queue(task_queue, num_threads): results = {} with ThreadPoolExecutor(max_workers=num_threads) as executor: while not task_queue.empty(): task = task_queue.get() try: result = executor.submit(process_task, task).result() results[result["id"]] = result["result"] except Exception as e: results[task["id"]] = f"Error processing task: {str(e)}" finally: task_queue.task_done() return results # Example usage tasks = [ {"id": 1, "data": 5}, {"id": 2, "data": 10}, {"id": 3, "data": 15} ] task_queue = queue.Queue() for task in tasks: task_queue.put(task) num_threads = 2 results = process_queue(task_queue, num_threads) print(results)
import { apiClient } from "../../../config/axios" export const getPosts = async (id) => { return apiClient.get(`/posts/${id}`) } export const updatePostById = async (id, data) => { return apiClient.put(`/posts/${id}`, data) }
#!/bin/bash # 删除上传的文件,用于 crontab 调用 # 每天凌晨 4 点调用:`0 4 * * * /home/work/wangEditor-team/wangEditor/server/rm.sh` filesExp="/home/work/wangEditor-team/wangEditor/server/upload-files/*" # 测试机 rm -rf "$filesExp"
<filename>src/main/java/net/oiyou/day010/Solution.java package net.oiyou.day010; import java.util.Arrays; public class Solution { public boolean isMatch(String s, String p) { boolean[] match = new boolean[s.length() + 1]; Arrays.fill(match, false); match[s.length()] = true; for (int i = p.length() - 1; i >= 0; i--) { if (p.charAt(i) == '*') { for (int j = s.length() - 1; j >= 0; j--) { match[j] = match[j] || match[j + 1] && (p.charAt(i - 1) == '.' || s.charAt(j) == p.charAt(i - 1)); } i--; } else { for (int j = 0; j < s.length(); j++) { match[j] = match[j + 1] && (p.charAt(i) == '.' || p.charAt(i) == s.charAt(j)); } match[s.length()] = false; } } return match[0]; } public boolean isMatch2(String s, String p) { // 输入都为null if (s == null && p == null) { return true; } // 有一个为null else if (s == null || p == null) { return false; } return isMatch(s, 0, p, 0); } /** * 正则表达式匹配 * * @param s 匹配串 * @param sIdx 当前匹配的位置 * @param p 模式串 * @param pIdx 模式串的匹配位置 * @return 匹配结果 */ public boolean isMatch(String s, int sIdx, String p, int pIdx) { // 同时到各自的末尾 if (s.length() == sIdx && p.length() == pIdx) { return true; } // 当匹配串没有到达末尾,模式串已经到了末尾 else if (s.length() != sIdx && p.length() == pIdx) { return false; } // 其它情况 else { // 如果当前匹配的下一个字符是*号 if (pIdx < p.length() - 1 && p.charAt(pIdx + 1) == '*') { // 匹配串未结束并且当前字符匹配(字符相等或者是.号) if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { return isMatch(s, sIdx + 1, p, pIdx + 2) // 匹配串向前移动一个字符(只匹配一次) || isMatch(s, sIdx + 1, p, pIdx) // 匹配串向前移动一个字符(下一次匹配同样的(模式串不动)) || isMatch(s, sIdx, p, pIdx + 2); // 忽略匹配的模式串 } else { // 忽略* return isMatch(s, sIdx, p, pIdx + 2); } } // 匹配一个字符 if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { return isMatch(s, sIdx + 1, p, pIdx + 1); } } return false; } }
<filename>app/containers/DuckDetails/DuckDetailsContainer.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { DuckDetails } from 'components' import * as duckActionCreators from 'reduxConfig/modules/ducks' import * as likeCountActionCreators from 'reduxConfig/modules/likeCount' import * as repliesActionCreators from 'reduxConfig/modules/replies' class DuckDetailsContainer extends Component { static propTypes = { authedUser: PropTypes.object.isRequired, duckId: PropTypes.string.isRequired, isFetching: PropTypes.bool.isRequired, error: PropTypes.string.isRequired, duckAlreadyFetched: PropTypes.bool.isRequired, removeFetching: PropTypes.func.isRequired, fetchAndHandleDuck: PropTypes.func.isRequired, initLikeFetch: PropTypes.func.isRequired, addAndHandleReply: PropTypes.func.isRequired, } componentDidMount () { this.props.initLikeFetch(this.props.duckId) if (this.props.duckAlreadyFetched === false) { this.props.fetchAndHandleDuck(this.props.duckId) } else { this.props.removeFetching() } } render () { return ( <DuckDetails addAndHandleReply={this.props.addAndHandleReply} authedUser={this.props.authedUser} duckId={this.props.duckId} isFetching={this.props.isFetching} error={this.props.error}/> ) } } function mapStateToProps ({ ducks, likeCount, users }, props) { return { isFetching: ducks.get('isFetching') || likeCount.isFetching, error: ducks.get('error'), authedUser: users[users.authedId].info, duckId: props.match.params.duckId, duckAlreadyFetched: !!ducks.get(props.match.params.duckId), } } function mapDispatchToProps (dispatch) { return bindActionCreators( { ...duckActionCreators, ...likeCountActionCreators, ...repliesActionCreators, }, dispatch ) } export default connect(mapStateToProps, mapDispatchToProps)( DuckDetailsContainer )
<filename>src/index.js export {default as DropzoneArea} from './components/DropzoneArea'; export {default as DropzoneDialog} from './components/DropzoneDialog';
<filename>vendor/bundle/ruby/2.7.0/gems/rubocop-ast-0.4.2/lib/rubocop/ast/version.rb # frozen_string_literal: true module RuboCop module AST module Version STRING = '0.4.2' end end end
package com.bendoerr.saltedmocha.nacl; import com.bendoerr.saltedmocha.CryptoException; import static com.bendoerr.saltedmocha.CryptoException.exceptionOf; import static com.bendoerr.saltedmocha.Util.checkedArrayCopy; import static com.bendoerr.saltedmocha.Util.validateLength; /** * <p>CryptoCore class.</p> */ public class CryptoCore { /** * Constant <code>crypto_core_hsalsa_INPUTBYTES=16</code> */ public static int crypto_core_hsalsa_INPUTBYTES = 16; /** * Constant <code>crypto_core_hsalsa_OUTPUTBYTES=32</code> */ public static int crypto_core_hsalsa_OUTPUTBYTES = 32; /** * Constant <code>crypto_core_hsalsa_KEYBYTES=32</code> */ public static int crypto_core_hsalsa_KEYBYTES = 32; /** * Constant <code>crypto_core_salsa_INPUTBYTES=16</code> */ public static int crypto_core_salsa_INPUTBYTES = 16; /** * Constant <code>crypto_core_salsa_OUTPUTBYTES=64</code> */ public static int crypto_core_salsa_OUTPUTBYTES = 64; /** * Constant <code>crypto_core_salsa_KEYBYTES=32</code> */ public static int crypto_core_salsa_KEYBYTES = 32; private CryptoCore() { } /** * <p>crypto_core_hsalsa20.</p> * * @param out an array of byte. * @param in an array of byte. * @param k an array of byte. * @throws com.bendoerr.saltedmocha.CryptoException if any. */ public static void crypto_core_hsalsa20(byte[] out, byte[] in, byte[] k) throws CryptoException { checkedArrayCopy( crypto_core_hsalsa20(in, k), 0, out, 0, crypto_core_hsalsa_OUTPUTBYTES); } /** * <p>crypto_core_hsalsa20.</p> * * @param in an array of byte. * @param k an array of byte. * @return an array of byte. * @throws com.bendoerr.saltedmocha.CryptoException if any. */ public static byte[] crypto_core_hsalsa20(byte[] in, byte[] k) throws CryptoException { validateLength(k, crypto_core_hsalsa_KEYBYTES, "key", "crypto_core_hsalsa_KEYBYTES"); try { return new CryptoStream.Salsa20Cipher(in, k, true).core(); } catch (RuntimeException re) { throw exceptionOf(re); } } /** * <p>crypto_core_salsa20.</p> * * @param out an array of byte. * @param in an array of byte. * @param k an array of byte. * @throws com.bendoerr.saltedmocha.CryptoException if any. */ public static void crypto_core_salsa20(byte[] out, byte[] in, byte[] k) throws CryptoException { checkedArrayCopy( crypto_core_salsa20(in, k), 0, out, 0, crypto_core_salsa_OUTPUTBYTES); } /** * <p>crypto_core_salsa20.</p> * * @param in an array of byte. * @param k an array of byte. * @return an array of byte. * @throws com.bendoerr.saltedmocha.CryptoException if any. */ public static byte[] crypto_core_salsa20(byte[] in, byte[] k) throws CryptoException { validateLength(k, crypto_core_salsa_KEYBYTES, "key", "crypto_core_salsa_KEYBYTES"); try { return new CryptoStream.Salsa20Cipher(in, k).core(); } catch (RuntimeException re) { throw exceptionOf(re); } } }
<filename>data-prepper-plugins/otel-trace-source/src/test/java/com/amazon/dataprepper/plugins/source/oteltrace/OtelTraceSourceConfigTests.java /* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package com.amazon.dataprepper.plugins.source.oteltrace; import com.amazon.dataprepper.model.configuration.PluginSetting; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static com.amazon.dataprepper.plugins.source.oteltrace.OTelTraceSourceConfig.DEFAULT_MAX_CONNECTION_COUNT; import static com.amazon.dataprepper.plugins.source.oteltrace.OTelTraceSourceConfig.DEFAULT_PORT; import static com.amazon.dataprepper.plugins.source.oteltrace.OTelTraceSourceConfig.DEFAULT_REQUEST_TIMEOUT_MS; import static com.amazon.dataprepper.plugins.source.oteltrace.OTelTraceSourceConfig.DEFAULT_THREAD_COUNT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class OtelTraceSourceConfigTests { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String PLUGIN_NAME = "otel_trace_source"; private static final String TEST_KEY_CERT = "test.crt"; private static final String TEST_KEY = "test.key"; private static final String TEST_KEY_CERT_S3 = "s3://test.crt"; private static final String TEST_KEY_S3 = "s3://test.key"; private static final String TEST_REGION = "us-east-1"; private static final int TEST_REQUEST_TIMEOUT_MS = 777; private static final int TEST_PORT = 45600; private static final int TEST_THREAD_COUNT = 888; private static final int TEST_MAX_CONNECTION_COUNT = 999; @Test public void testDefault() { // Prepare final OTelTraceSourceConfig otelTraceSourceConfig = new OTelTraceSourceConfig(); // When/Then assertEquals(OTelTraceSourceConfig.DEFAULT_REQUEST_TIMEOUT_MS, otelTraceSourceConfig.getRequestTimeoutInMillis()); assertEquals(OTelTraceSourceConfig.DEFAULT_PORT, otelTraceSourceConfig.getPort()); assertEquals(OTelTraceSourceConfig.DEFAULT_THREAD_COUNT, otelTraceSourceConfig.getThreadCount()); assertEquals(OTelTraceSourceConfig.DEFAULT_MAX_CONNECTION_COUNT, otelTraceSourceConfig.getMaxConnectionCount()); assertFalse(otelTraceSourceConfig.hasHealthCheck()); assertFalse(otelTraceSourceConfig.hasProtoReflectionService()); assertFalse(otelTraceSourceConfig.isSslCertAndKeyFileInS3()); assertTrue(otelTraceSourceConfig.isSsl()); assertNull(otelTraceSourceConfig.getSslKeyCertChainFile()); assertNull(otelTraceSourceConfig.getSslKeyFile()); } @Test public void testValidConfigWithoutS3CertAndKey() { // Prepare final PluginSetting validPluginSetting = completePluginSettingForOtelTraceSource( TEST_REQUEST_TIMEOUT_MS, TEST_PORT, true, true, false, true, TEST_KEY_CERT, TEST_KEY, TEST_THREAD_COUNT, TEST_MAX_CONNECTION_COUNT); // When final OTelTraceSourceConfig otelTraceSourceConfig = OBJECT_MAPPER.convertValue(validPluginSetting.getSettings(), OTelTraceSourceConfig.class); otelTraceSourceConfig.validateAndInitializeCertAndKeyFileInS3(); // Then assertEquals(TEST_REQUEST_TIMEOUT_MS, otelTraceSourceConfig.getRequestTimeoutInMillis()); assertEquals(TEST_PORT, otelTraceSourceConfig.getPort()); assertEquals(TEST_THREAD_COUNT, otelTraceSourceConfig.getThreadCount()); assertEquals(TEST_MAX_CONNECTION_COUNT, otelTraceSourceConfig.getMaxConnectionCount()); assertTrue(otelTraceSourceConfig.hasHealthCheck()); assertTrue(otelTraceSourceConfig.hasProtoReflectionService()); assertTrue(otelTraceSourceConfig.isSsl()); assertFalse(otelTraceSourceConfig.isSslCertAndKeyFileInS3()); assertEquals(TEST_KEY_CERT, otelTraceSourceConfig.getSslKeyCertChainFile()); assertEquals(TEST_KEY, otelTraceSourceConfig.getSslKeyFile()); } @Test public void testValidConfigWithS3CertAndKey() { // Prepare final PluginSetting validPluginSettingWithS3CertAndKey = completePluginSettingForOtelTraceSource( TEST_REQUEST_TIMEOUT_MS, TEST_PORT, false, false, false, true, TEST_KEY_CERT_S3, TEST_KEY_S3, TEST_THREAD_COUNT, TEST_MAX_CONNECTION_COUNT); validPluginSettingWithS3CertAndKey.getSettings().put(OTelTraceSourceConfig.AWS_REGION, TEST_REGION); final OTelTraceSourceConfig otelTraceSourceConfig = OBJECT_MAPPER.convertValue(validPluginSettingWithS3CertAndKey.getSettings(), OTelTraceSourceConfig.class); otelTraceSourceConfig.validateAndInitializeCertAndKeyFileInS3(); // Then assertEquals(TEST_REQUEST_TIMEOUT_MS, otelTraceSourceConfig.getRequestTimeoutInMillis()); assertEquals(TEST_PORT, otelTraceSourceConfig.getPort()); assertEquals(TEST_THREAD_COUNT, otelTraceSourceConfig.getThreadCount()); assertEquals(TEST_MAX_CONNECTION_COUNT, otelTraceSourceConfig.getMaxConnectionCount()); assertFalse(otelTraceSourceConfig.hasHealthCheck()); assertFalse(otelTraceSourceConfig.hasProtoReflectionService()); assertTrue(otelTraceSourceConfig.isSsl()); assertTrue(otelTraceSourceConfig.isSslCertAndKeyFileInS3()); assertEquals(TEST_KEY_CERT_S3, otelTraceSourceConfig.getSslKeyCertChainFile()); assertEquals(TEST_KEY_S3, otelTraceSourceConfig.getSslKeyFile()); } @Test public void testInvalidConfigWithNullKeyCert() { // Prepare final PluginSetting sslNullKeyCertPluginSetting = completePluginSettingForOtelTraceSource( DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_PORT, false, false, false, true, null, TEST_KEY, DEFAULT_THREAD_COUNT, DEFAULT_MAX_CONNECTION_COUNT); final OTelTraceSourceConfig otelTraceSourceConfig = OBJECT_MAPPER.convertValue(sslNullKeyCertPluginSetting.getSettings(), OTelTraceSourceConfig.class); // When/Then assertThrows(IllegalArgumentException.class, otelTraceSourceConfig::validateAndInitializeCertAndKeyFileInS3); } @Test public void testInvalidConfigWithEmptyKeyCert() { // Prepare final PluginSetting sslEmptyKeyCertPluginSetting = completePluginSettingForOtelTraceSource( DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_PORT, false, false, false, true, "", TEST_KEY, DEFAULT_THREAD_COUNT, DEFAULT_MAX_CONNECTION_COUNT); final OTelTraceSourceConfig otelTraceSourceConfig = OBJECT_MAPPER.convertValue(sslEmptyKeyCertPluginSetting.getSettings(), OTelTraceSourceConfig.class); // When/Then assertThrows(IllegalArgumentException.class, otelTraceSourceConfig::validateAndInitializeCertAndKeyFileInS3); } @Test public void testInvalidConfigWithEmptyKeyFile() { // Prepare final PluginSetting sslEmptyKeyFilePluginSetting = completePluginSettingForOtelTraceSource( DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_PORT, false, false, false, true, TEST_KEY_CERT, "", DEFAULT_THREAD_COUNT, DEFAULT_MAX_CONNECTION_COUNT); final OTelTraceSourceConfig otelTraceSourceConfig = OBJECT_MAPPER.convertValue(sslEmptyKeyFilePluginSetting.getSettings(), OTelTraceSourceConfig.class); // When/Then assertThrows(IllegalArgumentException.class, otelTraceSourceConfig::validateAndInitializeCertAndKeyFileInS3); } private PluginSetting completePluginSettingForOtelTraceSource(final int requestTimeoutInMillis, final int port, final boolean healthCheck, final boolean protoReflectionService, final boolean enableUnframedRequests, final boolean isSSL, final String sslKeyCertChainFile, final String sslKeyFile, final int threadCount, final int maxConnectionCount) { final Map<String, Object> settings = new HashMap<>(); settings.put(OTelTraceSourceConfig.REQUEST_TIMEOUT, requestTimeoutInMillis); settings.put(OTelTraceSourceConfig.PORT, port); settings.put(OTelTraceSourceConfig.HEALTH_CHECK_SERVICE, healthCheck); settings.put(OTelTraceSourceConfig.PROTO_REFLECTION_SERVICE, protoReflectionService); settings.put(OTelTraceSourceConfig.ENABLE_UNFRAMED_REQUESTS, enableUnframedRequests); settings.put(OTelTraceSourceConfig.SSL, isSSL); settings.put(OTelTraceSourceConfig.SSL_KEY_CERT_FILE, sslKeyCertChainFile); settings.put(OTelTraceSourceConfig.SSL_KEY_FILE, sslKeyFile); settings.put(OTelTraceSourceConfig.THREAD_COUNT, threadCount); settings.put(OTelTraceSourceConfig.MAX_CONNECTION_COUNT, maxConnectionCount); return new PluginSetting(PLUGIN_NAME, settings); } }
import java.util.Arrays; public class Main { // Function to calculate average public static double average(float[] array) { // return average value double average = 0.0; int len = array.length; double sum = 0.0; for (int i = 0; i < len; i++) sum += array[i]; average = sum / len; return average; } public static void main(String[] args) { float[] array = { 10.2f, 15.7f, 8.9f}; // calling average method double avg = average(array); // Print the average value System.out.println("Average : " + avg); } }
/* * 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.sshd.sftp.client.extensions.helpers; import java.io.IOException; import java.io.StreamCorruptedException; import java.util.Collection; import java.util.Map; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.sftp.client.RawSftpClient; import org.apache.sshd.sftp.client.SftpClient; import org.apache.sshd.sftp.client.extensions.FilenameTranslationControlExtension; import org.apache.sshd.sftp.common.SftpConstants; /** * Implements &quot;filename-translation-control&quot; extension command * * @see <A HREF="https://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#page-16">DRAFT 13 - page 16</A> * @author <a href="mailto:<EMAIL>">Apache MINA SSHD Project</a> */ public class FilenameTranslationControlExtensionImpl extends AbstractSftpClientExtension implements FilenameTranslationControlExtension { public FilenameTranslationControlExtensionImpl(SftpClient client, RawSftpClient raw, Collection<String> extras) { super(SftpConstants.EXT_FILENAME_XLATE_CONTROL, client, raw, GenericUtils.isNotEmpty(extras) && extras.contains(SftpConstants.EXT_FILENAME_CHARSET)); } public FilenameTranslationControlExtensionImpl(SftpClient client, RawSftpClient raw, Map<String, byte[]> extensions) { super(SftpConstants.EXT_FILENAME_XLATE_CONTROL, client, raw, MapEntryUtils.isNotEmpty(extensions) && extensions.containsKey(SftpConstants.EXT_FILENAME_CHARSET)); } @Override public void setFilenameTranslationControl(boolean doTranslate) throws IOException { Buffer request = getCommandBuffer(Byte.SIZE); request.putBoolean(doTranslate); if (log.isDebugEnabled()) { log.debug("setFilenameTranslationControl({}) doTranslate={}", getName(), doTranslate); } int id = sendExtendedCommand(request); Buffer response = receive(id); response = checkExtendedReplyBuffer(response); if (response != null) { throw new StreamCorruptedException("Unexpected extended reply data"); } } }
<gh_stars>1-10 # EnhancedStrftime module GeoffGarside #:nodoc: module Extensions #:nodoc: module Strftime def self.included(base) base.alias_method_chain :strftime, :geoffgarside end # Extended strftime method. Accepts some additional formatting # tokens over those parsed by the standard strftime functions. # * %o - Token %d (no leading zero's) with the 'st', 'nd', 'rd', 'th' suffix def strftime_with_geoffgarside(fmt='%F') o = '' fmt.scan(/%[EO]?.|./mo) do |c| cc = c.sub(/\A%[EO]?(.)\z/mo, '%\\1') case cc when '%o'; o << ActiveSupport::Inflector.ordinalize(mday) else o << c end end strftime_without_geoffgarside(o) end end end end
#!/usr/bin/env zsh # vim:ft=zsh # This file is the second component of the directory injection mechanism created in # https://github.com/issmirnov/oh-my-zsh/commit/48f3b0e1a2f2f02764504ab3157f2e643077936c # The functions get dynamically loaded into the prompt and allow transformations such as # `/super/long/common/path/a/b/c` -> `(p)/a/b/c` # Set up your shortcuts here typeset -A shortcuts # declare KV map shortcuts["$GOPATH/src/"]="(go)" shortcuts["/System/Library/Extensions"]="(S/L/E)" function dir_head(){ for k in "${(@k)shortcuts}"; do # (Q) removes one level of quotes from a variable # https://linux.die.net/man/1/zshexpn if [[ $PWD == ${(Q)k}* ]]; then echo -n "$shortcuts[$k]" break fi done } function dir_tail(){ for k in "${(@k)shortcuts}"; do # (Q) removes one level of quotes from a variable # https://linux.die.net/man/1/zshexpn if [[ $PWD == ${(Q)k}* ]]; then echo -n "/${PWD#${(Q)k}}" found=true break fi done # show full path by default if [[ ! "$found" ]]; then echo %~ fi }
const SEARCH_BOOKS_API = 'https://www.googleapis.com/books/v1/volumes?'; export const getSearchBooksUrl = (inputValue: string) => { return SEARCH_BOOKS_API + `q=${inputValue}&printType=books&projection=lite&startIndex=0&maxResults=21&`+ process.env.REACT_APP_SEARCH_BOOKS_API_KEY; };
#!/bin/sh date > /tmp/issue-MB-2811.log echo starting moxi # Start moxi with high timeouts, especially SASL auth_timeout, so that # a worker thread hangs during synchronous SASL auth. With this # configuration, we want to cause the main thread to (incorrectly) # hang for 30 seconds (before the fix). ./moxi -d -P /tmp/moxi-2811-test-moxi.pid \ -z http://127.0.0.1:22100/test \ -Z port_listen=11266,downstream_conn_max=1,downstream_max=0,downstream_timeout=30000,wait_queue_timeout=30000,downstream_conn_queue_timeout=30000,connect_timeout=30000,auth_timeout=30000 echo starting memcached simulant ./moxi -d -P /tmp/moxi-2811-test-memcached.pid -p 11277 # Control our stdout at this point, as it goes to nc -l. # First, stream to moxi one vbucket config. ( cat << EOF HTTP/1.0 200 OK {"name":"default", "bucketType":"membase", "authType":"sasl", "saslPassword":"", "nodes":[ {"replication":0.0,"clusterMembership":"active","status":"healthy", "hostname":"127.0.0.1:22100", "ports":{"proxy":11266,"direct":11277}} ], "nodeLocator":"vbucket", "vBucketServerMap":{ "hashAlgorithm":"CRC","numReplicas":0, "serverList":["127.0.0.1:11277"], "vBucketMap":[[0]] } } EOF ( sleep 5 date echo client request 0 - ensure moxi has started echo incr a 1 | nc 127.0.0.1 11266 date echo stopping memcached simulant... kill -STOP `cat /tmp/moxi-2811-test-memcached.pid` sleep 1 echo client request 1 - make 1 worker thread busy with auth time (echo incr a 3 | nc 127.0.0.1 11266) & sleep 1 ) >> /tmp/issue-MB-2811.log # Stream another reconfig message, which will hang # the main thread while a worker thread is hung. cat << EOF {"name":"default", "bucketType":"membase", "authType":"sasl", "saslPassword":"", "nodes":[ {"replication":0.0,"clusterMembership":"active","status":"healthy", "hostname":"127.0.0.1:22100", "ports":{"proxy":11266,"direct":11277}} ], "nodeLocator":"vbucket", "vBucketServerMap":{ "hashAlgorithm":"CRC","numReplicas":0, "serverList":["127.0.0.1:11277"], "vBucketMap":[[0],[0]] } } EOF ( echo client request 2 - incorrectly hangs for auth_timeout msecs time (echo version | nc 127.0.0.1 11266) ) >> /tmp/issue-MB-2811.log ) | nc -l 22100 echo OK - no more hanging killall moxi
<reponame>Adrian-Garcia/Algorithms<gh_stars>0 #include <iostream> #include <vector> #include <queue> using namespace std; int main() { std::vector<int> nums(5); nums[0]= 0; nums[1]= 1; nums[2]= 0; nums[3]= 3; nums[4]= 12; int counter = 0; queue<int> q; cout << "Original: "; for (int i=0; i<nums.size(); i++) { cout << nums[i] << " "; } // 1 1 0 3 12 for (int i=0; i<nums.size(); i++) { if (nums[i] != 0) { q.push(nums[i]); } } int i=0; while (!q.empty()) { nums[i] = q.front(); q.pop(); i++; } while(i<nums.size()) { nums[i] = 0; i++; } cout << "\nNew: "; for (int i=0; i<nums.size(); i++) { cout << nums[i] << " "; } cout << endl << endl; return 0; }
Begin loop through each number in the list Step 1: Find the smallest number in the list. Step 2: Swap it with the number at the first position in the list. Step 3: Repeat Step 1 and 2 for the rest of the numbers in the list. End loop After the loop is completed, the list is sorted in ascending order.
package com.leetcode; import java.util.HashMap; import java.util.Map; public class Solution_1394 { public int findLucky(int[] arr) { Map<Integer, Integer> map = new HashMap(); for (int i = 0; i < arr.length; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } return map.entrySet().stream() .filter(integerIntegerEntry -> integerIntegerEntry.getKey().equals(integerIntegerEntry.getValue())) .map(integerIntegerEntry -> integerIntegerEntry.getKey()) .max(Integer::compareTo).orElse(-1); } }
import re # input string string = "In the morning, the sun rises in the east and sets in the west. In the evening, the stars come out and shine in the night sky. The moon rises in the east and sets in the west." words = string.split(" ") # set that contains the frequnt phrases phrases = set() # loop over the words in the string for index, word in enumerate(words): # loop over the words ahead of the current word for ahead in range(index+1, min(index+4, len(words))): # check if the phrase exists in the string if " ".join(words[index:ahead+1]) in string: # add the phrase to the set phrases.add(" ".join(words[index:ahead+1])) # print the phrases print(phrases)
'use strict'; import SmartForm from './smart-forms'; import * as Inputs from './inputs'; import * as Validators from './validators'; module.exports = { SmartForm: SmartForm, Inputs: Inputs, Validators: Validators };
# Prepare Data disk PREPARE_DATA_DISK=false DATA_DISK=/dev/sdb DATA_PARTITION=${DATA_DISK}1 DATA_PARTITION_FS=ext4 # ext4 # Prepare OS disk PREPARE_OS_DISK=true if [[ -d /sys/firmware/efi ]]; then EFI_BOOT=true else EFI_BOOT=false fi OS_DISK=/dev/sda BOOT_PARTITION=${OS_DISK}1 BOOT_PARTITION_FS=fat32 # fat32 OS_PARTITION=${OS_DISK}2 OS_PARTITION_FS=btrfs # ext4, btrfs # Install OS MIRRORLIST_COUNTRY=NL DEVEL_PACKAGES=true OS_HOSTNAME="archlinux.local" OS_NEW_USERNAME="myname" OS_NEW_USERNAME_SUDO=true DATA_PARTITION_MOUNT_FOLDER=/mnt/datadisk # Install OS - part 2 OS_TIME_ZONE=Europe/Amsterdam OS_LOCALE=en_GB.UTF-8
import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { withStyles } from 'material-ui/styles'; import { GoogleMap, Marker, withScriptjs, withGoogleMap, } from 'react-google-maps'; import CustomMapMarker from '../CustomMapMarker'; const styles = theme => ({ root: { width: '100%', height: '100%', }, }); @observer @withStyles(styles) @withScriptjs @withGoogleMap class MapSection extends Component { renderMapMarkers = listing => { const { longitude, latitude, listingID } = listing; return ( <CustomMapMarker longitude={longitude} latitude={latitude} listingID={listingID} /> ); }; render() { const { classes, listing } = this.props; return ( <div className={classes.root}> <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }} > <Marker position={{ lat: -34.397, lng: 150.644 }} /> {/* listing && this.renderMapMarker(listing) */} </GoogleMap> </div> ); } } export default MapSection;
package config var defaultConfigFileName string = "gphp.yaml" var defaultConfig string = ` debug: true log: debug,log,error logFile: gphp.log expose: gphp daemonize: false agent: addr: 127.0.0.1:7070 readTimeout: 30 writeTimeout: 30 server: - network: http group: http addr: 127.0.0.1:80 readTimeout: 30 writeTimeout: 30 memory: 5242880 fastHttp: false websocket: false websocketOnly: false websocketPath: "" websocketReadTimeout: 30 websocketWriteTimeout: 30 websocketGroup: "" host: - 127.0.0.1 - localhost `
#!/usr/bin/env bash # vim: filetype=sh # Set IFS explicitly to space-tab-newline to avoid tampering IFS=' ' NAME= # Make sure that we're not on NixOS; if so, avoid tampering with PATH if [[ -f /etc/os-release ]] then . /etc/os-release fi if [[ "NixOS" != "$NAME" ]] then # If found, use getconf to constructing a reasonable PATH, otherwise # we set it manually. if [[ -x /usr/bin/getconf ]] then PATH=$(/usr/bin/getconf PATH) else PATH=/bin:/usr/bin:/usr/local/bin fi fi function error() { echo "Error: $@" >&2 exit 1 } test -d ${HOME}/.tmux/plugins/tpm || git clone https://github.com/tmux-plugins/tpm ${HOME}/.tmux/plugins/tpm ln -s ${PWD}/.tmux-work_vm.conf ${HOME}/.tmux.conf
from typing import List, Tuple def convert_labels_series_schema(labels: List[str], series: List[str]) -> Tuple[List[str], List[str]]: if len(labels) > len(series): labels = labels[:len(series)] elif len(series) > len(labels): labels += ["N/A"] * (len(series) - len(labels) return labels, series
<gh_stars>100-1000 import type { NodeProps } from 'react-flow-renderer'; export interface TChart { data: TStructuredResponse; } export interface TPath { device: string; } export interface TNode<D extends unknown> extends Omit<NodeProps, 'data'> { data: D; } export interface TNodeData { asn: string; name: string; hasChildren: boolean; hasParents?: boolean; } export interface BasePath { asn: string; name: string; } export interface TPathButton { onOpen(): void; }
#!/bin/bash set -e BUILD_TYPE=$1 source ./utils.sh platform=$(get_platform) # default build type if [ -z $BUILD_TYPE ]; then BUILD_TYPE=release fi # Return 0 if the command exists, 1 if it does not. exists() { command -v "$1" &>/dev/null } # Return the first value in $@ that's a runnable command. find_command() { for arg in "$@"; do if exists "$arg"; then echo "$arg" return 0 fi done return 1 } if [ "$BUILD_TYPE" == "release" ]; then echo "Building release" CONFIG="CONFIG+=release"; BIN_PATH=release/bin elif [ "$BUILD_TYPE" == "release-static" ]; then echo "Building release-static" if [ "$platform" != "darwin" ]; then CONFIG="CONFIG+=release static"; else # OS X: build static libwallet but dynamic Qt. echo "OS X: Building Qt project without static flag" CONFIG="CONFIG+=release"; fi BIN_PATH=release/bin elif [ "$BUILD_TYPE" == "release-android" ]; then echo "Building release for ANDROID" CONFIG="CONFIG+=release static WITH_SCANNER DISABLE_PASS_STRENGTH_METER"; ANDROID=true BIN_PATH=release/bin DISABLE_PASS_STRENGTH_METER=true elif [ "$BUILD_TYPE" == "debug-android" ]; then echo "Building debug for ANDROID : ultra INSECURE !!" CONFIG="CONFIG+=debug qml_debug WITH_SCANNER DISABLE_PASS_STRENGTH_METER"; ANDROID=true BIN_PATH=debug/bin DISABLE_PASS_STRENGTH_METER=true elif [ "$BUILD_TYPE" == "debug" ]; then echo "Building debug" CONFIG="CONFIG+=debug" BIN_PATH=debug/bin else echo "Valid build types are release, release-static, release-android, debug-android and debug" exit 1; fi source ./utils.sh pushd $(pwd) ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" KOSON_DIR=koson KOSOND_EXEC=kosond MAKE='make' if [[ $platform == *bsd* ]]; then MAKE='gmake' fi # build libwallet ./get_libwallet_api.sh $BUILD_TYPE # build zxcvbn if [ "$DISABLE_PASS_STRENGTH_METER" != true ]; then $MAKE -C src/zxcvbn-c || exit fi if [ ! -d build ]; then mkdir build; fi # Platform indepenent settings if [ "$ANDROID" != true ] && ([ "$platform" == "linux32" ] || [ "$platform" == "linux64" ]); then exists lsb_release && distro="$(lsb_release -is)" if [ "$distro" = "Ubuntu" ] || [ "$distro" = "Fedora" ] || test -f /etc/fedora-release; then CONFIG="$CONFIG libunwind_off" fi fi if [ "$platform" == "darwin" ]; then BIN_PATH=$BIN_PATH/koson-wallet-gui.app/Contents/MacOS/ elif [ "$platform" == "mingw64" ] || [ "$platform" == "mingw32" ]; then KOSOND_EXEC=kosond.exe fi # force version update get_tag echo "var GUI_VERSION = \"$TAGNAME\"" > version.js pushd "$KOSON_DIR" get_tag popd echo "var GUI_KOSON_VERSION = \"$TAGNAME\"" >> version.js cd build if ! QMAKE=$(find_command qmake qmake-qt5); then echo "Failed to find suitable qmake command." exit 1 fi $QMAKE ../koson-wallet-gui.pro "$CONFIG" || exit $MAKE || exit # Copy kosond to bin folder if [ "$platform" != "mingw32" ] && [ "$ANDROID" != true ]; then cp ../$KOSON_DIR/bin/$KOSOND_EXEC $BIN_PATH fi make deploy popd cp koson_default_settings.ini build/$BIN_PATH/koson.ini if [ "$platform" == "darwin" ]; then otool -l build/$BIN_PATH/koson-wallet-gui | grep sdk fi
<reponame>lrakai/bbb-dynamixel """ Serial communication primitives """ import array # PRINT_PACKETS = 1 # uncomment to print packets sent and received def makePacket( id, instruction, params ): """ Make a dynamixel formatted packet """ p = [ 0xff, 0xff, id & 0xff, len(params)+2, instruction & 0xff ] for param in params: p.append(param & 0xff) p.append(checksumPacket(p)) return p def checksumPacket( p ): """ Calculate the checksum byte for the packet """ sum = 0 for byte in p[2:]: sum = 0xff & (sum + byte) notSum = 0xff & (~sum) return notSum def checkPacket( id, p ): """ check bytes for errors or unexpected conditions (http://support.robotis.com/en/product/dynamixel/communication/dxl_packet.htm) """ if p[2] != id: print 'Bad packet read (Unexpected id)' return -1 if p[3] + 4 != len(p): print 'Bad packet read (Incorrect length)' return -1 if p[4] != 0x00: print 'Bad packet read (Error bits set: ', p[4], ' [decimal representation])' return -1 if p[-1] != checksumPacket(p[:-1]): print 'Bad packet read (bad checksum)' return -1 return 0 def p2str( p ): """ Convert packet to string """ return array.array('B', p).tostring(); def str2p( s ): """ Convert string to packet """ return [ord(char) for char in list(s)] def sendPacket( ser, p ): """ Send packet over serial channel """ if PRINT_PACKETS: print 'sent: ', p i = ser.write(p2str(p)) if i == 0: print 'No bytes written in sendPacket' return def receivePacket( ser, id ): """ Read a packet waiting in the buffer """ strHead = ser.read(4) # read packet up to length byte pHead = str2p(strHead) strTail = ser.read(pHead[3]) # read remaining bytes p = str2p(strHead + strTail) if checkPacket(id, p) != 0: return None if PRINT_PACKETS: print 'received: ', p return p
class Message: def __init__(self, text): self.text = text def __str__(self): return self.text
#include <cmath> #include "glass/vec" #include "glass/utils/str.h" #include "glass/utils/exceptions.h" #include "glass/utils/helper.h" double round(double value, uint n) { double ten_n = pow(10, n); return round(value * ten_n) / ten_n; } double fix(double value) { return value > 0 ? floor(value) : ceil(value); } bool is_zero(double value) { return (value < 1E-6 && value > -1E-6); } bool is_int(double value) { double abs_value = fabs(value); return (abs_value - int(abs_value) < 1E-6); } bool is_equal(double value1, double value2) { double delta = value1 - value2; return (delta < 1E-6 && delta > -1E-6); } double rad2deg(double rad) { return rad/PI*180; } double deg2rad(double deg) { return deg/180*PI; } dvec2 pow(const dvec2& v1, const dvec2& v2) { return dvec2(pow(v1.x, v2.x), pow(v1.y, v2.y)); } dvec2 pow(const dvec2& v, double value) { return dvec2(pow(v.x, value), pow(v.y, value)); } dvec2 pow(double value, const dvec2& v) { return dvec2(pow(value, v.x), pow(value, v.y)); } double length(const dvec2& v) { return sqrt(v.x*v.x + v.y*v.y); } dvec2 normalize(const dvec2& v) { double l = sqrt(v.x*v.x + v.y*v.y); return is_zero(l) ? dvec2(0.0f, 0.0f) : dvec2(v.x / l, v.y / l); } dvec2 reflect(dvec2 v_in, dvec2 v_norm) { v_in = normalize(v_in); v_norm = normalize(v_norm); return v_in - 2*dot(v_in, v_norm)*v_norm; } double dot(const dvec2& v1, const dvec2& v2) { return v1.x*v2.x + v1.y*v2.y; } double cross(const dvec2& v1, const dvec2& v2) { return v1.x*v2.y - v2.x*v1.x; } dvec2 mix(const dvec2& v1, const dvec2& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } dvec2 sin(const dvec2& v) { return dvec2(sin(v.x), sin(v.y)); } dvec2 cos(const dvec2& v) { return dvec2(cos(v.x), cos(v.y)); } dvec2 tan(const dvec2& v) { double k = v.x/PI-0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x can not be (k+0.5)*PI.\nBut v.x = " + str::str(v.x) + " = (" + str::str(int(k)) + "+0.5) * PI now."); } k = v.y/PI-0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y can not be (k+0.5)*PI.\nBut v.y = " + str::str(v.y) + " = (" + str::str(int(k)) + "+0.5) * PI now."); } return dvec2(tan(v.x), tan(v.y)); } dvec2 sinh(const dvec2& v) { return dvec2(sinh(v.x), sinh(v.y)); } dvec2 cosh(const dvec2& v) { return dvec2(cosh(v.x), cosh(v.y)); } dvec2 tanh(const dvec2& v) { return dvec2(tanh(v.x), tanh(v.y)); } dvec2 asin(const dvec2& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1].\nBut v.x = " + str::str(v.x) + " now."); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1].\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(asin(v.x), asin(v.y)); } dvec2 acos(const dvec2& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1].\nBut v.x = " + str::str(v.x) + " now."); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1].\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(acos(v.x), acos(v.y)); } dvec2 atan(const dvec2& v) { return dvec2(atan(v.x), atan(v.y)); } dvec2 asinh(const dvec2& v) { return dvec2(asinh(v.x), asinh(v.y)); } dvec2 acosh(const dvec2& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1.\nBut now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1.\nBut now v.y = " + str::str(v.y)); } return dvec2(acosh(v.x), acosh(v.y)); } dvec2 atanh(const dvec2& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1).\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1).\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(atanh(v.x), atanh(v.y)); } dvec2 atan2(const dvec2& Y, const dvec2& X) { return dvec2(atan2(Y.x, X.x), atan2(Y.y, X.y)); } dvec2 exp(const dvec2& v) { return dvec2(exp(v.x), exp(v.y)); } dvec2 log(const dvec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(log(v.x), log(v.y)); } dvec2 log2(const dvec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(log2(v.x), log2(v.y)); } dvec2 log10(const dvec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return dvec2(log10(v.x), log10(v.y)); } dvec2 abs(const dvec2& v) { return dvec2(fabs(v.x), fabs(v.y)); } dvec2 floor(const dvec2& v) { return dvec2(floor(v.x), floor(v.y)); } dvec2 ceil(const dvec2& v) { return dvec2(ceil(v.x), ceil(v.y)); } dvec2 round(const dvec2& v, uint n) { return dvec2(round(v.x, n), round(v.y, n)); } dvec2 trunc(const dvec2& v) { return dvec2(trunc(v.x), trunc(v.y)); } dvec2 fix(const dvec2& v) { return dvec2(fix(v.x), fix(v.y)); } dvec3 pow(const dvec3& v1, const dvec3& v2) { return dvec3(pow(v1.x, v2.x), pow(v1.y, v2.y), pow(v1.z, v2.z)); } dvec3 pow(const dvec3& v, double value) { return dvec3(pow(v.x, value), pow(v.y, value), pow(v.z, value)); } dvec3 pow(double value, const dvec3& v) { return dvec3(pow(value, v.x), pow(value, v.y), pow(value, v.z)); } double length(const dvec3& v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } dvec3 normalize(const dvec3& v) { double l = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); return is_zero(l) ? dvec3(0.0f, 0.0f, 0.0f) : dvec3(v.x / l, v.y / l, v.z / l); } dvec3 reflect(dvec3 v_in, dvec3 v_norm) { v_in = normalize(v_in); v_norm = normalize(v_norm); return v_in - 2*dot(v_in, v_norm)*v_norm; } double dot(const dvec3& v1, const dvec3& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } dvec3 cross(const dvec3& v1, const dvec3& v2) { return dvec3(v1.y*v2.z - v2.y*v1.z, v2.x*v1.z - v1.x*v2.z, v1.x*v2.y - v2.x*v1.y); } dvec3 mix(const dvec3& v1, const dvec3& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } dvec3 sin(const dvec3& v) { return dvec3(sin(v.x), sin(v.y), sin(v.z)); } dvec3 cos(const dvec3& v) { return dvec3(cos(v.x), cos(v.y), cos(v.z)); } dvec3 tan(const dvec3& v) { double k = v.x/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x cannot be (0.5+k)*PI. But now v.x = " + str::str(v.x) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.y/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y cannot be (0.5+k)*PI. But now v.y = " + str::str(v.y) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.z/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.z cannot be (0.5+k)*PI. But now v.z = " + str::str(v.z) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } return dvec3(tan(v.x), tan(v.y), tan(v.z)); } dvec3 sinh(const dvec3& v) { return dvec3(sinh(v.x), sinh(v.y), sinh(v.z)); } dvec3 cosh(const dvec3& v) { return dvec3(cosh(v.x), cosh(v.y), cosh(v.z)); } dvec3 tanh(const dvec3& v) { return dvec3(tanh(v.x), tanh(v.y), tanh(v.z)); } dvec3 asin(const dvec3& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } return dvec3(asin(v.x), asin(v.y), asin(v.z)); } dvec3 acos(const dvec3& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } return dvec3(acos(v.x), acos(v.y), acos(v.z)); } dvec3 atan(const dvec3& v) { return dvec3(atan(v.x), atan(v.y), atan(v.z)); } dvec3 asinh(const dvec3& v) { return dvec3(asinh(v.x), asinh(v.y), asinh(v.z)); } dvec3 acosh(const dvec3& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1. But now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1. But now v.y = " + str::str(v.y)); } if(v.z < 1) { throw glass::ArithmeticError("v.z cannot be less than 1. But now v.z = " + str::str(v.z)); } return dvec3(acosh(v.x), acosh(v.y), acosh(v.z)); } dvec3 atanh(const dvec3& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1). But now v.x = " + str::str(v.x)); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1). But now v.y = " + str::str(v.y)); } if(v.z <= -1 || v.z >= 1) { throw glass::ArithmeticError("v.z must be in range (-1, 1). But now v.z = " + str::str(v.z)); } return dvec3(atanh(v.x), atanh(v.y), atanh(v.z)); } dvec3 atan2(const dvec3& Y, const dvec3& X) { return dvec3(atan2(Y.x, X.x), atan2(Y.y, X.y), atan2(Y.z, X.z)); } dvec3 exp(const dvec3& v) { return dvec3(exp(v.x), exp(v.y), exp(v.z)); } dvec3 log(const dvec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return dvec3(log(v.x), log(v.y), log(v.z)); } dvec3 log2(const dvec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return dvec3(log2(v.x), log2(v.y), log2(v.z)); } dvec3 log10(const dvec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return dvec3(log10(v.x), log10(v.y), log10(v.z)); } dvec3 abs(const dvec3& v) { return dvec3(fabs(v.x), fabs(v.y), fabs(v.z)); } dvec3 floor(const dvec3& v) { return dvec3(floor(v.x), floor(v.y), floor(v.z)); } dvec3 ceil(const dvec3& v) { return dvec3(ceil(v.x), ceil(v.y), ceil(v.z)); } dvec3 round(const dvec3& v, uint n) { return dvec3(round(v.x, n), round(v.y, n), round(v.z, n)); } dvec3 trunc(const dvec3& v) { return dvec3(trunc(v.x), trunc(v.y), trunc(v.z)); } dvec3 fix(const dvec3& v) { return dvec3(fix(v.x), fix(v.y), fix(v.z)); } dvec4 pow(const dvec4& v1, const dvec4& v2) { return dvec4(pow(v1.x, v2.x), pow(v1.y, v2.y), pow(v1.z, v2.z), pow(v1.w, v2.w)); } dvec4 pow(const dvec4& v, double value) { return dvec4(pow(v.x, value), pow(v.y, value), pow(v.z, value), pow(v.w, value)); } dvec4 pow(double value, const dvec4& v) { return dvec4(pow(value, v.x), pow(value, v.y), pow(value, v.z), pow(value, v.w)); } double length(const dvec4& v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); } dvec4 normalize(const dvec4& v) { double l = sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); return is_zero(l) ? dvec4(0.0f, 0.0f, 0.0f, 0.0f) : dvec4(v.x / l, v.y / l, v.z / l, v.w / l); } double dot(const dvec4& v1, const dvec4& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w; } dvec4 mix(const dvec4& v1, const dvec4& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } dvec4 sin(const dvec4& v) { return dvec4(sin(v.x), sin(v.y), sin(v.z), sin(v.w)); } dvec4 cos(const dvec4& v) { return dvec4(cos(v.x), cos(v.y), cos(v.z), sin(v.w)); } dvec4 tan(const dvec4& v) { double k = v.x/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x cannot be (0.5 + k) * PI. But now v.x = " + str::str(v.x) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.y/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y cannot be (0.5 + k) * PI. But now v.y = " + str::str(v.y) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.z/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.z cannot be (0.5 + k) * PI. But now v.z = " + str::str(v.z) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.w/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.w cannot be (0.5 + k) * PI. But now v.w = " + str::str(v.w) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } return dvec4(tan(v.x), tan(v.y), tan(v.z), tan(v.w)); } dvec4 sinh(const dvec4& v) { return dvec4(sinh(v.x), sinh(v.y), sinh(v.z), sinh(v.w)); } dvec4 cosh(const dvec4& v) { return dvec4(cosh(v.x), cosh(v.y), cosh(v.z), cosh(v.w)); } dvec4 tanh(const dvec4& v) { return dvec4(tanh(v.x), tanh(v.y), tanh(v.z), tanh(v.w)); } dvec4 asin(const dvec4& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } if(v.w < -1 || v.w > 1) { throw glass::ArithmeticError("v.w must be in range [-1, 1]. But now v.w = " + str::str(v.w)); } return dvec4(asin(v.x), asin(v.y), asin(v.z), asin(v.w)); } dvec4 acos(const dvec4& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } if(v.w < -1 || v.w > 1) { throw glass::ArithmeticError("v.w must be in range [-1, 1]. But now v.w = " + str::str(v.w)); } return dvec4(acos(v.x), acos(v.y), acos(v.z), acos(v.w)); } dvec4 atan(const dvec4& v) { return dvec4(atan(v.x), atan(v.y), atan(v.z), atan(v.w)); } dvec4 asinh(const dvec4& v) { return dvec4(asinh(v.x), asinh(v.y), asinh(v.z), asinh(v.w)); } dvec4 acosh(const dvec4& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1. But now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1. But now v.y = " + str::str(v.y)); } if(v.z < 1) { throw glass::ArithmeticError("v.z cannot be less than 1. But now v.z = " + str::str(v.z)); } if(v.w < 1) { throw glass::ArithmeticError("v.w cannot be less than 1. But now v.w = " + str::str(v.w)); } return dvec4(acosh(v.x), acosh(v.y), acosh(v.z), acosh(v.w)); } dvec4 atanh(const dvec4& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1). But now v.x = " + str::str(v.x)); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1). But now v.y = " + str::str(v.y)); } if(v.z <= -1 || v.z >= 1) { throw glass::ArithmeticError("v.z must be in range (-1, 1). But now v.z = " + str::str(v.z)); } if(v.w <= -1 || v.w >= 1) { throw glass::ArithmeticError("v.w must be in range (-1, 1). But now v.w = " + str::str(v.w)); } return dvec4(atanh(v.x), atanh(v.y), atanh(v.z), atanh(v.w)); } dvec4 atan2(const dvec4& Y, const dvec4& X) { return dvec4(atan2(Y.x, X.x), atan2(Y.y, X.y), atan2(Y.z, X.z), atan2(Y.w, X.w)); } dvec4 exp(const dvec4& v) { return dvec4(exp(v.x), exp(v.y), exp(v.z), exp(v.w)); } dvec4 log(const dvec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return dvec4(log(v.x), log(v.y), log(v.z), log(v.w)); } dvec4 log2(const dvec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return dvec4(log2(v.x), log2(v.y), log2(v.z), log2(v.w)); } dvec4 log10(const dvec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return dvec4(log10(v.x), log10(v.y), log10(v.z), log10(v.w)); } dvec4 abs(const dvec4& v) { return dvec4(fabs(v.x), fabs(v.y), fabs(v.z), fabs(v.w)); } dvec4 floor(const dvec4& v) { return dvec4(floor(v.x), floor(v.y), floor(v.z), floor(v.w)); } dvec4 ceil(const dvec4& v) { return dvec4(ceil(v.x), ceil(v.y), ceil(v.z), ceil(v.w)); } dvec4 round(const dvec4& v, uint n) { return dvec4(round(v.x, n), round(v.y, n), round(v.z, n), round(v.w, n)); } dvec4 trunc(const dvec4& v) { return dvec4(trunc(v.x), trunc(v.y), trunc(v.z), trunc(v.w)); } dvec4 fix(const dvec4& v) { return dvec4(fix(v.x), fix(v.y), fix(v.z), fix(v.w)); } vec2 pow(const vec2& v1, const vec2& v2) { return vec2(pow(v1.x, v2.x), pow(v1.y, v2.y)); } vec2 pow(const vec2& v, double value) { return vec2(pow(v.x, value), pow(v.y, value)); } vec2 pow(double value, const vec2& v) { return vec2(pow(value, v.x), pow(value, v.y)); } double length(const vec2& v) { return sqrt(v.x*v.x + v.y*v.y); } vec2 normalize(const vec2& v) { double l = sqrt(v.x*v.x + v.y*v.y); return is_zero(l) ? vec2(0.0f, 0.0f) : vec2(v.x / l, v.y / l); } vec2 reflect(vec2 v_in, vec2 v_norm) { v_in = normalize(v_in); v_norm = normalize(v_norm); return v_in - 2*dot(v_in, v_norm)*v_norm; } double dot(const vec2& v1, const vec2& v2) { return v1.x*v2.x + v1.y*v2.y; } double cross(const vec2& v1, const vec2& v2) { return v1.x*v2.y - v2.x*v1.x; } vec2 mix(const vec2& v1, const vec2& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } vec2 sin(const vec2& v) { return vec2(sin(v.x), sin(v.y)); } vec2 cos(const vec2& v) { return vec2(cos(v.x), cos(v.y)); } vec2 tan(const vec2& v) { double k = v.x/PI-0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x can not be (k+0.5)*PI.\nBut v.x = " + str::str(v.x) + " = (" + str::str(int(k)) + "+0.5) * PI now."); } k = v.y/PI-0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y can not be (k+0.5)*PI.\nBut v.y = " + str::str(v.y) + " = (" + str::str(int(k)) + "+0.5) * PI now."); } return vec2(tan(v.x), tan(v.y)); } vec2 sinh(const vec2& v) { return vec2(sinh(v.x), sinh(v.y)); } vec2 cosh(const vec2& v) { return vec2(cosh(v.x), cosh(v.y)); } vec2 tanh(const vec2& v) { return vec2(tanh(v.x), tanh(v.y)); } vec2 asin(const vec2& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1].\nBut v.x = " + str::str(v.x) + " now."); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1].\nBut v.y = " + str::str(v.y) + " now."); } return vec2(asin(v.x), asin(v.y)); } vec2 acos(const vec2& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1].\nBut v.x = " + str::str(v.x) + " now."); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1].\nBut v.y = " + str::str(v.y) + " now."); } return vec2(acos(v.x), acos(v.y)); } vec2 atan(const vec2& v) { return vec2(atan(v.x), atan(v.y)); } vec2 asinh(const vec2& v) { return vec2(asinh(v.x), asinh(v.y)); } vec2 acosh(const vec2& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1.\nBut now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1.\nBut now v.y = " + str::str(v.y)); } return vec2(acosh(v.x), acosh(v.y)); } vec2 atanh(const vec2& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1).\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1).\nBut v.y = " + str::str(v.y) + " now."); } return vec2(atanh(v.x), atanh(v.y)); } vec2 atan2(const vec2& Y, const vec2& X) { return vec2(atan2(Y.x, X.x), atan2(Y.y, X.y)); } vec2 exp(const vec2& v) { return vec2(exp(v.x), exp(v.y)); } vec2 log(const vec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return vec2(log(v.x), log(v.y)); } vec2 log2(const vec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return vec2(log2(v.x), log2(v.y)); } vec2 log10(const vec2& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0.\nBut v.x = " + str::str(v.x) + " now."); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0.\nBut v.y = " + str::str(v.y) + " now."); } return vec2(log10(v.x), log10(v.y)); } vec2 abs(const vec2& v) { return vec2(fabs(v.x), fabs(v.y)); } vec2 floor(const vec2& v) { return vec2(floor(v.x), floor(v.y)); } vec2 ceil(const vec2& v) { return vec2(ceil(v.x), ceil(v.y)); } vec2 round(const vec2& v, uint n) { return vec2(round(v.x, n), round(v.y, n)); } vec2 trunc(const vec2& v) { return vec2(trunc(v.x), trunc(v.y)); } vec2 fix(const vec2& v) { return vec2(fix(v.x), fix(v.y)); } vec3 pow(const vec3& v1, const vec3& v2) { return vec3(pow(v1.x, v2.x), pow(v1.y, v2.y), pow(v1.z, v2.z)); } vec3 pow(const vec3& v, double value) { return vec3(pow(v.x, value), pow(v.y, value), pow(v.z, value)); } vec3 pow(double value, const vec3& v) { return vec3(pow(value, v.x), pow(value, v.y), pow(value, v.z)); } double length(const vec3& v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } vec3 normalize(const vec3& v) { double l = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); return is_zero(l) ? vec3(0.0f, 0.0f, 0.0f) : vec3(v.x / l, v.y / l, v.z / l); } vec3 reflect(vec3 v_in, vec3 v_norm) { v_in = normalize(v_in); v_norm = normalize(v_norm); return v_in - 2*dot(v_in, v_norm)*v_norm; } double dot(const vec3& v1, const vec3& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } vec3 cross(const vec3& v1, const vec3& v2) { return vec3(v1.y*v2.z - v2.y*v1.z, v2.x*v1.z - v1.x*v2.z, v1.x*v2.y - v2.x*v1.y); } vec3 mix(const vec3& v1, const vec3& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } vec3 sin(const vec3& v) { return vec3(sin(v.x), sin(v.y), sin(v.z)); } vec3 cos(const vec3& v) { return vec3(cos(v.x), cos(v.y), cos(v.z)); } vec3 tan(const vec3& v) { double k = v.x/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x cannot be (0.5+k)*PI. But now v.x = " + str::str(v.x) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.y/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y cannot be (0.5+k)*PI. But now v.y = " + str::str(v.y) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.z/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.z cannot be (0.5+k)*PI. But now v.z = " + str::str(v.z) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } return vec3(tan(v.x), tan(v.y), tan(v.z)); } vec3 sinh(const vec3& v) { return vec3(sinh(v.x), sinh(v.y), sinh(v.z)); } vec3 cosh(const vec3& v) { return vec3(cosh(v.x), cosh(v.y), cosh(v.z)); } vec3 tanh(const vec3& v) { return vec3(tanh(v.x), tanh(v.y), tanh(v.z)); } vec3 asin(const vec3& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } return vec3(asin(v.x), asin(v.y), asin(v.z)); } vec3 acos(const vec3& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } return vec3(acos(v.x), acos(v.y), acos(v.z)); } vec3 atan(const vec3& v) { return vec3(atan(v.x), atan(v.y), atan(v.z)); } vec3 asinh(const vec3& v) { return vec3(asinh(v.x), asinh(v.y), asinh(v.z)); } vec3 acosh(const vec3& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1. But now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1. But now v.y = " + str::str(v.y)); } if(v.z < 1) { throw glass::ArithmeticError("v.z cannot be less than 1. But now v.z = " + str::str(v.z)); } return vec3(acosh(v.x), acosh(v.y), acosh(v.z)); } vec3 atanh(const vec3& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1). But now v.x = " + str::str(v.x)); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1). But now v.y = " + str::str(v.y)); } if(v.z <= -1 || v.z >= 1) { throw glass::ArithmeticError("v.z must be in range (-1, 1). But now v.z = " + str::str(v.z)); } return vec3(atanh(v.x), atanh(v.y), atanh(v.z)); } vec3 atan2(const vec3& Y, const vec3& X) { return vec3(atan2(Y.x, X.x), atan2(Y.y, X.y), atan2(Y.z, X.z)); } vec3 exp(const vec3& v) { return vec3(exp(v.x), exp(v.y), exp(v.z)); } vec3 log(const vec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return vec3(log(v.x), log(v.y), log(v.z)); } vec3 log2(const vec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return vec3(log2(v.x), log2(v.y), log2(v.z)); } vec3 log10(const vec3& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } return vec3(log10(v.x), log10(v.y), log10(v.z)); } vec3 abs(const vec3& v) { return vec3(fabs(v.x), fabs(v.y), fabs(v.z)); } vec3 floor(const vec3& v) { return vec3(floor(v.x), floor(v.y), floor(v.z)); } vec3 ceil(const vec3& v) { return vec3(ceil(v.x), ceil(v.y), ceil(v.z)); } vec3 round(const vec3& v, uint n) { return vec3(round(v.x, n), round(v.y, n), round(v.z, n)); } vec3 trunc(const vec3& v) { return vec3(trunc(v.x), trunc(v.y), trunc(v.z)); } vec3 fix(const vec3& v) { return vec3(fix(v.x), fix(v.y), fix(v.z)); } vec4 pow(const vec4& v1, const vec4& v2) { return vec4(pow(v1.x, v2.x), pow(v1.y, v2.y), pow(v1.z, v2.z), pow(v1.w, v2.w)); } vec4 pow(const vec4& v, double value) { return vec4(pow(v.x, value), pow(v.y, value), pow(v.z, value), pow(v.w, value)); } vec4 pow(double value, const vec4& v) { return vec4(pow(value, v.x), pow(value, v.y), pow(value, v.z), pow(value, v.w)); } double length(const vec4& v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); } vec4 normalize(const vec4& v) { double l = sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); return is_zero(l) ? vec4(0.0f, 0.0f, 0.0f, 0.0f) : vec4(v.x / l, v.y / l, v.z / l, v.w / l); } double dot(const vec4& v1, const vec4& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w; } vec4 mix(const vec4& v1, const vec4& v2, double factor) { return factor * v1 + (1.0f - factor) * v2; } vec4 sin(const vec4& v) { return vec4(sin(v.x), sin(v.y), sin(v.z), sin(v.w)); } vec4 cos(const vec4& v) { return vec4(cos(v.x), cos(v.y), cos(v.z), sin(v.w)); } vec4 tan(const vec4& v) { double k = v.x/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.x cannot be (0.5 + k) * PI. But now v.x = " + str::str(v.x) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.y/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.y cannot be (0.5 + k) * PI. But now v.y = " + str::str(v.y) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.z/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.z cannot be (0.5 + k) * PI. But now v.z = " + str::str(v.z) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } k = v.w/PI - 0.5; if(is_int(k)) { throw glass::ArithmeticError("v.w cannot be (0.5 + k) * PI. But now v.w = " + str::str(v.w) + " = (0.5 + " + str::str(int(k)) + ") * PI"); } return vec4(tan(v.x), tan(v.y), tan(v.z), tan(v.w)); } vec4 sinh(const vec4& v) { return vec4(sinh(v.x), sinh(v.y), sinh(v.z), sinh(v.w)); } vec4 cosh(const vec4& v) { return vec4(cosh(v.x), cosh(v.y), cosh(v.z), cosh(v.w)); } vec4 tanh(const vec4& v) { return vec4(tanh(v.x), tanh(v.y), tanh(v.z), tanh(v.w)); } vec4 asin(const vec4& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } if(v.w < -1 || v.w > 1) { throw glass::ArithmeticError("v.w must be in range [-1, 1]. But now v.w = " + str::str(v.w)); } return vec4(asin(v.x), asin(v.y), asin(v.z), asin(v.w)); } vec4 acos(const vec4& v) { if(v.x < -1 || v.x > 1) { throw glass::ArithmeticError("v.x must be in range [-1, 1]. But now v.x = " + str::str(v.x)); } if(v.y < -1 || v.y > 1) { throw glass::ArithmeticError("v.y must be in range [-1, 1]. But now v.y = " + str::str(v.y)); } if(v.z < -1 || v.z > 1) { throw glass::ArithmeticError("v.z must be in range [-1, 1]. But now v.z = " + str::str(v.z)); } if(v.w < -1 || v.w > 1) { throw glass::ArithmeticError("v.w must be in range [-1, 1]. But now v.w = " + str::str(v.w)); } return vec4(acos(v.x), acos(v.y), acos(v.z), acos(v.w)); } vec4 atan(const vec4& v) { return vec4(atan(v.x), atan(v.y), atan(v.z), atan(v.w)); } vec4 asinh(const vec4& v) { return vec4(asinh(v.x), asinh(v.y), asinh(v.z), asinh(v.w)); } vec4 acosh(const vec4& v) { if(v.x < 1) { throw glass::ArithmeticError("v.x cannot be less than 1. But now v.x = " + str::str(v.x)); } if(v.y < 1) { throw glass::ArithmeticError("v.y cannot be less than 1. But now v.y = " + str::str(v.y)); } if(v.z < 1) { throw glass::ArithmeticError("v.z cannot be less than 1. But now v.z = " + str::str(v.z)); } if(v.w < 1) { throw glass::ArithmeticError("v.w cannot be less than 1. But now v.w = " + str::str(v.w)); } return vec4(acosh(v.x), acosh(v.y), acosh(v.z), acosh(v.w)); } vec4 atanh(const vec4& v) { if(v.x <= -1 || v.x >= 1) { throw glass::ArithmeticError("v.x must be in range (-1, 1). But now v.x = " + str::str(v.x)); } if(v.y <= -1 || v.y >= 1) { throw glass::ArithmeticError("v.y must be in range (-1, 1). But now v.y = " + str::str(v.y)); } if(v.z <= -1 || v.z >= 1) { throw glass::ArithmeticError("v.z must be in range (-1, 1). But now v.z = " + str::str(v.z)); } if(v.w <= -1 || v.w >= 1) { throw glass::ArithmeticError("v.w must be in range (-1, 1). But now v.w = " + str::str(v.w)); } return vec4(atanh(v.x), atanh(v.y), atanh(v.z), atanh(v.w)); } vec4 atan2(const vec4& Y, const vec4& X) { return vec4(atan2(Y.x, X.x), atan2(Y.y, X.y), atan2(Y.z, X.z), atan2(Y.w, X.w)); } vec4 exp(const vec4& v) { return vec4(exp(v.x), exp(v.y), exp(v.z), exp(v.w)); } vec4 log(const vec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return vec4(log(v.x), log(v.y), log(v.z), log(v.w)); } vec4 log2(const vec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return vec4(log2(v.x), log2(v.y), log2(v.z), log2(v.w)); } vec4 log10(const vec4& v) { if(v.x <= 0) { throw glass::ArithmeticError("v.x must be greater than 0. But now v.x = " + str::str(v.x)); } if(v.y <= 0) { throw glass::ArithmeticError("v.y must be greater than 0. But now v.y = " + str::str(v.y)); } if(v.z <= 0) { throw glass::ArithmeticError("v.z must be greater than 0. But now v.z = " + str::str(v.z)); } if(v.w <= 0) { throw glass::ArithmeticError("v.w must be greater than 0. But now v.w = " + str::str(v.w)); } return vec4(log10(v.x), log10(v.y), log10(v.z), log10(v.w)); } vec4 abs(const vec4& v) { return vec4(fabs(v.x), fabs(v.y), fabs(v.z), fabs(v.w)); } vec4 floor(const vec4& v) { return vec4(floor(v.x), floor(v.y), floor(v.z), floor(v.w)); } vec4 ceil(const vec4& v) { return vec4(ceil(v.x), ceil(v.y), ceil(v.z), ceil(v.w)); } vec4 round(const vec4& v, uint n) { return vec4(round(v.x, n), round(v.y, n), round(v.z, n), round(v.w, n)); } vec4 trunc(const vec4& v) { return vec4(trunc(v.x), trunc(v.y), trunc(v.z), trunc(v.w)); } vec4 fix(const vec4& v) { return vec4(fix(v.x), fix(v.y), fix(v.z), fix(v.w)); }