text
stringlengths
1
1.05M
/** * @module Experiences/Experience0 */ import React, { Profiler, useRef } from 'react' import { BehaviorSubject, interval } from 'rxjs' const onRender = (id, phase, actualDuration) => { console.log(id, phase, actualDuration) } const observable = interval(2000) const subject = new BehaviorSubject(0) const observerA = { next: (v) => console.log(`observerA: ${v}`) } const observerB = { next: (v) => console.log(`observerB: ${v}`) } /** * @function Experience * @return {Object} Return the dom of the Experience */ const Experience = () => { const subscriptionA = useRef() const subscriptionB = useRef() const handleClick = () => { observable.subscribe(subject) } const handleSubscribeA = () => { subscriptionA.current = subject.subscribe(observerA) } const handleSubscribeB = () => { subscriptionB.current = subject.subscribe(observerB) } const handleUnsubscribe = () => { subscriptionA.current.unsubscribe() subscriptionB.current.unsubscribe() } return ( <Profiler id="Experience" onRender={onRender}> <button onClick={handleClick}> Wait 5s, call the Observable and then look at the console </button> <div> Subscribe an observer to the subject and will return the curent value of observable </div> <button onClick={handleSubscribeA}>SubscribeA</button> <button onClick={handleSubscribeB}>SubscribeB</button> <button onClick={handleUnsubscribe}> SubscribeB and directly return the current value of the subject </button> </Profiler> ) } export default Experience
class DarshanBaseError(Exception): """ Base exception class for Darshan errors in Python. """ pass class DarshanVersionError(NotImplementedError): """ Error class for handling unsupported versions of the Darshan library. """ pass
#!/bin/bash # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This script is being run chrooted in the ubuntu live CD ISO image function ubuntu_remove_packages { local PKG=( ubiquity udisks2 ) # udisks2 is responsible for automounting if [[ ${DISTRIB_CODENAME} == "trusty" ]]; then PKG+=( friends friends-dispatcher friends-facebook friends-twitter ) fi apt-get -y remove "${BAD_PKG[@]}" } function install_forensication_tools { readonly local CHIPSEC_PKG=( python-dev libffi-dev build-essential gcc nasm ) readonly local FORENSIC_PKG=( dcfldd ) # install common utils apt-get -y install "${FORENSIC_PKG[@]}" "${CHIPSEC_PKG[@]}" } function install_basic_pkg { readonly local COMMON_UTILS=( git jq python-pip pv zenity ) readonly local WIRELESS_PKG=( firmware-b43-installer bcmwl-kernel-source ) apt-get -y update apt-get -y install "${COMMON_UTILS[@]}" "${WIRELESS_PKG[@]}" echo "PasswordAuthentication no" >> /etc/ssh/sshd_config } function ubuntu_fix_systemd { # By default, with systemd, /etc/resolv.conf is a link to # /run/systemd/resolve/resolve.conf, which is only created when # systemd-resoved has successfully started. # Since we're going to chroot, the link will be broken and we'll get no DNS # resolution. So we make our own temporary static resolv.conf here. if [[ -L /etc/resolv.conf ]]; then rm /etc/resolv.conf echo "nameserver 8.8.8.8" > /etc/resolv.conf.static ln -s /etc/resolv.conf.static /etc/resolv.conf fi # Systemd fails if DNSSEC fails by default. So we disable that if [[ -f /etc/systemd/resolved.conf ]]; then sed -i 's/^#DNSSEC=.*/DNSSEC=no/' /etc/systemd/resolved.conf fi apt-get -y install libnss-resolve } function ubuntu_fix_mbp { # This is installing SPI drivers for the keyboard & mousepads on # MacBook 2016 (with touchbar) apt-get -y install dkms git clone https://github.com/cb22/macbook12-spi-driver.git /usr/src/applespi-0.1 # We need to install for the kernel of the OS we're chrooted in, not the one # that's currently running on our workstation. # Ubuntu Live CD should only have one kernel installed, so this should work. dkms install -m applespi -v 0.1 -k "$(basename /lib/modules/*)" echo -e "\napplespi\nintel_lpss_pci\nspi_pxa2xx_platform" >> /etc/initramfs-tools/modules update-initramfs -u } function ignore_chipsec_logs { # Chipsec generates a ton of logs which can fill up the local storage echo -e ":msg, contains, \"IOCTL_RDMMIO\" stop\n\ :msg, contains, \"IOCTL_WRMMIO\" stop\n\ & stop" > /etc/rsyslog.d/00-chipsec.conf } # Comment out cdrom repo sed -e '/cdrom/ s/^#*/#/' -i /etc/apt/sources.list source /etc/lsb-release newest_ubuntus=("zesty" "artful") if [[ "${newest_ubuntus[@]}" =~ "${DISTRIB_CODENAME}" ]]; then ubuntu_fix_systemd fi ignore_chipsec_logs install_basic_pkg install_forensication_tools ubuntu_remove_packages ubuntu_fix_mbp
<reponame>wpisen/trace package com.wpisen.trace.agent.transfer; import com.wpisen.trace.agent.collect.CollectHandleProxy; import com.wpisen.trace.agent.common.logger.Logger; import com.wpisen.trace.agent.common.logger.LoggerFactory; import com.wpisen.trace.agent.trace.TraceContext; /** * 获取队列线程 * * @since 0.1.0 */ public class TransferTask extends Thread { private TraceContext context; private final Logger logger; public TransferTask(TraceContext context, String name) { this.setName(name); this.context = context; logger = LoggerFactory.getLogger(CollectHandleProxy.class); } @Override public void run() { for (;;) { try { context.uploadNode(20); } catch (Throwable e) { logger.error("upload Task error", e); } } } }
package dk.kvalitetsit.hjemmebehandling.controller; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import dk.kvalitetsit.hjemmebehandling.types.PageDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import dk.kvalitetsit.hjemmebehandling.api.CreatePatientRequest; import dk.kvalitetsit.hjemmebehandling.api.DtoMapper; import dk.kvalitetsit.hjemmebehandling.api.PatientDto; import dk.kvalitetsit.hjemmebehandling.api.PatientListResponse; import dk.kvalitetsit.hjemmebehandling.client.CustomUserClient; import dk.kvalitetsit.hjemmebehandling.constants.errors.ErrorDetails; import dk.kvalitetsit.hjemmebehandling.controller.exception.InternalServerErrorException; import dk.kvalitetsit.hjemmebehandling.controller.exception.ResourceNotFoundException; import dk.kvalitetsit.hjemmebehandling.model.PatientModel; import dk.kvalitetsit.hjemmebehandling.service.AuditLoggingService; import dk.kvalitetsit.hjemmebehandling.service.PatientService; import dk.kvalitetsit.hjemmebehandling.service.exception.ServiceException; import io.swagger.v3.oas.annotations.tags.Tag; @RestController @Tag(name = "Patient", description = "API for manipulating and retrieving patients.") public class PatientController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(PatientController.class); private PatientService patientService; private AuditLoggingService auditLoggingService; private DtoMapper dtoMapper; private CustomUserClient customUserClient; public PatientController(PatientService patientService, AuditLoggingService auditLoggingService, DtoMapper dtoMapper, CustomUserClient customUserClient) { this.patientService = patientService; this.auditLoggingService = auditLoggingService; this.dtoMapper = dtoMapper; this.customUserClient = customUserClient; } @GetMapping(value = "/v1/patientlist") public @ResponseBody PatientListResponse getPatientList() { logger.info("Getting patient list ..."); String clinicalIdentifier = getClinicalIdentifier(); List<PatientModel> patients = patientService.getPatients(clinicalIdentifier); auditLoggingService.log("GET /v1/patientlist", patients); return buildResponse(patients); } @PostMapping(value = "/v1/patient") public void createPatient(@RequestBody CreatePatientRequest request) { // Create the patient try { PatientModel patient = dtoMapper.mapPatientDto(request.getPatient()); patientService.createPatient(patient); auditLoggingService.log("POST /v1/patient", patient); } catch(ServiceException e) { logger.error("Error creating patient", e); throw new InternalServerErrorException(ErrorDetails.INTERNAL_SERVER_ERROR); } } @GetMapping(value = "/v1/patient") public @ResponseBody PatientDto getPatient(String cpr) { logger.info("Getting patient ..."); String clinicalIdentifier = getClinicalIdentifier(); PatientModel patient = patientService.getPatient(cpr); auditLoggingService.log("GET /v1/patient", patient); if(patient == null) { throw new ResourceNotFoundException("Patient did not exist!", ErrorDetails.PATIENT_DOES_NOT_EXIST); } return dtoMapper.mapPatientModel(patient); } @GetMapping(value = "/v1/patient/search") public @ResponseBody PatientListResponse searchPatients(String searchString) { logger.info("Getting patient ..."); List<PatientModel> patients = patientService.searchPatients(List.of(searchString)); auditLoggingService.log("GET /v1/patient/search", patients); return buildResponse(patients); } @GetMapping(value = "/v1/patients") public @ResponseBody PatientListResponse getPatients(boolean includeActive, boolean includeCompleted, @RequestParam("page_number") Optional<Integer> pageNumber, @RequestParam("page_size") Optional<Integer> pageSize) { logger.info("Getting patient ..."); if(!includeActive && !includeCompleted) return buildResponse(new ArrayList<>()); var pagedetails = new PageDetails(pageNumber.get(), pageSize.get()); List<PatientModel> patients = patientService.getPatients(includeActive,includeCompleted,pagedetails); auditLoggingService.log("GET /v1/patients", patients); return buildResponse(patients); } @PutMapping(value = "/v1/resetpassword") public void resetPassword(@RequestParam("cpr") String cpr) throws JsonMappingException, JsonProcessingException { logger.info("reset password for patient"); PatientModel patientModel = patientService.getPatient(cpr); customUserClient.resetPassword(cpr, patientModel.getCustomUserId()); } private String getClinicalIdentifier() { // TODO - get clinical identifier (from token?) return "1234"; } private PatientListResponse buildResponse(List<PatientModel> patients) { PatientListResponse response = new PatientListResponse(); response.setPatients(patients.stream().map(p -> dtoMapper.mapPatientModel(p)).collect(Collectors.toList())); return response; } }
#!/usr/bin/env bash ./_devtools/phpcbf --report=full --report-file=./logs/phpcbf.log --standard=PSR2 src/
def print_arr(arr): # find the maximum number of characters max_len = 0 for item in arr: item_len = len(str(item)) if item_len > max_len: max_len = item_len # now print each item with spaces for item in arr: item_len = len(str(item)) num_spaces = max_len - item_len print(" " * num_spaces + str(item), end = "") print()
class YearMonth class Serializer < ActiveRecord::Type::Value def type :year_month end def cast(value) value end def serialize(value) value = YearMonth.admin_value(value) value ? value.date : nil end def deserialize(value) case value when Date YearMonth.new(value.year, value.month) when String date = Date.parse(value) YearMonth.new(date.year, date.month) end end end include Comparable def initialize(year, month) @year = year.to_i @month = month.to_i @date = Date.new(@year, @month) end attr_reader :year, :month, :date def self.admin_value(value) if value.class == String d = Date.parse(value) YearMonth.new(d.year, d.month) else value end end def <=>(other) other = YearMonth.admin_value(other) (year <=> other.year).nonzero? || month <=> other.month end alias_method :eql?, :== def hash date.hash end def next if month == 12 self.class.new(year + 1, 1) else self.class.new(year, month + 1) end end alias_method :succ, :next def day date.day end def starts_on date end def ends_on date.end_of_month end def to_s "#{date.strftime('%B')} #{date.year}" end def to_formatted_s(format = :long_day_month_year) if format == :long_day_month_year end_date = date.end_of_month "#{date.to_formatted_s(:day_excluding_leading_zero)} to #{end_date.to_formatted_s(:long_day_month_year)}" else date.to_formatted_s(format) end end end
#!/bin/bash # # Test script file that maps itself into a docker container and runs # # Example invocation: # # $ AOSP_VOL=$PWD/build ./build-kitkat.sh # set -ex if [ "$1" = "docker" ]; then TEST_BRANCH=${TEST_BRANCH:-release} TEST_URL=${TEST_URL:-git://shanghai.source.codeaurora.org/platform/manifest.git} TEST_MANIFEST=${TEST_MANIFEST:-LNX.LA.3.7.2.c6-10200-8x16.0.xml} TEST_MODEL=${TEST_MODEL:-msm8916_32-userdebug} cpus=$(grep ^processor /proc/cpuinfo | wc -l) repo init --depth 1 -u "$TEST_URL" -b "$TEST_BRANCH" -m "$TEST_MANIFEST" --repo-url=git://shanghai.source.codeaurora.org/tools/repo.git --repo-branch=caf-stable # Use default sync '-j' value embedded in manifest file to be polite repo sync -j$cpus prebuilts/misc/linux-x86/ccache/ccache -M 10G source build/envsetup.sh lunch "$TEST_MODEL" make -j$cpus else aosp_url="https://raw.githubusercontent.com/kylemanna/docker-aosp/master/utils/aosp" args="bash run.sh docker" export AOSP_EXTRA_ARGS="-v $(cd $(dirname $0) && pwd -P)/$(basename $0):/usr/local/bin/run.sh:ro" export AOSP_VOL="/home/andrea/android/codeaurora" export AOSP_IMAGE="andreaji/android:4.4-kitkat" # # Try to invoke the aosp wrapper with the following priority: # # 1. If AOSP_BIN is set, use that # 2. If aosp is found in the shell $PATH # 3. Grab it from the web # if [ -n "$AOSP_BIN" ]; then $AOSP_BIN $args elif [ -x "../utils/aosp" ]; then ../utils/aosp $args elif [ -n "$(type -P aosp)" ]; then aosp $args else if [ -n "$(type -P curl)" ]; then bash <(curl -s $aosp_url) $args elif [ -n "$(type -P wget)" ]; then bash <(wget -q $aosp_url -O -) $args else echo "Unable to run the aosp binary" fi fi fi
<reponame>gemini133/mango /* MANGO Multimedia Development Platform Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include <string> #include <mango/core/configure.hpp> #include <mango/core/object.hpp> namespace mango { class DynamicLibrary : protected NonCopyable { protected: struct DynamicLibraryHandle* m_handle; public: DynamicLibrary(const std::string& filename); ~DynamicLibrary(); void* address(const std::string& symbol) const; }; } // namespace mango
import axios from "./axios"; const notebooksApi = { getNotebooks: () => axios.get("/notebooks").then(response => response.data), getNotebook: id => axios.get(`/notebooks/${id}`).then(response => response.data), updateNotebook: (id, data) => axios.put(`/notebooks/${id}`, data).then(response => response.data), createNotebook: notebook => axios.post("/notebooks", notebook).then(response => response.data), deleteNotebook: id => axios.delete(`/notebooks/${id}`) }; export default notebooksApi;
#!/bin/bash # Show real memory usage as a percentage of total memory. total=$(free -m | grep Mem | awk '{print $2}') used=$(free -m | grep Mem | awk '{print $3}') buffers=$(free -m | grep Mem | awk '{print $(NF-1)}') cached=$(free -m | grep Mem | awk '{print $NF}') percent=$(echo "($used-$cached-$buffers)/$total*100" | bc -l) printf '%.2f\n' $percent
import cv2 class VideoProcessor: def __init__(self, window_name): self.window_name = window_name self.gain_text = 'Gain' self.fps_text = 'FPS' self.x0_text = 'X0' self.x1_text = 'X1' self.y0_text = 'Y0' def __set_gain(self, value): # Callback function for gain trackbar pass def __set_fps(self, value): # Callback function for fps trackbar pass def __prepare_window(self, mode, frame_shape, video_bit='uint8'): h, w = frame_shape cv2.destroyAllWindows() cv2.namedWindow(self.window_name) if mode == 'prepare': cv2.createTrackbar(self.gain_text, self.window_name, 0, 2, self.__set_gain) cv2.createTrackbar(self.fps_text, self.window_name, 1, 4, self.__set_fps) cv2.createTrackbar(self.x0_text, self.window_name, 0, w, lambda x: x) cv2.createTrackbar(self.x1_text, self.window_name, w, w, lambda x: x) cv2.createTrackbar(self.y0_text, self.window_name, 0, h, lambda x: x) elif mode == 'update': # Add logic for updating trackbars based on new parameters pass
# Wait for Katacoda to initialize sleep 1 # Start Kubernetes launch.sh # Install Tekton Pipelines kubectl apply --filename https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml # Install the Tekton CLI curl -LO https://github.com/tektoncd/cli/releases/download/v0.10.0/tkn_0.10.0_Linux_x86_64.tar.gz sudo tar xvzf tkn_0.10.0_Linux_x86_64.tar.gz -C /usr/local/bin/ tkn
// Copyright © 2019 <NAME> // // 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 currentalert import ( "github.com/banzaicloud/kafka-operator/api/v1beta1" "github.com/banzaicloud/kafka-operator/pkg/k8sutil" "github.com/banzaicloud/kafka-operator/pkg/scale" "github.com/banzaicloud/kafka-operator/pkg/util" "github.com/prometheus/common/model" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" "sigs.k8s.io/controller-runtime/pkg/client" ) type ccConfig struct { Name string Namespace string CruiseControlEndpoint string } type disableScaling struct { Up bool Down bool } func (e *examiner) getCR() (*v1beta1.KafkaCluster, *ccConfig, error) { cr, err := k8sutil.GetCr(string(e.Alert.Labels["kafka_cr"]), string(e.Alert.Labels["namespace"]), e.Client) if err != nil { return nil, nil, err } cc := &ccConfig{ Name: cr.Name, Namespace: cr.Namespace, CruiseControlEndpoint: cr.Spec.CruiseControlConfig.CruiseControlEndpoint, } return cr, cc, nil } func (e *examiner) examineAlert(rollingUpgradeAlertCount int) (bool, error) { cr, cc, err := e.getCR() if err != nil { return false, err } if !e.IgnoreCCStatus { if err := cc.getCruiseControlStatus(); err != nil { return false, err } } if err := k8sutil.UpdateCrWithRollingUpgrade(rollingUpgradeAlertCount, cr, e.Client); err != nil { return false, err } if cr.Status.State == "rollingupgrade" { return false, nil } ds := disableScaling{} if cr.Spec.AlertManagerConfig != nil { if len(cr.Spec.Brokers) <= cr.Spec.AlertManagerConfig.DownScaleLimit { ds.Down = true } if cr.Spec.AlertManagerConfig.UpScaleLimit > 0 && len(cr.Spec.Brokers) >= cr.Spec.AlertManagerConfig.UpScaleLimit { ds.Up = true } } return e.processAlert(ds) } func (e *examiner) processAlert(ds disableScaling) (bool, error) { switch e.Alert.Annotations["command"] { case "addPVC": err := addPVC(e.Alert.Labels, e.Alert.Annotations, e.Client) if err != nil { return false, err } case "downScale": if ds.Down { e.Log.Info("downscaling is skipped due to downscale limit") return true, nil } err := downScale(e.Alert.Labels, e.Client) if err != nil { return false, err } case "upScale": if ds.Up { e.Log.Info("upscaling is skipped due to upscale limit") return true, nil } err := upScale(e.Alert.Labels, e.Alert.Annotations, e.Client) if err != nil { return false, err } } return false, nil } func addPVC(labels model.LabelSet, annotations model.LabelSet, client client.Client) error { //TODO return nil } func downScale(labels model.LabelSet, client client.Client) error { cr, err := k8sutil.GetCr(string(labels["kafka_cr"]), string(labels["namespace"]), client) if err != nil { return err } brokerId, err := scale.GetBrokerIDWithLeastPartition(string(labels["namespace"]), cr.Spec.CruiseControlConfig.CruiseControlEndpoint, cr.Name) if err != nil { return err } err = k8sutil.RemoveBrokerFromCr(brokerId, string(labels["kafka_cr"]), string(labels["namespace"]), client) if err != nil { return err } return nil } func upScale(labels model.LabelSet, annotations model.LabelSet, client client.Client) error { cr, err := k8sutil.GetCr(string(labels["kafka_cr"]), string(labels["namespace"]), client) if err != nil { return err } biggestId := int32(0) for _, broker := range cr.Spec.Brokers { if broker.Id > biggestId { biggestId = broker.Id } } var broker v1beta1.Broker brokerConfigGroupName := string(annotations["brokerConfigGroup"]) if _, ok := cr.Spec.BrokerConfigGroups[brokerConfigGroupName]; ok { broker.BrokerConfigGroup = brokerConfigGroupName broker.Id = biggestId + 1 } else { broker = v1beta1.Broker{ Id: biggestId + 1, BrokerConfig: &v1beta1.BrokerConfig{ Image: string(annotations["image"]), StorageConfigs: []v1beta1.StorageConfig{ { MountPath: string(annotations["mountPath"]), PVCSpec: &corev1.PersistentVolumeClaimSpec{ AccessModes: []corev1.PersistentVolumeAccessMode{ corev1.ReadWriteOnce, }, StorageClassName: util.StringPointer(string(annotations["storageClass"])), Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ "storage": resource.MustParse(string(annotations["diskSize"])), }, }, }, }, }, }, } } err = k8sutil.AddNewBrokerToCr(broker, string(labels["kafka_cr"]), string(labels["namespace"]), client) if err != nil { return err } return nil } func (c *ccConfig) getCruiseControlStatus() error { return scale.GetCruiseControlStatus(c.Namespace, c.CruiseControlEndpoint, c.Name) }
package facade.amazonaws import scala.scalajs.js import scala.scalajs.js.annotation.JSImport @js.native @JSImport("aws-sdk/lib/node_loader", "Credentials", "AWS.Credentials") class AWSCredentials() extends js.Object { def this(accessKeyId: String, secretAccessKey: String, sessionToken: js.UndefOr[String] = js.undefined) = this() def this(options: CredentialsOptions) = this() def getPromise(): js.Promise[Unit] = js.native def needsRefresh(): Boolean = js.native def refreshPromise(): js.Promise[Unit] = js.native val accessKeyId: String = js.native val secretAccessKey: String = js.native val sessionToken: String = js.native val expired: Boolean = js.native val expireTime: js.Date = js.native var expiryWindow: Int = js.native } trait CredentialsOptions extends js.Object { var accessKeyId: String var secretAccessKey: String var sessionToken: js.UndefOr[String] } object CredentialsOptions { def apply( accessKeyId: String, secretAccessKey: String, sessionToken: js.UndefOr[String] = js.undefined ): CredentialsOptions = { val _obj$ = js.Dynamic.literal( "accessKeyId" -> accessKeyId.asInstanceOf[js.Any], "secretAccessKey" -> secretAccessKey.asInstanceOf[js.Any] ) sessionToken.foreach(_v => _obj$.updateDynamic("sessionToken")(_v.asInstanceOf[js.Any])) _obj$.asInstanceOf[CredentialsOptions] } }
// Require local class dependencies const Helper = require('helper'); /** * Create Grid Helper class */ class GridHelper extends Helper { /** * Construct Grid Helper class * * @param {object} options */ constructor (options) { // Run super super(); // Bind public methods this.data = this.data.bind(this); this.type = this.type.bind(this); this.rows = this.rows.bind(this); this.live = this.live.bind(this); this.page = this.page.bind(this); this.post = this.post.bind(this); this.sort = this.sort.bind(this); this.model = this.model.bind(this); this.query = this.query.bind(this); this.route = this.route.bind(this); this.filter = this.filter.bind(this); this.render = this.render.bind(this); this.querySort = this.querySort.bind(this); // Bind private methods this._bind = this._bind.bind(this); // Set default options options = options || {}; // Set private variables this._way = options.way || false; this._rows = options.rows || 20; this._type = options.type || 'columns'; this._live = options.live || false; this._page = options.page || 1; this._sort = options.sort || false; this._model = options.model || false; this._where = options.where || this._model; this._route = options.route || ''; this._filter = options.filter || {}; this._filters = options.filters || {}; this._columns = options.columns || {}; // Run bind this._bind(); } /** * Set rows * * @param {*} rows * * @return {GridHelper} */ rows (rows) { // Set rows this._rows = rows; // Allow chainable return this; } /** * Set type * * @param {*} type * * @return {GridHelper} */ type (type) { // Set type this._type = type; // Allow chainable return this; } /** * Set live * * @param {boolean} live * * @return {GridHelper} */ live (live) { // Set live this._live = live; // Allow chainable return this; } /** * Set page * * @param {*} page * * @return {GridHelper} */ page (page) { // Set page this._page = page; // Allow chainable return this; } /** * Set sort * * @param {string} sort * @param {number} way * * @return {GridHelper} */ sort (sort, way) { // Set way and sort this._way = way; this._sort = sort; // Allow chainable return this; } /** * Set model * * @param {*} model * * @return {GridHelper} */ model (model) { // Set model this._model = model; // Run model bind this._bind(); // Allow chainable return this; } /** * Set route * * @param {string} route * * @return {GridHelper} */ route (route) { // Set route this._route = route; // Allow chainable return this; } /** * Returns filtered query * * @return {Promise} * * @async */ async query () { // Check filters for (const filter in this._filter) { // Check this filter has filter if (this._filter.hasOwnProperty(filter)) { // Check filter exists if (!this._filters[filter]) { continue; } // Check if filter has query if (this._filters[filter].query) { // Run query await this._filters[filter].query(this._filter[filter]); } else { // Run and this.where(filter, this._filter[filter]); } } } // Return this return this; } /** * Returns sorted query * * @return {Promise} * * @async */ async querySort () { // Check sort if (this._sort && this._columns[this._sort] && this._columns[this._sort].sort && this._way !== false) { // Check type if (typeof this._columns[this._sort].sort === 'function') { // Set sort this._where = await this._columns[this._sort].sort(this._where, this._way); } else if (this._columns[this._sort].sort === true) { // Set sort directly this._where = this._where.sort(this._sort, this._way); } } else if (this._sort && this._way !== false) { // Set sort directly this._where = this._where.sort(this._sort, this._way); } // Allow chainable return this; } /** * Add filter * * @param {string} key * @param {*} filter * * @return {GridHelper} */ filter (key, filter) { // Set filter this._filters[key] = filter; // Allow chainable return this; } /** * Add column * * @param {string} key * @param {*} column * * @return {GridHelper} */ column (key, column) { // Set column this._columns[key] = column; // Allow chainable return this; } /** * Runs post request * * @param {Request} req * @param {Response} res */ async post (req, res) { // Check rows if (req.body.rows) this._rows = parseInt(req.body.rows); // Check page if (req.body.page) this._page = parseInt(req.body.page); // Check sort if (req.body.sort) this._sort = req.body.sort; // Set way this._way = req.body.way; // Check filter if (req.body.filter) { // Loop filter for (const key in req.body.filter) { // Check filter has key if (req.body.filter.hasOwnProperty(key)) { // Check value if (!req.body.filter[key].length && !Object.keys(req.body.filter[key]).length) continue; // Set filter this._filter[key] = req.body.filter[key]; } } } // Send result res.json(await this.render()); } /** * Exports columns * * @param {array} rows * @param {string} type * * @return {Promise} */ data (rows, type) { // Check type if (this._type !== 'columns') { // Return sanitised return Promise.all(rows.map((row) => { return row.sanitise(); })); } else { // Return map return Promise.all(rows.map(async (row) => { // Set sanitised const sanitised = {}; // Loop columns await Promise.all(Object.keys(this._columns).map(async (column) => { // Check if column export if (typeof this._columns[column].type !== 'undefined' && type !== this._columns[column].type) return; // Load column let load = await row.get(column); // Check format if (this._columns[column].format) load = await this._columns[column].format(load, row, type); // Set to sanitised sanitised[column] = (load || '').toString(); })); // Return sanitised return sanitised; })); } } /** * Runs post request * * @param {Request} req * @param {string} type * * @return {Promise} * * @async */ async export (req, type) { // Check order if (req.body.sort) this._sort = req.body.sort; // Set way this._way = req.body.way; // Check where if (req.body.filter) { // Loop filter for (const key in req.body.filter) { // Check filter has key if (req.body.filter.hasOwnProperty(key)) { // Set filter this._filter[key] = req.body.filter[key]; } } } // Run query await this.query(); // Return result return await this.data(await this._where.find(), type); } /** * Renders grid view * * @param {Request} req * * @return {*} * * @async */ async render (req) { // Check rows if (req && req.query.rows) this._rows = parseInt(req.query.rows); // Check page if (req && req.query.page) this._page = parseInt(req.query.page); // Check order if (req && req.query.sort) this._sort = req.query.sort; // Set way if (req && req.query.way) this._way = (req.query.way === 'false' ? false : parseInt(req.query.way)); // Check filter if (req && req.query.filter) { // Loop filter for (const key in req.query.filter) { // Check filter has key if (req.query.filter.hasOwnProperty(key)) { // Check value if (!req.query.filter[key].length || !Object.keys(req.query.filter[key]).length) continue; // Set value this._filter[key] = req.query.filter[key]; } } } // Set response const response = { 'data' : [], 'filter' : this._filter, 'filters' : [], 'columns' : [] }; // Set standard vars response.way = this._way; response.page = this._page; response.rows = this._rows; response.sort = this._sort; response.live = this._live; response.type = this._type; response.route = this._route; // Do query await this.query(); // Set total response.total = await this._where.count(); // Do query await this.querySort(); // Complete query let rows = await this._where.skip(this._rows * (this._page - 1)).limit(this._rows).find(); // Get data response.data = await this.data(rows, false); // Check type columns if (this._type === 'columns') { // Loop columns for (const col in this._columns) { // Check columns has col if (this._columns.hasOwnProperty(col)) { // Check type if (this._columns[col].type) continue; // Push into columns response.columns.push({ 'id' : col, 'sort' : !!this._columns[col].sort, 'width' : this._columns[col].width || false, 'title' : this._columns[col].title }); } } } // Loop filters for (const filter in this._filters) { // Check filters has filter if (this._filters.hasOwnProperty(filter)) { // Push into filters response.filters.push({ 'id' : filter, 'type' : this._filters[filter].type, 'ajax' : this._filters[filter].ajax, 'title' : this._filters[filter].title, 'socket' : this._filters[filter].socket, 'options' : this._filters[filter].options }); } } // Return response return response; } /** * Binds model */ _bind () { // Check model if (!this._model) return; // Check where if (!this._where) this._where = this._model; // Bind query methods ['where', 'match', 'eq', 'ne', 'or', 'and', 'elem', 'in', 'nin', 'gt', 'lt', 'gte', 'lte'].forEach((method) => { // Create new function this[method] = (...args) => { // Set where return this._where = this._where[method](...args); }; }); } } /** * Export new Grid Helper instance * * @type {GridHelper} */ exports = module.exports = GridHelper;
#!/bin/csh # generated by BIGNASim metatrajectory generator #$ -cwd #$ -N BIGNaSim_curl_call_BIGNASim5707d48b857d0 #$ -o CURL.BIGNASim5707d48b857d0.out #$ -e CURL.BIGNASim5707d48b857d0.err # Launching CURL... # CURL is calling a REST WS that generates the metatrajectory. curl -i -H "Content-Type: application/json" -X GET -d '{"idSession":"ANONUSER5707d44d126ca","idTraj":"NAFlex_1tro","name":"BIGNASim5707d48b857d0-NAFlex_1tro-0_1_1","description":"Subtrajectory of NAFlex_1tro with 0_1_1 frames selected","mask":"name *","frames":"0:1:1","format":"pdb"}' http://ms2/download
# Define the _ENCODE constant _ENCODE = 'utf-8' # Import the necessary module(s) import os # Implement the function to open a log file def open_log_file(filename, mode): return logfile_open(filename, mode)
const ms = require('../help/ms') module.exports = ({ audience, expiresIn, iat = true, issuer, jti, kid, notBefore, now = new Date(), subject }, payload) => { if (!(now instanceof Date) || !now.getTime()) { throw new TypeError('options.now must be a valid Date object') } const unix = now.getTime() if (iat !== undefined) { if (typeof iat !== 'boolean') { throw new TypeError('options.iat must be a boolean') } if (iat) { payload.iat = new Date(unix) } } if (expiresIn !== undefined) { if (typeof expiresIn !== 'string') { throw new TypeError('options.expiresIn must be a string') } payload.exp = new Date(unix + ms(expiresIn)) } if (notBefore !== undefined) { if (typeof notBefore !== 'string') { throw new TypeError('options.notBefore must be a string') } payload.nbf = new Date(unix + ms(notBefore)) } if (audience !== undefined) { if (typeof audience !== 'string') { throw new TypeError('options.audience must be a string') } payload.aud = audience } if (issuer !== undefined) { if (typeof issuer !== 'string') { throw new TypeError('options.issuer must be a string') } payload.iss = issuer } if (subject !== undefined) { if (typeof subject !== 'string') { throw new TypeError('options.subject must be a string') } payload.sub = subject } if (kid !== undefined) { if (typeof kid !== 'string') { throw new TypeError('options.kid must be a string') } payload.kid = kid } if (jti !== undefined) { if (typeof jti !== 'string') { throw new TypeError('options.jti must be a string') } payload.jti = jti } return payload }
package com.example.videly.authentication; import com.example.videly.dao.ApplicationUserDAO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Service @Slf4j public class ApplicationUserService implements UserDetailsService { private final ApplicationUserDAO dao; @Autowired public ApplicationUserService(@Qualifier("MySQL") ApplicationUserDAO dao) { this.dao = dao; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { final String USER_NOT_FOUND_MSG = "Username %s not found in users table"; final String ERR_MSG = String.format(USER_NOT_FOUND_MSG, username); log.info(String.format(USER_NOT_FOUND_MSG, username)); return dao.loadUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException(ERR_MSG)); } public void createUser(ApplicationUser applicationUser) { Optional<ApplicationUser> user = dao.findByEmail(applicationUser.getEmail()); user.ifPresentOrElse(foundUser -> { verifyUserExistence(applicationUser, foundUser); }, () -> { final int insertSucceedStatus = dao.insertUser(applicationUser); log.info(String.format("Insertion %s user into database users status code %d\n", applicationUser.getUsername(), insertSucceedStatus)); final int insertUserRoleSucceedStatus = dao.insertUserRole(applicationUser, UserRole.ROLE_USER.toString()); log.info(String.format("Insertion %s user role %s into database users status code %d\n", applicationUser.getUsername(), UserRole.ROLE_USER.name(), insertUserRoleSucceedStatus)); }); } private void verifyUserExistence(ApplicationUser applicationUser, ApplicationUser foundUser) { final boolean userWithNameExists = foundUser.getUsername().equals(applicationUser.getUsername()); if (userWithNameExists) { final String USERNAME_FOUND_MSG = "Choose another username for creating account."; final String USERNAME_FOUND_LOG_MSG = "Registration failed for username %s with email %s"; final String USERNAME_FOUND_REASON_LOG = "Reason: %s already exists in the users_table"; log.error(String.format(USERNAME_FOUND_LOG_MSG, applicationUser.getUsername(), applicationUser.getEmail())); log.error(String.format(USERNAME_FOUND_REASON_LOG, applicationUser.getUsername())); throw new IllegalStateException(USERNAME_FOUND_MSG); } final String USER_EMAIL_FOUND = "Choose another email was found for creating account."; throw new IllegalStateException(USER_EMAIL_FOUND); } public boolean verifyUserAccountState(ApplicationUser applicationUser) { return applicationUser.isAccountNonExpired() && applicationUser.isAccountNonLocked() && applicationUser.isCredentialsNonExpired() && applicationUser.isEnabled() && applicationUser.hasUserRoleAssigned(); } }
public protocol RecommendationRuleProtocol { func generateRecommendations(forUser user: User) -> [Product] } public class RecommendationRuleData: RecommendationRuleProtocol { func generateRecommendations(forUser user: User) -> [Product] { // Implement recommendation rule logic based on user's browsing and purchase history // Example: Retrieve user's purchase history and suggest related products return [] } } public class RecommendationSystem { public static func createRecommendationRuleProtocol() -> RecommendationRuleProtocol { return RecommendationRuleData() } }
import z from './index.js' // Top-level define z.define('custom', (z, content, options) => { return `<div>${content}</div>` }) z.define('async', (z, content, options) => { return new Promise(resolve => { setTimeout(() => resolve(`<async>${content}</async>`), 500) }) }) // SubInstance const s = z.create() s('this is pure text part') s.h('custom', 'OoOoO') .h('p', 'chain calling is supported') .h('pre', 'no-defined tag will also rendered') s.async('this is also ok') s.h('div', s => { s.h('div', s => { s.h('div', s => s('禁止套娃')) }) }) s.x().then(console.log)
<reponame>bradmccoydev/keptn // Code generated by protoc-gen-gogo. // source: networking/v1alpha3/virtual_service.proto // Configuration affecting traffic routing. Here are a few terms useful to define // in the context of traffic routing. // // `Service` a unit of application behavior bound to a unique name in a // service registry. Services consist of multiple network *endpoints* // implemented by workload instances running on pods, containers, VMs etc. // // `Service versions (a.k.a. subsets)` - In a continuous deployment // scenario, for a given service, there can be distinct subsets of // instances running different variants of the application binary. These // variants are not necessarily different API versions. They could be // iterative changes to the same service, deployed in different // environments (prod, staging, dev, etc.). Common scenarios where this // occurs include A/B testing, canary rollouts, etc. The choice of a // particular version can be decided based on various criterion (headers, // url, etc.) and/or by weights assigned to each version. Each service has // a default version consisting of all its instances. // // `Source` - A downstream client calling a service. // // `Host` - The address used by a client when attempting to connect to a // service. // // `Access model` - Applications address only the destination service // (Host) without knowledge of individual service versions (subsets). The // actual choice of the version is determined by the proxy/sidecar, enabling the // application code to decouple itself from the evolution of dependent // services. // // A `VirtualService` defines a set of traffic routing rules to apply when a host is // addressed. Each routing rule defines matching criteria for traffic of a specific // protocol. If the traffic is matched, then it is sent to a named destination service // (or subset/version of it) defined in the registry. // // The source of traffic can also be matched in a routing rule. This allows routing // to be customized for specific client contexts. // // The following example on Kubernetes, routes all HTTP traffic by default to // pods of the reviews service with label "version: v1". In addition, // HTTP requests with path starting with /wpcatalog/ or /consumercatalog/ will // be rewritten to /newcatalog and sent to pods with label "version: v2". // // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route // spec: // hosts: // - reviews.prod.svc.cluster.local // http: // - name: "reviews-v2-routes" // match: // - uri: // prefix: "/wpcatalog" // - uri: // prefix: "/consumercatalog" // rewrite: // uri: "/newcatalog" // route: // - destination: // host: reviews.prod.svc.cluster.local // subset: v2 // - name: "reviews-v1-route" // route: // - destination: // host: reviews.prod.svc.cluster.local // subset: v1 // ``` // // A subset/version of a route destination is identified with a reference // to a named service subset which must be declared in a corresponding // `DestinationRule`. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: DestinationRule // metadata: // name: reviews-destination // spec: // host: reviews.prod.svc.cluster.local // subsets: // - name: v1 // labels: // version: v1 // - name: v2 // labels: // version: v2 // ``` // package v1alpha3 import ( proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // VirtualService type type VirtualService struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec VirtualServiceSpec `json:"spec"` } // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type VirtualServiceSpec struct { // REQUIRED. The destination hosts to which traffic is being sent. Could // be a DNS name with wildcard prefix or an IP address. Depending on the // platform, short-names can also be used instead of a FQDN (i.e. has no // dots in the name). In such a scenario, the FQDN of the host would be // derived based on the underlying platform. // // A single VirtualService can be used to describe all the traffic // properties of the corresponding hosts, including those for multiple // HTTP and TCP ports. Alternatively, the traffic properties of a host // can be defined using more than one VirtualService, with certain // caveats. Refer to the // [Operations Guide](https://istio.io/docs/ops/traffic-management/deploy-guidelines/#multiple-virtual-services-and-destination-rules-for-the-same-host) // for details. // // *Note for Kubernetes users*: When short names are used (e.g. "reviews" // instead of "reviews.default.svc.cluster.local"), Istio will interpret // the short name based on the namespace of the rule, not the service. A // rule in the "default" namespace containing a host "reviews will be // interpreted as "reviews.default.svc.cluster.local", irrespective of // the actual namespace associated with the reviews service. _To avoid // potential misconfigurations, it is recommended to always use fully // qualified domain names over short names._ // // The hosts field applies to both HTTP and TCP services. Service inside // the mesh, i.e., those found in the service registry, must always be // referred to using their alphanumeric names. IP addresses are allowed // only for services defined via the Gateway. Hosts []string `protobuf:"bytes,1,rep,name=hosts,proto3" json:"hosts,omitempty"` // The names of gateways and sidecars that should apply these routes. A // single VirtualService is used for sidecars inside the mesh as well as // for one or more gateways. The selection condition imposed by this // field can be overridden using the source field in the match conditions // of protocol-specific routes. The reserved word `mesh` is used to imply // all the sidecars in the mesh. When this field is omitted, the default // gateway (`mesh`) will be used, which would apply the rule to all // sidecars in the mesh. If a list of gateway names is provided, the // rules will apply only to the gateways. To apply the rules to both // gateways and sidecars, specify `mesh` as one of the gateway names. Gateways []string `protobuf:"bytes,2,rep,name=gateways,proto3" json:"gateways,omitempty"` // An ordered list of route rules for HTTP traffic. HTTP routes will be // applied to platform service ports named 'http-*'/'http2-*'/'grpc-*', gateway // ports with protocol HTTP/HTTP2/GRPC/ TLS-terminated-HTTPS and service // entry ports using HTTP/HTTP2/GRPC protocols. The first rule matching // an incoming request is used. Http []*HTTPRoute `protobuf:"bytes,3,rep,name=http,proto3" json:"http,omitempty"` // An ordered list of route rule for non-terminated TLS & HTTPS // traffic. Routing is typically performed using the SNI value presented // by the ClientHello message. TLS routes will be applied to platform // service ports named 'https-*', 'tls-*', unterminated gateway ports using // HTTPS/TLS protocols (i.e. with "passthrough" TLS mode) and service // entry ports using HTTPS/TLS protocols. The first rule matching an // incoming request is used. NOTE: Traffic 'https-*' or 'tls-*' ports // without associated virtual service will be treated as opaque TCP // traffic. Tls []*TLSRoute `protobuf:"bytes,5,rep,name=tls,proto3" json:"tls,omitempty"` // An ordered list of route rules for opaque TCP traffic. TCP routes will // be applied to any port that is not a HTTP or TLS port. The first rule // matching an incoming request is used. Tcp []*TCPRoute `protobuf:"bytes,4,rep,name=tcp,proto3" json:"tcp,omitempty"` // A list of namespaces to which this virtual service is exported. Exporting a // virtual service allows it to be used by sidecars and gateways defined in // other namespaces. This feature provides a mechanism for service owners // and mesh administrators to control the visibility of virtual services // across namespace boundaries. // // If no namespaces are specified then the virtual service is exported to all // namespaces by default. // // The value "." is reserved and defines an export to the same namespace that // the virtual service is declared in. Similarly the value "*" is reserved and // defines an export to all namespaces. // // NOTE: in the current release, the `exportTo` value is restricted to // "." or "*" (i.e., the current namespace or all namespaces). ExportTo []string `protobuf:"bytes,6,rep,name=export_to,json=exportTo,proto3" json:"export_to,omitempty"` } // Destination indicates the network addressable service to which the // request/connection will be sent after processing a routing rule. The // destination.host should unambiguously refer to a service in the service // registry. Istio's service registry is composed of all the services found // in the platform's service registry (e.g., Kubernetes services, Consul // services), as well as services declared through the // [ServiceEntry](https://istio.io/docs/reference/config/networking/v1alpha3/service-entry/#ServiceEntry) resource. // // *Note for Kubernetes users*: When short names are used (e.g. "reviews" // instead of "reviews.default.svc.cluster.local"), Istio will interpret // the short name based on the namespace of the rule, not the service. A // rule in the "default" namespace containing a host "reviews will be // interpreted as "reviews.default.svc.cluster.local", irrespective of the // actual namespace associated with the reviews service. _To avoid potential // misconfigurations, it is recommended to always use fully qualified // domain names over short names._ // // The following Kubernetes example routes all traffic by default to pods // of the reviews service with label "version: v1" (i.e., subset v1), and // some to subset v2, in a Kubernetes environment. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route // namespace: foo // spec: // hosts: // - reviews # interpreted as reviews.foo.svc.cluster.local // http: // - match: // - uri: // prefix: "/wpcatalog" // - uri: // prefix: "/consumercatalog" // rewrite: // uri: "/newcatalog" // route: // - destination: // host: reviews # interpreted as reviews.foo.svc.cluster.local // subset: v2 // - route: // - destination: // host: reviews # interpreted as reviews.foo.svc.cluster.local // subset: v1 // ``` // // And the associated DestinationRule // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: DestinationRule // metadata: // name: reviews-destination // namespace: foo // spec: // host: reviews # interpreted as reviews.foo.svc.cluster.local // subsets: // - name: v1 // labels: // version: v1 // - name: v2 // labels: // version: v2 // ``` // // The following VirtualService sets a timeout of 5s for all calls to // productpage.prod.svc.cluster.local service in Kubernetes. Notice that // there are no subsets defined in this rule. Istio will fetch all // instances of productpage.prod.svc.cluster.local service from the service // registry and populate the sidecar's load balancing pool. Also, notice // that this rule is set in the istio-system namespace but uses the fully // qualified domain name of the productpage service, // productpage.prod.svc.cluster.local. Therefore the rule's namespace does // not have an impact in resolving the name of the productpage service. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: my-productpage-rule // namespace: istio-system // spec: // hosts: // - productpage.prod.svc.cluster.local # ignores rule namespace // http: // - timeout: 5s // route: // - destination: // host: productpage.prod.svc.cluster.local // ``` // // To control routing for traffic bound to services outside the mesh, external // services must first be added to Istio's internal service registry using the // ServiceEntry resource. VirtualServices can then be defined to control traffic // bound to these external services. For example, the following rules define a // Service for wikipedia.org and set a timeout of 5s for http requests. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: ServiceEntry // metadata: // name: external-svc-wikipedia // spec: // hosts: // - wikipedia.org // location: MESH_EXTERNAL // ports: // - number: 80 // name: example-http // protocol: HTTP // resolution: DNS // // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: my-wiki-rule // spec: // hosts: // - wikipedia.org // http: // - timeout: 5s // route: // - destination: // host: wikipedia.org // ``` type Destination struct { // REQUIRED. The name of a service from the service registry. Service // names are looked up from the platform's service registry (e.g., // Kubernetes services, Consul services, etc.) and from the hosts // declared by [ServiceEntry](https://istio.io/docs/reference/config/networking/v1alpha3/service-entry/#ServiceEntry). Traffic forwarded to // destinations that are not found in either of the two, will be dropped. // // *Note for Kubernetes users*: When short names are used (e.g. "reviews" // instead of "reviews.default.svc.cluster.local"), Istio will interpret // the short name based on the namespace of the rule, not the service. A // rule in the "default" namespace containing a host "reviews will be // interpreted as "reviews.default.svc.cluster.local", irrespective of // the actual namespace associated with the reviews service. _To avoid // potential misconfigurations, it is recommended to always use fully // qualified domain names over short names._ Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` // The name of a subset within the service. Applicable only to services // within the mesh. The subset must be defined in a corresponding // DestinationRule. Subset string `protobuf:"bytes,2,opt,name=subset,proto3" json:"subset,omitempty"` // Specifies the port on the host that is being addressed. If a service // exposes only a single port it is not required to explicitly select the // port. Port *PortSelector `protobuf:"bytes,3,opt,name=port,proto3" json:"port,omitempty"` } // Describes match conditions and actions for routing HTTP/1.1, HTTP2, and // gRPC traffic. See VirtualService for usage examples. type HTTPRoute struct { // The name assigned to the route for debugging purposes. The // route's name will be concatenated with the match's name and will // be logged in the access logs for requests matching this // route/match. Name string `protobuf:"bytes,17,opt,name=name,proto3" json:"name,omitempty"` // Match conditions to be satisfied for the rule to be // activated. All conditions inside a single match block have AND // semantics, while the list of match blocks have OR semantics. The rule // is matched if any one of the match blocks succeed. Match []*HTTPMatchRequest `protobuf:"bytes,1,rep,name=match,proto3" json:"match,omitempty"` // A http rule can either redirect or forward (default) traffic. The // forwarding target can be one of several versions of a service (see // glossary in beginning of document). Weights associated with the // service version determine the proportion of traffic it receives. Route []*HTTPRouteDestination `protobuf:"bytes,2,rep,name=route,proto3" json:"route,omitempty"` // A http rule can either redirect or forward (default) traffic. If // traffic passthrough option is specified in the rule, // route/redirect will be ignored. The redirect primitive can be used to // send a HTTP 301 redirect to a different URI or Authority. Redirect *HTTPRedirect `protobuf:"bytes,3,opt,name=redirect,proto3" json:"redirect,omitempty"` // Rewrite HTTP URIs and Authority headers. Rewrite cannot be used with // Redirect primitive. Rewrite will be performed before forwarding. Rewrite *HTTPRewrite `protobuf:"bytes,4,opt,name=rewrite,proto3" json:"rewrite,omitempty"` // Deprecated. Websocket upgrades are done automatically starting from Istio 1.0. // $hide_from_docs WebsocketUpgrade bool `protobuf:"varint,5,opt,name=websocket_upgrade,json=websocketUpgrade,proto3" json:"websocket_upgrade,omitempty"` // Timeout for HTTP requests. Timeout *types.Duration `protobuf:"bytes,6,opt,name=timeout,proto3" json:"timeout,omitempty"` // Retry policy for HTTP requests. Retries *HTTPRetry `protobuf:"bytes,7,opt,name=retries,proto3" json:"retries,omitempty"` // Fault injection policy to apply on HTTP traffic at the client side. // Note that timeouts or retries will not be enabled when faults are // enabled on the client side. Fault *HTTPFaultInjection `protobuf:"bytes,8,opt,name=fault,proto3" json:"fault,omitempty"` // Mirror HTTP traffic to a another destination in addition to forwarding // the requests to the intended destination. Mirrored traffic is on a // best effort basis where the sidecar/gateway will not wait for the // mirrored cluster to respond before returning the response from the // original destination. Statistics will be generated for the mirrored // destination. Mirror *Destination `protobuf:"bytes,9,opt,name=mirror,proto3" json:"mirror,omitempty"` // Cross-Origin Resource Sharing policy (CORS). Refer to // [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) // for further details about cross origin resource sharing. CorsPolicy *CorsPolicy `protobuf:"bytes,10,opt,name=cors_policy,json=corsPolicy,proto3" json:"cors_policy,omitempty"` // $hide_from_docs AppendHeaders map[string]string `protobuf:"bytes,11,rep,name=append_headers,json=appendHeaders,proto3" json:"append_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Deprecated: Do not use. // $hide_from_docs RemoveResponseHeaders []string `protobuf:"bytes,12,rep,name=remove_response_headers,json=removeResponseHeaders,proto3" json:"remove_response_headers,omitempty"` // Deprecated: Do not use. // $hide_from_docs AppendResponseHeaders map[string]string `protobuf:"bytes,13,rep,name=append_response_headers,json=appendResponseHeaders,proto3" json:"append_response_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Deprecated: Do not use. // $hide_from_docs RemoveRequestHeaders []string `protobuf:"bytes,14,rep,name=remove_request_headers,json=removeRequestHeaders,proto3" json:"remove_request_headers,omitempty"` // Deprecated: Do not use. // $hide_from_docs AppendRequestHeaders map[string]string `protobuf:"bytes,15,rep,name=append_request_headers,json=appendRequestHeaders,proto3" json:"append_request_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Deprecated: Do not use. // Header manipulation rules Headers *Headers `protobuf:"bytes,16,opt,name=headers,proto3" json:"headers,omitempty"` } // Message headers can be manipulated when Envoy forwards requests to, // or responses from, a destination service. Header manipulation rules can // be specified for a specific route destination or for all destinations. // The following VirtualService adds a `test` header with the value `true` // to requests that are routed to any `reviews` service destination. // It also removes the `foo` response header, but only from responses // coming from the `v1` subset (version) of the `reviews` service. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route // spec: // hosts: // - reviews.prod.svc.cluster.local // http: // - headers: // request: // set: // test: true // route: // - destination: // host: reviews.prod.svc.cluster.local // subset: v2 // weight: 25 // - destination: // host: reviews.prod.svc.cluster.local // subset: v1 // headers: // response: // remove: // - foo // weight: 75 // ``` type Headers struct { // Header manipulation rules to apply before forwarding a request // to the destination service Request *Headers_HeaderOperations `protobuf:"bytes,1,opt,name=request,proto3" json:"request,omitempty"` // Header manipulation rules to apply before returning a response // to the caller Response *Headers_HeaderOperations `protobuf:"bytes,2,opt,name=response,proto3" json:"response,omitempty"` } // HeaderOperations Describes the header manipulations to apply type Headers_HeaderOperations struct { // Overwrite the headers specified by key with the given values Set map[string]string `protobuf:"bytes,1,rep,name=set,proto3" json:"set,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Append the given values to the headers specified by keys // (will create a comma-separated list of values) Add map[string]string `protobuf:"bytes,2,rep,name=add,proto3" json:"add,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Remove a the specified headers Remove []string `protobuf:"bytes,3,rep,name=remove,proto3" json:"remove,omitempty"` } // Describes match conditions and actions for routing unterminated TLS // traffic (TLS/HTTPS) The following routing rule forwards unterminated TLS // traffic arriving at port 443 of gateway called "mygateway" to internal // services in the mesh based on the SNI value. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: bookinfo-sni // spec: // hosts: // - "*.bookinfo.com" // gateways: // - mygateway // tls: // - match: // - port: 443 // sniHosts: // - login.bookinfo.com // route: // - destination: // host: login.prod.svc.cluster.local // - match: // - port: 443 // sniHosts: // - reviews.bookinfo.com // route: // - destination: // host: reviews.prod.svc.cluster.local // ``` type TLSRoute struct { // REQUIRED. Match conditions to be satisfied for the rule to be // activated. All conditions inside a single match block have AND // semantics, while the list of match blocks have OR semantics. The rule // is matched if any one of the match blocks succeed. Match []*TLSMatchAttributes `protobuf:"bytes,1,rep,name=match,proto3" json:"match,omitempty"` // The destination to which the connection should be forwarded to. Route []*RouteDestination `protobuf:"bytes,2,rep,name=route,proto3" json:"route,omitempty"` } // Describes match conditions and actions for routing TCP traffic. The // following routing rule forwards traffic arriving at port 27017 for // mongo.prod.svc.cluster.local to another Mongo server on port 5555. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: bookinfo-Mongo // spec: // hosts: // - mongo.prod.svc.cluster.local // tcp: // - match: // - port: 27017 // route: // - destination: // host: mongo.backup.svc.cluster.local // port: // number: 5555 // ``` type TCPRoute struct { // Match conditions to be satisfied for the rule to be // activated. All conditions inside a single match block have AND // semantics, while the list of match blocks have OR semantics. The rule // is matched if any one of the match blocks succeed. Match []*L4MatchAttributes `protobuf:"bytes,1,rep,name=match,proto3" json:"match,omitempty"` // The destination to which the connection should be forwarded to. Route []*RouteDestination `protobuf:"bytes,2,rep,name=route,proto3" json:"route,omitempty"` } // HttpMatchRequest specifies a set of criterion to be met in order for the // rule to be applied to the HTTP request. For example, the following // restricts the rule to match only requests where the URL path // starts with /ratings/v2/ and the request contains a custom `end-user` header // with value `jason`. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - match: // - headers: // end-user: // exact: jason // uri: // prefix: "/ratings/v2/" // ignoreUriCase: true // route: // - destination: // host: ratings.prod.svc.cluster.local // ``` // // HTTPMatchRequest CANNOT be empty. type HTTPMatchRequest struct { // The name assigned to a match. The match's name will be // concatenated with the parent route's name and will be logged in // the access logs for requests matching this route. Name string `protobuf:"bytes,11,opt,name=name,proto3" json:"name,omitempty"` // URI to match // values are case-sensitive and formatted as follows: // // - `exact: "value"` for exact string match // // - `prefix: "value"` for prefix-based match // // - `regex: "value"` for ECMAscript style regex-based match // // **Note:** Case-insensitive matching could be enabled via the // `ignore_uri_case` flag. Uri *StringMatch `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` // URI Scheme // values are case-sensitive and formatted as follows: // // - `exact: "value"` for exact string match // // - `prefix: "value"` for prefix-based match // // - `regex: "value"` for ECMAscript style regex-based match // Scheme *StringMatch `protobuf:"bytes,2,opt,name=scheme,proto3" json:"scheme,omitempty"` // HTTP Method // values are case-sensitive and formatted as follows: // // - `exact: "value"` for exact string match // // - `prefix: "value"` for prefix-based match // // - `regex: "value"` for ECMAscript style regex-based match // Method *StringMatch `protobuf:"bytes,3,opt,name=method,proto3" json:"method,omitempty"` // HTTP Authority // values are case-sensitive and formatted as follows: // // - `exact: "value"` for exact string match // // - `prefix: "value"` for prefix-based match // // - `regex: "value"` for ECMAscript style regex-based match // Authority *StringMatch `protobuf:"bytes,4,opt,name=authority,proto3" json:"authority,omitempty"` // The header keys must be lowercase and use hyphen as the separator, // e.g. _x-request-id_. // // Header values are case-sensitive and formatted as follows: // // - `exact: "value"` for exact string match // // - `prefix: "value"` for prefix-based match // // - `regex: "value"` for ECMAscript style regex-based match // // **Note:** The keys `uri`, `scheme`, `method`, and `authority` will be ignored. Headers map[string]*StringMatch `protobuf:"bytes,5,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Specifies the ports on the host that is being addressed. Many services // only expose a single port or label ports with the protocols they support, // in these cases it is not required to explicitly select the port. Port uint32 `protobuf:"varint,6,opt,name=port,proto3" json:"port,omitempty"` // $hide_from_docs SourceLabels map[string]string `protobuf:"bytes,7,rep,name=source_labels,json=sourceLabels,proto3" json:"source_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // $hide_from_docs Gateways []string `protobuf:"bytes,8,rep,name=gateways,proto3" json:"gateways,omitempty"` // Query parameters for matching. // // Ex: // - For a query parameter like "?key=true", the map key would be "key" and // the string match could be defined as `exact: "true"`. // - For a query parameter like "?key", the map key would be "key" and the // string match could be defined as `exact: ""`. // - For a query parameter like "?key=123", the map key would be "key" and the // string match could be defined as `regex: "\d+$"`. Note that this // configuration will only match values like "123" but not "a123" or "123a". // // **Note:** `prefix` matching is currently not supported. QueryParams map[string]*StringMatch `protobuf:"bytes,9,rep,name=query_params,json=queryParams,proto3" json:"query_params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Flag to specify whether the URI matching should be case-insensitive. // // **Note:** The case will be ignored only in the case of `exact` and `prefix` // URI matches. IgnoreUriCase bool `protobuf:"varint,10,opt,name=ignore_uri_case,json=ignoreUriCase,proto3" json:"ignore_uri_case,omitempty"` } // Each routing rule is associated with one or more service versions (see // glossary in beginning of document). Weights associated with the version // determine the proportion of traffic it receives. For example, the // following rule will route 25% of traffic for the "reviews" service to // instances with the "v2" tag and the remaining traffic (i.e., 75%) to // "v1". // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route // spec: // hosts: // - reviews.prod.svc.cluster.local // http: // - route: // - destination: // host: reviews.prod.svc.cluster.local // subset: v2 // weight: 25 // - destination: // host: reviews.prod.svc.cluster.local // subset: v1 // weight: 75 // ``` // // And the associated DestinationRule // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: DestinationRule // metadata: // name: reviews-destination // spec: // host: reviews.prod.svc.cluster.local // subsets: // - name: v1 // labels: // version: v1 // - name: v2 // labels: // version: v2 // ``` // // Traffic can also be split across two entirely different services without // having to define new subsets. For example, the following rule forwards 25% of // traffic to reviews.com to dev.reviews.com // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route-two-domains // spec: // hosts: // - reviews.com // http: // - route: // - destination: // host: dev.reviews.com // weight: 25 // - destination: // host: reviews.com // weight: 75 // ``` type HTTPRouteDestination struct { // REQUIRED. Destination uniquely identifies the instances of a service // to which the request/connection should be forwarded to. Destination *Destination `protobuf:"bytes,1,opt,name=destination,proto3" json:"destination,omitempty"` // REQUIRED. The proportion of traffic to be forwarded to the service // version. (0-100). Sum of weights across destinations SHOULD BE == 100. // If there is only one destination in a rule, the weight value is assumed to // be 100. Weight int32 `protobuf:"varint,2,opt,name=weight,proto3" json:"weight,omitempty"` // Use of `remove_response_header` is deprecated. Use the `headers` // field instead. RemoveResponseHeaders []string `protobuf:"bytes,3,rep,name=remove_response_headers,json=removeResponseHeaders,proto3" json:"remove_response_headers,omitempty"` // Deprecated: Do not use. // Use of `append_response_headers` is deprecated. Use the `headers` // field instead. AppendResponseHeaders map[string]string `protobuf:"bytes,4,rep,name=append_response_headers,json=appendResponseHeaders,proto3" json:"append_response_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Deprecated: Do not use. // Use of `remove_request_headers` is deprecated. Use the `headers` // field instead. RemoveRequestHeaders []string `protobuf:"bytes,5,rep,name=remove_request_headers,json=removeRequestHeaders,proto3" json:"remove_request_headers,omitempty"` // Deprecated: Do not use. // Use of `append_request_headers` is deprecated. Use the `headers` // field instead. AppendRequestHeaders map[string]string `protobuf:"bytes,6,rep,name=append_request_headers,json=appendRequestHeaders,proto3" json:"append_request_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Deprecated: Do not use. // Header manipulation rules Headers *Headers `protobuf:"bytes,7,opt,name=headers,proto3" json:"headers,omitempty"` } // L4 routing rule weighted destination. type RouteDestination struct { // REQUIRED. Destination uniquely identifies the instances of a service // to which the request/connection should be forwarded to. Destination *Destination `protobuf:"bytes,1,opt,name=destination,proto3" json:"destination,omitempty"` // REQUIRED. The proportion of traffic to be forwarded to the service // version. If there is only one destination in a rule, all traffic will be // routed to it irrespective of the weight. Weight int32 `protobuf:"varint,2,opt,name=weight,proto3" json:"weight,omitempty"` } // L4 connection match attributes. Note that L4 connection matching support // is incomplete. type L4MatchAttributes struct { // IPv4 or IPv6 ip addresses of destination with optional subnet. E.g., // a.b.c.d/xx form or just a.b.c.d. DestinationSubnets []string `protobuf:"bytes,1,rep,name=destination_subnets,json=destinationSubnets,proto3" json:"destination_subnets,omitempty"` // Specifies the port on the host that is being addressed. Many services // only expose a single port or label ports with the protocols they support, // in these cases it is not required to explicitly select the port. Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` // IPv4 or IPv6 ip address of source with optional subnet. E.g., a.b.c.d/xx // form or just a.b.c.d // $hide_from_docs SourceSubnet string `protobuf:"bytes,3,opt,name=source_subnet,json=sourceSubnet,proto3" json:"source_subnet,omitempty"` // One or more labels that constrain the applicability of a rule to // workloads with the given labels. If the VirtualService has a list of // gateways specified at the top, it should include the reserved gateway // `mesh` in order for this field to be applicable. SourceLabels map[string]string `protobuf:"bytes,4,rep,name=source_labels,json=sourceLabels,proto3" json:"source_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Names of gateways where the rule should be applied to. Gateway names // at the top of the VirtualService (if any) are overridden. The gateway // match is independent of sourceLabels. Gateways []string `protobuf:"bytes,5,rep,name=gateways,proto3" json:"gateways,omitempty"` } // TLS connection match attributes. type TLSMatchAttributes struct { // REQUIRED. SNI (server name indicator) to match on. Wildcard prefixes // can be used in the SNI value, e.g., *.com will match foo.example.com // as well as example.com. An SNI value must be a subset (i.e., fall // within the domain) of the corresponding virtual service's hosts. SniHosts []string `protobuf:"bytes,1,rep,name=sni_hosts,json=sniHosts,proto3" json:"sni_hosts,omitempty"` // IPv4 or IPv6 ip addresses of destination with optional subnet. E.g., // a.b.c.d/xx form or just a.b.c.d. DestinationSubnets []string `protobuf:"bytes,2,rep,name=destination_subnets,json=destinationSubnets,proto3" json:"destination_subnets,omitempty"` // Specifies the port on the host that is being addressed. Many services // only expose a single port or label ports with the protocols they // support, in these cases it is not required to explicitly select the // port. Port uint32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` // IPv4 or IPv6 ip address of source with optional subnet. E.g., a.b.c.d/xx // form or just a.b.c.d // $hide_from_docs SourceSubnet string `protobuf:"bytes,4,opt,name=source_subnet,json=sourceSubnet,proto3" json:"source_subnet,omitempty"` // One or more labels that constrain the applicability of a rule to // workloads with the given labels. If the VirtualService has a list of // gateways specified at the top, it should include the reserved gateway // `mesh` in order for this field to be applicable. SourceLabels map[string]string `protobuf:"bytes,5,rep,name=source_labels,json=sourceLabels,proto3" json:"source_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Names of gateways where the rule should be applied to. Gateway names // at the top of the VirtualService (if any) are overridden. The gateway // match is independent of sourceLabels. Gateways []string `protobuf:"bytes,6,rep,name=gateways,proto3" json:"gateways,omitempty"` } // HTTPRedirect can be used to send a 301 redirect response to the caller, // where the Authority/Host and the URI in the response can be swapped with // the specified values. For example, the following rule redirects // requests for /v1/getProductRatings API on the ratings service to // /v1/bookRatings provided by the bookratings service. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - match: // - uri: // exact: /v1/getProductRatings // redirect: // uri: /v1/bookRatings // authority: newratings.default.svc.cluster.local // ... // ``` type HTTPRedirect struct { // On a redirect, overwrite the Path portion of the URL with this // value. Note that the entire path will be replaced, irrespective of the // request URI being matched as an exact path or prefix. Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` // On a redirect, overwrite the Authority/Host portion of the URL with // this value. Authority string `protobuf:"bytes,2,opt,name=authority,proto3" json:"authority,omitempty"` // On a redirect, Specifies the HTTP status code to use in the redirect // response. The default response code is MOVED_PERMANENTLY (301). RedirectCode uint32 `protobuf:"varint,3,opt,name=redirect_code,json=redirectCode,proto3" json:"redirect_code,omitempty"` } // HTTPRewrite can be used to rewrite specific parts of a HTTP request // before forwarding the request to the destination. Rewrite primitive can // be used only with HTTPRouteDestination. The following example // demonstrates how to rewrite the URL prefix for api call (/ratings) to // ratings service before making the actual API call. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - match: // - uri: // prefix: /ratings // rewrite: // uri: /v1/bookRatings // route: // - destination: // host: ratings.prod.svc.cluster.local // subset: v1 // ``` // type HTTPRewrite struct { // rewrite the path (or the prefix) portion of the URI with this // value. If the original URI was matched based on prefix, the value // provided in this field will replace the corresponding matched prefix. Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` // rewrite the Authority/Host header with this value. Authority string `protobuf:"bytes,2,opt,name=authority,proto3" json:"authority,omitempty"` } // Describes how to match a given string in HTTP headers. Match is // case-sensitive. type StringMatch struct { // Types that are valid to be assigned to MatchType: // *StringMatch_Exact // *StringMatch_Prefix // *StringMatch_Regex MatchType isStringMatch_MatchType `protobuf_oneof:"match_type"` } type isStringMatch_MatchType interface { isStringMatch_MatchType() MarshalTo([]byte) (int, error) Size() int } type StringMatch_Exact struct { Exact string `protobuf:"bytes,1,opt,name=exact,proto3,oneof"` } type StringMatch_Prefix struct { Prefix string `protobuf:"bytes,2,opt,name=prefix,proto3,oneof"` } type StringMatch_Regex struct { Regex string `protobuf:"bytes,3,opt,name=regex,proto3,oneof"` } // Describes the retry policy to use when a HTTP request fails. For // example, the following rule sets the maximum number of retries to 3 when // calling ratings:v1 service, with a 2s timeout per retry attempt. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - route: // - destination: // host: ratings.prod.svc.cluster.local // subset: v1 // retries: // attempts: 3 // perTryTimeout: 2s // retryOn: gateway-error,connect-failure,refused-stream // ``` // type HTTPRetry struct { // REQUIRED. Number of retries for a given request. The interval // between retries will be determined automatically (25ms+). Actual // number of retries attempted depends on the httpReqTimeout. Attempts int32 `protobuf:"varint,1,opt,name=attempts,proto3" json:"attempts,omitempty"` // Timeout per retry attempt for a given request. format: 1h/1m/1s/1ms. MUST BE >=1ms. PerTryTimeout *types.Duration `protobuf:"bytes,2,opt,name=per_try_timeout,json=perTryTimeout,proto3" json:"per_try_timeout,omitempty"` // Specifies the conditions under which retry takes place. // One or more policies can be specified using a ‘,’ delimited list. // See the [supported policies](https://www.envoyproxy.io/docs/envoy/latest/configuration/http_filters/router_filter#x-envoy-retry-on) // and [here](https://www.envoyproxy.io/docs/envoy/latest/configuration/http_filters/router_filter#x-envoy-retry-grpc-on) for more details. RetryOn string `protobuf:"bytes,3,opt,name=retry_on,json=retryOn,proto3" json:"retry_on,omitempty"` } // Describes the Cross-Origin Resource Sharing (CORS) policy, for a given // service. Refer to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) // for further details about cross origin resource sharing. For example, // the following rule restricts cross origin requests to those originating // from example.com domain using HTTP POST/GET, and sets the // `Access-Control-Allow-Credentials` header to false. In addition, it only // exposes `X-Foo-bar` header and sets an expiry period of 1 day. // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - route: // - destination: // host: ratings.prod.svc.cluster.local // subset: v1 // corsPolicy: // allowOrigin: // - example.com // allowMethods: // - POST // - GET // allowCredentials: false // allowHeaders: // - X-Foo-Bar // maxAge: "24h" // ``` // type CorsPolicy struct { // The list of origins that are allowed to perform CORS requests. The // content will be serialized into the Access-Control-Allow-Origin // header. Wildcard * will allow all origins. AllowOrigin []string `protobuf:"bytes,1,rep,name=allow_origin,json=allowOrigin,proto3" json:"allow_origin,omitempty"` // List of HTTP methods allowed to access the resource. The content will // be serialized into the Access-Control-Allow-Methods header. AllowMethods []string `protobuf:"bytes,2,rep,name=allow_methods,json=allowMethods,proto3" json:"allow_methods,omitempty"` // List of HTTP headers that can be used when requesting the // resource. Serialized to Access-Control-Allow-Headers header. AllowHeaders []string `protobuf:"bytes,3,rep,name=allow_headers,json=allowHeaders,proto3" json:"allow_headers,omitempty"` // A white list of HTTP headers that the browsers are allowed to // access. Serialized into Access-Control-Expose-Headers header. ExposeHeaders []string `protobuf:"bytes,4,rep,name=expose_headers,json=exposeHeaders,proto3" json:"expose_headers,omitempty"` // Specifies how long the results of a preflight request can be // cached. Translates to the `Access-Control-Max-Age` header. MaxAge *types.Duration `protobuf:"bytes,5,opt,name=max_age,json=maxAge,proto3" json:"max_age,omitempty"` // Indicates whether the caller is allowed to send the actual request // (not the preflight) using credentials. Translates to // `Access-Control-Allow-Credentials` header. AllowCredentials *types.BoolValue `protobuf:"bytes,6,opt,name=allow_credentials,json=allowCredentials,proto3" json:"allow_credentials,omitempty"` } // HTTPFaultInjection can be used to specify one or more faults to inject // while forwarding http requests to the destination specified in a route. // Fault specification is part of a VirtualService rule. Faults include // aborting the Http request from downstream service, and/or delaying // proxying of requests. A fault rule MUST HAVE delay or abort or both. // // *Note:* Delay and abort faults are independent of one another, even if // both are specified simultaneously. type HTTPFaultInjection struct { // Delay requests before forwarding, emulating various failures such as // network issues, overloaded upstream service, etc. Delay *HTTPFaultInjection_Delay `protobuf:"bytes,1,opt,name=delay,proto3" json:"delay,omitempty"` // Abort Http request attempts and return error codes back to downstream // service, giving the impression that the upstream service is faulty. Abort *HTTPFaultInjection_Abort `protobuf:"bytes,2,opt,name=abort,proto3" json:"abort,omitempty"` } // Delay specification is used to inject latency into the request // forwarding path. The following example will introduce a 5 second delay // in 1 out of every 1000 requests to the "v1" version of the "reviews" // service from all pods with label env: prod // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: reviews-route // spec: // hosts: // - reviews.prod.svc.cluster.local // http: // - match: // - sourceLabels: // env: prod // route: // - destination: // host: reviews.prod.svc.cluster.local // subset: v1 // fault: // delay: // percentage: // value: 0.1 // fixedDelay: 5s // ``` // // The _fixedDelay_ field is used to indicate the amount of delay in seconds. // The optional _percentage_ field can be used to only delay a certain // percentage of requests. If left unspecified, all request will be delayed. type HTTPFaultInjection_Delay struct { // Percentage of requests on which the delay will be injected (0-100). // Use of integer `percent` value is deprecated. Use the double `percentage` // field instead. Percent int32 `protobuf:"varint,1,opt,name=percent,proto3" json:"percent,omitempty"` // Deprecated: Do not use. // Types that are valid to be assigned to HttpDelayType: // *HTTPFaultInjection_Delay_FixedDelay // *HTTPFaultInjection_Delay_ExponentialDelay HttpDelayType isHTTPFaultInjection_Delay_HttpDelayType `protobuf_oneof:"http_delay_type"` // Percentage of requests on which the delay will be injected. Percentage *Percent `protobuf:"bytes,5,opt,name=percentage,proto3" json:"percentage,omitempty"` } type isHTTPFaultInjection_Delay_HttpDelayType interface { isHTTPFaultInjection_Delay_HttpDelayType() MarshalTo([]byte) (int, error) Size() int } type HTTPFaultInjection_Delay_FixedDelay struct { FixedDelay *types.Duration `protobuf:"bytes,2,opt,name=fixed_delay,json=fixedDelay,proto3,oneof"` } type HTTPFaultInjection_Delay_ExponentialDelay struct { ExponentialDelay *types.Duration `protobuf:"bytes,3,opt,name=exponential_delay,json=exponentialDelay,proto3,oneof"` } // Abort specification is used to prematurely abort a request with a // pre-specified error code. The following example will return an HTTP 400 // error code for 1 out of every 1000 requests to the "ratings" service "v1". // // ```yaml // apiVersion: networking.istio.io/v1alpha3 // kind: VirtualService // metadata: // name: ratings-route // spec: // hosts: // - ratings.prod.svc.cluster.local // http: // - route: // - destination: // host: ratings.prod.svc.cluster.local // subset: v1 // fault: // abort: // percentage: // value: 0.1 // httpStatus: 400 // ``` // // The _httpStatus_ field is used to indicate the HTTP status code to // return to the caller. The optional _percentage_ field can be used to only // abort a certain percentage of requests. If not specified, all requests are // aborted. type HTTPFaultInjection_Abort struct { // Percentage of requests to be aborted with the error code provided (0-100). // Use of integer `percent` value is deprecated. Use the double `percentage` // field instead. Percent int32 `protobuf:"varint,1,opt,name=percent,proto3" json:"percent,omitempty"` // Deprecated: Do not use. // Types that are valid to be assigned to ErrorType: // *HTTPFaultInjection_Abort_HttpStatus // *HTTPFaultInjection_Abort_GrpcStatus // *HTTPFaultInjection_Abort_Http2Error ErrorType isHTTPFaultInjection_Abort_ErrorType `protobuf_oneof:"error_type"` // Percentage of requests to be aborted with the error code provided. Percentage *Percent `protobuf:"bytes,5,opt,name=percentage,proto3" json:"percentage,omitempty"` } type isHTTPFaultInjection_Abort_ErrorType interface { isHTTPFaultInjection_Abort_ErrorType() MarshalTo([]byte) (int, error) Size() int } type HTTPFaultInjection_Abort_HttpStatus struct { HttpStatus int32 `protobuf:"varint,2,opt,name=http_status,json=httpStatus,proto3,oneof"` } type HTTPFaultInjection_Abort_GrpcStatus struct { GrpcStatus string `protobuf:"bytes,3,opt,name=grpc_status,json=grpcStatus,proto3,oneof"` } type HTTPFaultInjection_Abort_Http2Error struct { Http2Error string `protobuf:"bytes,4,opt,name=http2_error,json=http2Error,proto3,oneof"` } // PortSelector specifies the number of a port to be used for // matching or selection for final routing. type PortSelector struct { // Types that are valid to be assigned to Port: // *PortSelector_Number // *PortSelector_Name Port isPortSelector_Port `protobuf_oneof:"port"` } type isPortSelector_Port interface { isPortSelector_Port() MarshalTo([]byte) (int, error) Size() int } type PortSelector_Number struct { Number uint32 `protobuf:"varint,1,opt,name=number,proto3,oneof"` } type PortSelector_Name struct { Name string `protobuf:"bytes,2,opt,name=name,proto3,oneof"` } // Percent specifies a percentage in the range of [0.0, 100.0]. type Percent struct { Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` }
<gh_stars>0 package com.xiaochen.mobilesafe.activity; import com.xiaochen.mobilesafe.R; import com.xiaochen.mobilesafe.utlis.ConstantValue; import com.xiaochen.mobilesafe.utlis.SpUtils; import com.xiaochen.mobilesafe.utlis.ToastUtli; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; public class SetupOverActivity extends StatusBarColorActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean setup_over = SpUtils.getBoolSp(this, ConstantValue.SETUP_OVER, false); if (setup_over) { setContentView(R.layout.activity_setself_over); initUI(); } else { Intent intent = new Intent(this, SetSelf1Activity.class); startActivity(intent); finish(); } } private void initUI() { String phone = SpUtils.getStringSp(this, ConstantValue.CONTACT_PHONE_NUMBER, ""); boolean open_self = SpUtils.getBoolSp(getApplicationContext(), ConstantValue.OPEN_SELF, false); TextView tv_self_phone = (TextView) findViewById(R.id.tv_self_phone); TextView tv_reset = (TextView) findViewById(R.id.tv_reset); TextView tv_set_pwd = (TextView) findViewById(R.id.tv_set_pwd); ImageView iv_self_lock = (ImageView) findViewById(R.id.iv_self_lock); // 回显存在sp中的安全号码 tv_self_phone.setText(phone); // 根据sp中的是否开启防盗保护 来设置锁的图片样式 if (open_self) { iv_self_lock.setBackgroundResource(R.drawable.lock); } else { iv_self_lock.setBackgroundResource(R.drawable.unlock); } // 设置textview重新进入设置向导的点击事件 tv_reset.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SpUtils.putBoolSp(getApplicationContext(), ConstantValue.SETUP_OVER, false); Intent intent = new Intent(SetupOverActivity.this, SetSelf1Activity.class); startActivity(intent); finish(); } }); // 设置textview设置锁屏密码的点击事件 tv_set_pwd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showSetPwdDialog(); } }); } // 设置密码对话框 private void showSetPwdDialog() { // 自定义对话框 要用dialog.setView(view); 来设置 Builder builder = new AlertDialog.Builder(this); final AlertDialog dialog = builder.create(); // 将一个xml转换成一个view对象 View view = View.inflate(this, R.layout.dialog_set_pwd, null); // 兼容低版本 去掉对话框的内边距 dialog.setView(view, 0, 0, 0, 0); // dialog.setView(view); dialog.show(); // 找到相应的控件 Button bt_submit = (Button) view.findViewById(R.id.bt_submit); Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel); final EditText et_set_pwd = (EditText) view .findViewById(R.id.et_set_pwd); final EditText et_confirm_pwd = (EditText) view .findViewById(R.id.et_confirm_pwd); // 确认的按钮 bt_submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 获取edittext的内容 String set_pwd = et_set_pwd.getText().toString().trim(); String confirm_pwd = et_confirm_pwd.getText().toString().trim(); if (TextUtils.isEmpty(set_pwd) || TextUtils.isEmpty(confirm_pwd)) { ToastUtli.show(getApplicationContext(), "密码不能为空"); } else if (set_pwd.equals(confirm_pwd)) { // 将加密后的密码存在sp中 SpUtils.putStringSp(getApplicationContext(), ConstantValue.REMOTE_LOCK_PASWORD, set_pwd); dialog.dismiss(); } else { ToastUtli.show(getApplicationContext(), "两次密码不一致"); } } }); // 取消的按钮 bt_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } }
#!/bin/bash set -e set -x if [[ "X$HADOOP_VERSION" = "X" ]]; then echo "HADOOP_VERSION not set" exit 1 fi if [[ "X$MAVEN_DIR" != "X" ]]; then export PATH="$PATH:$MAVEN_DIR/bin" fi RPM_DIR="$TEMP_OUTPUT_DIR" # Setup scratch dir SCRATCH_DIR="${RPM_DIR}/scratch" rm -rf $SCRATCH_DIR mkdir -p ${SCRATCH_DIR}/{SOURCES,SPECS,RPMS,SRPMS} cp -r sources/* ${SCRATCH_DIR}/SOURCES/ cp hadoop.spec ${SCRATCH_DIR}/SPECS/ # Set up src dir export SRC_DIR="${RPM_DIR}/hadoop-$HADOOP_VERSION-src" TAR_NAME=hadoop-$HADOOP_VERSION-src.tar.gz rm -rf $SRC_DIR rsync -a ../ $SRC_DIR --exclude rpm --exclude .git --exclude .docker-data cd $RPM_DIR tar -czf ${SCRATCH_DIR}/SOURCES/${TAR_NAME} $(basename $SRC_DIR) # Build srpm rpmbuild \ --define "_topdir $SCRATCH_DIR" \ --define "input_tar $TAR_NAME" \ --define "hadoop_version ${HADOOP_VERSION}" \ --define "release ${PKG_RELEASE}%{?dist}" \ -bs --nodeps --buildroot="${SCRATCH_DIR}/INSTALL" \ ${SCRATCH_DIR}/SPECS/hadoop.spec src_rpm=$(ls -1 ${SCRATCH_DIR}/SRPMS/hadoop-*) # build rpm rpmbuild \ --define "_topdir $SCRATCH_DIR" \ --define "input_tar $TAR_NAME" \ --define "hadoop_version ${HADOOP_VERSION}" \ --define "release ${PKG_RELEASE}%{?dist}" \ --rebuild $src_rpm if [[ -d $RPMS_OUTPUT_DIR ]]; then # Move rpms to output dir for upload find ${SCRATCH_DIR}/{SRPMS,RPMS} -name "*.rpm" -exec mv {} $RPMS_OUTPUT_DIR/ \; fi
/* TITLE Names & Score Chapter6Exercise4.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Store unique names and scores. Redo Exercise 19 from Chapter 4 using a single vector if type Name_value. Input: Name followed by its score. (Input termination: "No more") Output: Print all entered names and scores pairs. Author: <NAME> Data: 10.04.2015 */ #include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> /* classa: Name_value Data structure storing a pair of associated name and score. */ class Name_value { public: // data members std::string name; int score; // constructors Name_value(); Name_value(std::string& n, int s) : name(n), score(s) { } // used in sort() bool operator< (const Name_value& rhs) const { return name < rhs.name; } }; void populate_vector(std::vector<Name_value>&); bool all_unique(const std::vector<Name_value>&); void print_vector(const std::vector<Name_value>&); //============================================================================== int main(){ // data structure holding names and scores std::vector<Name_value> pairs; // read input and store in vector populate_vector(pairs); // check if all names unique and print if (all_unique(pairs)) { print_vector(pairs); } else { std::cout <<"Name occuring more than once!\n"; } getchar(); } //============================================================================== /* Function: populate_vector(); It prompts the used to input string: name and int: score on a single line separated by whitespace and stores them in the vector passed by reference. */ void populate_vector(std::vector<Name_value>& v) { std::string prompt = "Please type a name, followed by score:\n>>"; std::string sentinel = "No more"; std::string line; // input loop std::cout << prompt; while (getline(std::cin, line) && line != sentinel) { std::stringstream ss(line); std::string name; int score = 0; // check input format if (ss >> name >> score) { v.emplace_back(Name_value(name, score)); } else { std::cout <<"Wrong input format!\n"; } std::cout << prompt; } } /* Function: all_unique(); Returns true if all the names are unique. */ bool all_unique(const std::vector<Name_value>& v) { std::vector<Name_value> temp(v); sort(temp.begin(), temp.end()); for (size_t i = 0; i < temp.size() - 1; ++i) { if (temp[i].name == temp[i+1].name) { return false; } } return true; } /* Function: print_vector() Use: print_vector(vect) It prints all vector elements on a new line. */ void print_vector(const std::vector<Name_value>& v) { for (unsigned int i = 0; i < v.size(); ++i) { std::cout << v[i].name <<" "<< v[i].score <<'\n'; } }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-old/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-old/7-1024+0+512-shuffled-N-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_remove_all_but_nouns_first_two_thirds_sixth --eval_function penultimate_sixth_eval
#!/bin/sh ## Usage # sh step6-regionMatrix.sh snyder # sh step6-regionMatrix.sh hippo # Define variables EXPERIMENT=$1 SHORT="regMat-${EXPERIMENT}" ncore=5 cores="${ncore}cores" # Directories ROOTDIR=/dcl01/lieber/ajaffe/derRuns/derCountSupp MAINDIR=${ROOTDIR}/${EXPERIMENT} WDIR=${MAINDIR}/regionMatrix if [[ "${EXPERIMENT}" == "snyder" ]] then CUTOFF=5 RLENGTH=101 elif [[ "${EXPERIMENT}" == "hippo" ]] then CUTOFF=3 RLENGTH=36 else echo "Specify a valid experiment: snyder or hippo" fi # Construct shell files sname="${SHORT}" echo "Creating script ${sname}" cat > ${ROOTDIR}/.${sname}.sh <<EOF #!/bin/bash #$ -cwd #$ -m e #$ -l mem_free=50G,h_vmem=100G,h_fsize=30G #$ -N ${sname} #$ -pe local ${ncore} #$ -hold_jid fullCov-${EXPERIMENT} echo "**** Job starts ****" date # Make logs directory mkdir -p ${WDIR}/logs # Load coverage & get region matrix cd ${WDIR} module load R/3.2.x R -e "library(derfinder); message(Sys.time()); timeinfo <- NULL; timeinfo <- c(timeinfo, list(Sys.time())); load('${MAINDIR}/CoverageInfo/fullCov.Rdata'); timeinfo <- c(timeinfo, list(Sys.time())); proc.time(); message(Sys.time()); regionMat <- regionMatrix(fullCov, maxClusterGap = 3000L, L = ${RLENGTH}, mc.cores = ${ncore}, cutoff = ${CUTOFF}, returnBP = FALSE); timeinfo <- c(timeinfo, list(Sys.time())); save(regionMat, file='regionMat-cut${CUTOFF}.Rdata'); timeinfo <- c(timeinfo, list(Sys.time())); save(timeinfo, file='timeinfo-${cores}.Rdata'); proc.time(); message(Sys.time()); options(width = 120); devtools::session_info()" ## Move log files into the logs directory mv ${ROOTDIR}/${sname}.* ${WDIR}/logs/ echo "**** Job ends ****" date EOF call="qsub .${sname}.sh" echo $call $call
<gh_stars>1-10 // Copyright 2021 99cloud // // 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. export function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); } export function getText(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsText(file, 'UTF-8'); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); } export function getArrayBuffer(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); }
#!/bin/bash # Simple script to start an Elasticsearch and Kibana instance with Fleet and the Detection Engine. No data is retained. For information on customizing, see the Github repository. # # Usage: # ./elastic-container.sh [OPTION] # # Options: # stage - download the Elasticsearch, Kibana, and Elastic-Agent Docker images. This does not start them. # start - start the Elasticsearch node, connected Kibana instance, and start the Elastic-Agent as a Fleet Server. # stop - stop the Elasticsearch node, connected Kibana instance, and Fleet Server. # restart - restart the Elasticsearch, connected Kibana instance, and Fleet Server. # status - get the status of the Elasticsearch node, connected Kibana instance, and Fleet Server. # # More information at https://github.com/peasead/elastic-container" # Define variables ELASTIC_USERNAME="elastic" ELASTIC_PASSWORD="password" ELASTICSEARCH_URL="http://elasticsearch:9200" LOCAL_ES_URL="http://127.0.0.1:9200" KIBANA_URL="http://kibana:5601" LOCAL_KBN_URL="http://127.0.0.1:5601" FLEET_URL="http://fleet-server:8220" STACK_VERSION="7.17.0" HEADERS=( -H "kbn-version: ${STACK_VERSION}" -H "kbn-xsrf: kibana" -H 'Content-Type: application/json' ) # Create the script usage menu usage() { cat <<EOF | sed -e 's/^ //' usage: ./elastic-container.sh [-v] (stage|start|stop|restart|status|help) actions: stage downloads all necessary images to local storage start creates network and configures containers to run stop stops the containers created and removes the network restart simply restarts all the stack containers status check the status of the stack containers help print this message flags: -v enable verbose output EOF } # Create a function to enable the Detection Engine and load prebuilt rules in Kibana configure_kbn() { MAXTRIES=15 i=${MAXTRIES} while [ $i -gt 0 ]; do STATUS=$(curl -I "${LOCAL_KBN_URL}" 2>&3 | head -n 1 | cut -d$' ' -f2) echo echo "Attempting to enable the Detection Engine and Prebuilt-Detection Rules" if [ "${STATUS}" == "302" ]; then echo echo "Kibana is up. Proceeding" echo output=$(curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPOST "${LOCAL_KBN_URL}/api/detection_engine/index" 2>&3) [[ $output =~ '"acknowledged":true' ]] || ( echo echo "Detection Engine setup failed :-(" exit 1 ) echo "Detection engine enabled. Installing prepackaged rules." curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPUT "${LOCAL_KBN_URL}/api/detection_engine/rules/prepackaged" 1>&3 2>&3 echo echo "Prebuilt Detections Enabled!" break else echo echo "Kibana still loading. Trying again in 40 seconds" fi sleep 40 i=$((i - 1)) done [ $i -eq 0 ] && echo "Exceeded MAXTRIES (${MAXTRIES}) to setup detection engine." && exit 1 } setup_fleet() { curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPOST "${LOCAL_KBN_URL}/api/fleet/setup" | jq } &> /dev/null create_fleet_usr() { printf '{"forceRecreate": "true"}' | curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPOST "${LOCAL_KBN_URL}/api/fleet/agents/setup" -d @- | jq attempt_counter=0 max_attempts=5 until [ "$(curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XGET "${LOCAL_KBN_URL}/api/fleet/agents/setup" | jq -c 'select(.isReady==true)' | wc -l)" -gt 0 ]; do if [ ${attempt_counter} -eq ${max_attempts} ];then echo "Max attempts reached" exit 1 fi printf '.' attempt_counter=$((attempt_counter+1)) sleep 5 done } &> /dev/null configure_fleet() { printf '{"kibana_urls": ["%s"]}' "${KIBANA_URL}" | curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPUT "${KIBANA_URL}/api/fleet/settings" -d @- | jq printf '{"fleet_server_hosts": ["%s"]}' "${FLEET_URL}" | curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPUT "${LOCAL_KBN_URL}/api/fleet/settings" -d @- | jq OUTPUT_ID="$(curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XGET "${LOCAL_KBN_URL}/api/fleet/outputs" | jq --raw-output '.items[] | select(.name == "default") | .id')" printf '{"hosts": ["%s"]}' "${ELASTICSEARCH_URL}" | curl --silent "${HEADERS[@]}" --user "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -XPUT "${LOCAL_KBN_URL}/api/fleet/outputs/${OUTPUT_ID}" -d @- | jq } &> /dev/null # Logic to enable the verbose output if needed OPTIND=1 # Reset in case getopts has been used previously in the shell. verbose=0 while getopts "v" opt; do case "$opt" in v) verbose=1 ;; *) ;; esac done shift $((OPTIND - 1)) [ "${1:-}" = "--" ] && shift ACTION="${*:-help}" if [ $verbose -eq 1 ]; then exec 3<>/dev/stderr else exec 3<>/dev/null fi case "${ACTION}" in "stage") # Collect the Elastic, Kibana, and Elastic-Agent Docker images docker pull docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION} docker pull docker.elastic.co/kibana/kibana:${STACK_VERSION} docker pull docker.elastic.co/beats/elastic-agent:${STACK_VERSION} ;; "start") echo "Starting Elastic Stack network and containers" # Create the Docker network docker network create elastic 1>&3 2>&3 # Start the Elasticsearch container docker run -d --network elastic --rm --name elasticsearch -p 9200:9200 -p 9300:9300 \ -e "discovery.type=single-node" \ -e "xpack.security.enabled=true" \ -e "xpack.security.authc.api_key.enabled=true" \ -e "ELASTIC_PASSWORD=${ELASTIC_PASSWORD}" \ docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION} 1>&3 2>&3 # Start the Kibana container docker run -d --network elastic --rm --name kibana -p 5601:5601 \ -v "$(pwd)/kibana.yml:/usr/share/kibana/config/kibana.yml" \ -e "ELASTICSEARCH_HOSTS=${ELASTICSEARCH_URL}" \ -e "ELASTICSEARCH_USERNAME=elastic" \ -e "ELASTICSEARCH_PASSWORD=${ELASTIC_PASSWORD}" \ docker.elastic.co/kibana/kibana:${STACK_VERSION} 1>&3 2>&3 # Start the Elastic Fleet Server container docker run -d --network elastic --rm --name fleet-server -p 8220:8220 \ -e "KIBANA_HOST=${KIBANA_URL}" \ -e "KIBANA_USERNAME=elastic" \ -e "KIBANA_PASSWORD=${ELASTIC_PASSWORD}" \ -e "ELASTICSEARCH_HOSTS=${ELASTICSEARCH_URL}" \ -e "ELASTICSEARCH_USERNAME=elastic" \ -e "ELASTICSEARCH_PASSWORD=${ELASTIC_PASSWORD}" \ -e "KIBANA_FLEET_SETUP=1" \ -e "FLEET_SERVER_ENABLE=1" \ -e "FLEET_SERVER_INSECURE_HTTP=1" \ docker.elastic.co/beats/elastic-agent:${STACK_VERSION} 1>&3 2>&3 # Enables the Detection Engine and Prebuilt Rules function created above configure_kbn # Setup Fleet echo echo "Setting up Fleet" setup_fleet # Create the Fleet User echo echo "Creating Fleet User" create_fleet_usr # Configure Fleet Output echo echo "Configuring Fleet" configure_fleet echo echo "Browse to http://localhost:5601" echo "Username: elastic" echo "Passphrase: ${ELASTIC_PASSWORD}" echo ;; "stop") echo "#####" echo "Stopping and removing all Elastic Stack components." echo "#####" docker stop fleet-server 2>&3 docker stop kibana 2>&3 docker stop elasticsearch 2>&3 docker network rm elastic 2>&3 ;; "restart") echo "#####" echo "Restarting all Elastic Stack components." echo "#####" docker restart elasticsearch 2>&3 docker restart kibana 2>&3 docker restart fleet-server 2>&3 ;; "status") docker ps -f "name=kibana" -f "name=elasticsearch" -f "name=fleet-server" --format "table {{.Names}}: {{.Status}}" ;; "help") usage ;; *) echo -e "Proper syntax not used. See the usage\n" usage ;; esac # Close FD 3 exec 3>&-
// --------- Project informations Seq( name := "TStore", organization := "ch.epfl.data", version := "0.1" ) mainClass in run in Compile := Some("benchmark.OltpBenchmark") packSettings packMain := Map("compiler" -> "benchmark.OltpBenchmark") // --------- Paths Seq( scalaSource in Compile <<= baseDirectory / "src", javaSource in Compile <<= baseDirectory / "src", sourceDirectory in Compile <<= baseDirectory / "src", scalaSource in Test <<= baseDirectory / "test", javaSource in Test <<= baseDirectory / "test", sourceDirectory in Test <<= baseDirectory / "test", resourceDirectory in Compile <<= baseDirectory / "conf" ) // --------- Dependencies libraryDependencies ++= Seq( "org.scala-lang" % "scala-actors" % scalaVersion.value, // to compile legacy Scala "org.scala-lang" % "scala-compiler" % scalaVersion.value, "org.scalatest" %% "scalatest" % "2.2.4" % "test", "org.testng" % "testng" % "6.9.4" % "test" ) // --------- Compilation options Seq( scalaVersion := "2.11.7", scalacOptions ++= Seq("-deprecation","-unchecked","-feature","-optimise","-Yinline-warnings"), // ,"-target:jvm-1.7" javacOptions ++= Seq("-Xlint:unchecked","-Xlint:-options","-source","1.8","-target","1.8") // forces JVM 1.6 compatibility with JDK 1.7 compiler ) // --------- Execution options Seq( fork := true, // required to enable javaOptions //javaOptions ++= Seq("-agentpath:"+"/Applications/Tools/YourKit Profiler.app/bin/mac/libyjpagent.jnilib"+"=sampling,onexit=snapshot,builtinprobes=all"), javaOptions ++= Seq("-Xss128m","-XX:-DontCompileHugeMethods","-XX:+CMSClassUnloadingEnabled"), // ,"-Xss512m","-XX:MaxPermSize=2G" javaOptions ++= Seq("-Xmx8G","-Xms8G"/*,"-verbose:gc"*/), parallelExecution in Test := false, // for large benchmarks javacOptions ++= Seq("-source", "1.8", "-target", "1.8", "-Xlint"), javaOptions <+= (fullClasspath in Runtime) map (cp => "-Dsbt.classpath="+cp.files.absString) // propagate paths ) // --------- Custom tasks val numWarehouse = "1" lazy val reloadDB = taskKey[Unit]("Executes the shell script for reloading the database") reloadDB := { "bench/bench load "+numWarehouse ! } addCommandAlias("bench", ";run-main ddbt.tpcc.tx.TpccInMem -w "+numWarehouse) ++ addCommandAlias("bench-1", ";bench -i -1 -t 60") ++ addCommandAlias("bench1", ";bench -i 1 -t 60 ") ++ addCommandAlias("bench2", ";bench -i 2 -t 60 ") ++ addCommandAlias("bench3", ";bench -i 3 -t 60 ") ++ addCommandAlias("bench4", ";bench -i 4 -t 60 ") ++ addCommandAlias("bench5", ";bench -i 5 -t 60 ") ++ addCommandAlias("bench6", ";bench -i 6 -t 60 ") ++ addCommandAlias("bench7", ";bench -i 7 -t 60 ") ++ addCommandAlias("bench8", ";bench -i 8 -t 60 ") ++ addCommandAlias("bench9", ";bench -i 9 -t 60 ") ++ addCommandAlias("bench10", ";bench -i 10 -t 60 ") ++ addCommandAlias("bench11", ";bench -i 11 -t 60 ") addCommandAlias("unit", ";run-main ddbt.tpcc.loadtest.TpccUnitTest -w "+numWarehouse) ++ addCommandAlias("unit-1", ";unit -i -1; reloadDB") ++ addCommandAlias("unit1", ";unit -i 1; reloadDB") ++ addCommandAlias("unit2", ";unit -i 2; reloadDB") ++ addCommandAlias("unit3", ";unit -i 3; reloadDB") ++ addCommandAlias("unit4", ";unit -i 4; reloadDB") ++ addCommandAlias("unit5", ";unit -i 5; reloadDB") ++ addCommandAlias("unit6", ";unit -i 6; reloadDB") ++ addCommandAlias("unit7", ";unit -i 7; reloadDB") ++ addCommandAlias("unit8", ";unit -i 8; reloadDB") ++ addCommandAlias("unit9", ";unit -i 9; reloadDB") ++ addCommandAlias("unit10", ";unit -i 10; reloadDB") ++ addCommandAlias("unit11", ";unit -i 11; reloadDB") addCommandAlias("test-mvconcurrent", ";test-only ddbt.lib.mvconcurrent.*")
<reponame>rio9791/alumni_upi class CreateColleges < ActiveRecord::Migration def change create_table :colleges do |t| t.integer :join_year t.string :basic_training t.string :intermediate_training t.string :advanced_training t.string :senior_course t.string :commissariat t.string :korkom t.string :branch t.string :badko t.string :pb t.integer :alumni_id t.timestamps null: false end end end
#!/bin/sh if [ "$EUID" -ne 0 ]; then echo enter password in order to install Yin-Yang correctly sudo sh ./$0 exit 1 fi echo "removing old Yin-Yang files if they exist" echo "your home here is" $HOME echo "your current user is in install" $SUDO_USER sudo sh ./uninstall.sh $SUDO_USER echo "Installing Yin-Yang ..." echo "" echo "Checking for QT dependencies" echo "" #checking python dependencies pip3 install qtpy pip3 install pyqt5 pip3 install suntime echo "" echo "Checking and creating correct folders ..." #check if /opt/ directory exists else create if [ ! -d /opt/ ]; then mkdir /opt/ fi #check if /opt/ directory exists else create if [ ! -d /opt/yin-yang/ ]; then mkdir /opt/yin-yang/ fi echo "" echo "done" echo "" echo "Installin yin-yang for Commandline usage" # copy files cp -r ./* /opt/yin-yang/ #copy terminal executive cp ./src/yin-yang /usr/bin/ sudo chmod +x /usr/bin/yin-yang echo "Creating .desktop file for native enviroment execution" #create .desktop file cat <<EOF >/home/$SUDO_USER/.local/share/applications/Yin-Yang.desktop [Desktop Entry] # The type as listed above Type=Application # The version of the desktop entry specification to which this file complies Version=2.0.0 # The name of the application Name=Yin & Yang # A comment which can/will be used as a tooltip Comment=Auto Nightmode for KDE and VSCode # The path to the folder in which the executable is run Path=/opt/yin-yang # The executable of the application, possibly with arguments. Exec=env QT_AUTO_SCREEN_SCALE_FACTOR=1 sh /usr/bin/yin-yang # The name of the icon that will be used to display this entry Icon=/opt/yin-yang/src/ui/assets/yin-yang.svg # Describes whether this application needs to be run in a terminal or not Terminal=false # Describes the categories in which this entry should be shown Categories=Utility; System; EOF cat << "EOF" __ ___ __ __ \ \ / (_) \ \ / / \ \_/ / _ _ __ _____\ \_/ /_ _ _ __ __ _ \ / | | '_ \______\ / _` | '_ \ / _` | | | | | | | | | | (_| | | | | (_| | |_| |_|_| |_| |_|\__,_|_| |_|\__, | __/ | |___/ EOF echo "" echo "Yin-Yang brings Auto Nightmode for KDE and VSCode" echo "" cat << "EOF" _..oo8"""Y8b.._ .88888888o. "Yb. .d888P""Y8888b "b. o88888 88888) "b d888888b..d8888P 'b 88888888888888" 8 (88DWB8888888P 8) 8888888888P 8 Y88888888P ee .P Y888888( 8888 oP "Y88888b "" oP" "Y8888o._ _.oP" `""Y888boodP""' EOF echo "" echo "" echo "checkout https://github.com/daehruoydeef/Yin-Yang for help" echo "Yin-Yang is now installed"
import { SearchAttributes, upsertSearchAttributes, workflowInfo } from '@temporalio/workflow'; export async function upsertAndReadSearchAttributes(msSinceEpoch: number): Promise<SearchAttributes | undefined> { upsertSearchAttributes({ CustomIntField: [123], CustomBoolField: [true], }); upsertSearchAttributes({ CustomIntField: [], // clear CustomKeywordField: ['durable code'], CustomTextField: ['is useful'], CustomDatetimeField: [new Date(msSinceEpoch)], CustomDoubleField: [3.14], }); return workflowInfo().searchAttributes; }
import { UserModule } from '@/user/user.module'; import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { CalendarEntity } from 'core/entity/calendar.entity'; import { StatisEntity } from 'core/entity/statis.entity'; import { StatisController } from './statis.controller'; import { StatisService } from './statis.service'; @Module({ imports: [TypeOrmModule.forFeature([StatisEntity,CalendarEntity]), UserModule], providers: [StatisService], controllers: [StatisController], exports: [StatisService] }) export class StatisModule implements NestModule { public configure(consumer: MiddlewareConsumer) { } }
<reponame>kevin-luvian/opengl<filename>basic/src/object/Object.h #pragma once #include "Renderable.h" #include "draw/renderer/RendererManager.h" #include "mesh/Meshes.h" class Object : public Renderable { protected: glm::mat4 mModel; glm::vec4 mColour; glm::vec3 mPosition; glm::vec3 mRotations; float mSize; bool shouldUpdate; virtual void setMesh() override = 0; virtual void setMaterial() override { material = std::make_unique<Material>(); } virtual void setShaderType() override { shaderType = Enum::ShaderType::Simple; } virtual void setRenderer() override { auto gRenderer = RendererManager::CreateRendererFromShaderType(shaderType); renderer = std::unique_ptr<Renderer>(gRenderer); } public: Object() { shouldUpdate = true; mModel = glm::mat4(1); mPosition = glm::vec3(0); mSize = 1.0f; mColour = glm::vec4(1); } virtual ~Object() {} glm::mat4 getModel() { return mModel; } glm::vec3 getPosition() { return mPosition; } glm::vec4 getColour() { return mColour; } float getSize() { return mSize; } void rotateX(float angle) { shouldUpdate = true; mRotations.x = util::toRadians(angle); } void rotateY(float angle) { shouldUpdate = true; mRotations.y = util::toRadians(angle); } void rotateZ(float angle) { shouldUpdate = true; mRotations.z = util::toRadians(angle); } void setPosition(glm::vec3 position) { shouldUpdate = true; mPosition = position; } void setSize(float size) { shouldUpdate = true; mSize = size; } void setColour(glm::vec4 colour) { mColour = colour; } void update() { if (shouldUpdate) { shouldUpdate = false; mModel = glm::mat4(1.0f); mModel = glm::translate(mModel, mPosition); mModel = glm::rotate(mModel, mRotations.x, glm::vec3(0, 1, 0)); mModel = glm::rotate(mModel, mRotations.y, glm::vec3(-1, 0, 0)); mModel = glm::rotate(mModel, mRotations.z, glm::vec3(0, 0, 1)); mModel = glm::scale(mModel, glm::vec3(mSize, mSize, mSize)); } } };
package com.linkedin.gms.factory.secret; import com.linkedin.metadata.secret.SecretService; import javax.annotation.Nonnull; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class SecretServiceFactory { @Value("${secretService.encryptionKey}") private String encryptionKey; @Bean(name = "dataHubSecretService") @Primary @Nonnull protected SecretService getInstance() { return new SecretService(this.encryptionKey); } }
<reponame>huyenminnn/minshop $(document).ready(function () { // create slug function toSlug(str) { //Đổi chữ hoa thành chữ thường slug = str.toLowerCase(); //Đổi ký tự có dấu thành không dấu slug = slug.replace(/á|à|ả|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/gi, 'a'); slug = slug.replace(/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ/gi, 'e'); slug = slug.replace(/i|í|ì|ỉ|ĩ|ị/gi, 'i'); slug = slug.replace(/ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ/gi, 'o'); slug = slug.replace(/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/gi, 'u'); slug = slug.replace(/ý|ỳ|ỷ|ỹ|ỵ/gi, 'y'); slug = slug.replace(/đ/gi, 'd'); //Xóa các ký tự đặt biệt slug = slug.replace(/\`|\~|\!|\@|\#|\||\$|\%|\^|\&|\*|\(|\)|\+|\=|\,|\.|\/|\?|\>|\<|\'|\"|\:|\;|_/gi, ''); //Đổi khoảng trắng thành ký tự gạch ngang slug = slug.replace(/ /gi, "-"); //Đổi nhiều ký tự gạch ngang liên tiếp thành 1 ký tự gạch ngang //Phòng trường hợp người nhập vào quá nhiều ký tự trắng slug = slug.replace(/\-\-\-\-\-/gi, '-'); slug = slug.replace(/\-\-\-\-/gi, '-'); slug = slug.replace(/\-\-\-/gi, '-'); slug = slug.replace(/\-\-/gi, '-'); //Xóa các ký tự gạch ngang ở đầu và cuối slug = '@' + slug + '@'; slug = slug.replace(/\@\-|\-\@|\@/gi, ''); return slug; } //add picture $('body').on('click','.btn-pic', function(){ $('#modal-add-pic').modal('show') var id = $(this).data('id') $('#id-add-pic').val(id) $('.images-product').children().remove() $.ajax({ type: "get", url: '/admin/image/' + id, success: function (response){ jQuery.each( response, function( key, val ) { $('.images-product').append( `<div class="col-md-3 col-sm-12 col-xs-12 text-center"> <img src="/storage/`+val.image+`" class="img-responsive img-fluid img-rounded" style="height: 300px; margin:15px auto;"> <button type="button" class="btn btn-danger delete-image" data-id=`+val.id+`>Delete</button> </div>` ); }); } }) }) Dropzone.options.myDropzone = { maxFileSize : 10, parallelUploads : 10, uploadMultiple: true, autoProcessQueue : false, addRemoveLinks : true, init: function() { var submitButton = document.querySelector("#submit-pic") myDropzone = this; submitButton.addEventListener("click", function() { myDropzone.processQueue(); $('#modal-add-pic').modal('hide') toastr.success('Edit images success!') }); }, } // add new product $('.btn-add').click(function(){ $('#modal-add').modal('show') $("input").focus(function(){ if ($(this).next().attr('class') == 'error-noti') { $(this).next().remove(); } }); $('#name-add').keyup(function(){ var slug = toSlug($('#name-add').val()) $('#slug-add').val(slug) }) $('#price-add').keyup(function(){ var val = $('#price-add').val() var a = numeral(val).format('0,0') $('#price-add').val(a) $('#price-discount-add').val(a) }) $('#price-discount-add').keyup(function(){ var val = $('#price-discount-add').val() var a = numeral(val).format('0,0') $('#price-discount-add').val(a) }) }) $('#form-add').submit(function(e){ e.preventDefault() $('.error-noti').remove() var data = new FormData(); if ($('#thumbnail-add')[0].files[0]) { data.append('thumbnail',$('#thumbnail-add')[0].files[0]) } else data.append('thumbnail','') data.append('name',$('#name-add').val()) data.append('product_code',$('#product-code-add').val()) data.append('category_id',$('#category-add').val()) data.append('slug',$('#slug-add').val()) data.append('price',numeral($('#price-add').val()).value()) data.append('discount_price',numeral($('#price-discount-add').val()).value()) data.append('brand',$('#brand-add').val()) data.append('description',tinymce.get('description-add').getContent()) data.append('product_info',tinymce.get('product-info-add').getContent()) $.ajax({ type: "post", url: '/admin/product', data: data, processData: false, contentType: false, success: function(data, textStatus, jqXHR) { $('#modal-add').modal('hide') toastr.success('Add product success!') $('#productTable').DataTable().ajax.reload(null,false); }, error: function(data, textStatus, jqXHR) { if (data.responseJSON.errors.name) { $( '<p class="error-noti">'+data.responseJSON.errors.name[0]+"</p>" ).insertAfter( "#name-add" ); } if (data.responseJSON.errors.slug) { $( '<p class="error-noti">'+data.responseJSON.errors.slug[0]+"</p>" ).insertAfter( "#slug-add" ); } if (data.responseJSON.errors.thumbnail) { $( '<p class="error-noti">'+data.responseJSON.errors.thumbnail[0]+"</p>" ).insertAfter( "#thumbnail-add" ); } if (data.responseJSON.errors.product_code) { $( '<p class="error-noti">'+data.responseJSON.errors.product_code[0]+"</p>" ).insertAfter( "#product-code-add" ); } if (data.responseJSON.errors.brand) { $( '<p class="error-noti">'+data.responseJSON.errors.brand[0]+"</p>" ).insertAfter( "#brand-add" ); } if (data.responseJSON.errors.price) { $( '<p class="error-noti">'+data.responseJSON.errors.price[0]+"</p>" ).insertAfter( "#price-add" ); } }, }); }) // edit product $('body').on('click','.btn-edit', function(){ $('#modal-edit').modal('show') $("input").focus(function(){ if ($(this).next().attr('class') == 'error-noti') { $(this).next().remove(); } }); $('#name-edit').keyup(function(){ var slug = toSlug($('#name-edit').val()) $('#slug-edit').val(slug) }) $('#price-edit').keyup(function(){ var val = $('#price-edit').val() var a = numeral(val).format('0,0') $('#price-edit').val(a) $('#price-discount-edit').val(a) }) $('#price-discount-edit').keyup(function(){ var val = $('#price-discount-edit').val() var a = numeral(val).format('0,0') $('#price-discount-edit').val(a) }) var id = $(this).data('id') $.ajax({ type: 'get', url: '/admin/product_showedit/' + id, success: function (response){ $('#id-edit').val(response.id) $('#name-edit').val(response.name) $('#slug-edit').val(response.slug) $('#product-code-edit').val(response.product_code) $('#category-edit').val(response.category_id) $('#brand-edit').val(response.brand) $('#price-edit').val(numeral(response.price).format('0,0')) $('#price-discount-edit').val(numeral(response.discount_price).format('0,0')) tinymce.get('description-edit').setContent(response.description) tinymce.get('product-info-edit').setContent(response.product_info) $('#thumbnailShow-edit').attr('src','/storage/'+response.thumbnail) } }) }) $('#form-edit').submit(function(e){ e.preventDefault() $('.error-noti').remove() var id = $('#id-edit').val() var data = new FormData(); data.append('id',id) if ($('#thumbnail-edit')[0].files[0]) { data.append('thumbnail',$('#thumbnail-edit')[0].files[0]) } else data.append('thumbnail','none') data.append('name',$('#name-edit').val()) data.append('product_code',$('#product-code-edit').val()) data.append('category_id',$('#category-edit').val()) data.append('slug',$('#slug-edit').val()) data.append('price',numeral($('#price-edit').val()).value()) data.append('discount_price',numeral($('#price-discount-edit').val()).value()) data.append('brand',$('#brand-edit').val()) data.append('description',tinymce.get('description-edit').getContent()) data.append('product_info',tinymce.get('product-info-edit').getContent()) $.ajax({ type: 'post', url: '/admin/product_edit/' + id, data: data, processData: false, contentType: false, success: function (response){ toastr.success('Update product success!') setTimeout(function () { $('#modal-edit').modal('hide') $('#productTable').DataTable().ajax.reload(null,false); },800); }, error: function(data, textStatus, jqXHR) { if (data.responseJSON.errors.name) { $( '<p class="error-noti">'+data.responseJSON.errors.name[0]+"</p>" ).insertAfter( "#name-add" ); } if (data.responseJSON.errors.slug) { $( '<p class="error-noti">'+data.responseJSON.errors.slug[0]+"</p>" ).insertAfter( "#slug-add" ); } if (data.responseJSON.errors.product_code) { $( '<p class="error-noti">'+data.responseJSON.errors.product_code[0]+"</p>" ).insertAfter( "#product-code-add" ); } if (data.responseJSON.errors.brand) { $( '<p class="error-noti">'+data.responseJSON.errors.brand[0]+"</p>" ).insertAfter( "#brand-add" ); } if (data.responseJSON.errors.price) { $( '<p class="error-noti">'+data.responseJSON.errors.price[0]+"</p>" ).insertAfter( "#price-add" ); } }, }) }) // delete product $('body').on('click','.btn-delete', function(e){ e.preventDefault() var id = $(this).data('id') swal({ title: "Are you sure?", text: "Once deleted, you will not be able to recover this imaginary file!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ type: 'delete', url: '/admin/product/' + id, success: function (response) { // thông báo xoá thành công bằng toastr toastr.success('Delete product success!') setTimeout(function () { $('#productTable').DataTable().ajax.reload(null,false); },800); }, error: function (error) { } }) } }); }) //delete image of product $('body').on('click','.delete-image',function(e){ e.preventDefault() var id = $(this).data('id') swal({ title: "Are you sure?", text: "Once deleted, you will not be able to recover this image!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $(this).parent().remove() $.ajax({ type: 'delete', url: '/admin/image/' + id, success: function (response) { // thông báo xoá thành công bằng toastr toastr.success('Delete image success!') }, error: function (error) { } }) } }); }) // detail product $('body').on('click','.btn-show', function(){ $('#modal-show').modal('show') var id = $(this).data('id') $.ajax({ type: 'get', url: '/admin/product/' + id, success: function (response){ $('#product-id-detail').val(response.id) $('.name-product').html(response.name) } }) $('#productDetailTable').DataTable({ order: [ 0, "desc" ], processing: true, serverSide: true, destroy: true, ajax: '/admin/detailProduct/'+id, columns: [ { data: 'product_id', name: 'product_id' }, { data: 'size', name: 'size' }, { data: 'color_id', name: 'color_id' }, { data: 'quantity', name: 'quantity' }, { data: 'action', name: 'action' } ], }); }) // add new product detail $('.btn-add-product').click(function(){ $('#modal-add-product').modal('show') $("input").focus(function(){ if ($(this).next().attr('class') == 'error-noti') { $(this).next().remove(); } }); }) $('#form-add-product').submit(function(e){ e.preventDefault() $('.error-noti').remove() $.ajax({ type: "post", url: '/admin/detailProduct', data: { product_id: $('#product-id-detail').val(), color_id: $('#color-add').val(), size: $('#size-add').val(), quantity: $('#quantity-add').val(), }, success: function(data, textStatus, jqXHR) { $('#modal-add-product').modal('hide') toastr.success('Add product success!') $('#productDetailTable').DataTable().ajax.reload(null,false); }, error: function(data, textStatus, jqXHR) { if (data.responseJSON.errors.color_id) { $( '<p class="error-noti">'+data.responseJSON.errors.color_id[0]+"</p>" ).insertAfter( "#color-add" ); } if (data.responseJSON.errors.size) { $( '<p class="error-noti">'+data.responseJSON.errors.size[0]+"</p>" ).insertAfter( "#size-add" ); } if (data.responseJSON.errors.quantity) { $( '<p class="error-noti">'+data.responseJSON.errors.quantity[0]+"</p>" ).insertAfter( "#quantity-add" ); } }, }); }) // edit product detail $('body').on('click','.btn-edit-product', function(){ $('#modal-edit-product').modal('show') $("input").focus(function(){ if ($(this).next().attr('class') == 'error-noti') { $(this).next().remove(); } }); var id = $(this).data('id') $.ajax({ type: 'get', url: '/admin/detailProduct_edit/' + id, success: function (response){ $('#id-edit-product').val(response.id) $('#size-edit').val(response.size) $('#color-edit').val(response.color_id) $('#quantity-edit').val(response.quantity) console.log($('#product-id-detail').val()) } }) }) $('#form-edit-product').submit(function(e){ e.preventDefault() $('.error-noti').remove() var id = $('#id-edit-product').val() $.ajax({ type: 'post', url: '/admin/product_detail_edit/' + id, data:{ id: id, product_id: $('#product-id-detail').val(), color_id: $('#color-edit').val(), size: $('#size-edit').val(), quantity: $('#quantity-edit').val(), }, success: function (response){ toastr.success('Update product success!') setTimeout(function () { $('#modal-edit-product').modal('hide') $('#productDetailTable').DataTable().ajax.reload(null,false); },800); }, error: function(data, textStatus, jqXHR) { if (data.responseJSON.errors.name) { $( '<p class="error-noti">'+data.responseJSON.errors.name[0]+"</p>" ).insertAfter( "#name-add" ); } if (data.responseJSON.errors.slug) { $( '<p class="error-noti">'+data.responseJSON.errors.slug[0]+"</p>" ).insertAfter( "#slug-add" ); } if (data.responseJSON.errors.product_code) { $( '<p class="error-noti">'+data.responseJSON.errors.product_code[0]+"</p>" ).insertAfter( "#product-code-add" ); } if (data.responseJSON.errors.brand) { $( '<p class="error-noti">'+data.responseJSON.errors.brand[0]+"</p>" ).insertAfter( "#brand-add" ); } if (data.responseJSON.errors.price) { $( '<p class="error-noti">'+data.responseJSON.errors.price[0]+"</p>" ).insertAfter( "#price-add" ); } }, }) }) //delete product detail $('body').on('click','.btn-delete-product',function(e){ e.preventDefault() var id = $(this).data('id') swal({ title: "Are you sure?", text: "Once deleted, you will not be able to recover this image!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ type: 'delete', url: '/admin/detailProduct/' + id, success: function (response) { // thông báo xoá thành công bằng toastr toastr.success('Delete product success!') setTimeout(function () { $('#productDetailTable').DataTable().ajax.reload(null,false); },800); }, error: function (error) { } }) } }); }) })
<filename>pkg/volume/util/fs_darwin.go // +build darwin /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util import ( "errors" "fmt" "os/exec" "strings" "k8s.io/kubernetes/pkg/api/resource" ) // FSInfo linux returns (available bytes, byte capacity, error) for the filesystem that // path resides upon. func FsInfo(path string) (int64, int64, error) { return 0, 0, errors.New("FsInfo not supported for this build.") } func Du(path string) (*resource.Quantity, error) { out, err := exec.Command("nice", "-n", "19", "du", "-s", path).CombinedOutput() if err != nil { return nil, fmt.Errorf("failed command 'du' ($ nice -n 19 du -s) on path %s with error %v", path, err) } used, err := resource.ParseQuantity(strings.Fields(string(out))[0]) if err != nil { return nil, fmt.Errorf("failed to parse 'du' output %s due to error %v", out, err) } used.Format = resource.BinarySI return used, nil }
def convert_minutes(minutes): hours = minutes // 60 remaining_minutes = minutes % 60 return hours, remaining_minutes hours, minutes = convert_minutes(150) print(hours, minutes)
package ethereum import ( "math/big" "testing" "github.com/stretchr/testify/assert" ) func TestEthToWei(t *testing.T) { hugeEth, ok := new(big.Int).SetString("100000000123456789012345678", 10) assert.True(t, ok) tests := []struct { amount string expectedAmount *big.Int expectedError string }{ {"", nil, "Could not convert to *big.Rat"}, {"test", nil, "Could not convert to *big.Rat"}, {"0.0000000000000000001", nil, "Invalid precision"}, {"1.2345678912345678901", nil, "Invalid precision"}, {"0", big.NewInt(0), ""}, {"0.00", big.NewInt(0), ""}, {"0.000000000000000001", big.NewInt(1), ""}, {"1", big.NewInt(1000000000000000000), ""}, {"1.00", big.NewInt(1000000000000000000), ""}, {"1.234567890123456789", big.NewInt(1234567890123456789), ""}, {"100000000.123456789012345678", hugeEth, ""}, } for _, test := range tests { returnedAmount, err := EthToWei(test.amount) if test.expectedError != "" { assert.Error(t, err) assert.Contains(t, err.Error(), test.expectedError) } else { assert.NoError(t, err) assert.Equal(t, 0, returnedAmount.Cmp(test.expectedAmount)) } } }
// Controller for the Index view public class HomeController: Controller { public ActionResult Index() { return View(); } } // View for the Index page @{ ViewBag.Title = "Index"; } <h2>Index</h2> <a href="~/SecondView">Go to the second view</a> // Controller for the Second view public class HomeController: Controller { public ActionResult SecondView() { return View(); } } // View for the Second page @{ ViewBag.Title = "SecondView"; } <h2>Second View</h2>
/* * File : lwp_memheap.h * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Change Logs: * Date Author Notes */ #ifndef __LWP_MEMHEAP_H__ #define __LWP_MEMHEAP_H__ #include <stdint.h> #include <rtthread.h> /** * memory item on the heap */ struct rt_lwp_memheap_item { rt_uint32_t magic; /**< magic number for memheap */ struct rt_lwp_memheap *pool_ptr; /**< point of pool */ struct rt_lwp_memheap_item *next; /**< next memheap item */ struct rt_lwp_memheap_item *prev; /**< prev memheap item */ struct rt_lwp_memheap_item *next_free; /**< next free memheap item */ struct rt_lwp_memheap_item *prev_free; /**< prev free memheap item */ }; /** * Base structure of memory heap object */ struct rt_lwp_memheap { struct rt_object parent; /**< inherit from rt_object */ void *start_addr; /**< pool start address and size */ rt_uint32_t pool_size; /**< pool size */ rt_uint32_t available_size; /**< available size */ rt_uint32_t max_used_size; /**< maximum allocated size */ struct rt_lwp_memheap_item *block_list; /**< used block list */ struct rt_lwp_memheap_item *free_list; /**< free block list */ struct rt_lwp_memheap_item free_header; /**< free block list header */ struct rt_semaphore lock; /**< semaphore lock */ rt_list_t mlist; }; extern rt_err_t rt_lwp_memheap_init(struct rt_lwp_memheap *memheap, const char *name, void *start_addr, rt_uint32_t size); extern void *rt_lwp_memheap_alloc(struct rt_lwp_memheap *heap, rt_uint32_t size); extern void rt_lwp_memheap_free(void *ptr); extern void *rt_lwp_memheap_realloc(struct rt_lwp_memheap *heap, void *ptr, rt_size_t newsize); extern rt_bool_t rt_lwp_memheap_is_empty(struct rt_lwp_memheap *memheap); extern rt_bool_t rt_lwp_memheap_unavailable_size_get(void); #endif
package encryption; public class Sortable<T> implements Comparable<Sortable<T>> { T key; Integer value; public Sortable(T key, int value) { this.key = key; this.value = value; } public Object getKey() { return this.key; } public Integer getValue() { return this.value; } @Override public int compareTo(Sortable<T> o) { if (this.value == o.value) { return 0; } else if (this.value < o.value) { return -1; } else { return 1; } } }
#!/bin/bash #current directory is build directory test -d "/home/${USER}/NGX" || mkdir -p "/home/${USER}/NGX" test -d "/home/${USER}/NGX/sbin" || mkdir -p "/home/${USER}/NGX/sbin" test ! -f "/home/${USER}/NGX/sbin/nginx" || mv "/home/${USER}/NGX/sbin/nginx" "/home/${USER}/NGX/sbin/nginx.old" cp nginx_with_cpp "/home/${USER}/NGX/sbin/nginx" test -d "/home/${USER}/NGX/conf" || mkdir -p "/home/${USER}/NGX/conf" #I added this line to get back to project root. cd $1 cp conf/koi-win "/home/${USER}/NGX/conf" cp conf/koi-utf "/home/${USER}/NGX/conf" cp conf/win-utf "/home/${USER}/NGX/conf" test -f "/home/${USER}/NGX/conf/mime.types" || cp conf/mime.types "/home/${USER}/NGX/conf" cp conf/mime.types "/home/${USER}/NGX/conf/mime.types.default" test -f "/home/${USER}/NGX/conf/fastcgi_params" || cp conf/fastcgi_params "/home/${USER}/NGX/conf" cp conf/fastcgi_params "/home/${USER}/NGX/conf/fastcgi_params.default" test -f "/home/${USER}/NGX/conf/fastcgi.conf" || cp conf/fastcgi.conf "/home/${USER}/NGX/conf" cp conf/fastcgi.conf "/home/${USER}/NGX/conf/fastcgi.conf.default" test -f "/home/${USER}/NGX/conf/uwsgi_params" || cp conf/uwsgi_params "/home/${USER}/NGX/conf" cp conf/uwsgi_params "/home/${USER}/NGX/conf/uwsgi_params.default" test -f "/home/${USER}/NGX/conf/scgi_params" || cp conf/scgi_params "/home/${USER}/NGX/conf" cp conf/scgi_params "/home/${USER}/NGX/conf/scgi_params.default" test -f "/home/${USER}/NGX/conf/nginx.conf" || cp conf/nginx.conf "/home/${USER}/NGX/conf/nginx.conf" cp conf/nginx.conf "/home/${USER}/NGX/conf/nginx.conf.default" test -d "/home/${USER}/NGX/logs" || mkdir -p "/home/${USER}/NGX/logs" test -d "/home/${USER}/NGX/logs" || mkdir -p "/home/${USER}/NGX/logs" test -d "/home/${USER}/NGX/html" || cp -R html "/home/${USER}/NGX" test -d "/home/${USER}/NGX/logs" || mkdir -p "/home/${USER}/NGX/logs" echo "DONE copying conf files"
#!/bin/bash # source: https://github.com/istio/istio/blob/release-0.7/install/kubernetes/webhook-create-signed-cert.sh set -e [ -z ${KUBECTL} ] && KUBECTL="kubectl" usage() { cat <<EOF Generate certificate suitable for use with an Istio webhook service. This script uses k8s' CertificateSigningRequest API to a generate a certificate signed by k8s CA suitable for use with Istio webhook services. This requires permissions to create and approve CSR. See https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster for detailed explantion and additional instructions. The server key/cert k8s CA cert are stored in a k8s secret. usage: ${0} [OPTIONS] The following flags are required. --service Service name of webhook. --namespace Namespace where webhook service and secret reside. --secret Secret name for CA certificate and server certificate/key pair. EOF exit 1 } while [[ $# -gt 0 ]]; do case ${1} in --service) service="$2" shift ;; --secret) secret="$2" shift ;; --namespace) namespace="$2" shift ;; *) usage ;; esac shift done [ -z ${KUBECTL} ] && KUBECTL=kubectl [ -z ${service} ] && service=virtualmachine-template-validator [ -z ${secret} ] && secret=virtualmachine-template-validator-certs [ -z ${namespace} ] && namespace=kubevirt if [ ! -x "$(command -v openssl)" ]; then echo "openssl not found" exit 1 fi csrName=${service}.${namespace} tmpdir=$(mktemp -d) echo "creating certs in tmpdir ${tmpdir} " cat <<EOF >> ${tmpdir}/csr.conf [req] req_extensions = v3_req distinguished_name = req_distinguished_name [req_distinguished_name] [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment extendedKeyUsage = serverAuth subjectAltName = @alt_names [alt_names] DNS.1 = ${service} DNS.2 = ${service}.${namespace} DNS.3 = ${service}.${namespace}.svc EOF openssl genrsa -out ${tmpdir}/server-key.pem 2048 openssl req -new -key ${tmpdir}/server-key.pem -subj "/CN=${service}.${namespace}.svc" -out ${tmpdir}/server.csr -config ${tmpdir}/csr.conf # clean-up any previously created CSR for our service. Ignore errors if not present. ${KUBECTL} delete csr ${csrName} 2>/dev/null || true # create server cert/key CSR and send to k8s API cat <<EOF | ${KUBECTL} create -f - apiVersion: certificates.k8s.io/v1beta1 kind: CertificateSigningRequest metadata: name: ${csrName} spec: groups: - system:authenticated request: $(cat ${tmpdir}/server.csr | base64 | tr -d '\n') usages: - digital signature - key encipherment - server auth EOF # verify CSR has been created while true; do ${KUBECTL} get csr ${csrName} if [ "$?" -eq 0 ]; then break fi done # approve and fetch the signed certificate ${KUBECTL} certificate approve ${csrName} # verify certificate has been signed for x in $(seq 10); do serverCert=$(${KUBECTL} get csr ${csrName} -o jsonpath='{.status.certificate}') if [[ ${serverCert} != '' ]]; then break fi sleep 1 done if [[ ${serverCert} == '' ]]; then echo "ERROR: After approving csr ${csrName}, the signed certificate did not appear on the resource. Giving up after 10 attempts." >&2 echo "See https://istio.io/docs/setup/kubernetes/sidecar-injection.html for more details on troubleshooting." >&2 exit 1 fi echo ${serverCert} | openssl base64 -d -A -out ${tmpdir}/server-cert.pem # create the secret with CA cert and server cert/key ${KUBECTL} create secret generic ${secret} \ --from-file=key.pem=${tmpdir}/server-key.pem \ --from-file=cert.pem=${tmpdir}/server-cert.pem \ --dry-run -o yaml | ${KUBECTL} -n ${namespace} apply -f -
# Build docker run --rm --name slate -v $(pwd)/build:/srv/slate/build -v $(pwd)/source:/srv/slate/source slatedocs/slate
<filename>lib/fs-traversal.js<gh_stars>1-10 var orders = require('./orders'), filters = require('./filters'), switchString = require('./switchString'), async = require('async'), utils = require('./utils'), each = utils.each; var FSTraversal = module.exports = function(sdk) { // Allow the constructor to be called without the new keyword // Maintains backwards compatibility if(!(this instanceof FSTraversal)){ return new FSTraversal(sdk); } if(!sdk){ throw new Error('FamilySearch SDK is not defined'); } /** * The already initialized FamilySearch SDK * https://github.com/rootsdev/familysearch-javascript-sdk */ this._sdk = sdk; /** * The status of the traversal. * Possible values are ready, running, paused, done. */ this._status = 'ready'; /** * The object of persons we've visited, keyed by id. * Note that the value is the person-with-relationships object returned by the sdk. */ this._visited = {}; /** * The object of person id's we've fetched so far. * Note that we place these in here before calling the API. * It is possible that the API call failed, in which case we * do NOT clean these out. Use visited to see of a node has * been visited successfully. */ this._fetched = {}; /** * The total number of people we've fetched. * Defaults to 1 because we always fetch the root person. */ this._count = 1; /** * Order is a function that calculates weights and thereby determines * the order of traversal. Lower weights are higher priority. */ this._order = orders['distance']; /** * How many people we should visit during the traversal */ this._limit = Infinity; /** * Concurrency for the queue */ this._concurrency = 5; /** * Use an async priority queue to manage concurrency * of outstanding FS API requests */ this._queue = null; /** * All of our registered callbacks. */ this._callbacks = { filter: [], person: [], child: [], children: [], parent: [], parents: [], marriage: [], spouses: [], family: [], relationships: [], error: [], done: [] }; }; /** * Object to store language configs */ FSTraversal._langs = {}; /** * Expose functions to change options */ FSTraversal.prototype.order = function(order) { // Make sure we haven't or are not currently traversing. if(this._status !== 'ready') { throw new Error('You may only set the order before starting a traversal'); } // If order is a string, lookup the matching built-in order function if(utils.isString(order)){ if(orders[order]){ this._order = orders[order]; } else { throw new Error(order + ' is not a valid built-in order.'); } } // If order is a function... else if(utils.isFunction(order)){ this._order = order; } else { throw new Error('Order must be a string or a function'); } // If additional params were passed, wrap them so that they're // passed to the order function if(arguments.length > 1){ var additionalArgs = Array.prototype.slice.call(arguments, 1), originalOrder = this._order; this._order = function(fetchObj){ return originalOrder.apply(this, [fetchObj].concat(additionalArgs)); } } return this; }; /** * Register filters. Allow for built-in by passing a string * or custom by passing in a function, similar to order. * Multiple filters can be registered. */ FSTraversal.prototype.filter = function(filter) { // If filter is a string, lookup the matching built-in filter function if(utils.isString(filter)){ if(filters[filter]){ filter = filters[filter]; } else { throw new Error(filter + ' is not a valid built-in filter.'); } } else if(!utils.isFunction(filter)){ throw new Error('Order must be a string or a function'); } this._registerCallback('filter', filter); return this; }; /** * Set a limit on the number of people to visit */ FSTraversal.prototype.limit = function(num) { if(typeof num !== 'number') { throw new Error('invalid limit'); } this._limit = num; return this; }; /** * Set the concurrency of the queue */ FSTraversal.prototype.concurrency = function(num) { if(typeof num !== 'number') { throw new Error('invalid concurrency'); } if(this._queue){ this._queue.concurrency = num; this._concurrency = num; } else { this._concurrency = num; } return this; }; /** * Pause the traversal */ FSTraversal.prototype.pause = function(){ if(this._status === 'running'){ this._queue.pause(); this._status = 'paused'; } }; /** * Resume a paused traversal */ FSTraversal.prototype.resume = function(){ if(this._status === 'paused'){ this._queue.resume(); this._status = 'running'; } }; /** * End traversal immediately */ FSTraversal.prototype.stop = function(){ if(this._status === 'running' || this._status === 'paused'){ this._status = 'stopped'; this._queue.kill(); } }; /** * Register callbacks */ FSTraversal.prototype.person = function(func) {this._registerCallback('person', func); return this;}; FSTraversal.prototype.child = function(func) {this._registerCallback('child', func); return this;}; FSTraversal.prototype.children = function(func) {this._registerCallback('children', func); return this;}; FSTraversal.prototype.parent = function(func) {this._registerCallback('parent', func); return this;}; FSTraversal.prototype.parents = function(func) {this._registerCallback('parents', func); return this;}; FSTraversal.prototype.marriage = function(func) {this._registerCallback('marriage', func); return this;}; FSTraversal.prototype.spouses = function(func) {this._registerCallback('spouses', func); return this;}; FSTraversal.prototype.family = function(func) {this._registerCallback('family', func); return this;}; FSTraversal.prototype.relationships = function(func) {this._registerCallback('relationships', func); return this;}; FSTraversal.prototype.done = function(func) {this._registerCallback('done', func); return this;}; FSTraversal.prototype.error = function(func) {this._registerCallback('error', func); return this;}; FSTraversal.prototype._registerCallback = function(type, func) { if(typeof func !== 'function') { throw new Error(type+' must register a function'); } if(this._callbacks[type] == undefined) { throw new Error('Unknown type '+ type); } this._callbacks[type].push(func); }; FSTraversal.prototype.status = function() { return this._status; }; FSTraversal.prototype._isStopped = function() { return this._status === 'stopped'; }; /** * Begin the traversal. */ FSTraversal.prototype.start = function() { var self = this; if(arguments.length == 1) { self._traverse(arguments[0]); } else { self._sdk.getCurrentUser().then(function(response){ self._traverse(response.getUser().getPersonId()); }, function(error){ self._call('error', null, error); }); } return self; }; // Alias `traverse` to `start` for backwards compatibility FSTraversal.prototype.traverse = FSTraversal.prototype.start; /** * Internal traversal function */ FSTraversal.prototype._traverse = function(startId) { var self = this; // Make sure a start point was given if(typeof startId === 'undefined'){ throw new Error('Must specify a starting person id'); } // Make sure we haven't or are not currently traversing. if(self._status !== 'ready') { throw new Error('You may only start a traversal when status is ready'); } self._status = 'running'; var fetchStart = self._fetched[startId] = { type: 'root', depth: 0, distance: 0, weight: 0, path: [{ rel: 'start', person_id: startId }] }; fetchStart.weight = self._order(fetchStart); /** * Setup the queue */ self._queue = async.priorityQueue(function(personId, callback){ self._sdk.getPerson(personId).then(function(response) { self._processPerson(response); // Callback is after _processPerson so that the queue.drain function // will get called at the proper time. // TODO: move to before _processPerson and find better way of tracking "the end" of traversal callback(); }, function(error){ self._call('error', personId, error); }); }, self._concurrency); self._queue.push(startId); // Fire done callbacks when the queue drains self._queue.drain = function(){ self._status = 'done'; self._call('done'); }; return self; }; // This was put into a separate file because it's so big FSTraversal.prototype._processPerson = require('./_processPerson'); /** * Takes in a visited person id and returns the path array of format: * [{rel: 'relationship', person: personObject}, ... ] */ FSTraversal.prototype.pathTo = function(id){ if(!this._fetched[id] || !this._visited[id]){ return []; } var fetchPath = this._fetched[id].path, returnPath = []; for(var i = 0; i < fetchPath.length; i++){ returnPath.push({ rel: fetchPath[i].rel, person: this._visited[fetchPath[i].person_id].getPrimaryPerson() }); } return returnPath; }; /** * Returns the weight of a person. Only works for persons that have been fetched. */ FSTraversal.prototype.weight = function(personId){ if(this._fetched[personId]){ return this._fetched[personId].weight; } }; /** * Takes in a visited id and produces a string representing the relationship to the root node. */ FSTraversal.prototype.relationshipTo = function(id, lang) { if(!this._fetched[id]) { return ''; } var path = this.pathTo(id); return this._relationshipTo(path, lang); }; /** * Internal function that takes in a path and returns a human-readable string. * The relationship is calculated by first generating a coded string that * represents the path, then examining the string in chunks of decreasing size * to find the most relevant or shortest way to describe the relationship. */ FSTraversal.prototype._relationshipTo = function(path, lang) { if(!lang){ throw new Error('Language code is required.'); } var relations = [], remainder = '', done = false, relConfig = FSTraversal._langs[lang]; if(!relConfig){ throw new Error('Language ' + lang + ' has not been registered.'); } // Short circuit on base-person special case if(path.length === 1){ return relConfig.base; } var switchStr = switchString(path); while(!done) { var rel = ''; // Find a match for the current portion of the string, if we can for(var i = 0; i < relConfig.patterns.length; i++){ var c = relConfig.patterns[i]; if(c.regex.test(switchStr)){ if(utils.isString(c.rel)){ rel = c.rel; } else if(utils.isFunction(c.rel)){ rel = c.rel(switchStr); } break; } } // If we found a match, update the relationship string // and prepare to examine the remaining portion if(rel) { relations.push(rel); if(remainder) { switchStr = remainder; remainder = ''; } else { done = true; } } // If we didn't find a match, prepare to examine a // smaller portion of the switch string else { // Lengthen the remainder and shorten the switch string remainder = switchStr.substr(-1,1)+remainder; switchStr = switchStr.substr(0,switchStr.length-1); } } return relConfig.join(relations); }; /** * Register a new language. */ FSTraversal.lang = function(config){ if(!config.code){ throw new Error('Missing language code'); } FSTraversal._langs[config.code] = config; // Create regex objects for relConfig. This is done // so that we don't need to generate correct regex // objects in the patterns with leading ^ and // trailing $. This wouldn't be useful if we allowed // regex to only examine portions of a rel string // but we don't allow that. each(config.patterns, function(c){ c.regex = new RegExp('^' + c.pattern + '$'); }); }; FSTraversal.lang(require('../lang/en.js')); FSTraversal.lang(require('../lang/es.js')); /** * Helper function to fire all callbacks of a given category * with the specified arguments. */ FSTraversal.prototype._call = function(category, params){ var self = this, args = []; // Allow args to be an array or individual parameters if(!utils.isArray(params) || arguments.length > 2){ args = []; for(var i = 1; i < arguments.length; i++){ args.push(arguments[i]); } } else if(utils.isArray(params)) { args = params; } else { args = [params]; } each(self._callbacks[category], function(cb){ setTimeout(function() { if(self._isStopped()){ return; } cb.apply(self, args); }); }); };
<filename>secret-service/pkg/model/scope.go package model type Scopes struct { Scopes map[string]Scope `yaml:"scopes"` } type Scope struct { Capabilities map[string]Capability `yaml:"capabilities"` } type Capability struct { Permissions []string `yaml:"permissions"` }
#!/bin/bash <<<<<<< HEAD echo $(htpasswd -nb username mystrongpassword) | sed -e s/\\$/\\$\\$/g > htpasswd ======= echo "$(htpasswd -nb username mystrongpassword)" | sed -e s/\\$/\\$\\$/g >htpasswd >>>>>>> 341259022d27df6d90c63eddec3565008a444b05
<reponame>madhushree14/statsmodels # -*- coding: utf-8 -*- ''' Load Sunspots Data and plot the autocorrelation of the number of sunspots per year. ''' import matplotlib.pyplot as plt import pandas as pd import statsmodels.api as sm dta = sm.datasets.sunspots.load_pandas().data dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008')) del dta["YEAR"] sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40) plt.show()
#!/bin/bash dieharder -d 11 -g 60 -S 603029425
<reponame>IvanKozlov95/ft_select /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* termconfig.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/24 22:54:21 by ivankozlov #+# #+# */ /* Updated: 2019/06/26 21:09:21 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "memory.h" #include "ft_select.h" #include <stdlib.h> #include <unistd.h> static void init_terminal_data(void) { int success; char *termtype; char buf[1024]; termtype = getenv("TERM"); if (termtype == NULL) fatal(EXIT_ERROR, "Specify a terminal type with\ `setenv TERM <yourtype>'.\n"); success = tgetent(buf, termtype); if (success < 0) fatal(EXIT_ERROR, "Could not access the termcap data base.\n"); if (success == 0) fatal(EXIT_ERROR, "Terminal type `%s' is not defined.\n", termtype); } void reset_config(void) { t_info *info; info = get_set_info(); tcsetattr(STDERR_FILENO, TCSANOW, &(info->default_attr)); SETTERMCMD("ve"); SETTERMCMD("te"); } void init_config(void) { t_info *info; init_terminal_data(); info = get_set_info(); tcgetattr(STDERR_FILENO, &(info->default_attr)); ft_memcpy(&(info->attr), &(info->default_attr), sizeof(struct termios)); info->attr.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDERR_FILENO, TCSANOW, &(info->attr)); SETTERMCMD("ti"); SETTERMCMD("vi"); }
def check_triplet_sum(a, b, c): if a + b == c or b + c == a or a + c == b: return True else: return False a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) c = int(input("Enter the third number: ")) if check_triplet_sum(a, b, c): print("Numbers can form a triplet.") else: print("Numbers cannot form a triplet.")
for index, item in enumerate(sequence): if item > 23: sequence[index] = transform(item)
package xyz.meistertobias.rfc; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class UserRepo implements UserRepoRFC { private static List<User> users = new ArrayList<>(); @Override public List<User> getUsers() { return users; } @Override public User getUser(String nickname) { return findUser(nickname).orElse(null); } @Override public void addUser(User user) { if (!users.contains(user)) users.add(user); } @Override public void deleteUser(String nickname) { findUser(nickname).ifPresent(users::remove); } private Optional<User> findUser(String nickname) { return users.stream().filter(user -> user.getNickname().equals(nickname)).findFirst(); } }
def detectLoop(head): nodeSet = set() ptr = head while ptr != None: if ptr in nodeSet: return True nodeSet.add(ptr) ptr = ptr.next return False
<gh_stars>1-10 /* eslint-disable */ /* tslint:disable */ /** * This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from '@stencil/core/internal'; import { PickedFile, } from './components/file-picker/pickedfile'; export namespace Components { interface EvbAccordion { /** * When loaded, open the nth expansion panel. Count starts at 1 */ 'openNth'?: number; 'openPanel': (nth: number) => Promise<void>; } interface EvbButton { /** * Whether or not the button is disabled */ 'disabled': boolean; /** * Invert the coloring of the button */ 'ghost': boolean; /** * The target of the anchor tag */ 'href'?: string; /** * Extra rounded colors */ 'pill': boolean; /** * The type of the button, leave empty in case of a link */ 'type'?: 'submit' | 'button' | 'reset' | 'link' | 'icon'; /** * Button variants to add additional styling */ 'variant'?: 'primary' | 'secondary' | 'danger'; } interface EvbButtonBar { 'align': 'top' | 'center' | 'bottom'; /** * Justify the contents of the buttonbar */ 'justify': 'left' | 'center' | 'right'; } interface EvbColorselect { 'colors': string[]; 'value': string; } interface EvbDonut { 'diameter': number; 'invert': boolean; 'progress': number; 'text': boolean; 'thickness': number; } interface EvbDropzone { /** * A string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. To accept images, video and audio, use: accept="audio/*,video/*,image/*" otherwise provide the correct mimetype, eg: image/png for png images etc */ 'accept': string; } interface EvbExpansionPanel { /** * Where to align the title */ 'justify'?: 'left' | 'right' | 'center'; /** * Whether the panel is open, eg: shows it's content */ 'open': boolean; /** * The textual title of the panel */ 'text': string; 'toggle': (force?: boolean) => Promise<void>; } interface EvbFilepicker { /** * A string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. To accept images, video and audio, use: accept="audio/*,video/*,image/*" otherwise provide the correct mimetype, eg: image/png for png images etc */ 'accept': string; 'handleFiles': (files: FileList) => Promise<void>; /** * Should we show the input type=file? */ 'input': boolean; /** * indicates that the user may choose more than one file */ 'multiple': boolean; } interface EvbFilepreview { 'alt': string; 'caption'?: string; /** * The source (data) url of the image to preview */ 'src': string; } interface EvbFlyout { 'header': string; 'open': boolean; 'toggle': (forceOpen?: boolean) => Promise<void>; } interface EvbFormcontrol { /** * renders childs (eg. label + input) on the same line */ 'vertical': boolean; } interface EvbHeader { 'heading': number | string; } interface EvbIcon { 'name': string; 'size': 'small' | 'medium' | 'large' | 'fit'; } interface EvbList {} interface EvbListItem {} interface EvbProgressbar { /** * The height of the bar in pixels */ 'height': number; /** * Progress percentage */ 'progress': number; /** * Show the progress as text in the progress bar */ 'text': boolean; } interface EvbRange { 'disabled': boolean; 'max': number; 'min': number; 'step': number; 'value': number; } interface EvbToggle { 'labeloff': string; 'labelon': string; 'type': 'default' | 'flat' | 'rotate'; 'value': boolean; } } declare global { interface HTMLEvbAccordionElement extends Components.EvbAccordion, HTMLStencilElement {} var HTMLEvbAccordionElement: { prototype: HTMLEvbAccordionElement; new (): HTMLEvbAccordionElement; }; interface HTMLEvbButtonElement extends Components.EvbButton, HTMLStencilElement {} var HTMLEvbButtonElement: { prototype: HTMLEvbButtonElement; new (): HTMLEvbButtonElement; }; interface HTMLEvbButtonBarElement extends Components.EvbButtonBar, HTMLStencilElement {} var HTMLEvbButtonBarElement: { prototype: HTMLEvbButtonBarElement; new (): HTMLEvbButtonBarElement; }; interface HTMLEvbColorselectElement extends Components.EvbColorselect, HTMLStencilElement {} var HTMLEvbColorselectElement: { prototype: HTMLEvbColorselectElement; new (): HTMLEvbColorselectElement; }; interface HTMLEvbDonutElement extends Components.EvbDonut, HTMLStencilElement {} var HTMLEvbDonutElement: { prototype: HTMLEvbDonutElement; new (): HTMLEvbDonutElement; }; interface HTMLEvbDropzoneElement extends Components.EvbDropzone, HTMLStencilElement {} var HTMLEvbDropzoneElement: { prototype: HTMLEvbDropzoneElement; new (): HTMLEvbDropzoneElement; }; interface HTMLEvbExpansionPanelElement extends Components.EvbExpansionPanel, HTMLStencilElement {} var HTMLEvbExpansionPanelElement: { prototype: HTMLEvbExpansionPanelElement; new (): HTMLEvbExpansionPanelElement; }; interface HTMLEvbFilepickerElement extends Components.EvbFilepicker, HTMLStencilElement {} var HTMLEvbFilepickerElement: { prototype: HTMLEvbFilepickerElement; new (): HTMLEvbFilepickerElement; }; interface HTMLEvbFilepreviewElement extends Components.EvbFilepreview, HTMLStencilElement {} var HTMLEvbFilepreviewElement: { prototype: HTMLEvbFilepreviewElement; new (): HTMLEvbFilepreviewElement; }; interface HTMLEvbFlyoutElement extends Components.EvbFlyout, HTMLStencilElement {} var HTMLEvbFlyoutElement: { prototype: HTMLEvbFlyoutElement; new (): HTMLEvbFlyoutElement; }; interface HTMLEvbFormcontrolElement extends Components.EvbFormcontrol, HTMLStencilElement {} var HTMLEvbFormcontrolElement: { prototype: HTMLEvbFormcontrolElement; new (): HTMLEvbFormcontrolElement; }; interface HTMLEvbHeaderElement extends Components.EvbHeader, HTMLStencilElement {} var HTMLEvbHeaderElement: { prototype: HTMLEvbHeaderElement; new (): HTMLEvbHeaderElement; }; interface HTMLEvbIconElement extends Components.EvbIcon, HTMLStencilElement {} var HTMLEvbIconElement: { prototype: HTMLEvbIconElement; new (): HTMLEvbIconElement; }; interface HTMLEvbListElement extends Components.EvbList, HTMLStencilElement {} var HTMLEvbListElement: { prototype: HTMLEvbListElement; new (): HTMLEvbListElement; }; interface HTMLEvbListItemElement extends Components.EvbListItem, HTMLStencilElement {} var HTMLEvbListItemElement: { prototype: HTMLEvbListItemElement; new (): HTMLEvbListItemElement; }; interface HTMLEvbProgressbarElement extends Components.EvbProgressbar, HTMLStencilElement {} var HTMLEvbProgressbarElement: { prototype: HTMLEvbProgressbarElement; new (): HTMLEvbProgressbarElement; }; interface HTMLEvbRangeElement extends Components.EvbRange, HTMLStencilElement {} var HTMLEvbRangeElement: { prototype: HTMLEvbRangeElement; new (): HTMLEvbRangeElement; }; interface HTMLEvbToggleElement extends Components.EvbToggle, HTMLStencilElement {} var HTMLEvbToggleElement: { prototype: HTMLEvbToggleElement; new (): HTMLEvbToggleElement; }; interface HTMLElementTagNameMap { 'evb-accordion': HTMLEvbAccordionElement; 'evb-button': HTMLEvbButtonElement; 'evb-button-bar': HTMLEvbButtonBarElement; 'evb-colorselect': HTMLEvbColorselectElement; 'evb-donut': HTMLEvbDonutElement; 'evb-dropzone': HTMLEvbDropzoneElement; 'evb-expansion-panel': HTMLEvbExpansionPanelElement; 'evb-filepicker': HTMLEvbFilepickerElement; 'evb-filepreview': HTMLEvbFilepreviewElement; 'evb-flyout': HTMLEvbFlyoutElement; 'evb-formcontrol': HTMLEvbFormcontrolElement; 'evb-header': HTMLEvbHeaderElement; 'evb-icon': HTMLEvbIconElement; 'evb-list': HTMLEvbListElement; 'evb-list-item': HTMLEvbListItemElement; 'evb-progressbar': HTMLEvbProgressbarElement; 'evb-range': HTMLEvbRangeElement; 'evb-toggle': HTMLEvbToggleElement; } } declare namespace LocalJSX { interface EvbAccordion { /** * When loaded, open the nth expansion panel. Count starts at 1 */ 'openNth'?: number; } interface EvbButton { /** * Whether or not the button is disabled */ 'disabled'?: boolean; /** * Invert the coloring of the button */ 'ghost'?: boolean; /** * The target of the anchor tag */ 'href'?: string; /** * Blur event */ 'onEvbBlur'?: (event: CustomEvent<void>) => void; /** * Focus event */ 'onEvbFocus'?: (event: CustomEvent<void>) => void; /** * Extra rounded colors */ 'pill'?: boolean; /** * The type of the button, leave empty in case of a link */ 'type'?: 'submit' | 'button' | 'reset' | 'link' | 'icon'; /** * Button variants to add additional styling */ 'variant'?: 'primary' | 'secondary' | 'danger'; } interface EvbButtonBar { 'align'?: 'top' | 'center' | 'bottom'; /** * Justify the contents of the buttonbar */ 'justify'?: 'left' | 'center' | 'right'; } interface EvbColorselect { 'colors'?: string[]; 'onEvbBlur'?: (event: CustomEvent<void>) => void; 'onEvbChange'?: (event: CustomEvent<string>) => void; 'onEvbInput'?: (event: CustomEvent<string>) => void; 'value'?: string; } interface EvbDonut { 'diameter'?: number; 'invert'?: boolean; 'progress'?: number; 'text'?: boolean; 'thickness'?: number; } interface EvbDropzone { /** * A string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. To accept images, video and audio, use: accept="audio/*,video/*,image/*" otherwise provide the correct mimetype, eg: image/png for png images etc */ 'accept'?: string; /** * Fired after a file has been picked§ */ 'onDropped'?: (event: CustomEvent<PickedFile>) => void; } interface EvbExpansionPanel { /** * Where to align the title */ 'justify'?: 'left' | 'right' | 'center'; /** * Emits when the panel is closed */ 'onClosed'?: (event: CustomEvent<void>) => void; /** * Emits when the panel is opened */ 'onOpened'?: (event: CustomEvent<void>) => void; /** * Whether the panel is open, eg: shows it's content */ 'open'?: boolean; /** * The textual title of the panel */ 'text'?: string; } interface EvbFilepicker { /** * A string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. To accept images, video and audio, use: accept="audio/*,video/*,image/*" otherwise provide the correct mimetype, eg: image/png for png images etc */ 'accept'?: string; /** * Should we show the input type=file? */ 'input'?: boolean; /** * indicates that the user may choose more than one file */ 'multiple'?: boolean; /** * Emits the dataurl for the image */ 'onPick'?: (event: CustomEvent<PickedFile>) => void; } interface EvbFilepreview { 'alt'?: string; 'caption'?: string; /** * The source (data) url of the image to preview */ 'src'?: string; } interface EvbFlyout { 'header'?: string; 'onClose'?: (event: CustomEvent<void>) => void; 'onOpen'?: (event: CustomEvent<void>) => void; 'open'?: boolean; } interface EvbFormcontrol { /** * renders childs (eg. label + input) on the same line */ 'vertical'?: boolean; } interface EvbHeader { 'heading': number | string; } interface EvbIcon { 'name'?: string; 'size'?: 'small' | 'medium' | 'large' | 'fit'; } interface EvbList {} interface EvbListItem {} interface EvbProgressbar { /** * The height of the bar in pixels */ 'height'?: number; 'onCompleted'?: (event: CustomEvent<void>) => void; /** * Progress percentage */ 'progress'?: number; /** * Show the progress as text in the progress bar */ 'text'?: boolean; } interface EvbRange { 'disabled'?: boolean; 'max'?: number; 'min'?: number; 'onEvbBlur'?: (event: CustomEvent<void>) => void; 'onEvbChange'?: (event: CustomEvent<number>) => void; 'onEvbFocus'?: (event: CustomEvent<void>) => void; 'onEvbInput'?: (event: CustomEvent<number>) => void; 'step'?: number; 'value'?: number; } interface EvbToggle { 'labeloff'?: string; 'labelon'?: string; 'onEvbBlur'?: (event: CustomEvent<void>) => void; 'onEvbChange'?: (event: CustomEvent<boolean>) => void; 'onEvbFocus'?: (event: CustomEvent<void>) => void; 'onEvbInput'?: (event: CustomEvent<boolean>) => void; 'type'?: 'default' | 'flat' | 'rotate'; 'value'?: boolean; } interface IntrinsicElements { 'evb-accordion': EvbAccordion; 'evb-button': EvbButton; 'evb-button-bar': EvbButtonBar; 'evb-colorselect': EvbColorselect; 'evb-donut': EvbDonut; 'evb-dropzone': EvbDropzone; 'evb-expansion-panel': EvbExpansionPanel; 'evb-filepicker': EvbFilepicker; 'evb-filepreview': EvbFilepreview; 'evb-flyout': EvbFlyout; 'evb-formcontrol': EvbFormcontrol; 'evb-header': EvbHeader; 'evb-icon': EvbIcon; 'evb-list': EvbList; 'evb-list-item': EvbListItem; 'evb-progressbar': EvbProgressbar; 'evb-range': EvbRange; 'evb-toggle': EvbToggle; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { 'evb-accordion': LocalJSX.EvbAccordion & JSXBase.HTMLAttributes<HTMLEvbAccordionElement>; 'evb-button': LocalJSX.EvbButton & JSXBase.HTMLAttributes<HTMLEvbButtonElement>; 'evb-button-bar': LocalJSX.EvbButtonBar & JSXBase.HTMLAttributes<HTMLEvbButtonBarElement>; 'evb-colorselect': LocalJSX.EvbColorselect & JSXBase.HTMLAttributes<HTMLEvbColorselectElement>; 'evb-donut': LocalJSX.EvbDonut & JSXBase.HTMLAttributes<HTMLEvbDonutElement>; 'evb-dropzone': LocalJSX.EvbDropzone & JSXBase.HTMLAttributes<HTMLEvbDropzoneElement>; 'evb-expansion-panel': LocalJSX.EvbExpansionPanel & JSXBase.HTMLAttributes<HTMLEvbExpansionPanelElement>; 'evb-filepicker': LocalJSX.EvbFilepicker & JSXBase.HTMLAttributes<HTMLEvbFilepickerElement>; 'evb-filepreview': LocalJSX.EvbFilepreview & JSXBase.HTMLAttributes<HTMLEvbFilepreviewElement>; 'evb-flyout': LocalJSX.EvbFlyout & JSXBase.HTMLAttributes<HTMLEvbFlyoutElement>; 'evb-formcontrol': LocalJSX.EvbFormcontrol & JSXBase.HTMLAttributes<HTMLEvbFormcontrolElement>; 'evb-header': LocalJSX.EvbHeader & JSXBase.HTMLAttributes<HTMLEvbHeaderElement>; 'evb-icon': LocalJSX.EvbIcon & JSXBase.HTMLAttributes<HTMLEvbIconElement>; 'evb-list': LocalJSX.EvbList & JSXBase.HTMLAttributes<HTMLEvbListElement>; 'evb-list-item': LocalJSX.EvbListItem & JSXBase.HTMLAttributes<HTMLEvbListItemElement>; 'evb-progressbar': LocalJSX.EvbProgressbar & JSXBase.HTMLAttributes<HTMLEvbProgressbarElement>; 'evb-range': LocalJSX.EvbRange & JSXBase.HTMLAttributes<HTMLEvbRangeElement>; 'evb-toggle': LocalJSX.EvbToggle & JSXBase.HTMLAttributes<HTMLEvbToggleElement>; } } }
import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4]}) df['c'] = df['a'] + df['b']
<reponame>YMxiaobei/iconv-lite-ts2 export let cp949 = [ ["0","\u0000",127], ["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], ["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], ["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], ["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], ["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], ["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], ["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], ["8361","긝",18,"긲긳긵긶긹긻긼"], ["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], ["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], ["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], ["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], ["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], ["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], ["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], ["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], ["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], ["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], ["8741","놞",9,"놩",15], ["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], ["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], ["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], ["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], ["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], ["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], ["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], ["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], ["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], ["8a61","둧",4,"둭",18,"뒁뒂"], ["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], ["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], ["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], ["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], ["8c41","똀",15,"똒똓똕똖똗똙",4], ["8c61","똞",6,"똦",5,"똭",6,"똵",5], ["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], ["8d41","뛃",16,"뛕",8], ["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], ["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], ["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], ["8e61","럂",4,"럈럊",19], ["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], ["8f41","뢅",7,"뢎",17], ["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], ["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], ["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], ["9061","륾",5,"릆릈릋릌릏",15], ["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], ["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], ["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], ["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], ["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], ["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], ["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], ["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], ["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], ["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], ["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], ["9461","봞",5,"봥",6,"봭",12], ["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], ["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], ["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], ["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], ["9641","뺸",23,"뻒뻓"], ["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], ["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], ["9741","뾃",16,"뾕",8], ["9761","뾞",17,"뾱",7], ["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], ["9841","쁀",16,"쁒",5,"쁙쁚쁛"], ["9861","쁝쁞쁟쁡",6,"쁪",15], ["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], ["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], ["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], ["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], ["9a41","숤숥숦숧숪숬숮숰숳숵",16], ["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], ["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], ["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], ["9b61","쌳",17,"썆",7], ["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], ["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], ["9c61","쏿",8,"쐉",6,"쐑",9], ["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], ["9d41","쒪",13,"쒹쒺쒻쒽",8], ["9d61","쓆",25], ["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], ["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], ["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], ["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], ["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], ["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], ["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], ["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], ["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], ["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], ["a141","좥좦좧좩",18,"좾좿죀죁"], ["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], ["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], ["a241","줐줒",5,"줙",18], ["a261","줭",6,"줵",18], ["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], ["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], ["a361","즑",6,"즚즜즞",16], ["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], ["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], ["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], ["a481","쨦쨧쨨쨪",28,"ㄱ",93], ["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], ["a561","쩫",17,"쩾",5,"쪅쪆"], ["a581","쪇",16,"쪙",14,"ⅰ",9], ["a5b0","Ⅰ",9], ["a5c1","Α",16,"Σ",6], ["a5e1","α",16,"σ",6], ["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], ["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], ["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], ["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], ["a761","쬪",22,"쭂쭃쭄"], ["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], ["a841","쭭",10,"쭺",14], ["a861","쮉",18,"쮝",6], ["a881","쮤",19,"쮹",11,"ÆÐªĦ"], ["a8a6","IJ"], ["a8a8","ĿŁØŒºÞŦŊ"], ["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], ["a941","쯅",14,"쯕",10], ["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], ["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], ["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], ["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], ["aa81","챳챴챶",29,"ぁ",82], ["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], ["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], ["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], ["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], ["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], ["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], ["acd1","а",5,"ёж",25], ["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], ["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], ["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], ["ae41","췆",5,"췍췎췏췑",16], ["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], ["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], ["af41","츬츭츮츯츲츴츶",19], ["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], ["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], ["b041","캚",5,"캢캦",5,"캮",12], ["b061","캻",5,"컂",19], ["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], ["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], ["b161","켥",6,"켮켲",5,"켹",11], ["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], ["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], ["b261","쾎",18,"쾢",5,"쾩"], ["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], ["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], ["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], ["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], ["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], ["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], ["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], ["b541","킕",14,"킦킧킩킪킫킭",5], ["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], ["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], ["b641","턅",7,"턎",17], ["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], ["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], ["b741","텮",13,"텽",6,"톅톆톇톉톊"], ["b761","톋",20,"톢톣톥톦톧"], ["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], ["b841","퇐",7,"퇙",17], ["b861","퇫",8,"퇵퇶퇷퇹",13], ["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], ["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], ["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], ["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], ["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], ["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], ["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], ["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], ["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], ["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], ["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], ["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], ["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], ["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], ["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], ["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], ["be41","퐸",7,"푁푂푃푅",14], ["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], ["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], ["bf41","풞",10,"풪",14], ["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], ["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], ["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], ["c061","픞",25], ["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], ["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], ["c161","햌햍햎햏햑",19,"햦햧"], ["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], ["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], ["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], ["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], ["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], ["c361","홢",4,"홨홪",5,"홲홳홵",11], ["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], ["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], ["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], ["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], ["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], ["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], ["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], ["c641","힍힎힏힑",6,"힚힜힞",5], ["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], ["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], ["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], ["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], ["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], ["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], ["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], ["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], ["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], ["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], ["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], ["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], ["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], ["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], ["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], ["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], ["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], ["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], ["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], ["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], ["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], ["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], ["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], ["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], ["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], ["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], ["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], ["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], ["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], ["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], ["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], ["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], ["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], ["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], ["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], ["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], ["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], ["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], ["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], ["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], ["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], ["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], ["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], ["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], ["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], ["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], ["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], ["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], ["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], ["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], ["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], ["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], ["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], ["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], ["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] ]
function generateReplay() { for (let i=0, n=promptData.length; i<n; i++) { let item = promptData[i]; let prompt = item.prompt; let name = item.name; let isText = typeof prompt === 'string'; let elementName = isText ? 'showTextPrompt' : 'showCanvasPrompt'; // the overall one container for all content let replayContainerId = values.dom.CONTAINER_ID_PREFIX + values.dom.replay.attributes.id; // the name of the user who created the prompt let nameElementId = createElement('replayName', replayContainerId, i); let nameElement = document.getElementById(nameElementId); nameElement.textContent = name + values.text[isText ? 'TEXT_PROMPT_SUFFIX' : 'CANVAS_PROMPT_SUFFIX']; // the prompt data element let promptElementId = createElement(elementName, replayContainerId, i); // adds prompt data to element if (isText) { document.getElementById(promptElementId).textContent = prompt; } else { showDrawing(prompt, false, promptElementId); } } }
<reponame>Ravaelles/Elder function EngineView(width, height) { this.width = -1; this.height = -1; // ========================================================================= this.constructor = function (width, height) { this.width = width; this.height = height; }; this.constructor(width, height); // ========================================================================= this.getType = function () { return this.type; }; }
#!/bin/bash methods="BULK_COPY" grep_exp="^icc|^upcc|^UPCR|^GASNET" # veclen=100000 # showvec=no veclen=10 showvec=yes # blocksizes="1 VEC_LEN/NT \(VEC_LEN/NT\)+1" # threads="20 23" # blocksizes="1 VEC_LEN/NT" blocksizes="1" threads=2 function run { make clean > /dev/null; echo "=== $m threads=$1 BS=$2 ===" make run-matrix-addition UPC_THREADS=$1 VEC_LEN=$veclen \ SHOW_VEC=$showvec DO_CHECK=yes METHOD=$m BS=$2 | grep -vPe $grep_exp echo "" } for m in $methods do for bs in $blocksizes do for t in $threads do run $t $bs done done done
class ResourceManager: def __init__(self): self._producer = "" self._history = [] def register_producer(self, access, timestamp): self._producer = "" cause = access.get_cause() if cause is not None and cause.task is not None: self._producer = "task " + cause.task.task_id def get_producer(self): return self._producer
UUID="${UUID:-"a760e87e-e23a-4ea6-81f9-c4e29052db27"}" source global_settings echo -e "\n=========================" echo "Get connection" ${CURL_APP} --location \ --request GET "${URL}/connection?uuid=${UUID}" \ -b cookie --insecure \ | ${JQ_APP} echo -e "\n"
Yes, the easiest way to find the minumum value in a tree is to use a Breadth-first search to traverse the tree and find the node with the smallest value. This will ensure that we traverse the tree in a depth-first manner, which would enable us to find the minimum value quickly. Additionally, there is an optimized method called a Heap Sort which can be used to find the minimum value in O(n log n) time.
import time from pytorch_lightning.callbacks import Callback from pytorch_lightning.utilities import rank_zero_info __all__ = ['TimeCallback'] class TimeCallback(Callback): def __init__( self, timelimit_in_min = 1320, ##22h 1320 verbose = True, max_epoch_count = -1 ): super().__init__() self.verbose = verbose self.timelimit_in_min = timelimit_in_min self.epoch = -1 self.time_buffer = time.time() self.training_start_epoch = 0 self.max_epoch_count = max_epoch_count if self.verbose: rank_zero_info(f'TimeLimitCallback is set to {self.timelimit_in_min}min') def on_validation_end(self, trainer, pl_module): if trainer.running_sanity_check: return self._run_early_stopping_check(trainer, pl_module) def on_validation_epoch_end(self, trainer, pl_module): # trainer.callback_metrics['task_count/dataloader_idx_0'] if trainer.running_sanity_check: return def on_train_start(self, trainer, pl_module): """Called when the train begins.""" # set task start time self.time_buffer = time.time() self.training_start_epoch = pl_module.current_epoch def _run_early_stopping_check(self, trainer, pl_module): should_stop = False if self.epoch != trainer.current_epoch: self.epoch = trainer.current_epoch # check time if ((time.time() - self.time_buffer)/60 > self.timelimit_in_min or ( self.max_epoch_count != -1 and self.epoch - self.training_start_epoch > self.max_epoch_count )): # time limit reached should_stop = True rank_zero_info('STOPPED due to timelimit reached!') if bool(should_stop): self.stopped_epoch = trainer.current_epoch trainer.should_stop = True # stop every ddp process if any world process decides to stop trainer.should_stop = trainer.training_type_plugin.reduce_boolean_decision(trainer.should_stop) if self.verbose: string = 'Callback State\n' string += f'Trainger should stop: {should_stop} ' + str(int( (time.time() - self.time_buffer)/60 )) rank_zero_info(string) else: if self.verbose: rank_zero_info('Visited twice at same epoch')
<reponame>huangbin082/Bin package com.leetcode; public class Solution_50 { public double myPow(double x, int n) { if (n == 0) return 1d; if (x == 0) return 0; if (n > 0) { return pow(x, n); } else { return 1d / pow(x, -n); } } private double pow(double x, int n) { if (n == 0) { return 1.0; } if (n == 1) { return x; } double d = pow(x, n / 2); return n % 2 != 0 ? d * d * x : d * d; } }
module.exports = require('rubik-main/.eslintrc.js');
package cmd import ( "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/release" ) type Status struct { statusClient *action.Status releaseName string } func NewStatus(cfg *action.Configuration, releaseName string) (*Status, error) { client := action.NewStatus(cfg) debug("We use releaseName: \"%s\" to find out status", releaseName) return &Status{ statusClient: client, releaseName: releaseName, }, nil } func (status *Status) InfoStatus() (*release.Release, error) { results, err := status.statusClient.Run(status.releaseName) return results, err }
import { axiosWithAuth } from '../../utils/axiosWithAuth'; import axios from 'axios' export const TUTORIALS_GET_START = 'TUTORIALS_GET_START' export const TUTORIALS_GET_SUCCESS = 'TUTORIALS_GET_SUCCESS' export const TUTORIALS_GET_FAILURE = 'TUTORIALS_GET_FAILURE' export const TUTORIAL_GET_START = 'TUTORIAL_GET_START' export const TUTORIAL_GET_SUCCESS = 'TUTORIAL_GET_SUCCESS' export const TUTORIAL_GET_FAILURE = 'TUTORIAL_GET_FAILURE' export const TUTORIAL_POST_START = 'TUTORIAL_POST_START' export const TUTORIAL_POST_SUCCESS = 'TUTORIAL_POST_SUCCESS' export const TUTORIAL_POST_FAILURE = 'TUTORIAL_POST_FAILURE' export const TUTORIAL_PUT_START = 'TUTORIAL_PUT_START' export const TUTORIAL_PUT_SUCCESS = 'TUTORIAL_PUT_SUCCESS' export const TUTORIAL_PUT_FAILURE = 'TUTORIAL_PUT_FAILURE' export const TUTORIAL_DELETE_START = 'TUTORIAL_DELETE_START' export const TUTORIAL_DELETE_SUCCESS = 'TUTORIAL_DELETE_SUCCESS' export const TUTORIAL_DELETE_FAILURE = 'TUTORIAL_DELETE_FAILURE' export const TUTORIAL_CREATE_DIRECTIONS = 'TUTORIAL_CREATE_DIRECTIONS' const proxyurl = "https://cors-anywhere.herokuapp.com/"; const url = 'https://cors-anywhere.herokuapp.com/http://how2s.herokuapp.com/api/tutorials'; // site that doesn't send Access-Control-* export const getTutorials = value => (dispatch) => { dispatch({ type: TUTORIALS_GET_START }); axiosWithAuth() .get(`/tutorials`) .then((res) => { console.log({res}) dispatch({ type: TUTORIALS_GET_SUCCESS, payload:res.data }) //JSON.stringify(res.data.payload) // window.location.href= '/tutorialList' }) .catch((err) => { dispatch({ type: TUTORIALS_GET_FAILURE, payload: err, }) }) } export const postTutorial = (value) => (dispatch) => { console.log({value}) dispatch({ type: TUTORIAL_POST_START, payload: value }); axiosWithAuth() .post('/tutorials',value) .then( res => { console.log({res}) dispatch({ type: TUTORIAL_POST_SUCCESS, payload:res.data }) // //JSON.stringify(res.data.payload) //props.history.push() }) .catch((err) => { dispatch({ type: TUTORIAL_POST_FAILURE, payload: err, }) }) } export const putTutorial = (id,formState) => (dispatch) => { dispatch({ type: TUTORIAL_PUT_START, payload:formState}); axiosWithAuth() .put(`/tutorials/${id}`,formState) .then((res) => { dispatch({ type: TUTORIAL_PUT_SUCCESS, payload:res.data }) //JSON.stringify(res.data.payload) console.log({res}) //props.history.push() }) .catch((err) => { dispatch({ type: TUTORIAL_PUT_FAILURE, payload: err, }) }) } export const deleteTutorial = (value) => (dispatch) => { dispatch({ type: TUTORIAL_DELETE_START, payload: value }); axiosWithAuth() .delete(`/tutorials/${value}`) .then((res) => { dispatch({ type: TUTORIAL_DELETE_SUCCESS, payload:value }) //JSON.stringify(res.data.payload) console.log({res}) //props.history.push() }) .catch((err) => { dispatch({ type: TUTORIAL_DELETE_FAILURE, payload: err, }) }) } export const getTutorial = ({id,iId}) => (dispatch) => { dispatch({ type: TUTORIAL_GET_START, }); axiosWithAuth() .get(`/tutorials/${id}`,iId) .then(res => { console.log({res}) dispatch({ type: TUTORIAL_GET_SUCCESS, payload:res.data }) //JSON.stringify(res.data.payload) // window.location.href= '/tutorialList' }) .catch((err) => { dispatch({ type: TUTORIAL_GET_FAILURE, payload: err, }) }) } export const createTutorialDirections = (value) => (dispatch) => { console.log({value}) dispatch( { type: TUTORIAL_CREATE_DIRECTIONS, payload: value}) }
<reponame>infiniteoo/night_show_producer<gh_stars>0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package producerdemo; /** * * @author troy */ public class LogElement { private String artistName; private String songTitle; private String introTime; private String outroTime; private String totalTime; private String fileName; public LogElement(String artist, String title, String intro, String outro, String total, String file) { this.artistName = artist; this.songTitle = title; this.introTime = intro; this.outroTime = outro; this.totalTime = total; this.fileName = file; } public String getArtistName() { return this.artistName; } public String getSongTitle() { return this.songTitle; } public String getIntroTime() { return this.introTime; } public String getTotalTime() { return this.totalTime; } public String getFileName() { return this.fileName; } public String getOutroTime() { return this.outroTime; } }
<filename>blendedbackground/src/test/java/com/alxgrk/blendedbackground/util/UserDefinedColorTest.java<gh_stars>10-100 package com.alxgrk.blendedbackground.util; import static org.mockito.Mockito.*; import android.content.res.TypedArray; import android.graphics.Color; import com.alxgrk.blendedbackground.R; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import static org.junit.Assert.*; public class UserDefinedColorTest { private static final int USER_RES = R.styleable.BlendedBackgroundLayout_invert; private static final int USER_COLOR = Color.RED; private TypedArray mockArray; @Before public void setUp() throws Exception { mockArray = mock(TypedArray.class); } @Test public void isDefined_true() throws Exception { when(mockArray.hasValue(anyInt())).thenReturn(true); when(mockArray.getColor(anyInt(), anyInt())).thenReturn(USER_COLOR); UserDefinedColor uut = new UserDefinedColor(mockArray, USER_RES); boolean actualDefined = uut.isDefined(); int actualColor = uut.getColor(); assertEquals(true, actualDefined); assertEquals(USER_COLOR, actualColor); } @Test public void isDefined_false() throws Exception { when(mockArray.hasValue(anyInt())).thenReturn(false); UserDefinedColor uut = new UserDefinedColor(mockArray, USER_RES); boolean actualDefined = uut.isDefined(); Integer actualColor = uut.getColor(); assertEquals(false, actualDefined); assertNull(actualColor); } }
ln -sf $PWD/nginx/nginx.proxy.conf ~/homebrew/etc/nginx/servers/betchain.conf ln -sf $PWD/supervisor/dev/* ~/homebrew/etc/supervisor.d/
<reponame>zonesgame/StendhalArcClient /* $Id: NIONetworkServerManager.java,v 1.46 2010/11/25 08:25:03 martinfuchs Exp $ */ /*************************************************************************** * (C) Copyright 2003 - Marauroa * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package marauroa.server.net; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import marauroa.common.Log4J; import marauroa.common.net.Channel; import marauroa.common.net.ConnectionManager; import marauroa.common.net.message.Message; import marauroa.server.net.nio.NIONetworkConnectionManager; import marauroa.server.net.validator.ConnectionValidator; /** * This is the implementation of a worker that sends messages, receives them, ... * This class also handles validation of connection and disconnection events * * @author miguel * */ public final class NetworkServerManager implements IServerManager, INetworkServerManager { /** the logger instance. */ private static final marauroa.common.Logger logger = Log4J .getLogger(NetworkServerManager.class); /** We store the server for sending stuff. */ private final List<ConnectionManager> connectionManagers; /** A List of Message objects: List<Message> */ private final BlockingQueue<Message> messages; /** checks if the ip-address is banned */ private final ConnectionValidator connectionValidator; /** A list of the listeners to the onDisconnect event. */ private final List<IDisconnectedListener> listeners; /** A mapping from internal channels to Channels */ private final Map<Object, Channel> channels; /** * Constructor * * @throws IOException * if there any exception when starting the socket server. */ public NetworkServerManager() throws IOException { // init the packet validator (which can now only check if the address is banned) connectionValidator = new ConnectionValidator(); messages = new LinkedBlockingQueue<Message>(); channels = Collections.synchronizedMap(new HashMap<Object, Channel>()); listeners = new LinkedList<IDisconnectedListener>(); connectionManagers = new LinkedList<ConnectionManager>(); logger.debug("NetworkServerManager started successfully"); NIONetworkConnectionManager nio = new NIONetworkConnectionManager(this); nio.start(); connectionManagers.add(nio); } public void start() { // do nothing } /** * Associate this object with a server. This model a master-slave approach * for managing network messages. * * @param server * the master server. */ public void addServer(ConnectionManager server) { this.connectionManagers.add(server); } /** * This method notifies the thread to finish the execution */ public void finish() { logger.debug("shutting down NetworkServerManager"); connectionValidator.finish(); for (ConnectionManager server : connectionManagers) { server.finish(); } boolean waiting; do { waiting = false; for (ConnectionManager server : connectionManagers) { if (!server.isFinished()) { waiting = true; break; } } Thread.yield(); } while (waiting); logger.debug("NetworkServerManager is down"); } /** * This method blocks until a message is available * * @return a Message */ public Message getMessage() { try { return messages.take(); } catch (InterruptedException e) { /* If interrupted while waiting we just return null */ return null; } } /** * This method add a message to be delivered to the client the message is * pointed to. * * @param msg * the message to be delivered. */ public void sendMessage(Message msg) { if (logger.isDebugEnabled()) { logger.debug("send message(type=" + msg.getType() + ") from " + msg.getClientID() + " full [" + msg + "]"); } Channel channel = msg.getChannel(); if (msg.requiresPerception()) { channel.setWaitingForPerception(true); } channel.getConnectionManager().send(channel.getInternalChannel(), msg, channel.isWaitingForPerception()); if (msg.isPerception()) { channel.setWaitingForPerception(false); } } /** * This method disconnect a socket. * * @param channel * the socket channel to close */ public void disconnectClient(Channel channel) { try { channel.getConnectionManager().close(channel.getInternalChannel()); } catch (Exception e) { logger.error("Unable to disconnect a client " + channel.getInetAddress(), e); } } /** * Returns a instance of the connection validator * {@link ConnectionValidator} so that other layers can manipulate it for * banning IP. * * @return the Connection validator instance */ public ConnectionValidator getValidator() { return connectionValidator; } /** * Register a listener for disconnection events. * * @param listener * a listener for disconnection events. */ public void registerDisconnectedListener(IDisconnectedListener listener) { this.listeners.add(listener); } /** * gets the channel associated with an internalChannel * * @param internalChannel internel channel * @return Channel */ public Channel getChannel(Object internalChannel) { return channels.get(internalChannel); } // // IServerManager // /** * handles a connection from a client */ public Channel onConnect(ConnectionManager connectionManager, InetSocketAddress address, Object internalChannel) { if (connectionValidator.checkBanned(address.getAddress())) { logger.debug("Reject connection from banned IP: " + address); return null; } Channel channel = new Channel(connectionManager, address, internalChannel); this.channels.put(internalChannel, channel); return channel; } /** * Removes stored parts of message for this channel at the decoder. * * @param internalChannel * the channel to clear */ public void onDisconnect(ConnectionManager server, Object internalChannel) { Channel channel = channels.get(internalChannel); if (channel == null) { logger.warn("Cannot disconnect internalChannel " + internalChannel + " because it is unknown. (Happens on connection by a banned ip-address)"); return; } for (IDisconnectedListener listener : listeners) { listener.onDisconnect(channel); } channels.remove(internalChannel); } /** * This method is called when data is received from a socket channel * * @param server NioServer * @param internalChannel internal channel object * @param msg a Message */ public void onMessage(ConnectionManager server, Object internalChannel, Message msg) { Channel channel = channels.get(internalChannel); if (channel == null) { logger.warn(("Ignring message from unknown channel: " + msg + " from" + internalChannel)); return; } msg.setChannel(channel); messages.add(msg); } }
const assert = require("assert"); const config = require("../config"); const ripe = require("../../../src/js"); describe("Logic", function() { this.timeout(config.TEST_TIMEOUT); describe("#parseEngraving()", async function() { it("should be able to parse a single engraving value", async () => { let result; const properties = [ { name: "gold", type: "material" }, { name: "silver", type: "material" }, { name: "arial", type: "font" }, { name: "opensans", type: "font" } ]; const instance = await new ripe.Ripe({ init: false }); result = instance.parseEngraving("gold.opensans", properties); assert.deepStrictEqual(result, { values: [ { name: "gold", type: "material" }, { name: "opensans", type: "font" } ], valuesM: { material: "gold", font: "opensans" } }); result = instance.parseEngraving("opensans.gold", properties); assert.deepStrictEqual(result, { values: [ { name: "gold", type: "material" }, { name: "opensans", type: "font" } ], valuesM: { material: "gold", font: "opensans" } }); }); }); describe("#normalizeEngraving()", async function() { it("should be able to normalize an engraving value", async () => { let result; const properties = [ { name: "gold", type: "material" }, { name: "silver", type: "material" }, { name: "arial", type: "font" }, { name: "opensans", type: "font" } ]; const instance = await new ripe.Ripe({ init: false }); result = instance.normalizeEngraving("gold.opensans", properties); assert.strictEqual(result, "gold:material.opensans:font"); result = instance.normalizeEngraving("opensans.gold", properties); assert.strictEqual(result, "gold:material.opensans:font"); }); }); });
list1 = [1, 2, 3] list2 = [4, 5, 6] def addLists(list1, list2): result = [] for i in range(0, len(list1)): result.append(list1[i] + list2[i]) return result print(addLists(list1, list2))
<filename>Windows/Agora-Media-Source-Windows/AgoraMediaSource/AGComboBox.h #pragma once #include <afxtempl.h> #define WM_AGCBXNOTIFY_SELCHANGE WM_USER+ class CAGComboBox; // CAGComboBox class CAGComboBoxList : public CWnd { DECLARE_DYNAMIC(CAGComboBoxList) public: CAGComboBoxList(); virtual ~CAGComboBoxList(); virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, CAGComboBox *pAGComboBox, UINT nID); int GetCount() const; int GetCurSel() const; DWORD_PTR GetItemData(int nIndex) const; void GetText(int nIndex, CString& rString) const; int SetItemData(int nIndex, DWORD_PTR dwItemData); int AddString(LPCTSTR lpszString); int InsertString(int nIndex, LPCTSTR lpszString); int SetCurSel(int nSelect); int DeleteString(int nIndex); void ResetContent(); void SetFont(CFont* pFont, BOOL bRedraw = TRUE); void SetItemHeight(int nItemHeight); int GetItemHeight() const; protected: afx_msg void OnPaint(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); DECLARE_MESSAGE_MAP() protected: void DrawCanvas(CDC *lpDC); // the resource to draw the control private: CImageList m_imgSel; CPen m_penBorder; CFont *m_lpWndFont; COLORREF m_crBack; COLORREF m_crBorder; COLORREF m_crText; COLORREF m_crTextHot; // the controls private: CAGComboBox *m_lpComboBox; // private data private: CStringArray m_arrItemString; CArray<DWORD_PTR> m_arrItemPtrData; int m_nItemCount; int m_nCurSel; int m_nCurPointIndex; int m_nPerItemHeight; public: }; class CAGComboBox : public CWnd { enum { AGCBXBTN_NORMAL = 0, AGCBXBTN_HOVER, AGCBXBTN_PUSH, AGCBXBTN_DISABLE, }; DECLARE_DYNAMIC(CAGComboBox) public: CAGComboBox(); virtual ~CAGComboBox(); virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); int GetCount() const; int GetCurSel() const; DWORD_PTR GetItemData(int nIndex) const; void GetLBText(int nIndex, CString& rString) const; int SetItemData(int nIndex, DWORD_PTR dwItemData); void ShowDropDown(BOOL bShowIt); void SetListMaxHeight(int nMaxHeight); int AddString(LPCTSTR lpszString); int InsertString(int nIndex, LPCTSTR lpszString); int SetCurSel(int nSelect); int DeleteString(int nIndex); void ResetContent(); BOOL GetDroppedState() const; int GetListMaxHeight() const; BOOL SetButtonImage(UINT nIDButton, int cx, int cy, COLORREF crMask); void SetFaceColor(COLORREF crBorder, COLORREF crBack); void SetTextColor(COLORREF crNormal, COLORREF crHot); void SetFont(CFont* pFont, BOOL bRedraw = TRUE); protected: afx_msg void OnPaint(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnMouseLeave(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg BOOL OnEraseBkgnd(CDC* pDC); DECLARE_MESSAGE_MAP() protected: void OnDrawTextCtrl(CDC *pDC); void OnDrawBtnCtrl(CDC *pDC); private: CImageList m_imgDropBtn; CPen m_penBorder; COLORREF m_crBack; COLORREF m_crBorder; COLORREF m_crTextNormal; COLORREF m_crTextHot; UINT m_nBtnStat; int m_nMaxListHeight; BOOL m_bMouseTrack; CFont *m_lpWndFont; private: CAGComboBoxList m_ctrList; };
#include <iostream> #include <iomanip> #include <sstream> class util { public: static const int LARGE_COL_WIDTH = 20; static const int SMALL_COL_WIDTH = 10; static const std::string SPACE; static std::string column(std::string str, bool large) { unsigned long colSize = large ? LARGE_COL_WIDTH : SMALL_COL_WIDTH; if (str.size() > colSize) str = str.substr(0, colSize - 4) + "... "; std::ostringstream ss; ss << std::setw((int)colSize) << std::left << str << SPACE; return ss.str(); } static std::string to_string(float n) { std::ostringstream ss; ss.precision(2); ss << std::fixed << n; return ss.str(); } }; const std::string util::SPACE = " "; int main() { std::string longStr = "This is a very long string that needs to be truncated"; std::string shortStr = "Short"; float num = 123.456789; std::cout << util::column(longStr, true) << util::to_string(num) << std::endl; std::cout << util::column(shortStr, false) << util::to_string(num) << std::endl; return 0; }
#!/bin/bash onos-app $OC1 reinstall! target/*.oar
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class BlackoutpediaFileManager { private Path destinationFile; private Path storeDirectory; public BlackoutpediaFileManager() throws IOException { destinationFile = Files.createTempFile("blackoutpedia-destination", ".junit"); storeDirectory = Files.createTempDirectory("blackoutpedia-store"); } public void handleMapLoadedEvent() { // Add logic to handle map loaded event System.out.println("Map loaded event handled"); } public void handleMapFaultEvent() { // Add logic to handle map fault event System.out.println("Map fault event handled"); } // Additional methods for managing channels and other functionalities can be added here public static void main(String[] args) { try { BlackoutpediaFileManager fileManager = new BlackoutpediaFileManager(); fileManager.handleMapLoadedEvent(); fileManager.handleMapFaultEvent(); System.out.println("Temporary file created: " + fileManager.destinationFile); System.out.println("Temporary directory created: " + fileManager.storeDirectory); } catch (IOException e) { e.printStackTrace(); } } }
declare module "json8" { export function equal(a: any, b: any): boolean export function serialize(value: any, options?: any): string }
#!/usr/bin/python ''' Script to convert Raw input 8bit YUV nv12 format to I420 and vice versa I420 yuv : https://www.fourcc.org/pixel-format/yuv-i420/ nv12 yuv : https://www.fourcc.org/pixel-format/yuv-nv12/ ''' import numpy as np import sys import os class input_yuv: # Initialise and create a class for handling input yuv def __init__(self, inpath, width, height): subsample = 1.5 bpp = 8 self.file = inpath self.width, self.height = width, height if os.path.exists(inpath) == False: sys.exit("Input file does not exists : " + inpath) self.filesize = os.path.getsize(inpath) self.framesize = ((((width * height) * subsample) / 8) * bpp) self.frames = int(self.filesize / self.framesize) def read_I420frame(self, frame): Ystart = int(self.framesize * frame) Y_size = self.width * self.height Cb_size = Cr_Size = Y_size / 4 Yend = Ystart + Y_size with open(self.file, "rb") as finput: finput.seek(Ystart) Y = finput.read(Yend - Ystart) Cb_start = Yend Cb_end = Cb_start + Cb_size with open(self.file, "rb") as finput: finput.seek(Cb_start) Cb = finput.read((int)(Cb_end - Cb_start)) Cr_start = Cb_end Cr_end = Cr_start + Cr_Size with open(self.file, "rb") as finput: finput.seek((int)(Cr_start)) Cr = finput.read((int)(Cr_end - Cr_start)) return Y, Cb, Cr def read_NV12frame(self, frame): Ystart = int(self.framesize * frame) Y_size = self.width * self.height Chroma_size = Y_size / 2 Yend = Ystart + Y_size with open(self.file, "rb") as finput: finput.seek(Ystart) Y = finput.read(Yend - Ystart) Chroma_start = Yend Chroma_end = Chroma_start + Chroma_size with open(self.file, "rb") as finput: finput.seek(Chroma_start) Chroma = finput.read(int(Chroma_end - Chroma_start)) return Y, Chroma class output_yuv: def __init__(self,outpath,width,height): subsample = 1.5 bpp = 8 self.framesize = ((((width * height) * subsample) /8) * bpp) self.width,self.height = width,height self.file=open(outpath,"wb") self.startpos = 0 def write_NV12frame(self,luma_arr,Cb_arr,Cr_arr,frame): FrameStart = int(frame * self.framesize) self.file.write(luma_arr) Cb_seek = FrameStart + (self.width * self.height) self.file.seek(Cb_seek) nCb = np.fromstring(Cb_arr, dtype='uint8') nCr = np.fromstring(Cr_arr, dtype='uint8') nCbCr = np.array([nCb, nCr]) nChroma = nCbCr.reshape(-1, order='F') nChroma.tofile(self.file, "", format('uint8')) def write_I420frame(self,luma_arr,CbCr_arr,frame): FrameStart = int(frame * self.framesize) self.file.write(luma_arr) CbCr_seek = FrameStart + (self.width * self.height) size = (int)((self.width * self.height) / 4) self.file.seek(CbCr_seek) nCbCr = np.fromstring(CbCr_arr, dtype='uint8') nChroma = nCbCr.reshape(2,size, order='F') Cb = nChroma[0] Cr = nChroma[1] Cb.tofile(self.file, "", format('uint8')) self.file.seek((int)(CbCr_seek + size)) Cr.tofile(self.file, "", format('uint8')) if len(sys.argv) != 5: print("\nScript used to convert YUV 420 8bit I420 to NV12 and Vice versa") print("Usage : python convertYUV420p.py Input_YUV Width Height Mode\n") print("Mode: 1 - NV12 to I420, 0 - I420 to NV12\n") print("Ex (NV12 to I420): python convertNV12toPlanar.py tulips_176x144_420p_nv12.yuv 176 144 1\n") print("Ex (I420 to NV12): python convertNV12toPlanar.py tulips_176x144_420p.yuv 176 144 0\n") print("Your Input : {0}, nArgs : {1}" .format(sys.argv, len(sys.argv))) exit(-1) fin = sys.argv[1] width = int(sys.argv[2]) height = int(sys.argv[3]) mode = int(sys.argv[4]) out = "out_" + fin if mode == 1: print("\nConversion Started : NV12 to I420\n") fout = out.replace(".yuv", "_toI420.yuv") else: print("\nConversion Started : I420 to NV12\n") fout = out.replace(".yuv", "_toNV12.yuv") # Initialise YUV class yuv_in = input_yuv(fin,width,height) yuv_out = output_yuv(fout,width,height) for frame in range(yuv_in.frames): if frame == int(yuv_in.frames*0.25): print("Completed 25%....\n") elif frame == int(yuv_in.frames*0.50): print("Completed 50%....\n") elif frame == int(yuv_in.frames*0.75): print("Completed 75%....\n") if mode == 1: # Read nv12 input frame Y,CbCr = yuv_in.read_NV12frame(frame) # Convert and write to output file yuv_out.write_I420frame(Y,CbCr,frame) else: # Read I420 input frame Y, Cb, Cr = yuv_in.read_I420frame(frame) # Convert and write to output file yuv_out.write_NV12frame(Y,Cb,Cr,frame) print("Task Completed - Output file saved at {0}\n" .format(fout))
# scATAC-seq __init__.py __module_name__ = "__init__.py" __author__ = ", ".join(["<NAME>"]) __email__ = ", ".join(["<EMAIL>",]) from ._funcs._merge_reduce_peakset._merge_reduce_peakset_module import _PeakSet as PeakSet from ._funcs._annotate_peaks import _annotate_peaks as annotate_peaks from ._funcs._rank_features._RankFeaturesModule import _RankFeatures as RankFeatures # from ._funcs._rank_features._supporting_functions._calculate_FeatureSumDict2 import _calculate_FeatureSumDict as calc_FeatureSumDict
from typing import List def countWaysToReachTarget(scores: List[int], target: int) -> int: dp = [0] * (target + 1) dp[0] = 1 for i in range(1, target + 1): for score in scores: if i - score >= 0: dp[i] += dp[i - score] return dp[target]
#!/bin/sh rm -rf dist mkdir dist ( printf "/*! ${NPM_PACKAGE} ${NPM_VERSION} ${GITHUB_PROJ} @license MIT */" ; \ browserify ./ -s selectElement \ ) > dist/selectElement.js
<reponame>youaxa/ara-poc-open package com.decathlon.ara.service.dto.setting; import com.fasterxml.jackson.annotation.JsonValue; public enum SettingType { /** * A small text field (edited with an &lt;input/&gt;). */ STRING, /** * A bigger (than STRING), multi-lines text field (edited with a &lt;textarea/&gt;). */ TEXTAREA, /** * The value is a code present in a list of choices (see the 'options' array in {@link SettingDTO}). */ SELECT, /** * The value represents a password, and is write-only from the GUI perspective: it can be replaced but never read. */ PASSWORD, /** * The value is displayed as a check, if true, and edited with a checkbox. */ BOOLEAN, /** * A number value (edited with a number-specialized &lt;input/&gt;) */ INT; @JsonValue public String getJsonValue() { return name().toLowerCase(); } }
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ '../../native_client/build/untrusted.gypi', ], 'targets': [ { 'target_name': 'boringssl_nacl', 'type': 'none', 'variables': { 'nlib_target': 'libboringssl_nacl.a', 'build_glibc': 0, 'build_newlib': 0, 'build_pnacl_newlib': 1, }, 'dependencies': [ '<(DEPTH)/native_client/tools.gyp:prep_toolchain', '<(DEPTH)/native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted', ], 'includes': [ # Include the auto-generated gypi file. 'boringssl.gypi' ], 'sources': [ '<@(boringssl_lib_sources)', ], 'defines': [ 'OPENSSL_NO_ASM', ], 'include_dirs': [ 'src/include', # This is for arm_arch.h, which is needed by some asm files. Since the # asm files are generated and kept in a different directory, they # cannot use relative paths to find this file. 'src/crypto', ], 'direct_dependent_settings': { 'include_dirs': [ 'src/include', ], }, 'pnacl_compile_flags': [ '-Wno-sometimes-uninitialized', '-Wno-unused-variable', ], }, # target boringssl_nacl ], }
#!/usr/bin/env bash # # JHU: Jenkins test # set -exo pipefail source ~/.bash_profile # # Test # local_indicator="usafacts" cd "${WORKSPACE}/${local_indicator}" || exit # Linter #env/bin/pylint delphi_"${local_indicator}" echo "Skip linting because we have weird breakage :( \ TODO: https://github.com/cmu-delphi/covidcast-indicators/issues/333" # Unit tests and code coverage cd tests || exit && \ ../env/bin/pytest --cov=delphi_"${local_indicator}" --cov-report=term-missing
/* jshint indent: 1 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('inedit', { recid: { type: DataTypes.INTEGER, allowNull: false, field: 'RECID' }, pkey: { type: DataTypes.INTEGER, allowNull: false, field: 'PKEY' }, screen: { type: DataTypes.STRING, allowNull: false, field: 'SCREEN' }, indate: { type: DataTypes.DATEONLY, allowNull: false, field: 'INDATE' }, intime: { type: DataTypes.STRING, allowNull: false, field: 'INTIME' }, loginid: { type: DataTypes.STRING, allowNull: false, field: 'LOGINID' } }, { tableName: 'INEDIT', timestamps: false }); };
public class NumbersDescendingOrder { public static void main(String[] args) { for (int i = 10; i >= 1; i--) { System.out.println(i); } } }
<reponame>hdeadman/mailsink describe('src/test/javascript/directive-tests.js', function () { describe('messageText directive', function () { var scope; beforeEach(module('mailsinkApp')); beforeEach(inject(function ($compile, $rootScope) { scope = $rootScope.$new(); })); it('should set empty array when body is null', inject(function ($compile) { scope.text = null; var element = $compile('<message-text text="{{text}}"></message-text>')(scope); scope.$digest(); expect(element.isolateScope().messageText).toEqual([]); })); it('should return array with element "line"', inject(function ($compile) { scope.text = 'line'; var element = $compile('<message-text text="{{text}}"></message-text>')(scope); scope.$digest(); expect(element.isolateScope().messageText).toEqual(['line']); })); it('should return array with elements "first line" and "second line"', inject(function ($compile) { scope.text = 'first line\r\nsecond line\r\n'; var element = $compile('<message-text text="{{text}}"></message-text>')(scope); scope.$digest(); expect(element.isolateScope().messageText).toEqual(['first line', 'second line', '']); })); it('should respect whitespaces in line', inject(function ($compile) { scope.text = ' a line with whitespaces '; var element = $compile('<message-text text="{{text}}"></message-text>')(scope); scope.$digest(); expect(element.isolateScope().messageText).toEqual([' a line with whitespaces ']); })); it('should render text lines in right order', inject(function ($compile) { scope.text = 'first line\r\nsecond line\r\n'; var element = $compile('<message-text text="{{text}}"></message-text>')(scope); scope.$digest(); var selector = 'span'; expect(element.find(selector)[0].innerText).toBe('first line'); expect(element.find(selector)[1].innerText).toBe('second line'); expect(element.find(selector)[2].innerText).toBe(''); })); }); describe('alertMessage directive', function () { beforeEach(module('mailsinkApp')); var scope, rootScope; beforeEach(inject(function ($compile, $rootScope) { scope = $rootScope.$new(); rootScope = $rootScope; })); it('should set error as value on scope attribute message', inject(function ($compile) { $compile('<alert-message>{{message}}</alert-message>')(scope); rootScope.$emit('error', 'error'); expect(scope.message).toEqual('error'); })); it('should hide alert message when no error event triggered', inject(function ($compile) { var el = $compile('<alert-message class="hidden">{{message}}</alert-message>')(scope); scope.$digest(); expect(el.text()).toBe(''); })); it('should show alert message when error event triggered', inject(function ($compile) { var el = $compile('<alert-message class="hidden">{{message}}</alert-message>')(scope); rootScope.$emit('error', 'error'); scope.$digest(); expect(el.text()).toBe('error'); })); it('should hide alert message when dismissed', inject(function ($compile) { var el = $compile('<alert-message class="hidden">{{message}}</alert-message>')(scope); rootScope.$emit('error', 'èrror'); scope.close(); scope.$digest(); expect(el.text()).toBe(''); })); }); describe('toggleSmtpServer directive', function () { var scope, httpBackend, alertService; beforeEach(module('mailsinkApp')); beforeEach(inject(function ($compile, $rootScope, $httpBackend, _alertService_) { scope = $rootScope.$new(); httpBackend = $httpBackend; alertService = _alertService_; spyOn(alertService, 'alert'); })); it('should show play button', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond({isRunning: true}); var element = $compile('<a toggle-smtp-server></a>')(scope); httpBackend.flush(); scope.$digest(); expect(element.hasClass('glyphicon-play')).toEqual(true); expect(element.hasClass('glyphicon-stop')).toEqual(false); })); it('should show stop button', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond({isRunning: false}); var element = $compile('<a toggle-smtp-server></a>')(scope); httpBackend.flush(); scope.$digest(); expect(element.hasClass('glyphicon-stop')).toEqual(true); expect(element.hasClass('glyphicon-play')).toEqual(false); })); it('should show stop button when play pressed', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond({isRunning: true}); var element = $compile('<a toggle-smtp-server></a>')(scope); httpBackend.flush(); scope.$digest(); httpBackend.whenPOST('smtp/status').respond({isRunning: false}); element.click(); httpBackend.flush(); scope.$digest(); expect(element.hasClass('glyphicon-stop')).toEqual(true); })); it('should show play button when stop pressed', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond({isRunning: false}); var element = $compile('<a toggle-smtp-server></a>')(scope); httpBackend.flush(); scope.$digest(); httpBackend.whenPOST('smtp/status').respond({isRunning: true}); element.click(); httpBackend.flush(); scope.$digest(); expect(element.hasClass('glyphicon-play')).toEqual(true); })); it('should forward error response to alertService when toggle request failed', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond(500, 'expected error'); $compile('<a toggle-smtp-server></a>')(scope); httpBackend.flush(); expect(alertService.alert).toHaveBeenCalledWith(jasmine.objectContaining({ status: 500, data: 'expected error' })); })); it('should forward error response to alertService when toggle status request failed', inject(function ($compile) { httpBackend.whenGET('smtp/status').respond({isRunning: false}); var element = $compile('<a toggle-smtp-server></a>')(scope); httpBackend.whenPOST('smtp/status').respond(500, 'expected error'); element.click(); httpBackend.flush(); expect(alertService.alert).toHaveBeenCalledWith(jasmine.objectContaining({ status: 500, data: 'expected error' })); })); }); });
# Setups. cd ~/w mkdir Dropbox mkdir Dropbox/tools # Install p4v & p4 # ~/w/Dropbox/tools/perforce export PERFORCE_VERSION=r13.2 export P4V_VERSION=p4v-2013.2.685561 export PERFORCE_FTP_DIR=http://ftp.perforce.com/perforce/$PERFORCE_VERSION/bin.linux26x86_64 wget $PERFORCE_FTP_DIR/p4v.tgz tar zxvf p4v.tgz cp -r $P4V_VERSION ~/w/Dropbox/tools/perforce wget $PERFORCE_FTP_DIR/p4 cp -r p4 ~/w/Dropbox/tools/perforce/bin export PATH=$PATH:~/w/Dropbox/tools/perforce/bin # Install go mkdir ~/w/Dropbox/tools/golang mkdir ~/w/Dropbox/tools/golang/go_1.1.1 wget "http://go.googlecode.com/files/go1.1.1.linux-amd64.tar.gz" go1.1.1.linux-amd64.tar.gz tar zxvf go1.1.1.linux-amd64.tar.gz cp -r ./go ~/w/Dropbox/tools/golang/go_1.1.1 export PATH=$PATH:~/w/Dropbox/tools/golang/go_1.1.1/bin yum install curl cd /usr/local/src wget http://nodejs.org/dist/v0.6.16/node-v0.6.16.tar.gz cd ./node-v0.6.16 ./configure make make install node -v curl http://npmjs.org/install.sh | sudo sh npm -v
<reponame>tomasmaks/HealthyFood package my.food.tomas.healthyfood.data.local.models; import java.io.Serializable; /** * Created by Tomas on 25/10/2016. */ public class RecipeSearchParams implements Serializable { public String query; public String sort; public int page; public RecipeSearchParams() { query = ""; sort = "r"; page = 1; } }
<reponame>tdm1223/Algorithm // 1406. 에디터 // 2020.04.11 // 링크드 리스트 #include<iostream> #include<string> #include<list> using namespace std; int main() { string s; cin >> s; list<char> list; for (int i = 0; i < s.size(); i++) { list.push_back(s[i]); } auto cur = list.end(); int n; cin >> n; for (int i = 0; i < n; i++) { char order; cin >> order; switch (order) { case 'L': // 왼쪽으로 if (cur != list.begin()) { cur--; } break; case 'D': // 오른쪽으로 if (cur != list.end()) { cur++; } break; case 'B': // 왼쪽에 있는 문자 삭제 if (cur != list.begin()) { cur--; cur = list.erase(cur); } break; case 'P': // 왼쪽에 문자 추가 char tmp; cin >> tmp; list.insert(cur, tmp); break; } } for (auto iter = list.begin(); iter != list.end(); iter++) { cout << *iter; } cout << endl; return 0; }
set linesize 10000 set array 1 set head on set pagesize 10000 set long 10000 set trimspool on spool c:\TabRows.spl set serverout on size 1000000 declare cursor curTab is select rtrim(ltrim(object_name)) tabname from user_objects where object_type = 'TABLE'; rowCnt NUMBER; sqlStmt VARCHAR2(1000); begin for curVar in curTab loop sqlStmt := 'SELECT COUNT(*) FROM ' || curVar.tabname; EXECUTE IMMEDIATE sqlStmt INTO rowCnt; dbms_output.put_line( '-' || lpad(curVar.tabname,30,' ') || ' ' || lpad(rowCnt,30,' ')); end loop; end; / spool off
#!/bin/sh apt-get install zsh -y # install oh my zsh git clone https://github.com/robbyrussell/oh-my-zsh.git /root/.oh-my-zsh cp /root/.oh-my-zsh/templates/zshrc.zsh-template /root/.zshrc # load zsh chsh -s /bin/zsh vagrant zsh # syntax highlighting git clone https://github.com/zsh-users/zsh-syntax-highlighting.git "/root/.zsh-syntax-highlighting" --depth 1 echo "source /root/.zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" >> "/root/.zshrc" # theme sed -i 's/ZSH_THEME="robbyrussell"/ZSH_THEME="sonicradish"/g' /root/.zshrc # auto suggesstion git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-/root/.oh-my-zsh/custom}/plugins/zsh-autosuggestions sed -i 's/plugins=(git)/plugins=(zsh-autosuggestions git kubectl docker)/g' /root/.zshrc # kubectl aliases cp /root/.kubectl_aliases /root/.kubectl_aliases echo "[ -f ~/.kubectl_aliases ] && source ~/.kubectl_aliases" >> "/root/.zshrc"
import re def getRepoName(url): pattern = r"https://github.com/\w+/(\w+)" match = re.search(pattern, url) if match: return match.group(1) else: return "Invalid GitHub repository URL"
(function ($) { $(document).ready(function(){ // fade in .navbar $(function () { $(window).scroll(function () { // set distance user needs to scroll before we fadeIn navbar if ($(this).scrollTop() > 550) { $('.navbar').css('background', '#3a4349') $('.navbar-inverse .navbar-toggle .icon-bar').css('background-color', 'white'); // $('.navbar a').css('color', 'white'); } else if ($(this).scrollTop() < 550) { $('.navbar').css('background', 'transparent'); $('.navbar-inverse .navbar-toggle .icon-bar').css('background-color', '#3a4349'); // $('.navbar a').css('color', 'white'); } }); }); }); }(jQuery));