text
stringlengths
2
100k
meta
dict
5 Iris-setosa Iris-setosa 0.996 0.996 4.6 Iris-setosa Iris-setosa 0.999 0.999 5.1 Iris-setosa Iris-setosa 0.994 0.994 4.9 Iris-setosa Iris-setosa 0.991 0.991 5.4 Iris-setosa Iris-setosa 0.998 0.998 4.4 Iris-setosa Iris-setosa 0.994 0.994 5.3 Iris-setosa Iris-setosa 0.998 0.998 6.1 Iris-versicolor Iris-versicolor 0.887 0.887 6 Iris-versicolor Iris-versicolor 0.942 0.942 5.5 Iris-versicolor Iris-versicolor 0.903 0.903 6.5 Iris-versicolor Iris-versicolor 0.929 0.929 6.8 Iris-versicolor Iris-versicolor 0.957 0.957 6.2 Iris-versicolor Iris-versicolor 0.986 0.986 6.7 Iris-virginica Iris-virginica 0.970 0.970 6.4 Iris-virginica Iris-virginica 0.898 0.898 5.7 Iris-virginica Iris-virginica 0.992 0.992 6.7 Iris-virginica Iris-virginica 0.969 0.969 6.8 Iris-virginica Iris-virginica 0.996 0.996 7.7 Iris-virginica Iris-virginica 0.990 0.990 7.3 Iris-virginica Iris-virginica 0.977 0.977
{ "pile_set_name": "Github" }
/** * Copyright (c) 2016 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef NRF_CSENSE_MACROS_H__ #define NRF_CSENSE_MACROS_H__ /** @file * * @defgroup nrf_csense_macros Capacitive sensor macros * @{ * @ingroup nrf_csense * * @brief A set of macros to facilitate creation of a new capacitive sensor instance. */ #define NRF_CSENSE_INTERNAL_BUTTON_DEF(name, p1) \ static nrf_csense_pad_t CONCAT_2(name, _pad) = \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }; \ static nrf_csense_min_max_t CONCAT_2(name, _minmax); \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = &CONCAT_2(name, _pad), \ .min_max = &CONCAT_2(name, _minmax), \ .steps = 1, \ .number_of_pads = 1, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_SLIDER_2_DEF(name, steps_no, p1, p2) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[2] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[2]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 2, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_SLIDER_3_DEF(name, steps_no, p1, p2, p3) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[3] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[3]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 3, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_SLIDER_4_DEF(name, steps_no, p1, p2, p3, p4) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[4] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[3], \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p4, \ .pad_index = 3, \ .analog_input_number = GET_ARG_1 p4 \ } \ }; \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[4]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 4, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_SLIDER_5_DEF(name, steps_no, p1, p2, p3, p4, p5) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[5] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[3], \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[4], \ .threshold = GET_ARG_2 p4, \ .pad_index = 3, \ .analog_input_number = GET_ARG_1 p4 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p5, \ .pad_index = 4, \ .analog_input_number = GET_ARG_1 p5 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[5]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 5, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_WHEEL_3_DEF(name, steps_no, p1, p2, p3) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[4] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[3], \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p1, \ .pad_index = 3, \ .analog_input_number = GET_ARG_1 p1 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[4]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 4, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_WHEEL_4_DEF(name, steps_no, p1, p2, p3, p4) \ static nrf_csense_pad_t CONCAT_2(name, _pad)[5] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[3], \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[4], \ .threshold = GET_ARG_2 p4, \ .pad_index = 3, \ .analog_input_number = GET_ARG_1 p4 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p1, \ .pad_index = 4, \ .analog_input_number = GET_ARG_1 p1 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[5]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 5, \ .is_active = false, \ .is_touched = false \ }; #define NRF_CSENSE_INTERNAL_WHEEL_5_DEF(name, steps_no, p1, p2, p3, p4, p5)\ static nrf_csense_pad_t CONCAT_2(name, _pad)[6] = \ { \ { \ .p_next_pad = &CONCAT_2(name, _pad)[1], \ .threshold = GET_ARG_2 p1, \ .pad_index = 0, \ .analog_input_number = GET_ARG_1 p1 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[2], \ .threshold = GET_ARG_2 p2, \ .pad_index = 1, \ .analog_input_number = GET_ARG_1 p2 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[3], \ .threshold = GET_ARG_2 p3, \ .pad_index = 2, \ .analog_input_number = GET_ARG_1 p3 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[4], \ .threshold = GET_ARG_2 p4, \ .pad_index = 3, \ .analog_input_number = GET_ARG_1 p4 \ }, \ { \ .p_next_pad = &CONCAT_2(name, _pad)[5], \ .threshold = GET_ARG_2 p5, \ .pad_index = 4, \ .analog_input_number = GET_ARG_1 p5 \ }, \ { \ .p_next_pad = NULL, \ .threshold = GET_ARG_2 p1, \ .pad_index = 5, \ .analog_input_number = GET_ARG_1 p1 \ } \ }; \ \ static nrf_csense_min_max_t CONCAT_2(name, _minmax)[6]; \ static nrf_csense_instance_t name = \ { \ .p_nrf_csense_pad = CONCAT_2(name, _pad), \ .min_max = CONCAT_2(name, _minmax), \ .steps = steps_no, \ .number_of_pads = 6, \ .is_active = false, \ .is_touched = false \ }; /** @} */ #endif // NRF_CSENSE_MACROS_H__
{ "pile_set_name": "Github" }
/* net/atm/signaling.h - ATM signaling */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef NET_ATM_SIGNALING_H #define NET_ATM_SIGNALING_H #include <linux/atm.h> #include <linux/atmdev.h> #include <linux/atmsvc.h> extern struct atm_vcc *sigd; /* needed in svc_release */ /* * sigd_enq is a wrapper for sigd_enq2, covering the more common cases, and * avoiding huge lists of null values. */ void sigd_enq2(struct atm_vcc *vcc,enum atmsvc_msg_type type, struct atm_vcc *listen_vcc,const struct sockaddr_atmpvc *pvc, const struct sockaddr_atmsvc *svc,const struct atm_qos *qos,int reply); void sigd_enq(struct atm_vcc *vcc,enum atmsvc_msg_type type, struct atm_vcc *listen_vcc,const struct sockaddr_atmpvc *pvc, const struct sockaddr_atmsvc *svc); int sigd_attach(struct atm_vcc *vcc); #endif
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clientcmd import ( "fmt" "strconv" "time" ) // ParseTimeout returns a parsed duration from a string // A duration string value must be a positive integer, optionally followed by a corresponding time unit (s|m|h). func ParseTimeout(duration string) (time.Duration, error) { if i, err := strconv.ParseInt(duration, 10, 64); err == nil && i >= 0 { return (time.Duration(i) * time.Second), nil } if requestTimeout, err := time.ParseDuration(duration); err == nil { return requestTimeout, nil } return 0, fmt.Errorf("Invalid timeout value. Timeout must be a single integer in seconds, or an integer followed by a corresponding time unit (e.g. 1s | 2m | 3h)") }
{ "pile_set_name": "Github" }
国際観光ホテル整備法施行令 (昭和二十五年六月十日政令第百八十六号)最終改正:平成二〇年七月一八日政令第二三一号  内閣は、国際観光ホテル整備法 (昭和二十四年法律第二百七十九号)を実施するため並びに同法第十四条第三項 及び第二十九条 の規定に基き、この政令を制定する。 (登録実施機関の登録の有効期間) 第一条  国際観光ホテル整備法 (以下「法」という。)第二十一条第一項 の政令で定める期間は、五年とする。 (関係大臣との協議) 第二条  観光庁長官は、法第三十三条第一項 の規定による勧告をしようとする場合において、その勧告が、国立公園の区域内のホテル又は旅館に対して行われるときは環境大臣に、公衆衛生の改善を図る事項を内容とするときは厚生労働大臣に、それぞれ協議するものとする。    附 則  この政令は、公布の日から施行する。    附 則 (昭和二六年七月二八日政令第二七五号)  この政令は、公布の日から施行する。    附 則 (昭和三五年六月三〇日政令第一八五号)  この政令は、自治庁設置法の一部を改正する法律の施行の日(昭和三十五年七月一日)から施行する。    附 則 (昭和四〇年三月三一日政令第九九号) 抄 (施行期日) 第一条  この政令は、昭和四十年四月一日から施行する。 (その他の政令の一部改正に伴う経過規定の原則) 第六条  第二章の規定による改正後の政令の規定は、別段の定めがあるものを除き、昭和四十年分以後の所得税又はこれらの政令の規定に規定する法人の施行日以後に終了する事業年度分の法人税について適用し、昭和三十九年分以前の所得税又は当該法人の同日前に終了した事業年度分の法人税については、なお従前の例による。    附 則 (昭和四二年五月三一日政令第一〇六号) 抄 (施行期日) 第一条  この政令は、昭和四十二年六月一日から施行する。    附 則 (昭和四三年四月二〇日政令第九七号) 抄 (施行期日) 第一条  この政令は、公布の日から施行する。    附 則 (昭和四六年六月一日政令第一七二号)  第四条の規定は公布の日から、第一条から第三条まで及び第五条の規定は同日から起算して一月を経過した日から施行する。    附 則 (昭和四六年六月三〇日政令第二一九号) 抄 (施行期日) 第一条  この政令は、昭和四十六年七月一日から施行する。    附 則 (昭和五二年三月三一日政令第五四号) 抄 (施行期日) 第一条  この政令は、昭和五十二年四月一日から施行する。    附 則 (昭和五三年三月三一日政令第七九号) 抄 (施行期日) 第一条  この政令は、昭和五十三年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十二条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした前条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (昭和五五年三月三一日政令第四二号) 抄 (施行期日) 第一条  この政令は、昭和五十五年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十二条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等(取得又は製作若しくは建設をいう。以下この条において同じ。)をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした前条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (昭和五六年三月三一日政令第七三号) 抄 (施行期日) 第一条  この政令は、昭和五十六年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十一条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした前条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (昭和五八年三月三一日政令第六一号) 抄 (施行期日) 第一条  この政令は、昭和五十八年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十九条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした同条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (昭和六〇年三月三〇日政令第六一号) 抄 (施行期日) 第一条  この政令は、昭和六十年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十七条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした同条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (昭和六一年六月二〇日政令第二三一号)  この政令は、昭和六十一年七月一日から施行する。    附 則 (昭和六一年一二月二六日政令第三九四号)  この政令は、公布の日から施行する。    附 則 (昭和六三年三月三一日政令第七三号) 抄 (施行期日) 第一条  この政令は、昭和六十三年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第三十七条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした同条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (平成元年三月三一日政令第九四号) 抄 (施行期日) 第一条  この政令は、平成元年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十八条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした同条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (平成二年三月三一日政令第九三号) 抄 (施行期日) 第一条  この政令は、平成二年四月一日から施行する。 (国際観光ホテル整備法施行令の一部改正に伴う経過措置) 第二十八条  前条の規定による改正後の国際観光ホテル整備法施行令別表の規定は、個人又は法人が施行日以後に取得等をする同表に掲げる減価償却資産について適用し、個人又は法人が施行日前に取得等をした同条の規定による改正前の国際観光ホテル整備法施行令別表に掲げる減価償却資産については、なお従前の例による。    附 則 (平成四年一二月二四日政令第三九一号) 抄 (施行期日) 1  この政令は、国際観光ホテル整備法の一部を改正する法律の施行の日(平成五年四月一日)から施行する。    附 則 (平成一一年一〇月二七日政令第三三六号) (施行期日) 1  この政令は、地方分権の推進を図るための関係法律の整備等に関する法律の施行の日(平成十二年四月一日)から施行する。 (経過措置) 2  この政令の施行前に港湾法(昭和二十五年法律第二百十八号)又は旅行業法(昭和二十七年法律第二百三十九号)(これらの法律に基づく政令を含む。)の規定によりされた命令等の処分その他の行為(以下「処分等の行為」という。)で、この政令の施行の日においてこれらの行為に係る行政事務を行うべき者が異なることとなるものは、この政令の施行の日以後においては、この政令の施行の日において新たに当該行政事務を行うこととなる者のした処分等の行為とみなす。 3  この政令の施行前にした行為に対する罰則の適用については、なお従前の例による。    附 則 (平成一二年六月七日政令第三一二号) 抄 (施行期日) 1  この政令は、内閣法の一部を改正する法律(平成十一年法律第八十八号)の施行の日(平成十三年一月六日)から施行する。    附 則 (平成一五年一二月一〇日政令第四九六号)  この政令は、平成十六年三月一日から施行する。    附 則 (平成二〇年七月一八日政令第二三一号) 抄 (施行期日) 第一条  この政令は、平成二十年十月一日から施行する。 (罰則に関する経過措置) 第三条  第二十四条の規定の施行前にした行為に対する罰則の適用については、なお従前の例による。
{ "pile_set_name": "Github" }
/* * AppliedMicro X-Gene SoC GPIO Driver * * Copyright (c) 2014, Applied Micro Circuits Corporation * Author: Feng Kan <[email protected]>. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/io.h> #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/gpio/driver.h> #include <linux/types.h> #include <linux/bitops.h> #define GPIO_SET_DR_OFFSET 0x0C #define GPIO_DATA_OFFSET 0x14 #define GPIO_BANK_STRIDE 0x0C #define XGENE_GPIOS_PER_BANK 16 #define XGENE_MAX_GPIO_BANKS 3 #define XGENE_MAX_GPIOS (XGENE_GPIOS_PER_BANK * XGENE_MAX_GPIO_BANKS) #define GPIO_BIT_OFFSET(x) (x % XGENE_GPIOS_PER_BANK) #define GPIO_BANK_OFFSET(x) ((x / XGENE_GPIOS_PER_BANK) * GPIO_BANK_STRIDE) struct xgene_gpio { struct gpio_chip chip; void __iomem *base; spinlock_t lock; #ifdef CONFIG_PM u32 set_dr_val[XGENE_MAX_GPIO_BANKS]; #endif }; static inline struct xgene_gpio *to_xgene_gpio(struct gpio_chip *chip) { return container_of(chip, struct xgene_gpio, chip); } static int xgene_gpio_get(struct gpio_chip *gc, unsigned int offset) { struct xgene_gpio *chip = to_xgene_gpio(gc); unsigned long bank_offset; u32 bit_offset; bank_offset = GPIO_DATA_OFFSET + GPIO_BANK_OFFSET(offset); bit_offset = GPIO_BIT_OFFSET(offset); return !!(ioread32(chip->base + bank_offset) & BIT(bit_offset)); } static void __xgene_gpio_set(struct gpio_chip *gc, unsigned int offset, int val) { struct xgene_gpio *chip = to_xgene_gpio(gc); unsigned long bank_offset; u32 setval, bit_offset; bank_offset = GPIO_SET_DR_OFFSET + GPIO_BANK_OFFSET(offset); bit_offset = GPIO_BIT_OFFSET(offset) + XGENE_GPIOS_PER_BANK; setval = ioread32(chip->base + bank_offset); if (val) setval |= BIT(bit_offset); else setval &= ~BIT(bit_offset); iowrite32(setval, chip->base + bank_offset); } static void xgene_gpio_set(struct gpio_chip *gc, unsigned int offset, int val) { struct xgene_gpio *chip = to_xgene_gpio(gc); unsigned long flags; spin_lock_irqsave(&chip->lock, flags); __xgene_gpio_set(gc, offset, val); spin_unlock_irqrestore(&chip->lock, flags); } static int xgene_gpio_dir_in(struct gpio_chip *gc, unsigned int offset) { struct xgene_gpio *chip = to_xgene_gpio(gc); unsigned long flags, bank_offset; u32 dirval, bit_offset; bank_offset = GPIO_SET_DR_OFFSET + GPIO_BANK_OFFSET(offset); bit_offset = GPIO_BIT_OFFSET(offset); spin_lock_irqsave(&chip->lock, flags); dirval = ioread32(chip->base + bank_offset); dirval |= BIT(bit_offset); iowrite32(dirval, chip->base + bank_offset); spin_unlock_irqrestore(&chip->lock, flags); return 0; } static int xgene_gpio_dir_out(struct gpio_chip *gc, unsigned int offset, int val) { struct xgene_gpio *chip = to_xgene_gpio(gc); unsigned long flags, bank_offset; u32 dirval, bit_offset; bank_offset = GPIO_SET_DR_OFFSET + GPIO_BANK_OFFSET(offset); bit_offset = GPIO_BIT_OFFSET(offset); spin_lock_irqsave(&chip->lock, flags); dirval = ioread32(chip->base + bank_offset); dirval &= ~BIT(bit_offset); iowrite32(dirval, chip->base + bank_offset); __xgene_gpio_set(gc, offset, val); spin_unlock_irqrestore(&chip->lock, flags); return 0; } #ifdef CONFIG_PM static int xgene_gpio_suspend(struct device *dev) { struct xgene_gpio *gpio = dev_get_drvdata(dev); unsigned long bank_offset; unsigned int bank; for (bank = 0; bank < XGENE_MAX_GPIO_BANKS; bank++) { bank_offset = GPIO_SET_DR_OFFSET + bank * GPIO_BANK_STRIDE; gpio->set_dr_val[bank] = ioread32(gpio->base + bank_offset); } return 0; } static int xgene_gpio_resume(struct device *dev) { struct xgene_gpio *gpio = dev_get_drvdata(dev); unsigned long bank_offset; unsigned int bank; for (bank = 0; bank < XGENE_MAX_GPIO_BANKS; bank++) { bank_offset = GPIO_SET_DR_OFFSET + bank * GPIO_BANK_STRIDE; iowrite32(gpio->set_dr_val[bank], gpio->base + bank_offset); } return 0; } static SIMPLE_DEV_PM_OPS(xgene_gpio_pm, xgene_gpio_suspend, xgene_gpio_resume); #define XGENE_GPIO_PM_OPS (&xgene_gpio_pm) #else #define XGENE_GPIO_PM_OPS NULL #endif static int xgene_gpio_probe(struct platform_device *pdev) { struct resource *res; struct xgene_gpio *gpio; int err = 0; gpio = devm_kzalloc(&pdev->dev, sizeof(*gpio), GFP_KERNEL); if (!gpio) { err = -ENOMEM; goto err; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); gpio->base = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!gpio->base) { err = -ENOMEM; goto err; } gpio->chip.ngpio = XGENE_MAX_GPIOS; spin_lock_init(&gpio->lock); gpio->chip.dev = &pdev->dev; gpio->chip.direction_input = xgene_gpio_dir_in; gpio->chip.direction_output = xgene_gpio_dir_out; gpio->chip.get = xgene_gpio_get; gpio->chip.set = xgene_gpio_set; gpio->chip.label = dev_name(&pdev->dev); gpio->chip.base = -1; platform_set_drvdata(pdev, gpio); err = gpiochip_add(&gpio->chip); if (err) { dev_err(&pdev->dev, "failed to register gpiochip.\n"); goto err; } dev_info(&pdev->dev, "X-Gene GPIO driver registered.\n"); return 0; err: dev_err(&pdev->dev, "X-Gene GPIO driver registration failed.\n"); return err; } static int xgene_gpio_remove(struct platform_device *pdev) { struct xgene_gpio *gpio = platform_get_drvdata(pdev); gpiochip_remove(&gpio->chip); return 0; } static const struct of_device_id xgene_gpio_of_match[] = { { .compatible = "apm,xgene-gpio", }, {}, }; MODULE_DEVICE_TABLE(of, xgene_gpio_of_match); static struct platform_driver xgene_gpio_driver = { .driver = { .name = "xgene-gpio", .of_match_table = xgene_gpio_of_match, .pm = XGENE_GPIO_PM_OPS, }, .probe = xgene_gpio_probe, .remove = xgene_gpio_remove, }; module_platform_driver(xgene_gpio_driver); MODULE_AUTHOR("Feng Kan <[email protected]>"); MODULE_DESCRIPTION("APM X-Gene GPIO driver"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
<?php /** * Tencent is pleased to support the open source community by making Biny available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace biny\lib; /** * Created by PhpStorm. * User: billge * Date: 15-8-3 * Time: 上午11:50 * @method DoubleCond group($groupby) * @method DoubleCond having($having) * @method DoubleCond limit($len, $start=0) * @method DoubleCond order($orderby) * @method DoubleCond addition($additions) */ class DoubleFilter extends Filter { /** * @var DoubleDAO */ protected $DAO; protected $conds = []; /** * and 操作 * @param array $cond * @param string $link * @return DoubleFilter */ public function filter($cond=[], $link='and') { $link = (strtolower($link) == 'or') ? '__or__' : '__and__'; return $cond ? new self($this->DAO, $cond, "__and__", $this->conds[0], $link) : $this; } /** * or 操作 * @param $cond * @param string $link * @return DoubleFilter */ public function merge($cond, $link='or') { $link = (strtolower($link) == 'and') ? '__and__' : '__or__'; return $cond ? new self($this->DAO, $cond, "__or__", $this->conds[0], $link) : $this; } /** * 查询条件 * @param $method * @param $args * @return DoubleCond * @throws BinyException */ public function __call($method, $args) { if (in_array($method, $this->joins)){ return call_user_func_array([$this->DAO, $method], $args)->setCond($this->conds); } if (in_array($method, $this->methods) || in_array($method, $this->calcs)){ $cond = new DoubleCond($this->DAO); $cond->setWhere($this->buildWhere($this->conds)); return call_user_func_array([$cond, $method], $args); } else { throw new BinyException(3009, [$method, __CLASS__]); } } }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x", "filename" : "image_8.jpg" }, { "idiom" : "universal", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
(function() { var module = angular.module('manuskript.core.onAltEnter.directive', []); /** * focusOn directive gives focus when a scope parameter becomes true. */ module.directive('focusOn', function($timeout, $parse) { return { link: { post: function(scope, element, attrs) { var model = $parse(attrs.focusOn); scope.$watch(model, function(value) { if(value === true) { element[0].focus(); } }); element.bind('blur', function() { scope.$apply(model.assign(scope, false)); }); } } }; }); /** * 'onAltEnter' directive executed 'onAltEnter' handler when either * Command+Enter or Control+Enter is pressed. */ module.directive('onAltEnter', function() { return function(scope, element, attrs) { element.keydown(function(event) { if (event.which == 13 && (event.ctrlKey || event.metaKey)) { scope.$evalAsync(attrs.onAltEnter); } }); }; }); })();
{ "pile_set_name": "Github" }
<?php /** * Class Data Point Literal. * * @package Automattic\Jetpack\Global_Styles */ namespace Automattic\Jetpack\Global_Styles; require_once __DIR__ . '/interface-data-point.php'; /** * Literal Data Point. */ class Data_Point_Literal implements Data_Point { /** * Holds the literal value. * * @var any */ private $value; /** * Constructor. * * @param any $meta Data point description. */ public function __construct( $meta ) { if ( array_key_exists( 'default', $meta ) ) { $this->value = $meta['default']; } } /** * Implements \Automattic\Jetpack\Global_Styles\Data_Point interface. * * @return any The literal value. */ public function get_value() { return $this->value; } }
{ "pile_set_name": "Github" }
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "boost/mpl/aux_/advance_forward.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { namespace aux { template< long N > struct advance_forward; template<> struct advance_forward<0> { template< typename Iterator > struct apply { typedef Iterator iter0; typedef iter0 type; }; }; template<> struct advance_forward<1> { template< typename Iterator > struct apply { typedef Iterator iter0; typedef typename next<iter0>::type iter1; typedef iter1 type; }; }; template<> struct advance_forward<2> { template< typename Iterator > struct apply { typedef Iterator iter0; typedef typename next<iter0>::type iter1; typedef typename next<iter1>::type iter2; typedef iter2 type; }; }; template<> struct advance_forward<3> { template< typename Iterator > struct apply { typedef Iterator iter0; typedef typename next<iter0>::type iter1; typedef typename next<iter1>::type iter2; typedef typename next<iter2>::type iter3; typedef iter3 type; }; }; template<> struct advance_forward<4> { template< typename Iterator > struct apply { typedef Iterator iter0; typedef typename next<iter0>::type iter1; typedef typename next<iter1>::type iter2; typedef typename next<iter2>::type iter3; typedef typename next<iter3>::type iter4; typedef iter4 type; }; }; template< long N > struct advance_forward { template< typename Iterator > struct apply { typedef typename apply_wrap1< advance_forward<4> , Iterator >::type chunk_result_; typedef typename apply_wrap1< advance_forward<( (N - 4) < 0 ? 0 : N - 4 )> , chunk_result_ >::type type; }; }; }}}
{ "pile_set_name": "Github" }
var SetCache = require('./_SetCache'), arrayIncludes = require('./_arrayIncludes'), arrayIncludesWith = require('./_arrayIncludesWith'), arrayMap = require('./_arrayMap'), baseUnary = require('./_baseUnary'), cacheHas = require('./_cacheHas'); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference;
{ "pile_set_name": "Github" }
package gquic import ( "bytes" "crypto/tls" "errors" "net" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/handshake" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/protocol" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/utils" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/wire" "github.com/bifurcation/mint" ) type tlsSession struct { connID protocol.ConnectionID sess quicSession } type serverTLS struct { conn net.PacketConn config *Config mintConf *mint.Config params *handshake.TransportParameters cookieGenerator *handshake.CookieGenerator newSession func(connection, sessionRunner, protocol.ConnectionID, protocol.ConnectionID, protocol.ConnectionID, protocol.PacketNumber, *Config, *mint.Config, <-chan handshake.TransportParameters, utils.Logger, protocol.VersionNumber) (quicSession, error) sessionRunner sessionRunner sessionChan chan<- tlsSession logger utils.Logger } func newServerTLS( conn net.PacketConn, config *Config, runner sessionRunner, tlsConf *tls.Config, logger utils.Logger, ) (*serverTLS, <-chan tlsSession, error) { cookieGenerator, err := handshake.NewCookieGenerator() if err != nil { return nil, nil, err } params := &handshake.TransportParameters{ StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow, ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow, IdleTimeout: config.IdleTimeout, MaxBidiStreams: uint16(config.MaxIncomingStreams), MaxUniStreams: uint16(config.MaxIncomingUniStreams), DisableMigration: true, // TODO(#855): generate a real token StatelessResetToken: bytes.Repeat([]byte{42}, 16), } mconf, err := tlsToMintConfig(tlsConf, protocol.PerspectiveServer) if err != nil { return nil, nil, err } sessionChan := make(chan tlsSession) s := &serverTLS{ conn: conn, config: config, mintConf: mconf, sessionRunner: runner, sessionChan: sessionChan, cookieGenerator: cookieGenerator, params: params, newSession: newTLSServerSession, logger: logger, } return s, sessionChan, nil } func (s *serverTLS) HandleInitial(p *receivedPacket) { // TODO: add a check that DestConnID == SrcConnID s.logger.Debugf("<- Received Initial packet.") sess, connID, err := s.handleInitialImpl(p) if err != nil { s.logger.Errorf("Error occurred handling initial packet: %s", err) return } if sess == nil { // a stateless reset was done return } s.sessionChan <- tlsSession{ connID: connID, sess: sess, } } func (s *serverTLS) handleInitialImpl(p *receivedPacket) (quicSession, protocol.ConnectionID, error) { hdr := p.header if len(hdr.Token) == 0 && hdr.DestConnectionID.Len() < protocol.MinConnectionIDLenInitial { return nil, nil, errors.New("dropping Initial packet with too short connection ID") } if len(hdr.Raw)+len(p.data) < protocol.MinInitialPacketSize { return nil, nil, errors.New("dropping too small Initial packet") } var cookie *handshake.Cookie if len(hdr.Token) > 0 { c, err := s.cookieGenerator.DecodeToken(hdr.Token) if err == nil { cookie = c } } if !s.config.AcceptCookie(p.remoteAddr, cookie) { // Log the Initial packet now. // If no Retry is sent, the packet will be logged by the session. p.header.Log(s.logger) return nil, nil, s.sendRetry(p.remoteAddr, hdr) } extHandler := handshake.NewExtensionHandlerServer(s.params, s.config.Versions, hdr.Version, s.logger) mconf := s.mintConf.Clone() mconf.ExtensionHandler = extHandler connID, err := protocol.GenerateConnectionID(s.config.ConnectionIDLength) if err != nil { return nil, nil, err } s.logger.Debugf("Changing connection ID to %s.", connID) sess, err := s.newSession( &conn{pconn: s.conn, currentAddr: p.remoteAddr}, s.sessionRunner, hdr.DestConnectionID, hdr.SrcConnectionID, connID, 1, s.config, mconf, extHandler.GetPeerParams(), s.logger, hdr.Version, ) if err != nil { return nil, nil, err } go sess.run() sess.handlePacket(p) return sess, connID, nil } func (s *serverTLS) sendRetry(remoteAddr net.Addr, hdr *wire.Header) error { token, err := s.cookieGenerator.NewToken(remoteAddr) if err != nil { return err } connID, err := protocol.GenerateConnectionID(s.config.ConnectionIDLength) if err != nil { return err } replyHdr := &wire.Header{ IsLongHeader: true, Type: protocol.PacketTypeRetry, Version: hdr.Version, SrcConnectionID: connID, DestConnectionID: hdr.SrcConnectionID, OrigDestConnectionID: hdr.DestConnectionID, Token: token, } s.logger.Debugf("Changing connection ID to %s.\n-> Sending Retry", connID) replyHdr.Log(s.logger) buf := &bytes.Buffer{} if err := replyHdr.Write(buf, protocol.PerspectiveServer, hdr.Version); err != nil { return err } if _, err := s.conn.WriteTo(buf.Bytes(), remoteAddr); err != nil { s.logger.Debugf("Error sending Retry: %s", err) } return nil }
{ "pile_set_name": "Github" }
Plugins.Animation.Frames ======================== Класс, который используется для "нарезки" картинок из одной тайловой картинки. Обычно кадры анимации похожи между собой и имеет смысл множество их собрать в одно изображение подобно технологии css-sprites. Допустим, у вас ширина кадра анимации 50 пикселей, высота - 40, 15 кадров. Вы можете нарисовать их в три ряда в картинке размером 250*120. ![Пример нарезки кадров анимации](https://raw.github.com/theshock/libcanvas/master/Docs/Ru/Plugins/Animation/frames-demo.png) ### Инициализация ```js new Animation.Frames( Image image, int width = null, int height = null ) ``` * `image` (*Image*) - картинка-источник для нарезки * `width` (*int*) - ширина кадра. Равен ширине картинки, если `null` * `height` (*int*) - высота кадра. Равен высоте картинки, если `null` ```js var frames = new Animation.Frames( images.get('ship'), 100 ); ``` ### Методы `get length` - количество кадров в массиве ```js console.log( frames.length ); ``` #### get ```js canvasElement get( int index ); ``` Возвращает картинку-кадр, часть исходной картинки. ```js var frame = frames.get( 5 ); ```
{ "pile_set_name": "Github" }
/* QLogic qed NIC Driver * Copyright (c) 2015-2017 QLogic Corporation * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and /or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef _QED_INT_H #define _QED_INT_H #include <linux/types.h> #include <linux/slab.h> #include "qed.h" /* Fields of IGU PF CONFIGRATION REGISTER */ #define IGU_PF_CONF_FUNC_EN (0x1 << 0) /* function enable */ #define IGU_PF_CONF_MSI_MSIX_EN (0x1 << 1) /* MSI/MSIX enable */ #define IGU_PF_CONF_INT_LINE_EN (0x1 << 2) /* INT enable */ #define IGU_PF_CONF_ATTN_BIT_EN (0x1 << 3) /* attention enable */ #define IGU_PF_CONF_SINGLE_ISR_EN (0x1 << 4) /* single ISR mode enable */ #define IGU_PF_CONF_SIMD_MODE (0x1 << 5) /* simd all ones mode */ /* Fields of IGU VF CONFIGRATION REGISTER */ #define IGU_VF_CONF_FUNC_EN (0x1 << 0) /* function enable */ #define IGU_VF_CONF_MSI_MSIX_EN (0x1 << 1) /* MSI/MSIX enable */ #define IGU_VF_CONF_SINGLE_ISR_EN (0x1 << 4) /* single ISR mode enable */ #define IGU_VF_CONF_PARENT_MASK (0xF) /* Parent PF */ #define IGU_VF_CONF_PARENT_SHIFT 5 /* Parent PF */ /* Igu control commands */ enum igu_ctrl_cmd { IGU_CTRL_CMD_TYPE_RD, IGU_CTRL_CMD_TYPE_WR, MAX_IGU_CTRL_CMD }; /* Control register for the IGU command register */ struct igu_ctrl_reg { u32 ctrl_data; #define IGU_CTRL_REG_FID_MASK 0xFFFF /* Opaque_FID */ #define IGU_CTRL_REG_FID_SHIFT 0 #define IGU_CTRL_REG_PXP_ADDR_MASK 0xFFF /* Command address */ #define IGU_CTRL_REG_PXP_ADDR_SHIFT 16 #define IGU_CTRL_REG_RESERVED_MASK 0x1 #define IGU_CTRL_REG_RESERVED_SHIFT 28 #define IGU_CTRL_REG_TYPE_MASK 0x1 /* use enum igu_ctrl_cmd */ #define IGU_CTRL_REG_TYPE_SHIFT 31 }; enum qed_coalescing_fsm { QED_COAL_RX_STATE_MACHINE, QED_COAL_TX_STATE_MACHINE }; /** * @brief qed_int_igu_enable_int - enable device interrupts * * @param p_hwfn * @param p_ptt * @param int_mode - interrupt mode to use */ void qed_int_igu_enable_int(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_int_mode int_mode); /** * @brief qed_int_igu_disable_int - disable device interrupts * * @param p_hwfn * @param p_ptt */ void qed_int_igu_disable_int(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt); /** * @brief qed_int_igu_read_sisr_reg - Reads the single isr multiple dpc * register from igu. * * @param p_hwfn * * @return u64 */ u64 qed_int_igu_read_sisr_reg(struct qed_hwfn *p_hwfn); #define QED_SP_SB_ID 0xffff /** * @brief qed_int_sb_init - Initializes the sb_info structure. * * once the structure is initialized it can be passed to sb related functions. * * @param p_hwfn * @param p_ptt * @param sb_info points to an uninitialized (but * allocated) sb_info structure * @param sb_virt_addr * @param sb_phy_addr * @param sb_id the sb_id to be used (zero based in driver) * should use QED_SP_SB_ID for SP Status block * * @return int */ int qed_int_sb_init(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct qed_sb_info *sb_info, void *sb_virt_addr, dma_addr_t sb_phy_addr, u16 sb_id); /** * @brief qed_int_sb_setup - Setup the sb. * * @param p_hwfn * @param p_ptt * @param sb_info initialized sb_info structure */ void qed_int_sb_setup(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct qed_sb_info *sb_info); /** * @brief qed_int_sb_release - releases the sb_info structure. * * once the structure is released, it's memory can be freed * * @param p_hwfn * @param sb_info points to an allocated sb_info structure * @param sb_id the sb_id to be used (zero based in driver) * should never be equal to QED_SP_SB_ID * (SP Status block) * * @return int */ int qed_int_sb_release(struct qed_hwfn *p_hwfn, struct qed_sb_info *sb_info, u16 sb_id); /** * @brief qed_int_sp_dpc - To be called when an interrupt is received on the * default status block. * * @param p_hwfn - pointer to hwfn * */ void qed_int_sp_dpc(unsigned long hwfn_cookie); /** * @brief qed_int_get_num_sbs - get the number of status * blocks configured for this funciton in the igu. * * @param p_hwfn * @param p_sb_cnt_info * * @return int - number of status blocks configured */ void qed_int_get_num_sbs(struct qed_hwfn *p_hwfn, struct qed_sb_cnt_info *p_sb_cnt_info); /** * @brief qed_int_disable_post_isr_release - performs the cleanup post ISR * release. The API need to be called after releasing all slowpath IRQs * of the device. * * @param cdev * */ void qed_int_disable_post_isr_release(struct qed_dev *cdev); #define QED_CAU_DEF_RX_TIMER_RES 0 #define QED_CAU_DEF_TX_TIMER_RES 0 #define QED_SB_ATT_IDX 0x0001 #define QED_SB_EVENT_MASK 0x0003 #define SB_ALIGNED_SIZE(p_hwfn) \ ALIGNED_TYPE_SIZE(struct status_block_e4, p_hwfn) #define QED_SB_INVALID_IDX 0xffff struct qed_igu_block { u8 status; #define QED_IGU_STATUS_FREE 0x01 #define QED_IGU_STATUS_VALID 0x02 #define QED_IGU_STATUS_PF 0x04 #define QED_IGU_STATUS_DSB 0x08 u8 vector_number; u8 function_id; u8 is_pf; /* Index inside IGU [meant for back reference] */ u16 igu_sb_id; struct qed_sb_info *sb_info; }; struct qed_igu_info { struct qed_igu_block entry[MAX_TOT_SB_PER_PATH]; u16 igu_dsb_id; struct qed_sb_cnt_info usage; bool b_allow_pf_vf_change; }; /** * @brief - Make sure the IGU CAM reflects the resources provided by MFW * * @param p_hwfn * @param p_ptt */ int qed_int_igu_reset_cam(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt); /** * @brief Translate the weakly-defined client sb-id into an IGU sb-id * * @param p_hwfn * @param sb_id - user provided sb_id * * @return an index inside IGU CAM where the SB resides */ u16 qed_get_igu_sb_id(struct qed_hwfn *p_hwfn, u16 sb_id); /** * @brief return a pointer to an unused valid SB * * @param p_hwfn * @param b_is_pf - true iff we want a SB belonging to a PF * * @return point to an igu_block, NULL if none is available */ struct qed_igu_block *qed_get_igu_free_sb(struct qed_hwfn *p_hwfn, bool b_is_pf); void qed_int_igu_init_pure_rt(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, bool b_set, bool b_slowpath); void qed_int_igu_init_rt(struct qed_hwfn *p_hwfn); /** * @brief qed_int_igu_read_cam - Reads the IGU CAM. * This function needs to be called during hardware * prepare. It reads the info from igu cam to know which * status block is the default / base status block etc. * * @param p_hwfn * @param p_ptt * * @return int */ int qed_int_igu_read_cam(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt); typedef int (*qed_int_comp_cb_t)(struct qed_hwfn *p_hwfn, void *cookie); /** * @brief qed_int_register_cb - Register callback func for * slowhwfn statusblock. * * Every protocol that uses the slowhwfn status block * should register a callback function that will be called * once there is an update of the sp status block. * * @param p_hwfn * @param comp_cb - function to be called when there is an * interrupt on the sp sb * * @param cookie - passed to the callback function * @param sb_idx - OUT parameter which gives the chosen index * for this protocol. * @param p_fw_cons - pointer to the actual address of the * consumer for this protocol. * * @return int */ int qed_int_register_cb(struct qed_hwfn *p_hwfn, qed_int_comp_cb_t comp_cb, void *cookie, u8 *sb_idx, __le16 **p_fw_cons); /** * @brief qed_int_unregister_cb - Unregisters callback * function from sp sb. * Partner of qed_int_register_cb -> should be called * when no longer required. * * @param p_hwfn * @param pi * * @return int */ int qed_int_unregister_cb(struct qed_hwfn *p_hwfn, u8 pi); /** * @brief qed_int_get_sp_sb_id - Get the slowhwfn sb id. * * @param p_hwfn * * @return u16 */ u16 qed_int_get_sp_sb_id(struct qed_hwfn *p_hwfn); /** * @brief Status block cleanup. Should be called for each status * block that will be used -> both PF / VF * * @param p_hwfn * @param p_ptt * @param igu_sb_id - igu status block id * @param opaque - opaque fid of the sb owner. * @param b_set - set(1) / clear(0) */ void qed_int_igu_init_pure_rt_single(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u16 igu_sb_id, u16 opaque, bool b_set); /** * @brief qed_int_cau_conf - configure cau for a given status * block * * @param p_hwfn * @param ptt * @param sb_phys * @param igu_sb_id * @param vf_number * @param vf_valid */ void qed_int_cau_conf_sb(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, dma_addr_t sb_phys, u16 igu_sb_id, u16 vf_number, u8 vf_valid); /** * @brief qed_int_alloc * * @param p_hwfn * @param p_ptt * * @return int */ int qed_int_alloc(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt); /** * @brief qed_int_free * * @param p_hwfn */ void qed_int_free(struct qed_hwfn *p_hwfn); /** * @brief qed_int_setup * * @param p_hwfn * @param p_ptt */ void qed_int_setup(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt); /** * @brief - Enable Interrupt & Attention for hw function * * @param p_hwfn * @param p_ptt * @param int_mode * * @return int */ int qed_int_igu_enable(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_int_mode int_mode); /** * @brief - Initialize CAU status block entry * * @param p_hwfn * @param p_sb_entry * @param pf_id * @param vf_number * @param vf_valid */ void qed_init_cau_sb_entry(struct qed_hwfn *p_hwfn, struct cau_sb_entry *p_sb_entry, u8 pf_id, u16 vf_number, u8 vf_valid); int qed_int_set_timer_res(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u8 timer_res, u16 sb_id, bool tx); #define QED_MAPPING_MEMORY_SIZE(dev) (NUM_OF_SBS(dev)) #endif
{ "pile_set_name": "Github" }
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # ##### END GPL LICENSE BLOCK ##### import json import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs, quote as urlquote, urlparse import requests class SimpleOAuthAuthenticator(object): def __init__(self, server_url, client_id, ports): self.server_url = server_url self.client_id = client_id self.ports = ports def _get_tokens(self, authorization_code=None, refresh_token=None, grant_type="authorization_code"): data = { "grant_type": grant_type, "state": "random_state_string", "client_id": self.client_id, "scopes": "read write", } if hasattr(self, 'redirect_uri'): data["redirect_uri"] = self.redirect_uri if authorization_code: data['code'] = authorization_code if refresh_token: data['refresh_token'] = refresh_token response = requests.post( '%s/o/token/' % self.server_url, data=data ) if response.status_code != 200: print("error retrieving refresh tokens %s" % response.status_code) print(response.content) return None, None response_json = json.loads(response.content) refresh_token = response_json ['refresh_token'] access_token = response_json ['access_token'] return access_token, refresh_token, response_json def get_new_token(self, register=True, redirect_url=None): class HTTPServerHandler(BaseHTTPRequestHandler): html_template = '<html>%(head)s<h1>%(message)s</h1></html>' def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if 'code' in self.path: self.auth_code = self.path.split('=')[1] # Display to the user that they no longer need the browser window if redirect_url: redirect_string = ( '<head><meta http-equiv="refresh" content="0;url=%(redirect_url)s"></head>' '<script> window.location.href="%(redirect_url)s"; </script>' % {'redirect_url': redirect_url} ) else: redirect_string = "" self.wfile.write(bytes(self.html_template % {'head': redirect_string, 'message': 'You may now close this window.'}, 'utf-8')) qs = parse_qs(urlparse(self.path).query) self.server.authorization_code = qs['code'][0] else: self.wfile.write(bytes(self.html_template % {'head': '', 'message': 'Authorization failed.'}, 'utf-8')) for port in self.ports: try: httpServer = HTTPServer(('localhost', port), HTTPServerHandler) except OSError: continue break self.redirect_uri = "http://localhost:%s/consumer/exchange/" % port authorize_url = ( "/o/authorize?client_id=%s&state=random_state_string&response_type=code&" "redirect_uri=%s" % (self.client_id, self.redirect_uri) ) if register: authorize_url = "%s/accounts/register/?next=%s" % (self.server_url, urlquote(authorize_url)) else: authorize_url = "%s%s" % (self.server_url, authorize_url) webbrowser.open_new(authorize_url) httpServer.handle_request() authorization_code = httpServer.authorization_code return self._get_tokens(authorization_code=authorization_code) def get_refreshed_token(self, refresh_token): return self._get_tokens(refresh_token=refresh_token, grant_type="refresh_token")
{ "pile_set_name": "Github" }
sha256:90264c80d0cf925dc27eecd3be2fb36b333bf231703aa8f834fb39092ec5460c
{ "pile_set_name": "Github" }
#!/usr/bin/env python import os import sys import warnings try: from setuptools import setup from setuptools.command.test import test as TestCommand from setuptools.command.build_ext import build_ext from setuptools.extension import Extension class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, because outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) except ImportError: from distutils.core import setup, Extension from distutils.command.build_ext import build_ext def PyTest(x): x class custom_build_ext(build_ext): """ NOTE: This code was originally taken from tornado. Allows C extension building to fail. The C extension speeds up crc16, but is not essential. """ warning_message = """ ******************************************************************** WARNING: %s could not be compiled. No C extensions are essential for aredis to run, although they do result in significant speed improvements for websockets. %s Here are some hints for popular operating systems: If you are seeing this message on Linux you probably need to install GCC and/or the Python development package for your version of Python. Debian and Ubuntu users should issue the following command: $ sudo apt-get install build-essential python-dev RedHat and CentOS users should issue the following command: $ sudo yum install gcc python-devel Fedora users should issue the following command: $ sudo dnf install gcc python-devel If you are seeing this message on OSX please read the documentation here: https://api.mongodb.org/python/current/installation.html#osx ******************************************************************** """ def run(self): try: build_ext.run(self) except Exception: e = sys.exc_info()[1] sys.stdout.write('%s\n' % str(e)) warnings.warn(self.warning_message % ("Extension modules", "There was an issue with " "your platform configuration" " - see above.")) def build_extension(self, ext): name = ext.name try: build_ext.build_extension(self, ext) except Exception: e = sys.exc_info()[1] sys.stdout.write('%s\n' % str(e)) warnings.warn(self.warning_message % ("The %s extension " "module" % (name,), "The output above " "this warning shows how " "the compilation " "failed.")) f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) long_description = f.read() f.close() setup( name='aredis', version='1.1.8', description='Python async client for Redis key-value store', long_description=long_description, url='https://github.com/NoneGG/aredis', author='Jason Chen', author_email='[email protected]', maintainer='Jason Chen', maintainer_email='[email protected]', keywords=['Redis', 'key-value store', 'asyncio'], license='MIT', packages=['aredis', 'aredis.commands'], tests_require=['pytest', 'pytest_asyncio>=0.5.0'], cmdclass={ 'test': PyTest, 'build_ext': custom_build_ext }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8' ], ext_modules=[ Extension(name='aredis.speedups', sources=['aredis/speedups.c']), ], # The good news is that the standard library always # takes the precedence over site packages, # so even if a local contextvars module is installed, # the one from the standard library will be used. install_requires=[ 'contextvars;python_version<"3.7"' ] )
{ "pile_set_name": "Github" }
package(default_visibility = ["//visibility:public"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", "go_test", ) go_test( name = "go_default_test", srcs = ["passwordfile_test.go"], importpath = "k8s.io/apiserver/plugin/pkg/authenticator/password/passwordfile", library = ":go_default_library", deps = ["//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library"], ) go_library( name = "go_default_library", srcs = ["passwordfile.go"], importpath = "k8s.io/apiserver/plugin/pkg/authenticator/password/passwordfile", deps = [ "//vendor/github.com/golang/glog:go_default_library", "//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], )
{ "pile_set_name": "Github" }
package com.huawei.camera; import android.hardware.ICameraService; import android.media.ImageReader; import android.os.IBinder; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemProperties; import android.util.Log; public final class HwCameraUtil { private static final String TAG = "HwCameraUtil"; private HwCameraUtil() { } public static synchronized boolean requestPreviewImage(String cameraId, ImageReader imageReader) { synchronized (HwCameraUtil.class) { if (cameraId != null) { if (cameraId.length() != 0) { if (imageReader == null) { Log.e(TAG, "requestPreviewImage imageReader is null"); return false; } else if (imageReader.getSurface() == null) { Log.e(TAG, "requestPreviewImage imageReader surface is null"); return false; } else if (!imageReader.getSurface().isValid()) { Log.e(TAG, "requestPreviewImage imageReader surface is invalid"); return false; } else if (imageReader.getImageFormat() != 35) { Log.e(TAG, "requestPreviewImage unsupported format " + imageReader.getImageFormat()); return false; } else { ICameraService cameraService = CameraManagerGlobal.get().getCameraService(); if (cameraService == null) { Log.e(TAG, "getCameraService is null"); return false; } try { return cameraService.requestPreviewImage(cameraId, imageReader.getSurface()); } catch (RemoteException e) { Log.e(TAG, "requestPreviewImage RemoteException " + e.getMessage()); return false; } } } } Log.e(TAG, "requestPreviewImage cameraId illegal"); return false; } } private static final class CameraManagerGlobal implements IBinder.DeathRecipient { private static final CameraManagerGlobal CAMERA_MANAGER_GLOBAL = new CameraManagerGlobal(); private static final String CAMERA_SERVICE_BINDER_NAME = "media.camera"; private static final boolean IS_CAMERA_SERVICE_DISABLED = SystemProperties.getBoolean("config.disable_cameraservice", false); private static final String TAG = "CameraManagerGlobal"; private final Object lock = new Object(); private ICameraService mCameraService; private CameraManagerGlobal() { } public static CameraManagerGlobal get() { return CAMERA_MANAGER_GLOBAL; } public ICameraService getCameraService() { ICameraService iCameraService; synchronized (this.lock) { connectCameraServiceLocked(); if (this.mCameraService == null && !IS_CAMERA_SERVICE_DISABLED) { Log.e(TAG, "Camera service is unavailable"); } iCameraService = this.mCameraService; } return iCameraService; } private void connectCameraServiceLocked() { if (this.mCameraService == null && !IS_CAMERA_SERVICE_DISABLED) { Log.i(TAG, "Connecting to camera service"); IBinder cameraServiceBinder = ServiceManager.getService(CAMERA_SERVICE_BINDER_NAME); if (cameraServiceBinder == null) { Log.e(TAG, "Camera service is now down, leave mCameraService as null"); return; } try { cameraServiceBinder.linkToDeath(this, 0); this.mCameraService = ICameraService.Stub.asInterface(cameraServiceBinder); } catch (RemoteException e) { Log.e(TAG, "linkToDeath failed"); } } } public void binderDied() { synchronized (this.lock) { if (this.mCameraService != null) { this.mCameraService = null; } } } } }
{ "pile_set_name": "Github" }
/** * Copyright (c) Areslabs. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import './base.dart'; class Template extends BaseWidget { Object tempVnode; String datakey; Template({Object tempVnode, String datakey}) : super(diuu: null, tempName: null, child: null, children: null) { this.tempVnode = tempVnode; this.datakey = datakey; } }
{ "pile_set_name": "Github" }
import * as React from 'react'; import { grey400, grey800, grey50, white, black } from '../styles/colors'; import { NativeModules, Platform, StyleProp, Switch as NativeSwitch, ViewStyle, } from 'react-native'; import setColor from 'color'; import { withTheme } from '../core/theming'; const version = NativeModules.PlatformConstants ? NativeModules.PlatformConstants.reactNativeVersion : undefined; type Props = React.ComponentPropsWithRef<typeof NativeSwitch> & { /** * Disable toggling the switch. */ disabled?: boolean; /** * Value of the switch, true means 'on', false means 'off'. */ value?: boolean; /** * Custom color for switch. */ color?: string; /** * Callback called with the new value when it changes. */ onValueChange?: Function; style?: StyleProp<ViewStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }; /** * Switch is a visual toggle between two mutually exclusive states — on and off. * * <div class="screenshots"> * <figure> * <img src="screenshots/switch-enabled.android.png" /> * <figcaption>Android (enabled)</figcaption> * </figure> * <figure> * <img src="screenshots/switch-disabled.android.png" /> * <figcaption>Android (disabled)</figcaption> * </figure> * <figure> * <img src="screenshots/switch-enabled.ios.png" /> * <figcaption>iOS (enabled)</figcaption> * </figure> * <figure> * <img src="screenshots/switch-disabled.ios.png" /> * <figcaption>iOS (disabled)</figcaption> * </figure> * </div> * * ## Usage * ```js * import * as React from 'react'; * import { Switch } from 'react-native-paper'; * * const MyComponent = () => { * const [isSwitchOn, setIsSwitchOn] = React.useState(false); * * const onToggleSwitch = () => setIsSwitchOn(!isSwitchOn); * * return <Switch value={isSwitchOn} onValueChange={onToggleSwitch} />; * }; * * export default MyComponent; * ``` */ class Switch extends React.Component<Props> { render() { const { value, disabled, onValueChange, color, theme, ...rest } = this.props; const checkedColor = color || theme.colors.accent; const onTintColor = Platform.OS === 'ios' ? checkedColor : disabled ? theme.dark ? setColor(white).alpha(0.1).rgb().string() : setColor(black).alpha(0.12).rgb().string() : setColor(checkedColor).alpha(0.5).rgb().string(); const thumbTintColor = Platform.OS === 'ios' ? undefined : disabled ? theme.dark ? grey800 : grey400 : value ? checkedColor : theme.dark ? grey400 : grey50; const props = version && version.major === 0 && version.minor <= 56 ? { onTintColor, thumbTintColor, } : { thumbColor: thumbTintColor, trackColor: { true: onTintColor, false: '', }, }; return ( <NativeSwitch value={value} disabled={disabled} onValueChange={disabled ? undefined : onValueChange} {...props} {...rest} /> ); } } export default withTheme(Switch);
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* afdummy.h */ /* */ /* Auto-fitter dummy routines to be used if no hinting should be */ /* performed (specification). */ /* */ /* Copyright 2003, 2004, 2005 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __AFDUMMY_H__ #define __AFDUMMY_H__ #include "aftypes.h" FT_BEGIN_HEADER /* A dummy script metrics class used when no hinting should * be performed. This is the default for non-latin glyphs! */ FT_CALLBACK_TABLE const AF_ScriptClassRec af_dummy_script_class; /* */ FT_END_HEADER #endif /* __AFDUMMY_H__ */ /* END */
{ "pile_set_name": "Github" }
/** * Copyright 2018 The Feign Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package reactivefeign.client; /** * Used to modify request before call. May be used to set auth headers to all requests. * * @author Sergii Karpenko */ public class InterceptorReactiveHttpClient { public static ReactiveHttpClient intercept(ReactiveHttpClient reactiveHttpClient, ReactiveHttpRequestInterceptor interceptor) { return request -> reactiveHttpClient.executeRequest(interceptor.apply(request)); } }
{ "pile_set_name": "Github" }
// Copyright 2020 The VectorSQL Authors. // // Code is licensed under Apache License, Version 2.0. package planners import ( "encoding/json" "base/errors" "parsers/sqlparser" ) type DropTablePlan struct { Name string Ast *sqlparser.DDL } func NewDropTablePlan(ast sqlparser.Statement) IPlan { return &DropTablePlan{ Name: "DropTablePlan", Ast: ast.(*sqlparser.DDL), } } func (plan *DropTablePlan) Build() error { if plan.Ast.Name() != sqlparser.NodeNameTableDrop { return errors.Errorf("DropTable Plan must be 'Drop' operation, got:%s", plan.Ast.Name()) } return nil } func (plan *DropTablePlan) Walk(visit Visit) error { return nil } func (plan *DropTablePlan) String() string { out, err := json.MarshalIndent(plan, "", " ") if err != nil { return err.Error() } return string(out) }
{ "pile_set_name": "Github" }
# Odoo Individual Contributor License Agreement ## Odoo ICLA v1.0 Based on the Apache Software Foundation Individual Contributor License Agreement v2.0, with modifications Thank you for your interest in an Odoo S.A. (the "Project Leads" ) open source project. In order to clarify the intellectual property license granted with Contributions from any person or entity, the Odoo Project Leads must have a Contributor License Agreement (the "Agreement") on file that has been signed by each Contributor, indicating agreement to the license terms below. This license is for your protection as a Contributor as well as the protection of the Project, its users, and the Odoo Project Leads; it does not change your rights to use your own Contributions for any other purpose. If you have not already done so, please complete and sign the Agreement by: * following the electronic procedure to complete, sign and submit the ICLA at https://www.odoo.com/sign-cla * or scanning and emailing the signed Agreement to [email protected] **Please read this document carefully before signing and keep a copy for your records.** You accept and agree to the following terms and conditions for Your present and future Contributions submitted to the Project. Except for the license granted herein to the Project Leads and recipients of software distributed by the Project Leads, You reserve all right, title, and interest in and to Your Contributions. 1. Definitions. "You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the Project Leads for inclusion in, or documentation of, any of the products managed or maintained by the Project Leads (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Project Leads or their representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project Leads for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution." 2. Grant of Copyright License. Subject to the terms and conditions of this Agreement, You hereby grant to the Project Leads and to recipients of software distributed by the Project Leads a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. 3. Grant of Patent License. Subject to the terms and conditions of this Agreement, You hereby grant to the Project Leads and to recipients of software distributed by the Project Leads a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed. 4. You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to the Project Leads, or that your employer has executed a separate Corporate Contributor License Agreement with the Project Leads. 5. You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions. 6. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. 7. Should You wish to submit work that is not Your original creation, You may submit it to the Project Leads separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]". 8. You agree to notify the Project Leads of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. ``` Full Name: _________________________________________________ Email: _____________________________________________________ Telephone: _________________________________________________ Mailing Address: ___________________________________________ ___________________________________________ Country: ___________________________________________________ Signature: _________________________________________________ Date: ______________________________________________________ ```
{ "pile_set_name": "Github" }
package fr.inria.spirals.repairnator.process.inspectors; import fr.inria.jtravis.entities.Build; import fr.inria.spirals.repairnator.BuildToBeInspected; import fr.inria.spirals.repairnator.config.RepairnatorConfig; import fr.inria.spirals.repairnator.notifier.AbstractNotifier; import fr.inria.spirals.repairnator.notifier.ErrorNotifier; import fr.inria.spirals.repairnator.notifier.PatchNotifier; import fr.inria.spirals.repairnator.pipeline.RepairToolsManager; import fr.inria.spirals.repairnator.process.git.GitHelper; import fr.inria.spirals.repairnator.process.inspectors.properties.Properties; import fr.inria.spirals.repairnator.process.inspectors.properties.machineInfo.MachineInfo; import fr.inria.spirals.repairnator.process.step.AbstractStep; import fr.inria.spirals.repairnator.process.step.AddExperimentalPluginRepo; import fr.inria.spirals.repairnator.process.step.BuildProject; import fr.inria.spirals.repairnator.process.step.JenkinsCloneRepository; import fr.inria.spirals.repairnator.process.step.TestProject; import fr.inria.spirals.repairnator.process.step.WritePropertyFile; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutBuggyBuild; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutPatchedBuild; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutType; import fr.inria.spirals.repairnator.process.step.gatherinfo.BuildShouldFail; import fr.inria.spirals.repairnator.process.step.gatherinfo.BuildShouldPass; import fr.inria.spirals.repairnator.process.step.gatherinfo.GatherTestInformation; import fr.inria.spirals.repairnator.process.step.paths.ComputeClasspath; import fr.inria.spirals.repairnator.process.step.paths.ComputeModules; import fr.inria.spirals.repairnator.process.step.paths.ComputeSourceDir; import fr.inria.spirals.repairnator.process.step.paths.ComputeTestDir; import fr.inria.spirals.repairnator.process.step.push.CommitPatch; import fr.inria.spirals.repairnator.process.step.push.CommitProcessEnd; import fr.inria.spirals.repairnator.process.step.push.CommitType; import fr.inria.spirals.repairnator.process.step.push.InitRepoToPush; import fr.inria.spirals.repairnator.process.step.push.PushProcessEnd; import fr.inria.spirals.repairnator.process.step.repair.AbstractRepairStep; import fr.inria.spirals.repairnator.serializer.AbstractDataSerializer; import fr.inria.spirals.repairnator.states.ScannedBuildStatus; import fr.inria.spirals.repairnator.utils.Utils; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * This class initialize the pipelines by creating the steps: * it's the backbone of the pipeline. */ public class JenkinsProjectInspector extends ProjectInspector{ private final Logger logger = LoggerFactory.getLogger(ProjectInspector.class); private GitHelper gitHelper; private BuildToBeInspected buildToBeInspected; private String gitUrl; private String gitSlug; private String gitBranch; private String gitCommit; private String repoLocalPath; private String repoToPushLocalPath; private String workspace; private String m2LocalPath; private List<AbstractDataSerializer> serializers; private JobStatus jobStatus; private List<AbstractNotifier> notifiers; private PatchNotifier patchNotifier; private CheckoutType checkoutType; private List<AbstractStep> steps; private AbstractStep finalStep; private boolean pipelineEnding; public JenkinsProjectInspector(BuildToBeInspected buildToBeInspected, String workspace, List<AbstractDataSerializer> serializers, List<AbstractNotifier> notifiers) { super(buildToBeInspected,workspace,serializers,notifiers); } public JenkinsProjectInspector(String workspace,String gitUrl,String gitBranch,String gitCommit,List<AbstractDataSerializer> serializers, List<AbstractNotifier> notifiers) { super(workspace,gitUrl,gitBranch,gitCommit,serializers,notifiers); this.gitUrl = gitUrl; this.gitBranch = gitBranch; this.gitCommit = gitCommit; this.gitSlug = this.gitUrl.split("https://github.com/",2)[1].replace(".git",""); this.workspace = workspace; this.repoLocalPath = workspace + File.separator + this.getRepoSlug(); this.repoToPushLocalPath = repoLocalPath+"_topush"; this.m2LocalPath = new File(this.repoLocalPath + File.separator + ".m2").getAbsolutePath(); this.serializers = null; this.gitHelper = new GitHelper(); this.jobStatus = new JobStatus(repoLocalPath); this.notifiers = notifiers; this.checkoutType = CheckoutType.NO_CHECKOUT; this.steps = new ArrayList<>(); this.initProperties(); } /* This is the new branch for end process */ @Override public String getRemoteBranchName() { return this.getRepoSlug().replace('/', '-'); } @Override public String getRepoSlug() { return this.gitSlug; } public String getGitUrl() { return this.gitUrl; } /* This is the branch , which repairnator will repair*/ public String getCheckoutBranchName() { return this.gitBranch; } public String getGitCommit() { return this.gitCommit; } @Override protected void initProperties() { try { Properties properties = this.jobStatus.getProperties(); /* ProcessDurations use checkoutBuggyBuild*/ fr.inria.spirals.repairnator.process.inspectors.properties.repository.Repository repository = properties.getRepository(); repository.setName(this.getRepoSlug()); repository.setUrl(this.getGitUrl()); GitHub gitHub; try { gitHub = RepairnatorConfig.getInstance().getGithub(); GHRepository repo = gitHub.getRepository(this.getRepoSlug()); repository.setGithubId(repo.getId()); if (repo.isFork()) { repository.setIsFork(true); repository.getOriginal().setName(repo.getParent().getFullName()); repository.getOriginal().setGithubId(repo.getParent().getId()); repository.getOriginal().setUrl(Utils.getSimpleGithubRepoUrl(repo.getParent().getFullName())); } } catch (IOException e) { this.logger.warn("It was not possible to retrieve information to check if " + this.getRepoSlug() + " is a fork."); this.logger.debug(e.toString()); } } catch (Exception e) { this.logger.error("Error while initializing metrics.", e); } } public String getRepoLocalPath() { return this.repoLocalPath; } public void run() { AbstractStep cloneRepo = new JenkinsCloneRepository(this); // If we have experimental plugins, we need to add them here. String[] repos = RepairnatorConfig.getInstance().getExperimentalPluginRepoList(); if(repos != null) { for(int i = 0; i < repos.length-1; i =+ 2) { cloneRepo.addNextStep(new AddExperimentalPluginRepo(this, repos[i], repos[i+1], repos[i+2])); } } cloneRepo .addNextStep(new BuildProject(this)) .addNextStep(new TestProject(this)) .addNextStep(new GatherTestInformation(this, true, new BuildShouldFail(), false)) .addNextStep(new InitRepoToPush(this)) .addNextStep(new ComputeClasspath(this, false)) .addNextStep(new ComputeSourceDir(this, false, false)) .addNextStep(new ComputeTestDir(this, false)); for (String repairToolName : RepairnatorConfig.getInstance().getRepairTools()) { AbstractRepairStep repairStep = RepairToolsManager.getStepFromName(repairToolName); if (repairStep != null) { repairStep.setProjectInspector(this); cloneRepo.addNextStep(repairStep); } else { logger.error("Error while getting repair step class for following name: " + repairToolName); } } cloneRepo.addNextStep(new CommitPatch(this, CommitType.COMMIT_REPAIR_INFO)) .addNextStep(new CheckoutPatchedBuild(this, true)) .addNextStep(new BuildProject(this)) .addNextStep(new TestProject(this)) .addNextStep(new GatherTestInformation(this, true, new BuildShouldPass(), true)) .addNextStep(new CommitPatch(this, CommitType.COMMIT_HUMAN_PATCH)); this.finalStep = new ComputeSourceDir(this, false, true); // this step is used to compute code metrics on the project this.finalStep. addNextStep(new ComputeModules(this, false)). addNextStep(new WritePropertyFile(this)). addNextStep(new CommitProcessEnd(this)). addNextStep(new PushProcessEnd(this)); cloneRepo.setDataSerializer(this.serializers); cloneRepo.setNotifiers(this.notifiers); this.printPipeline(); try { cloneRepo.execute(); } catch (Exception e) { this.jobStatus.addStepError("Unknown", e.getMessage()); this.logger.error("Exception catch while executing steps: ", e); this.jobStatus.setFatalError(e); ErrorNotifier errorNotifier = ErrorNotifier.getInstance(); if (errorNotifier != null) { errorNotifier.observe(this); } for (AbstractDataSerializer serializer : this.serializers) { serializer.serialize(); } } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Xamarin.Forms.Controls.GalleryPages.ShapesGalleries.ClipViewsGallery" Title="ClipViews Gallery"> <ContentPage.Resources> <ResourceDictionary> <EllipseGeometry x:Key="EllipseClip" RadiusX="300" RadiusY="50" /> </ResourceDictionary> </ContentPage.Resources> <ContentPage.Content> <ScrollView> <StackLayout Padding="12"> <Button BackgroundColor="Red" Text="Button" Clip="{StaticResource EllipseClip}" /> <DatePicker BackgroundColor="Red" Clip="{StaticResource EllipseClip}" /> <Entry BackgroundColor="Red" Placeholder="Entry" Clip="{StaticResource EllipseClip}" /> <Editor BackgroundColor="Red" Placeholder="Editor" Clip="{StaticResource EllipseClip}" /> <Grid BackgroundColor="Red" HeightRequest="50" Clip="{StaticResource EllipseClip}"> <Label Text="Grid" /> </Grid> <SearchBar BackgroundColor="Red" Clip="{StaticResource EllipseClip}" /> <TimePicker BackgroundColor="Red" Clip="{StaticResource EllipseClip}" /> </StackLayout> </ScrollView> </ContentPage.Content> </ContentPage>
{ "pile_set_name": "Github" }
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { render } from 'enzyme'; import { requiredProps } from '../../../test/required_props'; import { EuiPageHeader } from './page_header'; describe('EuiPageHeader', () => { test('is rendered', () => { const component = render(<EuiPageHeader {...requiredProps} />); expect(component).toMatchSnapshot(); }); });
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Knp\DoctrineBehaviors\Tests\Fixtures\Entity; use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface; use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait; /** * @ORM\Entity */ class TimestampableEntity implements TimestampableInterface { use TimestampableTrait; /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") * @var int */ private $id; /** * @ORM\Column(type="string", nullable=true) * @var string */ private $title; public function getId(): int { return $this->id; } public function getTitle(): string { return $this->title; } public function setTitle(string $title): void { $this->title = $title; } }
{ "pile_set_name": "Github" }
<resources> <!-- Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). --> <dimen name="activity_horizontal_margin">64dp</dimen> </resources>
{ "pile_set_name": "Github" }
#!/bin/bash #FUNCTION DECLARATION ############################################################################### if [ "-bash" = $0 ]; then BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" else BASEDIR="$(cd "$(dirname "$0")" && pwd)" fi BASEDIR=$(dirname $(dirname $BASEDIR)) # set BASEDIR to root of TorQ directory mkdir -p ${BASEDIR}/monit/logs # create directory for monit logs checkst(){ #function to check if file exists case $3 in exist) if [[ -e $1 ]]; then echo -e "[ \033[01;32mOK\033[0m ] $2" else echo -e "[ \033[01;31mFAILED\033[0m ] $2" fi ;; nexist) if [[ -e $1 ]]; then echo -e "[ \033[01;31mFAILED\033[0m ] $2" else echo -e "[ \033[01;32mOK\033[0m ] $2" fi ;; *) echo "Not yet implemented" ;; esac } createmonconfig(){ #function to read all processes from the processes.csv #and build the array #generating the monitconfig.cfg procs=$1 startstopsc=$2 procs="${procs:-${BASEDIR}/appconfig/process.csv}" # sets procs to default only if unset already startstopsc="${startstopsc:-${BASEDIR}/torq.sh}" output="$configs/monitconfig.cfg" proclist=`tail -n +2 ${procs} | awk -F "\"*,\"*" '{print $3 " " $4}'|cut -d" " -f1,2` echo "$proclist"|while read procs;do array=($procs) proctype=${array[0]} procname=${array[1]} if [[ ! "$procname" == "killtick" ]];then # exclude killtick from the list of monitored processes #eval "echo $2" >> $output eval "echo \"${monittemplate}\"" >> $output echo "" >> $output fi done checkst "$configs/monitconfig.cfg" "Output file created..." "exist" } createmonalert(){ #generating the monitalert file from template if [ -f ${configs}/monitalert.cfg ];then rm ${configs}/monitalert.cfg checkst "${configs}/monitalert.cfg" "Deleting monitalert.cfg..." "nexist" fi cp ${templates}/monitalert.cfg ${configs} checkst "${configs}/monitalert.cfg" "Copying monitalert from ${templates}..." "exist" } generate(){ eval "cd $BASEDIR && . setenv.sh && cd - > /dev/null" # set environment variables templates="${BASEDIR}/monit/templates" # set temmplates folder configs="${BASEDIR}/monit/config" # set configs folder monit_control="${BASEDIR}/monit/config/monitrc" # set output file for main monit conf monittemplate="$(cat ${templates}/monittemplate.txt)" mkdir -p $configs case $1 in monitalert) if [ ! -f ${configs}/monitalert.cfg ];then createmonalert fi ;; monitconfig) if [ ! -f ${configs}/monitconfig.cfg ];then createmonconfig "$2" "$3" fi ;; monitrc) if [ ! -f ${monit_control} ];then if [ -z $2 ]; then controltemplate="$(cat ${templates}/monitrc)" else controltemplate="$(cat $2)" fi eval "echo \"${controltemplate}\"" > ${monit_control} chmod 700 ${monit_control} checkst "$monit_control" "Creating monitrc" "exist" fi ;; all) #create monitalert if [ ! -f ${configs}/monitalert.cfg ];then createmonalert fi #create monitconfig if [ ! -f ${configs}/monitconfig.cfg ];then createmonconfig "$2" "$3" fi #create monitrc if [ ! -f ${monit_control} ];then if [ -z $4 ]; then controltemplate="$(cat ${templates}/monitrc)" else controltemplate="$(cat $4)" fi eval "echo \"${controltemplate}\"" > ${monit_control} chmod 700 ${monit_control} checkst "$monit_control" "Creating monitrc" "exist" fi ;; *) echo "Not yet implemented" ;; esac } start(){ #this function just starts monit and specifies the location of the monitrc if [ -z $1 ];then echo "Argument not provided monit will default to the following monitrc file: ${BASEDIR}/monit/config/monitrc" monit -c ${BASEDIR}/monit/config/monitrc else monit -c $1 fi } usage(){ echo "" echo "NOTE: if any of the arguments are missing the default locations will be used" echo "" echo "----------------------------------------------------------------------------" printf "%-20s | %-30s | %-30s\n" "FILE" "DEFAULT TEMPLATE PATH" "DEFAULT CONFIG PATH" echo "----------------------------------------------------------------------------" printf "%-20s | %-30s | %-30s\n" "monitconfig.cfg" "deploy/monit/templates" "deploy/monit/config" printf "%-20s | %-30s | %-30s\n" "monitalert.cfg" "deploy/monit/templates" "deploy/monit/config" printf "%-20s | %-30s | %-30s\n" "monitrc" "deploy/monit/templates" "deploy/monit/config" printf "%-20s | %-30s | %-30s\n" "monit.log" "NA" "deploy/monit/logs" printf "%-20s | %-30s | %-30s\n" "monit.state" "NA" "deploy/monit/logs" echo "----------------------------------------------------------------------------" echo "" echo "" echo "----------------------------------------------------------------------------------------------------------------------------------------------" printf "%-10s | %-15s | %-40s | %-75s\n" "FUNCTION" "OPTION" "COMMENTS" "ARGUMENTS" echo "----------------------------------------------------------------------------------------------------------------------------------------------" printf "%-10s | %-15s | %-40s | %-75s\n" "generate" "monitalert" "generates the monitalert.cfg" "no arguments" printf "%-10s | %-15s | %-40s | %-75s\n" "generate" "monitconfig" "generates the monitconfig.cfg" "\"<path process.csv>\" & \"<path torq.sh>\"" printf "%-10s | %-15s | %-40s | %-75s\n" "generate" "monitrc" "generates the monitrc.cfg" "\"<path monitrc template>\"" printf "%-10s | %-15s | %-40s | %-75s\n" "generate" "all" "generates all *.cfg files & monitrc" "\"<path process.csv>\" & \"<path torq.sh>\" & \"<path monitrc template>\"" printf "%-10s | %-15s | %-40s | %-75s\n" "start" "NA" "starts monit" "\"<path monitrc>\"" echo "----------------------------------------------------------------------------------------------------------------------------------------------" echo "" } "$@"
{ "pile_set_name": "Github" }
fr: SilverStripe\Admin\LeftAndMain: VersionUnknown: Inconnu SilverStripe\AssetAdmin\Forms\UploadField: Dimensions: Dimensions EDIT: Éditer EDITINFO: 'Éditer ce fichier' REMOVE: Retirer SilverStripe\Control\ChangePasswordEmail_ss: CHANGEPASSWORDFOREMAIL: 'Le mot de passe du compte correspondant à l''adresse {email} a été modifié. Si vous n''avez pas modifié votre mot de passe, merci de le changer à l''aide du lien suivant' CHANGEPASSWORDTEXT1: 'Votre mot de passe est maintenant' CHANGEPASSWORDTEXT3: 'Changer le mot de passe' HELLO: Bonjour SilverStripe\Control\Email\ForgotPasswordEmail_ss: HELLO: Bonjour TEXT1: 'Voici votre' TEXT2: 'Lien de réinitialisation de mot de passe' TEXT3: pour SilverStripe\Control\RequestProcessor: INVALID_REQUEST: 'Requête invalide' REQUEST_ABORTED: 'Requête non aboutie' SilverStripe\Core\Manifest\VersionProvider: VERSIONUNKNOWN: Inconnu SilverStripe\Forms\CheckboxField: NOANSWER: Non YESANSWER: Oui SilverStripe\Forms\CheckboxSetField_ss: NOOPTIONSAVAILABLE: 'Aucune option disponible' SilverStripe\Forms\ConfirmedPasswordField: ATLEAST: 'Le mot de passe doit comporter au moins {min} caractères.' BETWEEN: 'Le mot de passe doit comporter entre {min} et {max} caractères.' CURRENT_PASSWORD_ERROR: 'Le mot de passe que vous avez saisi n''est pas correct' CURRENT_PASSWORD_MISSING: 'Vous devez saisir votre mot de passe actuel.' LOGGED_IN_ERROR: 'Vous devez être connecté pour pouvoir changer votre mot de passe' MAXIMUM: 'Le mot de passe ne doit pas comporter plus de {max} caractères.' SHOWONCLICKTITLE: 'Changer le mot de passe' SilverStripe\Forms\DateField: VALIDDATEFORMAT2: 'Saisissez une date au format valide ({format})' VALIDDATEMAXDATE: 'La date doit être antérieure ou égale à celle autorisée ({date})' VALIDDATEMINDATE: 'La date doit être postérieure ou égale à celle autorisée ({date})' SilverStripe\Forms\DatetimeField: VALIDDATEMAXDATETIME: 'La date doit être antérieure ou égale à celle autorisée ({datetime})' VALIDDATETIMEFORMAT: 'Saisissez un format de date et d''heure valide ({format})' VALIDDATETIMEMINDATE: 'La date doit être postérieure ou égale à celle autorisée ({datetime})' SilverStripe\Forms\DropdownField: CHOOSE: (Choisir) SOURCE_VALIDATION: 'Merci de choisir une valeur parmi celles proposées dans la liste. {value} n''est pas une option valide' SilverStripe\Forms\EmailField: VALIDATION: 'Merci de saisir une adresse email' SilverStripe\Forms\FileUploadReceiver: FIELDNOTSET: 'Information sur le fichier introuvable' SilverStripe\Forms\Form: BAD_METHOD: 'Ce formulaire requiert une action {method}' CSRF_EXPIRED_MESSAGE: 'Votre session a expiré. Merci de renvoyer le formulaire.' CSRF_FAILED_MESSAGE: 'Un problème technique est probablement survenu. Merci de cliquer sur le bouton "retour", de rafraîchir la page de votre navigateur, et de réessayer.' VALIDATIONPASSWORDSDONTMATCH: 'Les mots de passe ne correspondent pas' VALIDATIONPASSWORDSNOTEMPTY: 'Les mots de passe ne peuvent pas être vides' VALIDATIONSTRONGPASSWORD: 'Le mot de passe doit comporter au moins un chiffre et un caractère alphanumérique' VALIDATOR: Validateur VALIDCURRENCY: 'Saisissez une monnaie valide' SilverStripe\Forms\FormField: EXAMPLE: 'Par ex. {format}' NONE: aucun SilverStripe\Forms\FormScaffolder: TABMAIN: Principal SilverStripe\Forms\GridField\GridField: Add: 'Ajouter {name}' CSVEXPORT: 'Exporter vers un fichier CSV' CSVIMPORT: 'Importer un fichier CSV' Filter: Filtrer FilterBy: 'Filtrer par' Find: Trouver LinkExisting: 'Lien existant' NewRecord: 'Nouveau {type}' NoItemsFound: 'Aucun élément n’a été trouvé.' PRINTEDAT: 'Imprimé à' PRINTEDBY: 'Imprimé par' PlaceHolder: 'Rechercher {type}' PlaceHolderWithLabels: 'Rechercher {type} par {name}' Print: Imprimer RelationSearch: 'Rechercher relations' ResetFilter: Réinitialiser SilverStripe\Forms\GridField\GridFieldDeleteAction: Delete: Supprimer DeletePermissionsFailure: 'Vous n’avez pas les autorisations pour supprimer' EditPermissionsFailure: 'Pas de permissions pour délier l''enregistrement' UnlinkRelation: Séparer SilverStripe\Forms\GridField\GridFieldDetailForm: CancelBtn: Annuler Create: Créer Delete: Supprimer DeletePermissionsFailure: 'Vous n’avez pas les autorisations pour supprimer' Deleted: '{type} {name} supprimés' Save: Enregistrer SilverStripe\Forms\GridField\GridFieldGroupDeleteAction: UnlinkSelfFailure: 'Impossible de retirer votre propre profil de ce groupe, vous perdriez vos droits d''administration' SilverStripe\Forms\GridField\GridFieldPaginator: OF: de Page: Page View: Vue SilverStripe\Forms\MoneyField: FIELDLABELAMOUNT: Quantité FIELDLABELCURRENCY: Devise INVALID_CURRENCY: '{currency} ne figure pas dans la liste des devises autorisées' SilverStripe\Forms\MultiSelectField: SOURCE_VALIDATION: 'Merci de choisir des valeurs parmi celles proposées dans la liste. Option(s) {value} non valide(s)' SilverStripe\Forms\NullableField: IsNullLabel: 'Est Null' SilverStripe\Forms\NumericField: VALIDATION: "«\_{value}\_» n’est pas un nombre, seul type de donnée acceptée dans ce champ " SilverStripe\Forms\TimeField: VALIDATEFORMAT: 'Merci de saisir un format de date valide ({format})' SilverStripe\ORM\DataObject: PLURALNAME: 'Modèles de donnée' PLURALS: one: 'Un modèle de donnée' other: '{count} modèles de donnée' SINGULARNAME: 'Modèle de donnée' SilverStripe\ORM\FieldType\DBBoolean: ANY: Tout NOANSWER: Non YESANSWER: Oui SilverStripe\ORM\FieldType\DBDate: DAYS_SHORT_PLURALS: one: '{count} jour' other: '{count} jours' HOURS_SHORT_PLURALS: one: '{count} heure' other: '{count} heures' LessThanMinuteAgo: 'moins d''une minute' MINUTES_SHORT_PLURALS: one: '{count} min.' other: '{count} min.' MONTHS_SHORT_PLURALS: one: '{count} mois' other: '{count} mois' SECONDS_SHORT_PLURALS: one: '{count} sec.' other: '{count} sec.' TIMEDIFFAGO: 'Il y a {difference}' TIMEDIFFIN: 'Dans {difference}' YEARS_SHORT_PLURALS: one: '{count} année' other: '{count} années' SilverStripe\ORM\FieldType\DBEnum: ANY: Tout SilverStripe\ORM\Hierarchy: LIMITED_TITLE: 'Enfants trop nombreux ({count})' SilverStripe\ORM\Hierarchy\Hierarchy: InfiniteLoopNotAllowed: "Une boucle sans fin s’est produite dans la hiérarchie «\_{type}\_». Merci de modifier le parent pour résoudre le problème." LIMITED_TITLE: 'Enfants trop nombreux ({count})' SilverStripe\ORM\ValidationException: DEFAULT_ERROR: 'Erreur de validation' SilverStripe\Security\BasicAuth: ENTERINFO: 'Merci d''entrer un identifiant et un mot de passe.' ERRORNOTADMIN: 'Cet utilisateur n''est pas un administrateur.' ERRORNOTREC: 'Identifiant et/ou mot de passe non reconnus' SilverStripe\Security\CMSMemberLoginForm: PASSWORDEXPIRED: '<p>Votre mot de passe a expiré. <a target="_top" href="{link}">Merci d''en choisir un nouveau.</a></p>' SilverStripe\Security\CMSSecurity: INVALIDUSER: '<p>Utilisateur non valide. <a target="_top" href="{link}">Merci de vous authentifier de nouveau ici</a> pour poursuivre.</p>' LOGIN_MESSAGE: '<p>Votre session a expiré pour cause d''inactivité</p>' LOGIN_TITLE: 'Retournez là où vous en étiez en vos connectant de nouveau' SUCCESS: Succès SUCCESSCONTENT: '<p>Connexion réussie. Si vous n''êtes pas automatiquement redirigé <a target="_top" href="{link}">cliquez ici</a></p>' SUCCESS_TITLE: 'Connexion réussie' SilverStripe\Security\DefaultAdminService: DefaultAdminFirstname: 'Administrateur par défaut' SilverStripe\Security\Group: AddRole: 'Ajouter un rôle pour ce groupe' Code: 'Code du groupe' DefaultGroupTitleAdministrators: Administrateur DefaultGroupTitleContentAuthors: 'Auteurs du contenu' Description: Description GROUPNAME: 'Nom du groupe' GroupReminder: 'Si vous choisissez un groupe parent, ce groupe prendra tous ses rôles' HierarchyPermsError: 'Impossible d''attribuer des autorisations au groupe parent "{group}" (requiert un accès en tant qu''administrateur)' Locked: 'Verrouillé?' MEMBERS: Membres NEWGROUP: 'Nouveau groupe' NoRoles: 'Aucun rôle trouvé' PERMISSIONS: Permissions PLURALNAME: Groupes PLURALS: one: 'Un groupe' other: '{count} groupes' Parent: 'Groupe parent' ROLES: Rôles ROLESDESCRIPTION: 'Les rôles sont des ensembles de permissions prédéfinies, et ils peuvent être attribués à des groupes. <br />Si nécessaire, ils peuvent hériter de groupes parents.' RolesAddEditLink: 'Ajouter/éditer les rôles' SINGULARNAME: Groupe Sort: 'Ordre de tri' has_many_Permissions: Autorisations many_many_Members: Membres SilverStripe\Security\LoginAttempt: Email: 'Adresse email' EmailHashed: 'Adresse Email (hashed)' IP: 'Adresse IP' PLURALNAME: 'Tentatives de connexion' PLURALS: one: 'Une tentative de connexion' other: '{count} tentatives de connexion' SINGULARNAME: 'Tentative de connexion' Status: Statut SilverStripe\Security\Member: ADDGROUP: 'Ajouter un groupe' BUTTONCHANGEPASSWORD: 'Changer mot de passe' BUTTONLOGIN: 'Se connecter' BUTTONLOGINOTHER: 'Se connecter avec un identifiant différent' BUTTONLOGOUT: Déconnexion BUTTONLOSTPASSWORD: 'J''ai perdu mon mot de passe' CONFIRMNEWPASSWORD: 'Confirmer nouveau mot de passe' CONFIRMPASSWORD: 'Confirmer Mot De Passe' CURRENT_PASSWORD: 'Mot de passe actuel' EDIT_PASSWORD: 'Nouveau mot de passe' EMAIL: Email EMPTYNEWPASSWORD: 'Le champs nouveau mot de passe ne peut être vide, merci de réessayer' ENTEREMAIL: 'Veuillez entrer une adresse email pour obtenir un lien de réinitialisation du mot de passe.' ERRORLOCKEDOUT2: 'Votre compte a été temporairement désactivé en raison d''un nombre trop élevé d''échecs d''identification. Veuillez réessayer dans {count} minutes.' ERRORNEWPASSWORD: 'Vous avez entré votre nouveau mot de passe différemment, réessayez' ERRORPASSWORDNOTMATCH: 'Votre actuel mot de passe ne correspond pas, merci de réessayer' ERRORWRONGCRED: 'Il semble que ce ne soit pas le bon email ou mot de passe. Merci de réessayer.' FIRSTNAME: Prénom INTERFACELANG: 'Langue de l''interface' KEEPMESIGNEDIN: 'Se souvenir de moi' LOGGEDINAS: 'Vous êtes connecté en tant que {name}.' NEWPASSWORD: 'Nouveau mot de passe' PASSWORD: 'Mot de passe' PASSWORDEXPIRED: 'Votre mot de passe a expiré. Merci d''en choisir un nouveau.' PLURALNAME: Membres PLURALS: one: 'Un membre' other: '{count} membres' REMEMBERME: 'Se souvenir de moi la prochaine fois ? (pour une durée de {count} jours sur cet appareil)' SINGULARNAME: Membre SUBJECTPASSWORDCHANGED: 'Votre mot de passe a été changé' SUBJECTPASSWORDRESET: 'Lien pour modifier votre mot de passe' SURNAME: 'Nom de famille' VALIDATIONADMINLOSTACCESS: 'Impossible de retirer tous les groupes d''administrateur à partir de votre profil' ValidationIdentifierFailed: 'Impossible de réenregistrer le membre nº {id} avec un identifiant identique ({name} = {value}))' YOUROLDPASSWORD: 'Votre ancien mot de passe' belongs_many_many_Groups: Groupes db_Locale: 'Langue de l''Interface' db_LockedOutUntil: 'Verrouillé jusqu''à' db_Password: 'Mot de passe' db_PasswordExpiry: 'Date d''expiration du mot de passe' SilverStripe\Security\MemberAuthenticator\CMSMemberLoginForm: AUTHENTICATORNAME: 'Formulaire de connexion pour un utilisateur du CMS' BUTTONFORGOTPASSWORD: 'Mot de passe oublié' BUTTONLOGIN: 'De retour dans' BUTTONLOGOUT: 'Se déconnecter' SilverStripe\Security\MemberAuthenticator\MemberAuthenticator: ERRORWRONGCRED: 'Les renseignements fournis semblent incorrects. Merci de réessayer.' NoPassword: 'Ce membre n''a pas de mot de passe' SilverStripe\Security\MemberAuthenticator\MemberLoginForm: AUTHENTICATORNAME: 'Email & Mot de passe' SilverStripe\Security\MemberPassword: PLURALNAME: 'Mots de passe utilisateur' PLURALS: one: 'Un mot de passe utilisateur' other: '{count} mots de passe utilisateur' SINGULARNAME: 'Mot de passe utilisateur' SilverStripe\Security\PasswordValidator: LOWCHARSTRENGTH: 'Veuillez renforcer votre mot de passe en ajoutant certains des caractères suivants : {chars}' PREVPASSWORD: 'Vous avez déjà utilisé ce mot de passe par le passé, veuillez en choisir un autre' TOOSHORT: 'Le mot de passe est trop court, il doit contenir au moins {minimum} caractères' SilverStripe\Security\Permission: AdminGroup: Administrateur CMS_ACCESS_CATEGORY: 'Accès au CMS' CONTENT_CATEGORY: 'Permissions de contenu' FULLADMINRIGHTS: 'Droits d''administration complets' FULLADMINRIGHTS_HELP: 'Prévaut sur toutes les autres autorisations assignées.' PERMISSIONS_CATEGORY: 'Rôles et autorisations d’accès' PLURALNAME: Permissions PLURALS: one: 'Une autorisation' other: '{count} autorisations' SINGULARNAME: Permission UserPermissionsIntro: "Assigner des groupes à cet utilisateur modifiera les autorisations dont il dispose. Consultez la section «\_Groupes\_» pour plus de détails sur les autorisations associées à chaque groupe." SilverStripe\Security\PermissionCheckboxSetField: AssignedTo: 'assigné au groupe « {title} »' FromGroup: "hérite du groupe «\_{title}\_»" FromRole: "hérite du rôle «\_{title}\_»" FromRoleOnGroup: "hérite du rôle «\_{roletitle}\_» du groupe «\_{grouptitle}\_»" SilverStripe\Security\PermissionRole: OnlyAdminCanApply: 'Limité aux administrateurs' PLURALNAME: Rôles PLURALS: one: 'Un rôle' other: '{count} rôles' SINGULARNAME: Rôle Title: Titre SilverStripe\Security\PermissionRoleCode: PLURALNAME: 'Codes d''autorisations liés au rôle' PLURALS: one: 'Un code d''autorisation lié au rôle' other: '{count} codes d''autorisation liés au rôle' PermsError: 'Impossible d''attribuer le code "{code}" (requiert un accès en tant qu''administrateur)' SINGULARNAME: 'Code d''autorisation lié au rôle' SilverStripe\Security\RememberLoginHash: PLURALNAME: 'Signatures de mot de passe' PLURALS: one: 'Une signature de mot de passe' other: '{count} signatures de mot de passe' SINGULARNAME: 'Signature de mot de passe' SilverStripe\Security\Security: ALREADYLOGGEDIN: 'Vous n''avez pas accès à cette page. Si un autre de vos identifiants vous permet d''accéder à cette page, merci de vous reconnecter ci-dessous en l''utilisant.' BUTTONSEND: 'Envoyer moi le lien pour modifier le mot de passe' CHANGEPASSWORDBELOW: 'Vous pouvez modifier votre mot de passe ci-dessous.' CHANGEPASSWORDHEADER: 'Modifier votre mot de passe' CONFIRMLOGOUT: 'Merci de cliquer le bouton ci-dessous pour confirmer que vous souhaitez vous déconnecter.' ENTERNEWPASSWORD: 'Entrer un nouveau mot de passe s''il vous plaît.' ERRORPASSWORDPERMISSION: 'Vous devez être connecté pour modifier votre mot de passe !' LOGIN: 'Se connecter' LOGOUT: 'Se déconnecter' LOSTPASSWORDHEADER: 'Mot de passe oublié' NOTEPAGESECURED: 'Cette page est sécurisée. Entrez vos identifiants ci-dessous et vous pourrez y avoir accès.' NOTERESETPASSWORD: 'Entrez votre adresse email et nous vous enverrons un lien pour modifier votre mot de passe'
{ "pile_set_name": "Github" }
function updateMediaAudioSettings(mediaVideo, settings) { mediaVideo.el.setAttribute("media-video", { distanceModel: settings.mediaDistanceModel, rolloffFactor: settings.mediaRolloffFactor, refDistance: settings.mediaRefDistance, maxDistance: settings.mediaMaxDistance, coneInnerAngle: settings.mediaConeInnerAngle, coneOuterAngle: settings.mediaConeOuterAngle, coneOuterGain: settings.mediaConeOuterGain }); } function updateAvatarAudioSettings(avatarAudioSource, settings, positional) { avatarAudioSource.el.setAttribute("avatar-audio-source", { positional, distanceModel: settings.avatarDistanceModel, maxDistance: settings.avatarMaxDistance, refDistance: settings.avatarRefDistance, rolloffFactor: settings.avatarRolloffFactor }); } export class AudioSettingsSystem { constructor(sceneEl) { this.sceneEl = sceneEl; this.defaultSettings = { avatarDistanceModel: "inverse", avatarRolloffFactor: 2, avatarRefDistance: 1, avatarMaxDistance: 10000, mediaVolume: 0.5, mediaDistanceModel: "inverse", mediaRolloffFactor: 1, mediaRefDistance: 1, mediaMaxDistance: 10000, mediaConeInnerAngle: 360, mediaConeOuterAngle: 0, mediaConeOuterGain: 0 }; this.audioSettings = this.defaultSettings; this.mediaVideos = []; this.avatarAudioSources = []; this.sceneEl.addEventListener("reset_scene", this.onSceneReset); if (window.APP.store.state.preferences.audioOutputMode === "audio") { //hack to always reset to "panner" window.APP.store.update({ preferences: { audioOutputMode: "panner" } }); } this.audioOutputMode = window.APP.store.state.preferences.audioOutputMode; this.onPreferenceChanged = () => { const newPref = window.APP.store.state.preferences.audioOutputMode; const shouldUpdateAudioSettings = this.audioOutputMode !== newPref; this.audioOutputMode = newPref; if (shouldUpdateAudioSettings) { this.updateAudioSettings(this.audioSettings); } }; window.APP.store.addEventListener("statechanged", this.onPreferenceChanged); } registerMediaAudioSource(mediaVideo) { const index = this.mediaVideos.indexOf(mediaVideo); if (index === -1) { this.mediaVideos.push(mediaVideo); } updateMediaAudioSettings(mediaVideo, this.audioSettings); } unregisterMediaAudioSource(mediaVideo) { this.mediaVideos.splice(this.mediaVideos.indexOf(mediaVideo), 1); } registerAvatarAudioSource(avatarAudioSource) { const index = this.avatarAudioSources.indexOf(avatarAudioSource); if (index === -1) { this.avatarAudioSources.push(avatarAudioSource); } const positional = window.APP.store.state.preferences.audioOutputMode !== "audio"; updateAvatarAudioSettings(avatarAudioSource, this.audioSettings, positional); } unregisterAvatarAudioSource(avatarAudioSource) { const index = this.avatarAudioSources.indexOf(avatarAudioSource); if (index !== -1) { this.avatarAudioSources.splice(index, 1); } } updateAudioSettings(settings) { this.audioSettings = Object.assign({}, this.defaultSettings, settings); for (const mediaVideo of this.mediaVideos) { updateMediaAudioSettings(mediaVideo, settings); } const positional = window.APP.store.state.preferences.audioOutputMode !== "audio"; for (const avatarAudioSource of this.avatarAudioSources) { updateAvatarAudioSettings(avatarAudioSource, settings, positional); } } onSceneReset = () => { this.updateAudioSettings(this.defaultSettings); }; } AFRAME.registerComponent("use-audio-system-settings", { init() { this.onVideoLoaded = this.onVideoLoaded.bind(this); this.el.addEventListener("video-loaded", this.onVideoLoaded); }, onVideoLoaded() { const audioSettingsSystem = this.el.sceneEl.systems["hubs-systems"].audioSettingsSystem; if (this.mediaVideo) { audioSettingsSystem.unregisterMediaAudioSource(this.mediaVideo); } this.mediaVideo = this.el.components["media-video"]; audioSettingsSystem.registerMediaAudioSource(this.mediaVideo); }, remove() { const audioSettingsSystem = this.el.sceneEl.systems["hubs-systems"].audioSettingsSystem; if (this.mediaVideo) { audioSettingsSystem.unregisterMediaAudioSource(this.mediaVideo); } this.el.removeEventListener("video-loaded", this.onVideoLoaded); } });
{ "pile_set_name": "Github" }
" Vim syntax file " Language: Symbian meta-makefile definition (MMP) " Maintainer: Ron Aaron <[email protected]> " Last Change: 2007/11/07 " URL: http://ronware.org/wiki/vim/mmp " Filetypes: *.mmp " For version 5.x: Clear all syntax items " For version 6.x: Quit when a syntax file was already loaded if version < 600 syntax clear elseif exists("b:current_syntax") finish endif syn case ignore syn match mmpComment "//.*" syn region mmpComment start="/\*" end="\*\/" syn keyword mmpKeyword aif asspabi assplibrary aaspexports baseaddress syn keyword mmpKeyword debuglibrary deffile document epocheapsize syn keyword mmpKeyword epocprocesspriority epocstacksize exportunfrozen syn keyword mmpStorage lang library linkas macro nostrictdef option syn keyword mmpStorage resource source sourcepath srcdbg startbitmap syn keyword mmpStorage start end staticlibrary strictdepend systeminclude syn keyword mmpStorage systemresource target targettype targetpath uid syn keyword mmpStorage userinclude win32_library syn match mmpIfdef "\#\(include\|ifdef\|ifndef\|if\|endif\|else\|elif\)" syn match mmpNumber "\d+" syn match mmpNumber "0x\x\+" " Define the default highlighting. " For version 5.7 and earlier: only when not done already " For version 5.8 and later: only when an item doesn't have highlighting yet if !exists("did_mmp_syntax_inits") let did_mmp_syntax_inits=1 hi def link mmpComment Comment hi def link mmpKeyword Keyword hi def link mmpStorage StorageClass hi def link mmpString String hi def link mmpNumber Number hi def link mmpOrdinal Operator hi def link mmpIfdef PreCondit endif let b:current_syntax = "mmp" " vim: ts=8
{ "pile_set_name": "Github" }
#ifndef BOOST_MPL_BEGIN_END_HPP_INCLUDED #define BOOST_MPL_BEGIN_END_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/begin_end_fwd.hpp> #include <boost/mpl/aux_/begin_end_impl.hpp> #include <boost/mpl/sequence_tag.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> namespace boost { namespace mpl { // agurt, 13/sep/02: switched from inheritance to typedef; MSVC is more // happy this way (less ETI-related errors), and it doesn't affect // anything else template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) > struct begin { typedef typename sequence_tag<Sequence>::type tag_; typedef typename begin_impl< tag_ > ::template apply< Sequence >::type type; BOOST_MPL_AUX_LAMBDA_SUPPORT(1,begin,(Sequence)) }; template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) > struct end { typedef typename sequence_tag<Sequence>::type tag_; typedef typename end_impl< tag_ > ::template apply< Sequence >::type type; BOOST_MPL_AUX_LAMBDA_SUPPORT(1,end,(Sequence)) }; BOOST_MPL_AUX_NA_SPEC(1, begin) BOOST_MPL_AUX_NA_SPEC(1, end) }} #endif // BOOST_MPL_BEGIN_END_HPP_INCLUDED
{ "pile_set_name": "Github" }
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import ArtistPoster from 'Artist/ArtistPoster'; import DeleteArtistModal from 'Artist/Delete/DeleteArtistModal'; import EditArtistModalConnector from 'Artist/Edit/EditArtistModalConnector'; import ArtistIndexProgressBar from 'Artist/Index/ProgressBar/ArtistIndexProgressBar'; import Label from 'Components/Label'; import IconButton from 'Components/Link/IconButton'; import Link from 'Components/Link/Link'; import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; import { icons } from 'Helpers/Props'; import getRelativeDate from 'Utilities/Date/getRelativeDate'; import ArtistIndexPosterInfo from './ArtistIndexPosterInfo'; import styles from './ArtistIndexPoster.css'; class ArtistIndexPoster extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditArtistModalOpen: false, isDeleteArtistModalOpen: false }; } // // Listeners onEditArtistPress = () => { this.setState({ isEditArtistModalOpen: true }); } onEditArtistModalClose = () => { this.setState({ isEditArtistModalOpen: false }); } onDeleteArtistPress = () => { this.setState({ isEditArtistModalOpen: false, isDeleteArtistModalOpen: true }); } onDeleteArtistModalClose = () => { this.setState({ isDeleteArtistModalOpen: false }); } onPosterLoad = () => { if (this.state.hasPosterError) { this.setState({ hasPosterError: false }); } } onPosterLoadError = () => { if (!this.state.hasPosterError) { this.setState({ hasPosterError: true }); } } // // Render render() { const { id, artistName, monitored, foreignArtistId, status, nextAiring, statistics, images, posterWidth, posterHeight, detailedProgressBar, showTitle, showMonitored, showQualityProfile, qualityProfile, showSearchAction, showRelativeDates, shortDateFormat, timeFormat, isRefreshingArtist, isSearchingArtist, onRefreshArtistPress, onSearchPress, ...otherProps } = this.props; const { albumCount, sizeOnDisk, trackCount, trackFileCount, totalTrackCount } = statistics; const { hasPosterError, isEditArtistModalOpen, isDeleteArtistModalOpen } = this.state; const link = `/artist/${foreignArtistId}`; const elementStyle = { width: `${posterWidth}px`, height: `${posterHeight}px` }; return ( <div className={styles.container}> <div className={styles.content}> <div className={styles.posterContainer}> <Label className={styles.controls}> <SpinnerIconButton className={styles.action} name={icons.REFRESH} title="Refresh Artist" isSpinning={isRefreshingArtist} onPress={onRefreshArtistPress} /> { showSearchAction && <SpinnerIconButton className={styles.action} name={icons.SEARCH} title="Search for monitored albums" isSpinning={isSearchingArtist} onPress={onSearchPress} /> } <IconButton className={styles.action} name={icons.EDIT} title="Edit Artist" onPress={this.onEditArtistPress} /> </Label> { status === 'ended' && <div className={styles.ended} title="Ended" /> } <Link className={styles.link} style={elementStyle} to={link} > <ArtistPoster className={styles.poster} style={elementStyle} images={images} size={250} lazy={false} overflow={true} onError={this.onPosterLoadError} onLoad={this.onPosterLoad} /> { hasPosterError && <div className={styles.overlayTitle}> {artistName} </div> } </Link> </div> <ArtistIndexProgressBar monitored={monitored} status={status} trackCount={trackCount} trackFileCount={trackFileCount} totalTrackCount={totalTrackCount} posterWidth={posterWidth} detailedProgressBar={detailedProgressBar} /> { showTitle && <div className={styles.title}> {artistName} </div> } { showMonitored && <div className={styles.title}> {monitored ? 'Monitored' : 'Unmonitored'} </div> } { showQualityProfile && <div className={styles.title}> {qualityProfile.name} </div> } { nextAiring && <div className={styles.nextAiring}> { getRelativeDate( nextAiring, shortDateFormat, showRelativeDates, { timeFormat, timeForToday: true } ) } </div> } <ArtistIndexPosterInfo albumCount={albumCount} sizeOnDisk={sizeOnDisk} qualityProfile={qualityProfile} showQualityProfile={showQualityProfile} showRelativeDates={showRelativeDates} shortDateFormat={shortDateFormat} timeFormat={timeFormat} {...otherProps} /> <EditArtistModalConnector isOpen={isEditArtistModalOpen} artistId={id} onModalClose={this.onEditArtistModalClose} onDeleteArtistPress={this.onDeleteArtistPress} /> <DeleteArtistModal isOpen={isDeleteArtistModalOpen} artistId={id} onModalClose={this.onDeleteArtistModalClose} /> </div> </div> ); } } ArtistIndexPoster.propTypes = { id: PropTypes.number.isRequired, artistName: PropTypes.string.isRequired, monitored: PropTypes.bool.isRequired, status: PropTypes.string.isRequired, foreignArtistId: PropTypes.string.isRequired, nextAiring: PropTypes.string, statistics: PropTypes.object.isRequired, images: PropTypes.arrayOf(PropTypes.object).isRequired, posterWidth: PropTypes.number.isRequired, posterHeight: PropTypes.number.isRequired, detailedProgressBar: PropTypes.bool.isRequired, showTitle: PropTypes.bool.isRequired, showMonitored: PropTypes.bool.isRequired, showQualityProfile: PropTypes.bool.isRequired, qualityProfile: PropTypes.object.isRequired, showSearchAction: PropTypes.bool.isRequired, showRelativeDates: PropTypes.bool.isRequired, shortDateFormat: PropTypes.string.isRequired, timeFormat: PropTypes.string.isRequired, isRefreshingArtist: PropTypes.bool.isRequired, isSearchingArtist: PropTypes.bool.isRequired, onRefreshArtistPress: PropTypes.func.isRequired, onSearchPress: PropTypes.func.isRequired }; ArtistIndexPoster.defaultProps = { statistics: { albumCount: 0, trackCount: 0, trackFileCount: 0, totalTrackCount: 0 } }; export default ArtistIndexPoster;
{ "pile_set_name": "Github" }
Contribution Guide for Manhattan Project ======================================== ## Git Commit Guidelines These guidelines have been copied from the [AngularJS](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#-git-commit-guidelines) project. We have very precise rules over how our git commit messages can be formatted. This leads to **more readable messages** that are easy to follow when looking through the **project history**. But also, we use the git commit messages to **generate the change log**. ### Commit Message Format Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**: ``` <type>(<scope>): <subject> <BLANK LINE> <body> <BLANK LINE> <footer> ``` Any line of the commit message cannot be longer 100 characters! This allows the message to be easier to read on github as well as in various git tools. ### Type Must be one of the following: * **feat**: A new feature * **fix**: A bug fix * **docs**: Documentation only changes * **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) * **refactor**: A code change that neither fixes a bug or adds a feature * **perf**: A code change that improves performance * **test**: Adding missing tests * **chore**: Changes to the build process or auxiliary tools and libraries such as documentation generation ### Scope In our project scope refers to BEM block which is touched by changes. ### Subject The subject contains succinct description of the change: * use the imperative, present tense: "change" not "changed" nor "changes" * don't capitalize first letter * no dot (.) at the end ###Body Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes" The body should include the motivation for the change and contrast this with previous behavior. ###Footer The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**. The last line of commits introducing breaking changes should be in the form `BREAKING_CHANGE: <desc>` A detailed explanation can be found in this [document][commit-message-format]. [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# ## Pull Request reviews comments Following abbreviations should be used in PR merge comments: * `r+ {sha}`: review passed for all commits up to `{sha}` * `r-`: review revealed some errors, changes must be done to proceed * `r? @spanferov`: request for review from another user * `re-r? @spanferov`: request another user to do review again * `cc @spanferov, @smbd`: current message is also intended for...
{ "pile_set_name": "Github" }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_GTK_KEY_BINDINGS_HANDLER_H_ #define CONTENT_BROWSER_RENDERER_HOST_GTK_KEY_BINDINGS_HANDLER_H_ #pragma once #include <gtk/gtk.h> #include <string> #include "content/common/edit_command.h" #include "content/common/content_export.h" #include "ui/base/gtk/owned_widget_gtk.h" struct NativeWebKeyboardEvent; // This class is a convenience class for handling editor key bindings defined // in gtk keyboard theme. // In gtk, only GtkEntry and GtkTextView support customizing editor key bindings // through keyboard theme. And in gtk keyboard theme definition file, each key // binding must be bound to a specific class or object. So existing keyboard // themes only define editor key bindings exactly for GtkEntry and GtkTextView. // Then, the only way for us to intercept editor key bindings defined in // keyboard theme, is to create a GtkEntry or GtkTextView object and call // gtk_bindings_activate_event() against it for the key events. If a key event // matches a predefined key binding, corresponding signal will be emitted. // GtkTextView is used here because it supports more key bindings than GtkEntry, // but in order to minimize the side effect of using a GtkTextView object, a new // class derived from GtkTextView is used, which overrides all signals related // to key bindings, to make sure GtkTextView won't receive them. // // See third_party/WebKit/Source/WebCore/editing/EditorCommand.cpp for detailed // definition of webkit edit commands. // See webkit/glue/editor_client_impl.cc for key bindings predefined in our // webkit glue. class CONTENT_EXPORT GtkKeyBindingsHandler { public: explicit GtkKeyBindingsHandler(GtkWidget* parent_widget); ~GtkKeyBindingsHandler(); // Matches a key event against predefined gtk key bindings, false will be // returned if the key event doesn't correspond to a predefined key binding. // Edit commands matched with |wke| will be stored in |edit_commands|. bool Match(const NativeWebKeyboardEvent& wke, EditCommands* edit_commands); private: // Object structure of Handler class, which is derived from GtkTextView. struct Handler { GtkTextView parent_object; GtkKeyBindingsHandler *owner; }; // Class structure of Handler class. struct HandlerClass { GtkTextViewClass parent_class; }; // Creates a new instance of Handler class. GtkWidget* CreateNewHandler(); // Adds an edit command to the key event. void EditCommandMatched(const std::string& name, const std::string& value); // Initializes Handler structure. static void HandlerInit(Handler *self); // Initializes HandlerClass structure. static void HandlerClassInit(HandlerClass *klass); // Registeres Handler class to GObject type system and return its type id. static GType HandlerGetType(); // Gets the GtkKeyBindingsHandler object which owns the Handler object. static GtkKeyBindingsHandler* GetHandlerOwner(GtkTextView* text_view); // Handler of "backspace" signal. static void BackSpace(GtkTextView* text_view); // Handler of "copy-clipboard" signal. static void CopyClipboard(GtkTextView* text_view); // Handler of "cut-clipboard" signal. static void CutClipboard(GtkTextView* text_view); // Handler of "delete-from-cursor" signal. static void DeleteFromCursor(GtkTextView* text_view, GtkDeleteType type, gint count); // Handler of "insert-at-cursor" signal. static void InsertAtCursor(GtkTextView* text_view, const gchar* str); // Handler of "move-cursor" signal. static void MoveCursor(GtkTextView* text_view, GtkMovementStep step, gint count, gboolean extend_selection); // Handler of "move-viewport" signal. static void MoveViewport(GtkTextView* text_view, GtkScrollStep step, gint count); // Handler of "paste-clipboard" signal. static void PasteClipboard(GtkTextView* text_view); // Handler of "select-all" signal. static void SelectAll(GtkTextView* text_view, gboolean select); // Handler of "set-anchor" signal. static void SetAnchor(GtkTextView* text_view); // Handler of "toggle-cursor-visible" signal. static void ToggleCursorVisible(GtkTextView* text_view); // Handler of "toggle-overwrite" signal. static void ToggleOverwrite(GtkTextView* text_view); // Handler of "show-help" signal. static gboolean ShowHelp(GtkWidget* widget, GtkWidgetHelpType arg1); // Handler of "move-focus" signal. static void MoveFocus(GtkWidget* widget, GtkDirectionType arg1); ui::OwnedWidgetGtk handler_; // Buffer to store the match results. EditCommands edit_commands_; }; #endif // CONTENT_BROWSER_RENDERER_HOST_GTK_KEY_BINDINGS_HANDLER_H_
{ "pile_set_name": "Github" }
<?php
{ "pile_set_name": "Github" }
# globals [![Build Status](https://travis-ci.org/sindresorhus/globals.svg?branch=master)](https://travis-ci.org/sindresorhus/globals) > Global identifiers from different JavaScript environments Extracted from [JSHint](https://github.com/jshint/jshint/blob/3a8efa979dbb157bfb5c10b5826603a55a33b9ad/src/vars.js) and [ESLint](https://github.com/eslint/eslint/blob/b648406218f8a2d7302b98f5565e23199f44eb31/conf/environments.json) and merged. It's just a [JSON file](globals.json), so use it in whatever environment you like. **This module [no longer accepts](https://github.com/sindresorhus/globals/issues/82) new environments. If you need it for ESLint, just [create a plugin](http://eslint.org/docs/developer-guide/working-with-plugins#environments-in-plugins).** ## Install ``` $ npm install globals ``` ## Usage ```js const globals = require('globals'); console.log(globals.browser); /* { addEventListener: false, applicationCache: false, ArrayBuffer: false, atob: false, ... } */ ``` Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise. ## License MIT © [Sindre Sorhus](https://sindresorhus.com)
{ "pile_set_name": "Github" }
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
{ "pile_set_name": "Github" }
// name: GroupImport // status: correct loadFile("GroupImport.mo"); list();getErrorString(); instantiateModel(GroupImport);getErrorString(); // Result: // true // "package B // constant Real c = 1, d = 2; // end B; // // class GroupImport // import B.{c,e = d}; // Real r = c + e; // end GroupImport;" // "" // "class GroupImport // Real r = 3.0; // end GroupImport; // " // "" // endResult
{ "pile_set_name": "Github" }
// Copyright (c) 2010 Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // source_line_resolver_base.cc: Implementation of SourceLineResolverBase. // // See source_line_resolver_base.h and source_line_resolver_base_types.h for // more documentation. // // Author: Siyang Xie ([email protected]) #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <map> #include <utility> #include "google_breakpad/processor/source_line_resolver_base.h" #include "processor/source_line_resolver_base_types.h" #include "processor/module_factory.h" using std::map; using std::make_pair; namespace google_breakpad { SourceLineResolverBase::SourceLineResolverBase( ModuleFactory *module_factory) : modules_(new ModuleMap), corrupt_modules_(new ModuleSet), memory_buffers_(new MemoryMap), module_factory_(module_factory) { } SourceLineResolverBase::~SourceLineResolverBase() { ModuleMap::iterator it; // Iterate through ModuleMap and delete all loaded modules. for (it = modules_->begin(); it != modules_->end(); ++it) { // Delete individual module. delete it->second; } // Delete the map of modules. delete modules_; modules_ = NULL; // Delete the set of corrupt modules. delete corrupt_modules_; corrupt_modules_ = NULL; MemoryMap::iterator iter = memory_buffers_->begin(); for (; iter != memory_buffers_->end(); ++iter) { delete [] iter->second; } // Delete the map of memory buffers. delete memory_buffers_; memory_buffers_ = NULL; delete module_factory_; module_factory_ = NULL; } bool SourceLineResolverBase::ReadSymbolFile(const string &map_file, char **symbol_data, size_t *symbol_data_size) { if (symbol_data == NULL || symbol_data_size == NULL) { BPLOG(ERROR) << "Could not Read file into Null memory pointer"; return false; } struct stat buf; int error_code = stat(map_file.c_str(), &buf); if (error_code == -1) { string error_string; error_code = ErrnoString(&error_string); BPLOG(ERROR) << "Could not open " << map_file << ", error " << error_code << ": " << error_string; return false; } off_t file_size = buf.st_size; // Allocate memory for file contents, plus a null terminator // since we may use strtok() on the contents. *symbol_data_size = file_size + 1; *symbol_data = new char[file_size + 1]; if (*symbol_data == NULL) { BPLOG(ERROR) << "Could not allocate memory for " << map_file; return false; } BPLOG(INFO) << "Opening " << map_file; FILE *f = fopen(map_file.c_str(), "rt"); if (!f) { string error_string; error_code = ErrnoString(&error_string); BPLOG(ERROR) << "Could not open " << map_file << ", error " << error_code << ": " << error_string; delete [] (*symbol_data); *symbol_data = NULL; return false; } AutoFileCloser closer(f); int items_read = 0; items_read = fread(*symbol_data, 1, file_size, f); if (items_read != file_size) { string error_string; error_code = ErrnoString(&error_string); BPLOG(ERROR) << "Could not slurp " << map_file << ", error " << error_code << ": " << error_string; delete [] (*symbol_data); *symbol_data = NULL; return false; } (*symbol_data)[file_size] = '\0'; return true; } bool SourceLineResolverBase::LoadModule(const CodeModule *module, const string &map_file) { if (module == NULL) return false; // Make sure we don't already have a module with the given name. if (modules_->find(module->code_file()) != modules_->end()) { BPLOG(INFO) << "Symbols for module " << module->code_file() << " already loaded"; return false; } BPLOG(INFO) << "Loading symbols for module " << module->code_file() << " from " << map_file; char *memory_buffer; size_t memory_buffer_size; if (!ReadSymbolFile(map_file, &memory_buffer, &memory_buffer_size)) return false; BPLOG(INFO) << "Read symbol file " << map_file << " succeeded"; bool load_result = LoadModuleUsingMemoryBuffer(module, memory_buffer, memory_buffer_size); if (load_result && !ShouldDeleteMemoryBufferAfterLoadModule()) { // memory_buffer has to stay alive as long as the module. memory_buffers_->insert(make_pair(module->code_file(), memory_buffer)); } else { delete [] memory_buffer; } return load_result; } bool SourceLineResolverBase::LoadModuleUsingMapBuffer( const CodeModule *module, const string &map_buffer) { if (module == NULL) return false; // Make sure we don't already have a module with the given name. if (modules_->find(module->code_file()) != modules_->end()) { BPLOG(INFO) << "Symbols for module " << module->code_file() << " already loaded"; return false; } size_t memory_buffer_size = map_buffer.size() + 1; char *memory_buffer = new char[memory_buffer_size]; if (memory_buffer == NULL) { BPLOG(ERROR) << "Could not allocate memory for " << module->code_file(); return false; } // Can't use strcpy, as the data may contain '\0's before the end. memcpy(memory_buffer, map_buffer.c_str(), map_buffer.size()); memory_buffer[map_buffer.size()] = '\0'; bool load_result = LoadModuleUsingMemoryBuffer(module, memory_buffer, memory_buffer_size); if (load_result && !ShouldDeleteMemoryBufferAfterLoadModule()) { // memory_buffer has to stay alive as long as the module. memory_buffers_->insert(make_pair(module->code_file(), memory_buffer)); } else { delete [] memory_buffer; } return load_result; } bool SourceLineResolverBase::LoadModuleUsingMemoryBuffer( const CodeModule *module, char *memory_buffer, size_t memory_buffer_size) { if (!module) return false; // Make sure we don't already have a module with the given name. if (modules_->find(module->code_file()) != modules_->end()) { BPLOG(INFO) << "Symbols for module " << module->code_file() << " already loaded"; return false; } BPLOG(INFO) << "Loading symbols for module " << module->code_file() << " from memory buffer"; Module *basic_module = module_factory_->CreateModule(module->code_file()); // Ownership of memory is NOT transfered to Module::LoadMapFromMemory(). if (!basic_module->LoadMapFromMemory(memory_buffer, memory_buffer_size)) { BPLOG(ERROR) << "Too many error while parsing symbol data for module " << module->code_file(); // Returning false from here would be an indication that the symbols for // this module are missing which would be wrong. Intentionally fall through // and add the module to both the modules_ and the corrupt_modules_ lists. assert(basic_module->IsCorrupt()); } modules_->insert(make_pair(module->code_file(), basic_module)); if (basic_module->IsCorrupt()) { corrupt_modules_->insert(module->code_file()); } return true; } bool SourceLineResolverBase::ShouldDeleteMemoryBufferAfterLoadModule() { return true; } void SourceLineResolverBase::UnloadModule(const CodeModule *code_module) { if (!code_module) return; ModuleMap::iterator mod_iter = modules_->find(code_module->code_file()); if (mod_iter != modules_->end()) { Module *symbol_module = mod_iter->second; delete symbol_module; corrupt_modules_->erase(mod_iter->first); modules_->erase(mod_iter); } if (ShouldDeleteMemoryBufferAfterLoadModule()) { // No-op. Because we never store any memory buffers. } else { // There may be a buffer stored locally, we need to find and delete it. MemoryMap::iterator iter = memory_buffers_->find(code_module->code_file()); if (iter != memory_buffers_->end()) { delete [] iter->second; memory_buffers_->erase(iter); } } } bool SourceLineResolverBase::HasModule(const CodeModule *module) { if (!module) return false; return modules_->find(module->code_file()) != modules_->end(); } bool SourceLineResolverBase::IsModuleCorrupt(const CodeModule *module) { if (!module) return false; return corrupt_modules_->find(module->code_file()) != corrupt_modules_->end(); } void SourceLineResolverBase::FillSourceLineInfo(StackFrame *frame) { if (frame->module) { ModuleMap::const_iterator it = modules_->find(frame->module->code_file()); if (it != modules_->end()) { it->second->LookupAddress(frame); } } } WindowsFrameInfo *SourceLineResolverBase::FindWindowsFrameInfo( const StackFrame *frame) { if (frame->module) { ModuleMap::const_iterator it = modules_->find(frame->module->code_file()); if (it != modules_->end()) { return it->second->FindWindowsFrameInfo(frame); } } return NULL; } CFIFrameInfo *SourceLineResolverBase::FindCFIFrameInfo( const StackFrame *frame) { if (frame->module) { ModuleMap::const_iterator it = modules_->find(frame->module->code_file()); if (it != modules_->end()) { return it->second->FindCFIFrameInfo(frame); } } return NULL; } bool SourceLineResolverBase::CompareString::operator()( const string &s1, const string &s2) const { return strcmp(s1.c_str(), s2.c_str()) < 0; } bool SourceLineResolverBase::Module::ParseCFIRuleSet( const string &rule_set, CFIFrameInfo *frame_info) const { CFIFrameInfoParseHandler handler(frame_info); CFIRuleParser parser(&handler); return parser.Parse(rule_set); } } // namespace google_breakpad
{ "pile_set_name": "Github" }
From 35ad0e50bd6683c6699586e3bd5045f0695586d9 Mon Sep 17 00:00:00 2001 From: Felix Fietkau <[email protected]> Date: Wed, 13 May 2015 09:10:51 +0200 Subject: [PATCH] ARM: BCM5301X: Add USB LED for Buffalo WZR-1750DHP Signed-off-by: Felix Fietkau <[email protected]> Signed-off-by: Florian Fainelli <[email protected]> --- arch/arm/boot/dts/bcm4708-buffalo-wzr-1750dhp.dts | 6 ++++++ 1 file changed, 6 insertions(+) --- a/arch/arm/boot/dts/bcm4708-buffalo-wzr-1750dhp.dts +++ b/arch/arm/boot/dts/bcm4708-buffalo-wzr-1750dhp.dts @@ -47,6 +47,12 @@ leds { compatible = "gpio-leds"; + usb { + label = "bcm53xx:blue:usb"; + gpios = <&hc595 0 GPIO_ACTIVE_HIGH>; + linux,default-trigger = "default-off"; + }; + power0 { label = "bcm53xx:red:power"; gpios = <&hc595 1 GPIO_ACTIVE_HIGH>;
{ "pile_set_name": "Github" }
module linker_test_1 1.0; require { class file { read write }; class lnk_file append; role g_b_role_2; attribute g_b_attr_3; attribute g_b_attr_5; attribute o4_b_attr_1; type g_b_type_3; } type tag_g_m1; #test for type in module and attr in module, added to in module attribute g_m1_attr_1; type g_m1_type_1, g_m1_attr_1; type g_m1_type_2; typeattribute g_m1_type_2 g_m1_attr_1; #add role in module test role g_m1_role_1; role g_m1_role_1 types g_m1_type_1; # test for attr declared in base, added to in module type g_m1_type_3; typeattribute g_m1_type_3 g_b_attr_3; # test for attr declared in base, added to in 2 modules type g_m1_type_4; typeattribute g_m1_type_4 g_b_attr_5; # test for attr declared in base optional, added to in module type g_m1_type_5; typeattribute g_m1_type_5 o4_b_attr_1; # test for attr declared in module, added to in base optional attribute g_m1_attr_2; #add type to base role test role g_b_role_2 types g_m1_type_1; role g_b_role_3; role g_b_role_3 types g_m1_type_2; #add type to base optional role test role o1_b_role_2; role o1_b_role_2 types g_m1_type_1; #optional base role w/ adds in 2 modules role o4_b_role_1; role o4_b_role_1 types g_m1_type_2; # attr a added to in base optional, declared/added to in module, added to in other module attribute g_m1_attr_3; type g_m1_type_6, g_m1_attr_3; # attr a added to in base optional, declared/added in module , added to in other module optional attribute g_m1_attr_4; type g_m1_type_7, g_m1_attr_4; # alias tests typealias g_b_type_3 alias g_m_alias_1; # single boolean in module bool g_m1_bool_1 true; if (g_m1_bool_1) { allow g_m1_type_1 g_m1_type_2 : lnk_file append; } optional { require { type optional_type; attribute g_b_attr_4; attribute o1_b_attr_2; class lnk_file { ioctl }; } type tag_o1_m1; attribute o1_m1_attr_1; type o1_m1_type_2, o1_m1_attr_1; type o1_m1_type_1; role o1_m1_role_1; role o1_m1_role_1 types o1_m1_type_1; type o1_m1_type_3; typeattribute o1_m1_type_3 g_b_attr_4; type o1_m1_type_5; typeattribute o1_m1_type_5 o1_b_attr_2; bool o1_m1_bool_1 false; if (o1_m1_bool_1) { allow o1_m1_type_2 o1_m1_type_1 : lnk_file ioctl; } } optional { require { type optional_type; #role g_b_role_4; // This causes a bug where the role scope doesn't get copied into base } type tag_o2_m1; role g_b_role_4; role g_b_role_4 types g_m1_type_2; } optional { require { attribute g_b_attr_6; } type tag_o3_m1; type o3_m1_type_1; role o3_b_role_1; role o3_b_role_1 types o3_m1_type_1; type o3_m1_type_2, g_b_attr_6; attribute o3_m1_attr_1; # attr a added to in base optional, declared/added in module optional, added to in other module attribute o3_m1_attr_2; type o3_m1_type_3, o3_m1_attr_2; } optional { require { type enable_optional; } type tag_o4_m1; attribute o4_m1_attr_1; type o4_m1_type_1; typeattribute o4_m1_type_1 o4_m1_attr_1; }
{ "pile_set_name": "Github" }
import java.util.List; public class SuperBuilderWithGenerics2 { @lombok.experimental.SuperBuilder public static class Parent<A> { A field1; @lombok.Singular List<String> items; } @lombok.experimental.SuperBuilder(builderMethodName="builder2") public static class Child<A> extends Parent<String> { A field3; } public static void test() { Child<Integer> x = Child.<Integer>builder2().field3(1).field1("value").item("").build(); } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>Passport-TOTP Example</title> </head> <body> <% if (!user) { %> <p> <a href="/">Home</a> | <a href="/login">Log In</a> </p> <% } else { %> <p> <a href="/">Home</a> | <a href="/account">Account</a> | <a href="/logout">Log Out</a> </p> <% } %> <%- body %> </body> </html>
{ "pile_set_name": "Github" }
import React from 'react'; import PropTypes from 'prop-types'; const UilLink = (props) => { const { color, size, ...otherProps } = props return React.createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: color, ...otherProps }, React.createElement('path', { d: 'M10,17.55,8.23,19.27a2.47,2.47,0,0,1-3.5-3.5l4.54-4.55a2.46,2.46,0,0,1,3.39-.09l.12.1a1,1,0,0,0,1.4-1.43A2.75,2.75,0,0,0,14,9.59a4.46,4.46,0,0,0-6.09.22L3.31,14.36a4.48,4.48,0,0,0,6.33,6.33L11.37,19A1,1,0,0,0,10,17.55ZM20.69,3.31a4.49,4.49,0,0,0-6.33,0L12.63,5A1,1,0,0,0,14,6.45l1.73-1.72a2.47,2.47,0,0,1,3.5,3.5l-4.54,4.55a2.46,2.46,0,0,1-3.39.09l-.12-.1a1,1,0,0,0-1.4,1.43,2.75,2.75,0,0,0,.23.21,4.47,4.47,0,0,0,6.09-.22l4.55-4.55A4.49,4.49,0,0,0,20.69,3.31Z' })); }; UilLink.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; UilLink.defaultProps = { color: 'currentColor', size: '24', }; export default UilLink;
{ "pile_set_name": "Github" }
state.rockchipes8316c { control.1 { iface CARD name 'Headphones Jack' value false comment { access read type BOOLEAN count 1 } } control.2 { iface MIXER name 'Headphone Playback Volume' value.0 0 value.1 0 comment { access 'read write' type INTEGER count 2 range '0 - 3' dbmin -4800 dbmax 0 dbvalue.0 -4800 dbvalue.1 -4800 } } control.3 { iface MIXER name 'Headphone Mixer Volume' value.0 11 value.1 11 comment { access 'read write' type INTEGER count 2 range '0 - 11' dbmin -1200 dbmax 0 dbvalue.0 0 dbvalue.1 0 } } control.4 { iface MIXER name 'Playback Polarity' value Normal comment { access 'read write' type ENUMERATED count 1 item.0 Normal item.1 'R Invert' item.2 'L Invert' item.3 'L + R Invert' } } control.5 { iface MIXER name 'DAC Playback Volume' value.0 192 value.1 192 comment { access 'read write' type INTEGER count 2 range '0 - 192' dbmin -9999999 dbmax 0 dbvalue.0 0 dbvalue.1 0 } } control.6 { iface MIXER name 'DAC Soft Ramp Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.7 { iface MIXER name 'DAC Soft Ramp Rate' value 4 comment { access 'read write' type INTEGER count 1 range '0 - 4' } } control.8 { iface MIXER name 'DAC Notch Filter Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.9 { iface MIXER name 'DAC Double Fs Switch' value true comment { access 'read write' type BOOLEAN count 1 } } control.10 { iface MIXER name 'DAC Stereo Enhancement' value 7 comment { access 'read write' type INTEGER count 1 range '0 - 7' } } control.11 { iface MIXER name 'DAC Mono Mix Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.12 { iface MIXER name 'Capture Polarity' value Normal comment { access 'read write' type ENUMERATED count 1 item.0 Normal item.1 Invert } } control.13 { iface MIXER name 'Mic Boost Switch' value true comment { access 'read write' type BOOLEAN count 1 } } control.14 { iface MIXER name 'ADC Capture Volume' value 0 comment { access 'read write' type INTEGER count 1 range '0 - 192' dbmin -9999999 dbmax 0 dbvalue.0 -9999999 } } control.15 { iface MIXER name 'ADC PGA Gain Volume' value 0 comment { access 'read write' type INTEGER count 1 range '0 - 10' } } control.16 { iface MIXER name 'ADC Soft Ramp Switch' value true comment { access 'read write' type BOOLEAN count 1 } } control.17 { iface MIXER name 'ADC Double Fs Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.18 { iface MIXER name 'ALC Capture Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.19 { iface MIXER name 'ALC Capture Max Volume' value 28 comment { access 'read write' type INTEGER count 1 range '0 - 28' dbmin -650 dbmax 3550 dbvalue.0 3550 } } control.20 { iface MIXER name 'ALC Capture Min Volume' value 0 comment { access 'read write' type INTEGER count 1 range '0 - 28' dbmin -1200 dbmax 3000 dbvalue.0 -1200 } } control.21 { iface MIXER name 'ALC Capture Target Volume' value 11 comment { access 'read write' type INTEGER count 1 range '0 - 10' dbmin -1650 dbmax -150 dbvalue.0 0 } } control.22 { iface MIXER name 'ALC Capture Hold Time' value 0 comment { access 'read write' type INTEGER count 1 range '0 - 10' } } control.23 { iface MIXER name 'ALC Capture Decay Time' value 3 comment { access 'read write' type INTEGER count 1 range '0 - 10' } } control.24 { iface MIXER name 'ALC Capture Attack Time' value 2 comment { access 'read write' type INTEGER count 1 range '0 - 10' } } control.25 { iface MIXER name 'ALC Capture Noise Gate Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.26 { iface MIXER name 'ALC Capture Noise Gate Threshold' value 0 comment { access 'read write' type INTEGER count 1 range '0 - 31' } } control.27 { iface MIXER name 'ALC Capture Noise Gate Type' value 'Constant PGA Gain' comment { access 'read write' type ENUMERATED count 1 item.0 'Constant PGA Gain' item.1 'Mute ADC Output' } } control.28 { iface MIXER name 'Speaker Switch' value true comment { access 'read write' type BOOLEAN count 1 } } control.29 { iface MIXER name 'Differential Mux' value lin1-rin1 comment { access 'read write' type ENUMERATED count 1 item.0 lin1-rin1 item.1 lin2-rin2 item.2 'lin1-rin1 with 20db Boost' item.3 'lin2-rin2 with 20db Boost' } } control.30 { iface MIXER name 'Digital Mic Mux' value 'dmic disable' comment { access 'read write' type ENUMERATED count 1 item.0 'dmic disable' item.1 'dmic data at high level' item.2 'dmic data at low level' } } control.31 { iface MIXER name 'DAC Source Mux' value 'LDATA TO LDAC, RDATA TO RDAC' comment { access 'read write' type ENUMERATED count 1 item.0 'LDATA TO LDAC, RDATA TO RDAC' item.1 'LDATA TO LDAC, LDATA TO RDAC' item.2 'RDATA TO LDAC, RDATA TO RDAC' item.3 'RDATA TO LDAC, LDATA TO RDAC' } } control.32 { iface MIXER name 'Left Headphone Mux' value lin2-rin2 comment { access 'read write' type ENUMERATED count 1 item.0 lin1-rin1 item.1 lin2-rin2 item.2 'lin-rin with Boost' item.3 'lin-rin with Boost and PGA' } } control.33 { iface MIXER name 'Right Headphone Mux' value lin1-rin1 comment { access 'read write' type ENUMERATED count 1 item.0 lin1-rin1 item.1 lin2-rin2 item.2 'lin-rin with Boost' item.3 'lin-rin with Boost and PGA' } } control.34 { iface MIXER name 'Left Headphone Mixer LLIN Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.35 { iface MIXER name 'Left Headphone Mixer Left DAC Switch' value true comment { access 'read write' type BOOLEAN count 1 } } control.36 { iface MIXER name 'Right Headphone Mixer RLIN Switch' value false comment { access 'read write' type BOOLEAN count 1 } } control.37 { iface MIXER name 'Right Headphone Mixer Right DAC Switch' value true comment { access 'read write' type BOOLEAN count 1 } } }
{ "pile_set_name": "Github" }
/* This file is part of Ext JS 3.4 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-04-03 15:07:25 */ /** * @class Ext.Window * @extends Ext.Panel * <p>A specialized panel intended for use as an application window. Windows are floated, {@link #resizable}, and * {@link #draggable} by default. Windows can be {@link #maximizable maximized} to fill the viewport, * restored to their prior size, and can be {@link #minimize}d.</p> * <p>Windows can also be linked to a {@link Ext.WindowGroup} or managed by the {@link Ext.WindowMgr} to provide * grouping, activation, to front, to back and other application-specific behavior.</p> * <p>By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element * specify {@link Ext.Component#renderTo renderTo}.</p> * <p><b>Note:</b> By default, the <code>{@link #closable close}</code> header tool <i>destroys</i> the Window resulting in * destruction of any child Components. This makes the Window object, and all its descendants <b>unusable</b>. To enable * re-use of a Window, use <b><code>{@link #closeAction closeAction: 'hide'}</code></b>.</p> * @constructor * @param {Object} config The config object * @xtype window */ Ext.Window = Ext.extend(Ext.Panel, { /** * @cfg {Number} x * The X position of the left edge of the window on initial showing. Defaults to centering the Window within * the width of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to). */ /** * @cfg {Number} y * The Y position of the top edge of the window on initial showing. Defaults to centering the Window within * the height of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to). */ /** * @cfg {Boolean} modal * True to make the window modal and mask everything behind it when displayed, false to display it without * restricting access to other UI elements (defaults to false). */ /** * @cfg {String/Element} animateTarget * Id or element from which the window should animate while opening (defaults to null with no animation). */ /** * @cfg {String} resizeHandles * A valid {@link Ext.Resizable} handles config string (defaults to 'all'). Only applies when resizable = true. */ /** * @cfg {Ext.WindowGroup} manager * A reference to the WindowGroup that should manage this window (defaults to {@link Ext.WindowMgr}). */ /** * @cfg {String/Number/Component} defaultButton * <p>Specifies a Component to receive focus when this Window is focussed.</p> * <p>This may be one of:</p><div class="mdetail-params"><ul> * <li>The index of a footer Button.</li> * <li>The id of a Component.</li> * <li>A Component.</li> * </ul></div> */ /** * @cfg {Function} onEsc * Allows override of the built-in processing for the escape key. Default action * is to close the Window (performing whatever action is specified in {@link #closeAction}. * To prevent the Window closing when the escape key is pressed, specify this as * Ext.emptyFn (See {@link Ext#emptyFn}). */ /** * @cfg {Boolean} collapsed * True to render the window collapsed, false to render it expanded (defaults to false). Note that if * {@link #expandOnShow} is true (the default) it will override the <tt>collapsed</tt> config and the window * will always be expanded when shown. */ /** * @cfg {Boolean} maximized * True to initially display the window in a maximized state. (Defaults to false). */ /** * @cfg {String} baseCls * The base CSS class to apply to this panel's element (defaults to 'x-window'). */ baseCls : 'x-window', /** * @cfg {Boolean} resizable * True to allow user resizing at each edge and corner of the window, false to disable resizing (defaults to true). */ resizable : true, /** * @cfg {Boolean} draggable * True to allow the window to be dragged by the header bar, false to disable dragging (defaults to true). Note * that by default the window will be centered in the viewport, so if dragging is disabled the window may need * to be positioned programmatically after render (e.g., myWindow.setPosition(100, 100);). */ draggable : true, /** * @cfg {Boolean} closable * <p>True to display the 'close' tool button and allow the user to close the window, false to * hide the button and disallow closing the window (defaults to true).</p> * <p>By default, when close is requested by either clicking the close button in the header * or pressing ESC when the Window has focus, the {@link #close} method will be called. This * will <i>{@link Ext.Component#destroy destroy}</i> the Window and its content meaning that * it may not be reused.</p> * <p>To make closing a Window <i>hide</i> the Window so that it may be reused, set * {@link #closeAction} to 'hide'. */ closable : true, /** * @cfg {String} closeAction * <p>The action to take when the close header tool is clicked: * <div class="mdetail-params"><ul> * <li><b><code>'{@link #close}'</code></b> : <b>Default</b><div class="sub-desc"> * {@link #close remove} the window from the DOM and {@link Ext.Component#destroy destroy} * it and all descendant Components. The window will <b>not</b> be available to be * redisplayed via the {@link #show} method. * </div></li> * <li><b><code>'{@link #hide}'</code></b> : <div class="sub-desc"> * {@link #hide} the window by setting visibility to hidden and applying negative offsets. * The window will be available to be redisplayed via the {@link #show} method. * </div></li> * </ul></div> * <p><b>Note:</b> This setting does not affect the {@link #close} method * which will always {@link Ext.Component#destroy destroy} the window. To * programatically <i>hide</i> a window, call {@link #hide}.</p> */ closeAction : 'close', /** * @cfg {Boolean} constrain * True to constrain the window within its containing element, false to allow it to fall outside of its * containing element. By default the window will be rendered to document.body. To render and constrain the * window within another element specify {@link #renderTo}. * (defaults to false). Optionally the header only can be constrained using {@link #constrainHeader}. */ constrain : false, /** * @cfg {Boolean} constrainHeader * True to constrain the window header within its containing element (allowing the window body to fall outside * of its containing element) or false to allow the header to fall outside its containing element (defaults to * false). Optionally the entire window can be constrained using {@link #constrain}. */ constrainHeader : false, /** * @cfg {Boolean} plain * True to render the window body with a transparent background so that it will blend into the framing * elements, false to add a lighter background color to visually highlight the body element and separate it * more distinctly from the surrounding frame (defaults to false). */ plain : false, /** * @cfg {Boolean} minimizable * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button * and disallow minimizing the window (defaults to false). Note that this button provides no implementation -- * the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a * custom minimize behavior implemented for this option to be useful. */ minimizable : false, /** * @cfg {Boolean} maximizable * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button * and disallow maximizing the window (defaults to false). Note that when a window is maximized, the tool button * will automatically change to a 'restore' button with the appropriate behavior already built-in that will * restore the window to its previous size. */ maximizable : false, /** * @cfg {Number} minHeight * The minimum height in pixels allowed for this window (defaults to 100). Only applies when resizable = true. */ minHeight : 100, /** * @cfg {Number} minWidth * The minimum width in pixels allowed for this window (defaults to 200). Only applies when resizable = true. */ minWidth : 200, /** * @cfg {Boolean} expandOnShow * True to always expand the window when it is displayed, false to keep it in its current state (which may be * {@link #collapsed}) when displayed (defaults to true). */ expandOnShow : true, /** * @cfg {Number} showAnimDuration The number of seconds that the window show animation takes if enabled. * Defaults to 0.25 */ showAnimDuration: 0.25, /** * @cfg {Number} hideAnimDuration The number of seconds that the window hide animation takes if enabled. * Defaults to 0.25 */ hideAnimDuration: 0.25, // inherited docs, same default collapsible : false, /** * @cfg {Boolean} initHidden * True to hide the window until show() is explicitly called (defaults to true). * @deprecated */ initHidden : undefined, /** * @cfg {Boolean} hidden * Render this component hidden (default is <tt>true</tt>). If <tt>true</tt>, the * {@link #hide} method will be called internally. */ hidden : true, // The following configs are set to provide the basic functionality of a window. // Changing them would require additional code to handle correctly and should // usually only be done in subclasses that can provide custom behavior. Changing them // may have unexpected or undesirable results. /** @cfg {String} elements @hide */ elements : 'header,body', /** @cfg {Boolean} frame @hide */ frame : true, /** @cfg {Boolean} floating @hide */ floating : true, // private initComponent : function(){ this.initTools(); Ext.Window.superclass.initComponent.call(this); this.addEvents( /** * @event activate * Fires after the window has been visually activated via {@link #setActive}. * @param {Ext.Window} this */ /** * @event deactivate * Fires after the window has been visually deactivated via {@link #setActive}. * @param {Ext.Window} this */ /** * @event resize * Fires after the window has been resized. * @param {Ext.Window} this * @param {Number} width The window's new width * @param {Number} height The window's new height */ 'resize', /** * @event maximize * Fires after the window has been maximized. * @param {Ext.Window} this */ 'maximize', /** * @event minimize * Fires after the window has been minimized. * @param {Ext.Window} this */ 'minimize', /** * @event restore * Fires after the window has been restored to its original size after being maximized. * @param {Ext.Window} this */ 'restore' ); // for backwards compat, this should be removed at some point if(Ext.isDefined(this.initHidden)){ this.hidden = this.initHidden; } if(this.hidden === false){ this.hidden = true; this.show(); } }, // private getState : function(){ return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox(true)); }, // private onRender : function(ct, position){ Ext.Window.superclass.onRender.call(this, ct, position); if(this.plain){ this.el.addClass('x-window-plain'); } // this element allows the Window to be focused for keyboard events this.focusEl = this.el.createChild({ tag: 'a', href:'#', cls:'x-dlg-focus', tabIndex:'-1', html: '&#160;'}); this.focusEl.swallowEvent('click', true); this.proxy = this.el.createProxy('x-window-proxy'); this.proxy.enableDisplayMode('block'); if(this.modal){ this.mask = this.container.createChild({cls:'ext-el-mask'}, this.el.dom); this.mask.enableDisplayMode('block'); this.mask.hide(); this.mon(this.mask, 'click', this.focus, this); } if(this.maximizable){ this.mon(this.header, 'dblclick', this.toggleMaximize, this); } }, // private initEvents : function(){ Ext.Window.superclass.initEvents.call(this); if(this.animateTarget){ this.setAnimateTarget(this.animateTarget); } if(this.resizable){ this.resizer = new Ext.Resizable(this.el, { minWidth: this.minWidth, minHeight:this.minHeight, handles: this.resizeHandles || 'all', pinned: true, resizeElement : this.resizerAction, handleCls: 'x-window-handle' }); this.resizer.window = this; this.mon(this.resizer, 'beforeresize', this.beforeResize, this); } if(this.draggable){ this.header.addClass('x-window-draggable'); } this.mon(this.el, 'mousedown', this.toFront, this); this.manager = this.manager || Ext.WindowMgr; this.manager.register(this); if(this.maximized){ this.maximized = false; this.maximize(); } if(this.closable){ var km = this.getKeyMap(); km.on(27, this.onEsc, this); km.disable(); } }, initDraggable : function(){ /** * <p>If this Window is configured {@link #draggable}, this property will contain * an instance of {@link Ext.dd.DD} which handles dragging the Window's DOM Element.</p> * <p>This has implementations of <code>startDrag</code>, <code>onDrag</code> and <code>endDrag</code> * which perform the dragging action. If extra logic is needed at these points, use * {@link Function#createInterceptor createInterceptor} or {@link Function#createSequence createSequence} to * augment the existing implementations.</p> * @type Ext.dd.DD * @property dd */ this.dd = new Ext.Window.DD(this); }, // private onEsc : function(k, e){ if (this.activeGhost) { this.unghost(); } e.stopEvent(); this[this.closeAction](); }, // private beforeDestroy : function(){ if(this.rendered){ this.hide(); this.clearAnchor(); Ext.destroy( this.focusEl, this.resizer, this.dd, this.proxy, this.mask ); } Ext.Window.superclass.beforeDestroy.call(this); }, // private onDestroy : function(){ if(this.manager){ this.manager.unregister(this); } Ext.Window.superclass.onDestroy.call(this); }, // private initTools : function(){ if(this.minimizable){ this.addTool({ id: 'minimize', handler: this.minimize.createDelegate(this, []) }); } if(this.maximizable){ this.addTool({ id: 'maximize', handler: this.maximize.createDelegate(this, []) }); this.addTool({ id: 'restore', handler: this.restore.createDelegate(this, []), hidden:true }); } if(this.closable){ this.addTool({ id: 'close', handler: this[this.closeAction].createDelegate(this, []) }); } }, // private resizerAction : function(){ var box = this.proxy.getBox(); this.proxy.hide(); this.window.handleResize(box); return box; }, // private beforeResize : function(){ this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); // 40 is a magic minimum content size? this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40); this.resizeBox = this.el.getBox(); }, // private updateHandles : function(){ if(Ext.isIE9m && this.resizer){ this.resizer.syncHandleHeight(); this.el.repaint(); } }, // private handleResize : function(box){ var rz = this.resizeBox; if(rz.x != box.x || rz.y != box.y){ this.updateBox(box); }else{ this.setSize(box); if (Ext.isIE6 && Ext.isStrict) { this.doLayout(); } } this.focus(); this.updateHandles(); this.saveState(); }, /** * Focuses the window. If a defaultButton is set, it will receive focus, otherwise the * window itself will receive focus. */ focus : function(){ var f = this.focusEl, db = this.defaultButton, t = typeof db, el, ct; if(Ext.isDefined(db)){ if(Ext.isNumber(db) && this.fbar){ f = this.fbar.items.get(db); }else if(Ext.isString(db)){ f = Ext.getCmp(db); }else{ f = db; } el = f.getEl(); ct = Ext.getDom(this.container); if (el && ct) { if (ct != document.body && !Ext.lib.Region.getRegion(ct).contains(Ext.lib.Region.getRegion(el.dom))){ return; } } } f = f || this.focusEl; f.focus.defer(10, f); }, /** * Sets the target element from which the window should animate while opening. * @param {String/Element} el The target element or id */ setAnimateTarget : function(el){ el = Ext.get(el); this.animateTarget = el; }, // private beforeShow : function(){ delete this.el.lastXY; delete this.el.lastLT; if(this.x === undefined || this.y === undefined){ var xy = this.el.getAlignToXY(this.container, 'c-c'); var pos = this.el.translatePoints(xy[0], xy[1]); this.x = this.x === undefined? pos.left : this.x; this.y = this.y === undefined? pos.top : this.y; } this.el.setLeftTop(this.x, this.y); if(this.expandOnShow){ this.expand(false); } if(this.modal){ Ext.getBody().addClass('x-body-masked'); this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.mask.show(); } }, /** * Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden. * @param {String/Element} animateTarget (optional) The target element or id from which the window should * animate while opening (defaults to null with no animation) * @param {Function} callback (optional) A callback function to call after the window is displayed * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window. * @return {Ext.Window} this */ show : function(animateTarget, cb, scope){ if(!this.rendered){ this.render(Ext.getBody()); } if(this.hidden === false){ this.toFront(); return this; } if(this.fireEvent('beforeshow', this) === false){ return this; } if(cb){ this.on('show', cb, scope, {single:true}); } this.hidden = false; if(Ext.isDefined(animateTarget)){ this.setAnimateTarget(animateTarget); } this.beforeShow(); if(this.animateTarget){ this.animShow(); }else{ this.afterShow(); } return this; }, // private afterShow : function(isAnim){ if (this.isDestroyed){ return false; } this.proxy.hide(); this.el.setStyle('display', 'block'); this.el.show(); if(this.maximized){ this.fitContainer(); } if(Ext.isMac && Ext.isGecko2){ // work around stupid FF 2.0/Mac scroll bar bug this.cascade(this.setAutoScroll); } if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.onWindowResize(this.onWindowResize, this); } this.doConstrain(); this.doLayout(); if(this.keyMap){ this.keyMap.enable(); } this.toFront(); this.updateHandles(); if(isAnim && (Ext.isIE || Ext.isWebKit)){ var sz = this.getSize(); this.onResize(sz.width, sz.height); } this.onShow(); this.fireEvent('show', this); }, // private animShow : function(){ this.proxy.show(); this.proxy.setBox(this.animateTarget.getBox()); this.proxy.setOpacity(0); var b = this.getBox(); this.el.setStyle('display', 'none'); this.proxy.shift(Ext.apply(b, { callback: this.afterShow.createDelegate(this, [true], false), scope: this, easing: 'easeNone', duration: this.showAnimDuration, opacity: 0.5 })); }, /** * Hides the window, setting it to invisible and applying negative offsets. * @param {String/Element} animateTarget (optional) The target element or id to which the window should * animate while hiding (defaults to null with no animation) * @param {Function} callback (optional) A callback function to call after the window is hidden * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window. * @return {Ext.Window} this */ hide : function(animateTarget, cb, scope){ if(this.hidden || this.fireEvent('beforehide', this) === false){ return this; } if(cb){ this.on('hide', cb, scope, {single:true}); } this.hidden = true; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } if(this.modal){ this.mask.hide(); Ext.getBody().removeClass('x-body-masked'); } if(this.animateTarget){ this.animHide(); }else{ this.el.hide(); this.afterHide(); } return this; }, // private afterHide : function(){ this.proxy.hide(); if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.removeResizeListener(this.onWindowResize, this); } if(this.keyMap){ this.keyMap.disable(); } this.onHide(); this.fireEvent('hide', this); }, // private animHide : function(){ this.proxy.setOpacity(0.5); this.proxy.show(); var tb = this.getBox(false); this.proxy.setBox(tb); this.el.hide(); this.proxy.shift(Ext.apply(this.animateTarget.getBox(), { callback: this.afterHide, scope: this, duration: this.hideAnimDuration, easing: 'easeNone', opacity: 0 })); }, /** * Method that is called immediately before the <code>show</code> event is fired. * Defaults to <code>Ext.emptyFn</code>. */ onShow : Ext.emptyFn, /** * Method that is called immediately before the <code>hide</code> event is fired. * Defaults to <code>Ext.emptyFn</code>. */ onHide : Ext.emptyFn, // private onWindowResize : function(){ if(this.maximized){ this.fitContainer(); } if(this.modal){ this.mask.setSize('100%', '100%'); var force = this.mask.dom.offsetHeight; this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); } this.doConstrain(); }, // private doConstrain : function(){ if(this.constrain || this.constrainHeader){ var offsets; if(this.constrain){ offsets = { right:this.el.shadowOffset, left:this.el.shadowOffset, bottom:this.el.shadowOffset }; }else { var s = this.getSize(); offsets = { right:-(s.width - 100), bottom:-(s.height - 25 + this.el.getConstrainOffset()) }; } var xy = this.el.getConstrainToXY(this.container, true, offsets); if(xy){ this.setPosition(xy[0], xy[1]); } } }, // private - used for dragging ghost : function(cls){ var ghost = this.createGhost(cls); var box = this.getBox(true); ghost.setLeftTop(box.x, box.y); ghost.setWidth(box.width); this.el.hide(); this.activeGhost = ghost; return ghost; }, // private unghost : function(show, matchPosition){ if(!this.activeGhost) { return; } if(show !== false){ this.el.show(); this.focus.defer(10, this); if(Ext.isMac && Ext.isGecko2){ // work around stupid FF 2.0/Mac scroll bar bug this.cascade(this.setAutoScroll); } } if(matchPosition !== false){ this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true)); } this.activeGhost.hide(); this.activeGhost.remove(); delete this.activeGhost; }, /** * Placeholder method for minimizing the window. By default, this method simply fires the {@link #minimize} event * since the behavior of minimizing a window is application-specific. To implement custom minimize behavior, * either the minimize event can be handled or this method can be overridden. * @return {Ext.Window} this */ minimize : function(){ this.fireEvent('minimize', this); return this; }, /** * <p>Closes the Window, removes it from the DOM, {@link Ext.Component#destroy destroy}s * the Window object and all its descendant Components. The {@link Ext.Panel#beforeclose beforeclose} * event is fired before the close happens and will cancel the close action if it returns false.<p> * <p><b>Note:</b> This method is not affected by the {@link #closeAction} setting which * only affects the action triggered when clicking the {@link #closable 'close' tool in the header}. * To hide the Window without destroying it, call {@link #hide}.</p> */ close : function(){ if(this.fireEvent('beforeclose', this) !== false){ if(this.hidden){ this.doClose(); }else{ this.hide(null, this.doClose, this); } } }, // private doClose : function(){ this.fireEvent('close', this); this.destroy(); }, /** * Fits the window within its current container and automatically replaces * the {@link #maximizable 'maximize' tool button} with the 'restore' tool button. * Also see {@link #toggleMaximize}. * @return {Ext.Window} this */ maximize : function(){ if(!this.maximized){ this.expand(false); this.restoreSize = this.getSize(); this.restorePos = this.getPosition(true); if (this.maximizable){ this.tools.maximize.hide(); this.tools.restore.show(); } this.maximized = true; this.el.disableShadow(); if(this.dd){ this.dd.lock(); } if(this.collapsible){ this.tools.toggle.hide(); } this.el.addClass('x-window-maximized'); this.container.addClass('x-window-maximized-ct'); this.setPosition(0, 0); this.fitContainer(); this.fireEvent('maximize', this); } return this; }, /** * Restores a {@link #maximizable maximized} window back to its original * size and position prior to being maximized and also replaces * the 'restore' tool button with the 'maximize' tool button. * Also see {@link #toggleMaximize}. * @return {Ext.Window} this */ restore : function(){ if(this.maximized){ var t = this.tools; this.el.removeClass('x-window-maximized'); if(t.restore){ t.restore.hide(); } if(t.maximize){ t.maximize.show(); } this.setPosition(this.restorePos[0], this.restorePos[1]); this.setSize(this.restoreSize.width, this.restoreSize.height); delete this.restorePos; delete this.restoreSize; this.maximized = false; this.el.enableShadow(true); if(this.dd){ this.dd.unlock(); } if(this.collapsible && t.toggle){ t.toggle.show(); } this.container.removeClass('x-window-maximized-ct'); this.doConstrain(); this.fireEvent('restore', this); } return this; }, /** * A shortcut method for toggling between {@link #maximize} and {@link #restore} based on the current maximized * state of the window. * @return {Ext.Window} this */ toggleMaximize : function(){ return this[this.maximized ? 'restore' : 'maximize'](); }, // private fitContainer : function(){ var vs = this.container.getViewSize(false); this.setSize(vs.width, vs.height); }, // private // z-index is managed by the WindowManager and may be overwritten at any time setZIndex : function(index){ if(this.modal){ this.mask.setStyle('z-index', index); } this.el.setZIndex(++index); index += 5; if(this.resizer){ this.resizer.proxy.setStyle('z-index', ++index); } this.lastZIndex = index; }, /** * Aligns the window to the specified element * @param {Mixed} element The element to align to. * @param {String} position (optional, defaults to "tl-bl?") The position to align to (see {@link Ext.Element#alignTo} for more details). * @param {Array} offsets (optional) Offset the positioning by [x, y] * @return {Ext.Window} this */ alignTo : function(element, position, offsets){ var xy = this.el.getAlignToXY(element, position, offsets); this.setPagePosition(xy[0], xy[1]); return this; }, /** * Anchors this window to another element and realigns it when the window is resized or scrolled. * @param {Mixed} element The element to align to. * @param {String} position The position to align to (see {@link Ext.Element#alignTo} for more details) * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter * is a number, it is used as the buffer delay (defaults to 50ms). * @return {Ext.Window} this */ anchorTo : function(el, alignment, offsets, monitorScroll){ this.clearAnchor(); this.anchorTarget = { el: el, alignment: alignment, offsets: offsets }; Ext.EventManager.onWindowResize(this.doAnchor, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', this.doAnchor, this, {buffer: tm == 'number' ? monitorScroll : 50}); } return this.doAnchor(); }, /** * Performs the anchor, using the saved anchorTarget property. * @return {Ext.Window} this * @private */ doAnchor : function(){ var o = this.anchorTarget; this.alignTo(o.el, o.alignment, o.offsets); return this; }, /** * Removes any existing anchor from this window. See {@link #anchorTo}. * @return {Ext.Window} this */ clearAnchor : function(){ if(this.anchorTarget){ Ext.EventManager.removeResizeListener(this.doAnchor, this); Ext.EventManager.un(window, 'scroll', this.doAnchor, this); delete this.anchorTarget; } return this; }, /** * Brings this window to the front of any other visible windows * @param {Boolean} e (optional) Specify <tt>false</tt> to prevent the window from being focused. * @return {Ext.Window} this */ toFront : function(e){ if(this.manager.bringToFront(this)){ if(!e || !e.getTarget().focus){ this.focus(); } } return this; }, /** * Makes this the active window by showing its shadow, or deactivates it by hiding its shadow. This method also * fires the {@link #activate} or {@link #deactivate} event depending on which action occurred. This method is * called internally by {@link Ext.WindowMgr}. * @param {Boolean} active True to activate the window, false to deactivate it (defaults to false) */ setActive : function(active){ if(active){ if(!this.maximized){ this.el.enableShadow(true); } this.fireEvent('activate', this); }else{ this.el.disableShadow(); this.fireEvent('deactivate', this); } }, /** * Sends this window to the back of (lower z-index than) any other visible windows * @return {Ext.Window} this */ toBack : function(){ this.manager.sendToBack(this); return this; }, /** * Centers this window in the viewport * @return {Ext.Window} this */ center : function(){ var xy = this.el.getAlignToXY(this.container, 'c-c'); this.setPagePosition(xy[0], xy[1]); return this; } /** * @cfg {Boolean} autoWidth @hide **/ }); Ext.reg('window', Ext.Window); // private - custom Window DD implementation Ext.Window.DD = Ext.extend(Ext.dd.DD, { constructor : function(win){ this.win = win; Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id); this.setHandleElId(win.header.id); this.scroll = false; }, moveOnly:true, headerOffsets:[100, 25], startDrag : function(){ var w = this.win; this.proxy = w.ghost(w.initialConfig.cls); if(w.constrain !== false){ var so = w.el.shadowOffset; this.constrainTo(w.container, {right: so, left: so, bottom: so}); }else if(w.constrainHeader !== false){ var s = this.proxy.getSize(); this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])}); } }, b4Drag : Ext.emptyFn, onDrag : function(e){ this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY()); }, endDrag : function(e){ this.win.unghost(); this.win.saveState(); } }); /** * @class Ext.WindowGroup * An object that manages a group of {@link Ext.Window} instances and provides z-order management * and window activation behavior. * @constructor */ Ext.WindowGroup = function(){ var list = {}; var accessList = []; var front = null; // private var sortWindows = function(d1, d2){ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1; }; // private var orderWindows = function(){ var a = accessList, len = a.length; if(len > 0){ a.sort(sortWindows); var seed = a[0].manager.zseed; for(var i = 0; i < len; i++){ var win = a[i]; if(win && !win.hidden){ win.setZIndex(seed + (i*10)); } } } activateLast(); }; // private var setActiveWin = function(win){ if(win != front){ if(front){ front.setActive(false); } front = win; if(win){ win.setActive(true); } } }; // private var activateLast = function(){ for(var i = accessList.length-1; i >=0; --i) { if(!accessList[i].hidden){ setActiveWin(accessList[i]); return; } } // none to activate setActiveWin(null); }; return { /** * The starting z-index for windows in this WindowGroup (defaults to 9000) * @type Number The z-index value */ zseed : 9000, /** * <p>Registers a {@link Ext.Window Window} with this WindowManager. This should not * need to be called under normal circumstances. Windows are automatically registered * with a {@link Ext.Window#manager manager} at construction time.</p> * <p>Where this may be useful is moving Windows between two WindowManagers. For example, * to bring the Ext.MessageBox dialog under the same manager as the Desktop's * WindowManager in the desktop sample app:</p><code><pre> var msgWin = Ext.MessageBox.getDialog(); MyDesktop.getDesktop().getManager().register(msgWin); </pre></code> * @param {Window} win The Window to register. */ register : function(win){ if(win.manager){ win.manager.unregister(win); } win.manager = this; list[win.id] = win; accessList.push(win); win.on('hide', activateLast); }, /** * <p>Unregisters a {@link Ext.Window Window} from this WindowManager. This should not * need to be called. Windows are automatically unregistered upon destruction. * See {@link #register}.</p> * @param {Window} win The Window to unregister. */ unregister : function(win){ delete win.manager; delete list[win.id]; win.un('hide', activateLast); accessList.remove(win); }, /** * Gets a registered window by id. * @param {String/Object} id The id of the window or a {@link Ext.Window} instance * @return {Ext.Window} */ get : function(id){ return typeof id == "object" ? id : list[id]; }, /** * Brings the specified window to the front of any other active windows in this WindowGroup. * @param {String/Object} win The id of the window or a {@link Ext.Window} instance * @return {Boolean} True if the dialog was brought to the front, else false * if it was already in front */ bringToFront : function(win){ win = this.get(win); if(win != front){ win._lastAccess = new Date().getTime(); orderWindows(); return true; } return false; }, /** * Sends the specified window to the back of other active windows in this WindowGroup. * @param {String/Object} win The id of the window or a {@link Ext.Window} instance * @return {Ext.Window} The window */ sendToBack : function(win){ win = this.get(win); win._lastAccess = -(new Date().getTime()); orderWindows(); return win; }, /** * Hides all windows in this WindowGroup. */ hideAll : function(){ for(var id in list){ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){ list[id].hide(); } } }, /** * Gets the currently-active window in this WindowGroup. * @return {Ext.Window} The active window */ getActive : function(){ return front; }, /** * Returns zero or more windows in this WindowGroup using the custom search function passed to this method. * The function should accept a single {@link Ext.Window} reference as its only argument and should * return true if the window matches the search criteria, otherwise it should return false. * @param {Function} fn The search function * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Window being tested. * that gets passed to the function if not specified) * @return {Array} An array of zero or more matching windows */ getBy : function(fn, scope){ var r = []; for(var i = accessList.length-1; i >=0; --i) { var win = accessList[i]; if(fn.call(scope||win, win) !== false){ r.push(win); } } return r; }, /** * Executes the specified function once for every window in this WindowGroup, passing each * window as the only parameter. Returning false from the function will stop the iteration. * @param {Function} fn The function to execute for each item * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Window in the iteration. */ each : function(fn, scope){ for(var id in list){ if(list[id] && typeof list[id] != "function"){ if(fn.call(scope || list[id], list[id]) === false){ return; } } } } }; }; /** * @class Ext.WindowMgr * @extends Ext.WindowGroup * The default global window group that is available automatically. To have more than one group of windows * with separate z-order stacks, create additional instances of {@link Ext.WindowGroup} as needed. * @singleton */ Ext.WindowMgr = new Ext.WindowGroup();/** * @class Ext.MessageBox * <p>Utility class for generating different styles of message boxes. The alias Ext.Msg can also be used.<p/> * <p>Note that the MessageBox is asynchronous. Unlike a regular JavaScript <code>alert</code> (which will halt * browser execution), showing a MessageBox will not cause the code to stop. For this reason, if you have code * that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function * (see the <code>function</code> parameter for {@link #show} for more details).</p> * <p>Example usage:</p> *<pre><code> // Basic alert: Ext.Msg.alert('Status', 'Changes saved successfully.'); // Prompt for user data and process the result using a callback: Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){ if (btn == 'ok'){ // process text value and close... } }); // Show a dialog using config options: Ext.Msg.show({ title:'Save Changes?', msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?', buttons: Ext.Msg.YESNOCANCEL, fn: processResult, animEl: 'elId', icon: Ext.MessageBox.QUESTION }); </code></pre> * @singleton */ Ext.MessageBox = function(){ var dlg, opt, mask, waitTimer, bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl, buttons, activeTextEl, bwidth, bufferIcon = '', iconCls = '', buttonNames = ['ok', 'yes', 'no', 'cancel']; // private var handleButton = function(button){ buttons[button].blur(); if(dlg.isVisible()){ dlg.hide(); handleHide(); Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1); } }; // private var handleHide = function(){ if(opt && opt.cls){ dlg.el.removeClass(opt.cls); } progressBar.reset(); }; // private var handleEsc = function(d, k, e){ if(opt && opt.closable !== false){ dlg.hide(); handleHide(); } if(e){ e.stopEvent(); } }; // private var updateButtons = function(b){ var width = 0, cfg; if(!b){ Ext.each(buttonNames, function(name){ buttons[name].hide(); }); return width; } dlg.footer.dom.style.display = ''; Ext.iterate(buttons, function(name, btn){ cfg = b[name]; if(cfg){ btn.show(); btn.setText(Ext.isString(cfg) ? cfg : Ext.MessageBox.buttonText[name]); width += btn.getEl().getWidth() + 15; }else{ btn.hide(); } }); return width; }; return { /** * Returns a reference to the underlying {@link Ext.Window} element * @return {Ext.Window} The window */ getDialog : function(titleText){ if(!dlg){ var btns = []; buttons = {}; Ext.each(buttonNames, function(name){ btns.push(buttons[name] = new Ext.Button({ text: this.buttonText[name], handler: handleButton.createCallback(name), hideMode: 'offsets' })); }, this); dlg = new Ext.Window({ autoCreate : true, title:titleText, resizable:false, constrain:true, constrainHeader:true, minimizable : false, maximizable : false, stateful: false, modal: true, shim:true, buttonAlign:"center", width:400, height:100, minHeight: 80, plain:true, footer:true, closable:true, close : function(){ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){ handleButton("no"); }else{ handleButton("cancel"); } }, fbar: new Ext.Toolbar({ items: btns, enableOverflow: false }) }); dlg.render(document.body); dlg.getEl().addClass('x-window-dlg'); mask = dlg.mask; bodyEl = dlg.body.createChild({ html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>' }); iconEl = Ext.get(bodyEl.dom.firstChild); var contentEl = bodyEl.dom.childNodes[1]; msgEl = Ext.get(contentEl.firstChild); textboxEl = Ext.get(contentEl.childNodes[2].firstChild); textboxEl.enableDisplayMode(); textboxEl.addKeyListener([10,13], function(){ if(dlg.isVisible() && opt && opt.buttons){ if(opt.buttons.ok){ handleButton("ok"); }else if(opt.buttons.yes){ handleButton("yes"); } } }); textareaEl = Ext.get(contentEl.childNodes[2].childNodes[1]); textareaEl.enableDisplayMode(); progressBar = new Ext.ProgressBar({ renderTo:bodyEl }); bodyEl.createChild({cls:'x-clear'}); } return dlg; }, /** * Updates the message box body text * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to * the XHTML-compliant non-breaking space character '&amp;#160;') * @return {Ext.MessageBox} this */ updateText : function(text){ if(!dlg.isVisible() && !opt.width){ dlg.setSize(this.maxWidth, 100); // resize first so content is never clipped from previous shows } // Append a space here for sizing. In IE, for some reason, it wraps text incorrectly without one in some cases msgEl.update(text ? text + ' ' : '&#160;'); var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0, mw = msgEl.getWidth() + msgEl.getMargins('lr'), fw = dlg.getFrameWidth('lr'), bw = dlg.body.getFrameWidth('lr'), w; w = Math.max(Math.min(opt.width || iw+mw+fw+bw, opt.maxWidth || this.maxWidth), Math.max(opt.minWidth || this.minWidth, bwidth || 0)); if(opt.prompt === true){ activeTextEl.setWidth(w-iw-fw-bw); } if(opt.progress === true || opt.wait === true){ progressBar.setSize(w-iw-fw-bw); } if(Ext.isIE9m && w == bwidth){ w += 4; //Add offset when the content width is smaller than the buttons. } msgEl.update(text || '&#160;'); dlg.setSize(w, 'auto').center(); return this; }, /** * Updates a progress-style message box's text and progress bar. Only relevant on message boxes * initiated via {@link Ext.MessageBox#progress} or {@link Ext.MessageBox#wait}, * or by calling {@link Ext.MessageBox#show} with progress: true. * @param {Number} value Any number between 0 and 1 (e.g., .5, defaults to 0) * @param {String} progressText The progress text to display inside the progress bar (defaults to '') * @param {String} msg The message box's body text is replaced with the specified string (defaults to undefined * so that any existing body text will not get overwritten by default unless a new value is passed in) * @return {Ext.MessageBox} this */ updateProgress : function(value, progressText, msg){ progressBar.updateProgress(value, progressText); if(msg){ this.updateText(msg); } return this; }, /** * Returns true if the message box is currently displayed * @return {Boolean} True if the message box is visible, else false */ isVisible : function(){ return dlg && dlg.isVisible(); }, /** * Hides the message box if it is displayed * @return {Ext.MessageBox} this */ hide : function(){ var proxy = dlg ? dlg.activeGhost : null; if(this.isVisible() || proxy){ dlg.hide(); handleHide(); if (proxy){ // unghost is a private function, but i saw no better solution // to fix the locking problem when dragging while it closes dlg.unghost(false, false); } } return this; }, /** * Displays a new message box, or reinitializes an existing message box, based on the config options * passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally, * although those calls are basic shortcuts and do not support all of the config options allowed here. * @param {Object} config The following config options are supported: <ul> * <li><b>animEl</b> : String/Element<div class="sub-desc">An id or Element from which the message box should animate as it * opens and closes (defaults to undefined)</div></li> * <li><b>buttons</b> : Object/Boolean<div class="sub-desc">A button config object (e.g., Ext.MessageBox.OKCANCEL or {ok:'Foo', * cancel:'Bar'}), or false to not show any buttons (defaults to false)</div></li> * <li><b>closable</b> : Boolean<div class="sub-desc">False to hide the top-right close button (defaults to true). Note that * progress and wait dialogs will ignore this property and always hide the close button as they can only * be closed programmatically.</div></li> * <li><b>cls</b> : String<div class="sub-desc">A custom CSS class to apply to the message box's container element</div></li> * <li><b>defaultTextHeight</b> : Number<div class="sub-desc">The default height in pixels of the message box's multiline textarea * if displayed (defaults to 75)</div></li> * <li><b>fn</b> : Function<div class="sub-desc">A callback function which is called when the dialog is dismissed either * by clicking on the configured buttons, or on the dialog close button, or by pressing * the return button to enter input. * <p>Progress and wait dialogs will ignore this option since they do not respond to user * actions and can only be closed programmatically, so any required function should be called * by the same code after it closes the dialog. Parameters passed:<ul> * <li><b>buttonId</b> : String<div class="sub-desc">The ID of the button pressed, one of:<div class="sub-desc"><ul> * <li><tt>ok</tt></li> * <li><tt>yes</tt></li> * <li><tt>no</tt></li> * <li><tt>cancel</tt></li> * </ul></div></div></li> * <li><b>text</b> : String<div class="sub-desc">Value of the input field if either <tt><a href="#show-option-prompt" ext:member="show-option-prompt" ext:cls="Ext.MessageBox">prompt</a></tt> * or <tt><a href="#show-option-multiline" ext:member="show-option-multiline" ext:cls="Ext.MessageBox">multiline</a></tt> is true</div></li> * <li><b>opt</b> : Object<div class="sub-desc">The config object passed to show.</div></li> * </ul></p></div></li> * <li><b>scope</b> : Object<div class="sub-desc">The scope of the callback function</div></li> * <li><b>icon</b> : String<div class="sub-desc">A CSS class that provides a background image to be used as the body icon for the * dialog (e.g. Ext.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li> * <li><b>iconCls</b> : String<div class="sub-desc">The standard {@link Ext.Window#iconCls} to * add an optional header icon (defaults to '')</div></li> * <li><b>maxWidth</b> : Number<div class="sub-desc">The maximum width in pixels of the message box (defaults to 600)</div></li> * <li><b>minWidth</b> : Number<div class="sub-desc">The minimum width in pixels of the message box (defaults to 100)</div></li> * <li><b>modal</b> : Boolean<div class="sub-desc">False to allow user interaction with the page while the message box is * displayed (defaults to true)</div></li> * <li><b>msg</b> : String<div class="sub-desc">A string that will replace the existing message box body text (defaults to the * XHTML-compliant non-breaking space character '&amp;#160;')</div></li> * <li><a id="show-option-multiline"></a><b>multiline</b> : Boolean<div class="sub-desc"> * True to prompt the user to enter multi-line text (defaults to false)</div></li> * <li><b>progress</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li> * <li><b>progressText</b> : String<div class="sub-desc">The text to display inside the progress bar if progress = true (defaults to '')</div></li> * <li><a id="show-option-prompt"></a><b>prompt</b> : Boolean<div class="sub-desc">True to prompt the user to enter single-line text (defaults to false)</div></li> * <li><b>proxyDrag</b> : Boolean<div class="sub-desc">True to display a lightweight proxy while dragging (defaults to false)</div></li> * <li><b>title</b> : String<div class="sub-desc">The title text</div></li> * <li><b>value</b> : String<div class="sub-desc">The string value to set into the active textbox element if displayed</div></li> * <li><b>wait</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li> * <li><b>waitConfig</b> : Object<div class="sub-desc">A {@link Ext.ProgressBar#waitConfig} object (applies only if wait = true)</div></li> * <li><b>width</b> : Number<div class="sub-desc">The width of the dialog in pixels</div></li> * </ul> * Example usage: * <pre><code> Ext.Msg.show({ title: 'Address', msg: 'Please enter your address:', width: 300, buttons: Ext.MessageBox.OKCANCEL, multiline: true, fn: saveAddress, animEl: 'addAddressBtn', icon: Ext.MessageBox.INFO }); </code></pre> * @return {Ext.MessageBox} this */ show : function(options){ if(this.isVisible()){ this.hide(); } opt = options; var d = this.getDialog(opt.title || "&#160;"); d.setTitle(opt.title || "&#160;"); var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true); d.tools.close.setDisplayed(allowClose); activeTextEl = textboxEl; opt.prompt = opt.prompt || (opt.multiline ? true : false); if(opt.prompt){ if(opt.multiline){ textboxEl.hide(); textareaEl.show(); textareaEl.setHeight(Ext.isNumber(opt.multiline) ? opt.multiline : this.defaultTextHeight); activeTextEl = textareaEl; }else{ textboxEl.show(); textareaEl.hide(); } }else{ textboxEl.hide(); textareaEl.hide(); } activeTextEl.dom.value = opt.value || ""; if(opt.prompt){ d.focusEl = activeTextEl; }else{ var bs = opt.buttons; var db = null; if(bs && bs.ok){ db = buttons["ok"]; }else if(bs && bs.yes){ db = buttons["yes"]; } if (db){ d.focusEl = db; } } if(Ext.isDefined(opt.iconCls)){ d.setIconClass(opt.iconCls); } this.setIcon(Ext.isDefined(opt.icon) ? opt.icon : bufferIcon); bwidth = updateButtons(opt.buttons); progressBar.setVisible(opt.progress === true || opt.wait === true); this.updateProgress(0, opt.progressText); this.updateText(opt.msg); if(opt.cls){ d.el.addClass(opt.cls); } d.proxyDrag = opt.proxyDrag === true; d.modal = opt.modal !== false; d.mask = opt.modal !== false ? mask : false; if(!d.isVisible()){ // force it to the end of the z-index stack so it gets a cursor in FF document.body.appendChild(dlg.el.dom); d.setAnimateTarget(opt.animEl); //workaround for window internally enabling keymap in afterShow d.on('show', function(){ if(allowClose === true){ d.keyMap.enable(); }else{ d.keyMap.disable(); } }, this, {single:true}); d.show(opt.animEl); } if(opt.wait === true){ progressBar.wait(opt.waitConfig); } return this; }, /** * Adds the specified icon to the dialog. By default, the class 'ext-mb-icon' is applied for default * styling, and the class passed in is expected to supply the background image url. Pass in empty string ('') * to clear any existing icon. This method must be called before the MessageBox is shown. * The following built-in icon classes are supported, but you can also pass in a custom class name: * <pre> Ext.MessageBox.INFO Ext.MessageBox.WARNING Ext.MessageBox.QUESTION Ext.MessageBox.ERROR *</pre> * @param {String} icon A CSS classname specifying the icon's background image url, or empty string to clear the icon * @return {Ext.MessageBox} this */ setIcon : function(icon){ if(!dlg){ bufferIcon = icon; return; } bufferIcon = undefined; if(icon && icon != ''){ iconEl.removeClass('x-hidden'); iconEl.replaceClass(iconCls, icon); bodyEl.addClass('x-dlg-icon'); iconCls = icon; }else{ iconEl.replaceClass(iconCls, 'x-hidden'); bodyEl.removeClass('x-dlg-icon'); iconCls = ''; } return this; }, /** * Displays a message box with a progress bar. This message box has no buttons and is not closeable by * the user. You are responsible for updating the progress bar as needed via {@link Ext.MessageBox#updateProgress} * and closing the message box when the process is complete. * @param {String} title The title bar text * @param {String} msg The message box body text * @param {String} progressText (optional) The text to display inside the progress bar (defaults to '') * @return {Ext.MessageBox} this */ progress : function(title, msg, progressText){ this.show({ title : title, msg : msg, buttons: false, progress:true, closable:false, minWidth: this.minProgressWidth, progressText: progressText }); return this; }, /** * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user * interaction while waiting for a long-running process to complete that does not have defined intervals. * You are responsible for closing the message box when the process is complete. * @param {String} msg The message box body text * @param {String} title (optional) The title bar text * @param {Object} config (optional) A {@link Ext.ProgressBar#waitConfig} object * @return {Ext.MessageBox} this */ wait : function(msg, title, config){ this.show({ title : title, msg : msg, buttons: false, closable:false, wait:true, modal:true, minWidth: this.minProgressWidth, waitConfig: config }); return this; }, /** * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript alert prompt). * If a callback function is passed it will be called after the user clicks the button, and the * id of the button that was clicked will be passed as the only parameter to the callback * (could also be the top-right close button). * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked after the message box is closed * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @return {Ext.MessageBox} this */ alert : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.OK, fn: fn, scope : scope, minWidth: this.minWidth }); return this; }, /** * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's confirm). * If a callback function is passed it will be called after the user clicks either button, * and the id of the button that was clicked will be passed as the only parameter to the callback * (could also be the top-right close button). * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked after the message box is closed * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @return {Ext.MessageBox} this */ confirm : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.YESNO, fn: fn, scope : scope, icon: this.QUESTION, minWidth: this.minWidth }); return this; }, /** * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to JavaScript's prompt). * The prompt can be a single-line or multi-line textbox. If a callback function is passed it will be called after the user * clicks either button, and the id of the button that was clicked (could also be the top-right * close button) and the text that was entered will be passed as the two parameters to the callback. * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked after the message box is closed * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight * property, or the height in pixels to create the textbox (defaults to false / single-line) * @param {String} value (optional) Default value of the text input element (defaults to '') * @return {Ext.MessageBox} this */ prompt : function(title, msg, fn, scope, multiline, value){ this.show({ title : title, msg : msg, buttons: this.OKCANCEL, fn: fn, minWidth: this.minPromptWidth, scope : scope, prompt:true, multiline: multiline, value: value }); return this; }, /** * Button config that displays a single OK button * @type Object */ OK : {ok:true}, /** * Button config that displays a single Cancel button * @type Object */ CANCEL : {cancel:true}, /** * Button config that displays OK and Cancel buttons * @type Object */ OKCANCEL : {ok:true, cancel:true}, /** * Button config that displays Yes and No buttons * @type Object */ YESNO : {yes:true, no:true}, /** * Button config that displays Yes, No and Cancel buttons * @type Object */ YESNOCANCEL : {yes:true, no:true, cancel:true}, /** * The CSS class that provides the INFO icon image * @type String */ INFO : 'ext-mb-info', /** * The CSS class that provides the WARNING icon image * @type String */ WARNING : 'ext-mb-warning', /** * The CSS class that provides the QUESTION icon image * @type String */ QUESTION : 'ext-mb-question', /** * The CSS class that provides the ERROR icon image * @type String */ ERROR : 'ext-mb-error', /** * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75) * @type Number */ defaultTextHeight : 75, /** * The maximum width in pixels of the message box (defaults to 600) * @type Number */ maxWidth : 600, /** * The minimum width in pixels of the message box (defaults to 100) * @type Number */ minWidth : 100, /** * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful * for setting a different minimum width than text-only dialogs may need (defaults to 250). * @type Number */ minProgressWidth : 250, /** * The minimum width in pixels of the message box if it is a prompt dialog. This is useful * for setting a different minimum width than text-only dialogs may need (defaults to 250). * @type Number */ minPromptWidth: 250, /** * An object containing the default button text strings that can be overriden for localized language support. * Supported properties are: ok, cancel, yes and no. Generally you should include a locale-specific * resource file for handling language support across the framework. * Customize the default text like so: Ext.MessageBox.buttonText.yes = "oui"; //french * @type Object */ buttonText : { ok : "OK", cancel : "Cancel", yes : "Yes", no : "No" } }; }(); /** * Shorthand for {@link Ext.MessageBox} */ Ext.Msg = Ext.MessageBox;/** * @class Ext.dd.PanelProxy * A custom drag proxy implementation specific to {@link Ext.Panel}s. This class is primarily used internally * for the Panel's drag drop implementation, and should never need to be created directly. * @constructor * @param panel The {@link Ext.Panel} to proxy for * @param config Configuration options */ Ext.dd.PanelProxy = Ext.extend(Object, { constructor : function(panel, config){ this.panel = panel; this.id = this.panel.id +'-ddproxy'; Ext.apply(this, config); }, /** * @cfg {Boolean} insertProxy True to insert a placeholder proxy element while dragging the panel, * false to drag with no proxy (defaults to true). */ insertProxy : true, // private overrides setStatus : Ext.emptyFn, reset : Ext.emptyFn, update : Ext.emptyFn, stop : Ext.emptyFn, sync: Ext.emptyFn, /** * Gets the proxy's element * @return {Element} The proxy's element */ getEl : function(){ return this.ghost; }, /** * Gets the proxy's ghost element * @return {Element} The proxy's ghost element */ getGhost : function(){ return this.ghost; }, /** * Gets the proxy's element * @return {Element} The proxy's element */ getProxy : function(){ return this.proxy; }, /** * Hides the proxy */ hide : function(){ if(this.ghost){ if(this.proxy){ this.proxy.remove(); delete this.proxy; } this.panel.el.dom.style.display = ''; this.ghost.remove(); delete this.ghost; } }, /** * Shows the proxy */ show : function(){ if(!this.ghost){ this.ghost = this.panel.createGhost(this.panel.initialConfig.cls, undefined, Ext.getBody()); this.ghost.setXY(this.panel.el.getXY()); if(this.insertProxy){ this.proxy = this.panel.el.insertSibling({cls:'x-panel-dd-spacer'}); this.proxy.setSize(this.panel.getSize()); } this.panel.el.dom.style.display = 'none'; } }, // private repair : function(xy, callback, scope){ this.hide(); if(typeof callback == "function"){ callback.call(scope || this); } }, /** * Moves the proxy to a different position in the DOM. This is typically called while dragging the Panel * to keep the proxy sync'd to the Panel's location. * @param {HTMLElement} parentNode The proxy's parent DOM node * @param {HTMLElement} before (optional) The sibling node before which the proxy should be inserted (defaults * to the parent's last child if not specified) */ moveProxy : function(parentNode, before){ if(this.proxy){ parentNode.insertBefore(this.proxy.dom, before); } } }); // private - DD implementation for Panels Ext.Panel.DD = Ext.extend(Ext.dd.DragSource, { constructor : function(panel, cfg){ this.panel = panel; this.dragData = {panel: panel}; this.proxy = new Ext.dd.PanelProxy(panel, cfg); Ext.Panel.DD.superclass.constructor.call(this, panel.el, cfg); var h = panel.header, el = panel.body; if(h){ this.setHandleElId(h.id); el = panel.header; } el.setStyle('cursor', 'move'); this.scroll = false; }, showFrame: Ext.emptyFn, startDrag: Ext.emptyFn, b4StartDrag: function(x, y) { this.proxy.show(); }, b4MouseDown: function(e) { var x = e.getPageX(), y = e.getPageY(); this.autoOffset(x, y); }, onInitDrag : function(x, y){ this.onStartDrag(x, y); return true; }, createFrame : Ext.emptyFn, getDragEl : function(e){ return this.proxy.ghost.dom; }, endDrag : function(e){ this.proxy.hide(); this.panel.saveState(); }, autoOffset : function(x, y) { x -= this.startPageX; y -= this.startPageY; this.setDelta(x, y); } });
{ "pile_set_name": "Github" }
<!-- Based on https://stackoverflow.com/a/25543713/1130282 --> {% extends "!page.html" %} {% block footer %} <script type="text/javascript"> $(document).ready(function() { $(".toggle > *").hide(); $(".toggle .header").show(); $(".toggle .header").click(function() { $(this).parent().children().not(".header").toggle(400); $(this).parent().children(".header").toggleClass("open"); }) }); </script> {% endblock %}
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MuonInterpreter { public class InterpreterState { public Stack<Frame> Frames; public Frame Current; public List<LocalVariable> Locals; public int FirstLocalIndex; public Namespace Top; public object Debug_CurrentStatement; public string[] FakeCommandLineArgs; } public struct Frame { public Namespace Ns; public FunctionDef Func; public int FirstLocalIndex; public override string ToString() { return Ns.Name + "." + Func.Name.Value; } } public class LocalVariable { public string Name; public object Value; } public struct BoundFunction { public FunctionDef Func; public object Instance; } public struct BoundBuiltinFunction { public BuiltinFunction Func; public object Instance; } public struct FunctionWithTypeArgs { public FunctionDef Func; public TypeArgsExpression TypeArgs; } public struct BoundField { public object Instance; public FieldDef Field; } public struct BoundElement { public object Instance; public long Index; } public struct RunStatementResult { public bool ShouldBreak; public bool ShouldContinue; public bool ShouldReturn; public object ReturnValue; } public enum BuiltinFunction { Identity = 0, Assert = 1, As = 2, Is = 3, Format = 4, Transmute = 5, Min = 6, Max = 7, Cast = 8, } public class Interpreter { public static object EvalFunction(InterpreterState s, FunctionDef func, TypeArgsExpression typeArgs = null) { s.Current = new Frame { Func = func, Ns = func.Parent != null ? func.Parent.Ns : s.Top, FirstLocalIndex = s.FirstLocalIndex }; if (func.InternalName != null) { return EvalInternalFunction(s, func, typeArgs); } var res = RunBlockStatement(s, func.Body); if (res.ShouldReturn) { return res.ReturnValue; } if (res.ShouldBreak || res.ShouldContinue) { throw new InvalidOperationException("break or continue is not allowed here"); } return null; } public static RunStatementResult RunStatement(InterpreterState s, object statement) { s.Debug_CurrentStatement = statement; switch (statement) { case BlockStatement st: return RunBlockStatement(s, st); case ExpressionStatement st: return RunExpressionStatement(s, st); case ReturnStatement st: return RunReturnStatement(s, st); case BreakStatement st: return RunBreakStatement(s, st); case ContinueStatement st: return RunContinueStatement(s, st); case IfStatement st: return RunIfStatement(s, st); case WhileStatement st: return RunWhileStatement(s, st); case ForEachStatement st: return RunForEachStatement(s, st); case ForIndexStatement st: return RunForIndexStatement(s, st); case MatchStatement st: return RunMatchStatement(s, st); default: throw new InvalidOperationException(); } } private static RunStatementResult RunBreakStatement(InterpreterState s, BreakStatement st) { return new RunStatementResult { ShouldBreak = true }; } private static RunStatementResult RunContinueStatement(InterpreterState s, ContinueStatement st) { return new RunStatementResult { ShouldContinue = true }; } private static RunStatementResult RunIfStatement(InterpreterState s, IfStatement st) { if ((bool)EvalExpression(s, st.ConditionExpr)) { return RunStatement(s, st.IfBranch); } else if (st.ElseBranch != null) { return RunStatement(s, st.ElseBranch); } return new RunStatementResult(); } private static RunStatementResult RunWhileStatement(InterpreterState s, WhileStatement st) { while ((bool)EvalExpression(s, st.ConditionExpr)) { var res = RunStatement(s, st.Body); if (res.ShouldReturn) { return res; } if (res.ShouldBreak) { return new RunStatementResult(); } } return new RunStatementResult(); } private static RunStatementResult RunForEachStatement(InterpreterState s, ForEachStatement st) { var prevLocalsCount = s.Locals.Count; AddLocalVar(s, st.IteratorVariable != null ? st.IteratorVariable.Value : "it", null); LocalVariable loopIndexVariable = null; if (st.IndexIteratorVariable != null) { loopIndexVariable = AddLocalVar(s, st.IndexIteratorVariable.Value, (long)0); } var seq = EvalExpression(s, st.SequenceExpression); if (seq is object[] || seq is List<object> || seq is HashSet<object>) { foreach (var it in (IEnumerable<object>)seq) { s.Locals[prevLocalsCount].Value = it; var res = RunStatement(s, st.Body); if (res.ShouldReturn) { s.Locals.SetSize(prevLocalsCount); return res; } if (res.ShouldBreak) { s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } if (loopIndexVariable != null) { loopIndexVariable.Value = ((long)loopIndexVariable.Value) + 1; } } } else { var dict = ((Map)seq).Dict; var mapEntryType = (Namespace)s.Top.Members["MapEntry"]; foreach (var p in dict) { var e = (Dictionary<string, object>)CreateInstance(s, mapEntryType); e["key"] = p.Key; e["value"] = p.Value; s.Locals[prevLocalsCount].Value = e; var res = RunStatement(s, st.Body); if (res.ShouldReturn) { s.Locals.SetSize(prevLocalsCount); return res; } if (res.ShouldBreak) { s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } if (loopIndexVariable != null) { loopIndexVariable.Value = ((long)loopIndexVariable.Value) + 1; } } } s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } private static RunStatementResult RunForIndexStatement(InterpreterState s, ForIndexStatement st) { var prevLocalsCount = s.Locals.Count; LocalVariable loopVariable = null; if (st.InitializerStatement != null) { var res = RunStatement(s, st.InitializerStatement); if (res.ShouldReturn || res.ShouldBreak || res.ShouldContinue) { throw new InvalidOperationException(); } loopVariable = GetLocalVar(s, ((Token)((BinaryOperatorExpression)st.InitializerStatement.Expr).Lhs).Value); } while ((bool)EvalExpression(s, st.ConditionExpr)) { var res = RunStatement(s, st.Body); if (res.ShouldReturn) { s.Locals.SetSize(prevLocalsCount); return res; } if (res.ShouldBreak) { s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } if (st.NextStatement != null) { res = RunStatement(s, st.NextStatement); if (res.ShouldReturn || res.ShouldBreak || res.ShouldContinue) { throw new InvalidOperationException(); } } else { loopVariable.Value = ((long)loopVariable.Value) + 1; } } s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } public static RunStatementResult RunMatchStatement(InterpreterState s, MatchStatement st) { if (!st.IsInitialized) { foreach (var cs in st.Cases) { if (cs.Token.Value == "null" || (cs.Second != null && cs.Second.Value == "null")) { st.NullCase = cs; } if (cs.Token.Value == "default" || (cs.Second != null && cs.Second.Value == "default")) { st.DefaultCase = cs; } } st.IsInitialized = true; } var value = EvalExpression(s, st.Expr); if (value == null) { if (st.NullCase == null) { throw new InvalidOperationException("No match"); } return RunStatement(s, st.NullCase.Statement); } var typename = GetTypeOfInstance(s, value).Name; foreach (var cs in st.Cases) { if (cs.Token.Value == typename) { return RunStatement(s, cs.Statement); } } if (st.DefaultCase == null) { throw new InvalidOperationException("No match"); } return RunStatement(s, st.DefaultCase.Statement); } public static RunStatementResult RunBlockStatement(InterpreterState s, BlockStatement st) { var prevLocalsCount = s.Locals.Count; foreach (var cst in st.Content) { var res = RunStatement(s, cst); if (res.ShouldReturn || res.ShouldBreak || res.ShouldContinue) { s.Locals.SetSize(prevLocalsCount); return res; } } s.Locals.SetSize(prevLocalsCount); return new RunStatementResult(); } public static RunStatementResult RunExpressionStatement(InterpreterState s, ExpressionStatement st) { EvalExpression(s, st.Expr); return new RunStatementResult(); } public static RunStatementResult RunReturnStatement(InterpreterState s, ReturnStatement st) { return new RunStatementResult { ShouldReturn = true, ReturnValue = st.Expr != null ? EvalExpression(s, st.Expr) : null }; } public static object EvalExpression(InterpreterState s, object expr) { switch (expr) { case Token t: return EvalToken(s, t); case UnaryOperatorExpression e: return EvalUnaryOperatorExpression(s, e); case DotExpression e: return EvalDotExpression(s, e); case BinaryOperatorExpression e: return EvalBinaryOperatorExpression(s, e); case TernaryOperatorExpression e : return EvalTernaryOperatorExpression(s, e); case CallExpression e: return EvalCallExpression(s, e); case StructInitializerExpression e: return EvalStructInitializerExpression(s, e); case IndexExpression e: return EvalIndexExpression(s, e); default: throw new InvalidOperationException(); } } public static object EvalToken(InterpreterState s, Token t) { if (t.Type == TokenType.StringLiteral || t.Type == TokenType.NumberLiteral || t.Type == TokenType.CharacterLiteral) { return t.AdditionalInfo; } else if (t.Type == TokenType.Identifier) { if (t.Value == "true") { return true; } else if (t.Value == "false") { return false; } else if (t.Value == "null") { return null; } var local = GetLocalVar(s, t.Value); if (local != null) { return local.Value; } if (!s.Current.Ns.Members.TryGetValue(t.Value, out object member)) { member = s.Top.Members[t.Value]; } if (member is Namespace) { return member; } var sf = (StaticFieldDef)member; EnsureStaticFieldInitialized(s, sf); return sf.Value; } throw new InvalidOperationException(); } public static object EvalUnaryOperatorExpression(InterpreterState s, UnaryOperatorExpression e) { switch (e.Op.Value) { case "!": return !(bool)EvalExpression(s, e.Expr); case "-": return -(long)EvalExpression(s, e.Expr); case "~": return ~(long)EvalExpression(s, e.Expr); case "new": return EvalExpression(s, e.Expr); // Ignore case "ref": return EvalExpression(s, e.Expr); // Ignore default: throw new InvalidOperationException(); } } public static object EvalDotExpression(InterpreterState s, DotExpression e) { var lhs = EvalExpression(s, e.Lhs); var memberName = e.Rhs.Value; if (lhs is Namespace) { var mem = ((Namespace)lhs).Members[memberName]; if (mem is StaticFieldDef) { var sf = (StaticFieldDef)mem; EnsureStaticFieldInitialized(s, sf); return sf.Value; } else if (mem is FunctionDef) { return "fun<>__not__implemented"; } else { throw new InvalidOperationException(); } } switch (memberName) { case "length": { switch (lhs) { case string a: return (long)a.Length; } break; } case "count": { switch (lhs) { case object[] a: return (long)a.Length; case List<object> a: return (long)a.Count; case HashSet<object> a: return (long)a.Count; case Map a: return (long)a.Dict.Count; case StringBuilder a: return (long)a.Length; } break; } } return ((Dictionary<string, object>)lhs)[memberName]; } public static object EvalBinaryOperatorExpression(InterpreterState s, BinaryOperatorExpression e) { switch (e.Op.Value) { case "=": case "+=": case "-=": case "*=": case "/=": case "%=": case "&=": case "|=": case "&&=": case "||=": { var target = ResolveAssignTarget(s, e.Lhs); var val = EvalExpression(s, e.Rhs); Assign(s, e.Op.Value, target, val); return null; } case ":=": { var variableName = ((Token)e.Lhs).Value; AddLocalVar(s, variableName, EvalExpression(s, e.Rhs)); return null; } case "+": return (long)EvalExpression(s, e.Lhs) + (long)EvalExpression(s, e.Rhs); case "-": { var lhs = EvalExpression(s, e.Lhs); switch (lhs) { case char a: return (long)(a - (char)EvalExpression(s, e.Rhs)); case long a: return a - (long)EvalExpression(s, e.Rhs); default: throw new InvalidOperationException(); } } case "*": return (long)EvalExpression(s, e.Lhs) * (long)EvalExpression(s, e.Rhs); case "/": return (long)EvalExpression(s, e.Lhs) / (long)EvalExpression(s, e.Rhs); case "%": return (long)EvalExpression(s, e.Lhs) % (long)EvalExpression(s, e.Rhs); case "&": return (long)EvalExpression(s, e.Lhs) & (long)EvalExpression(s, e.Rhs); case "|": return (long)EvalExpression(s, e.Lhs) | (long)EvalExpression(s, e.Rhs); case ">>": return (long)EvalExpression(s, e.Lhs) >> (int)(long)EvalExpression(s, e.Rhs); case "<<": return (long)EvalExpression(s, e.Lhs) << (int)(long)EvalExpression(s, e.Rhs); case "&&": return (bool)EvalExpression(s, e.Lhs) && (bool)EvalExpression(s, e.Rhs); case "||": return (bool)EvalExpression(s, e.Lhs) || (bool)EvalExpression(s, e.Rhs); case "==": return EvalCompareEqualsExpression(s, e); case "!=": return !EvalCompareEqualsExpression(s, e); case "<": return EvalCompareOrderedExpression(s, e); case ">": return EvalCompareOrderedExpression(s, e); case "<=": return EvalCompareOrderedExpression(s, e); case ">=": return EvalCompareOrderedExpression(s, e); default: throw new InvalidOperationException(); } } public static bool EvalCompareEqualsExpression(InterpreterState s, BinaryOperatorExpression e) { var lhs = EvalExpression(s, e.Lhs); var rhs = EvalExpression(s, e.Rhs); if (rhs == null) { return lhs == null; } switch (lhs) { case string a: return string.Equals(a, (string)rhs); case long a: return a == (long)rhs; case bool a: return a == (bool)rhs; case char a: return a == (char)rhs; case Dictionary<string, object> a: { var type = (Namespace)a["__type__"]; if (!type.IsRefType) { throw new InvalidOperationException("Cannot compare struct values"); } return a == rhs; } case null: return rhs == null; default: throw new InvalidOperationException(); } } public static bool EvalCompareOrderedExpression(InterpreterState s, BinaryOperatorExpression e) { var lhs = EvalExpression(s, e.Lhs); var rhs = EvalExpression(s, e.Rhs); if (lhs is ulong) { lhs = (long)(ulong)lhs; } if (rhs is ulong) { rhs = (long)(ulong)rhs; } int cmp; switch (lhs) { case string a: { cmp = string.Compare(a, (string)rhs); break; } case long a: { cmp = LongCompare(a, (long)rhs); break; } case char a: { cmp = CharCompare(a, (char)rhs); break; } default: throw new InvalidOperationException(); } var op = e.Op.Value; switch (op) { case "<": return cmp < 0; case ">": return cmp > 0; case "<=": return cmp <= 0; case ">=": return cmp >= 0; default: throw new InvalidOperationException(); } } public static int LongCompare(long a, long b) { if (a < b) { return -1; } else if (a > b) { return 1; } return 0; } public static int CharCompare(char a, char b) { if (a < b) { return -1; } else if (a > b) { return 1; } return 0; } public static object EvalTernaryOperatorExpression(InterpreterState s, TernaryOperatorExpression e) { if ((bool)EvalExpression(s, e.ConditionExpr)) { return EvalExpression(s, e.First); } else { return EvalExpression(s, e.Second); } } public static object EvalCallExpression(InterpreterState s, CallExpression e) { var target = ResolveCallTarget(s, e.Target); FunctionDef func; var hasFirstArg = false; var firstArg = (object)null; var typeArgs = (TypeArgsExpression)null; switch (target) { case FunctionDef f: { func = f; break; } case BoundFunction f: { func = f.Func; hasFirstArg = true; firstArg = f.Instance; break; } case FunctionWithTypeArgs f: { func = f.Func; typeArgs = f.TypeArgs; break; } case BuiltinFunction.Identity: return EvalIdentity(s, e); case BuiltinFunction.Assert: return EvalAssert(s, e); case BuiltinFunction.Format: return EvalFormat(s, e); case BuiltinFunction.Transmute: return EvalTransmute(s, e); case BuiltinFunction.Min: return EvalMin(s, e); case BuiltinFunction.Max: return EvalMax(s, e); case BuiltinFunction.Cast: return EvalCast(s, e); case BoundBuiltinFunction bbf: { switch (bbf.Func) { case BuiltinFunction.As: return EvalAs(s, bbf.Instance, e); case BuiltinFunction.Is: return EvalIs(s, bbf.Instance, e); default: throw new InvalidOperationException(); } } default: throw new InvalidOperationException(); } var bias = hasFirstArg ? 1 : 0; var argCount = e.Args.Count + bias; if (func.Params.Count != argCount) { throw new InvalidOperationException(string.Format("Expected {0} arguments but got {1} arguments", func.Params.Count, argCount)); } var prevFirstLocal = s.FirstLocalIndex; var prevCurrentLocal = s.Locals.Count; if (hasFirstArg) { s.Locals.Add(new LocalVariable { Name = func.Params[0].Name.Value, Value = firstArg }); } for (int i = 0; i < e.Args.Count; i++) { s.Locals.Add(new LocalVariable { Name = func.Params[i + bias].Name.Value, Value = EvalExpression(s, e.Args[i]) }); } s.FirstLocalIndex = prevCurrentLocal; s.Frames.Push(s.Current); var savedStatement = s.Debug_CurrentStatement; s.Debug_CurrentStatement = null; var result = EvalFunction(s, func, typeArgs); s.Debug_CurrentStatement = savedStatement; s.Current = s.Frames.Pop(); s.Locals.SetSize(s.FirstLocalIndex); s.FirstLocalIndex = prevFirstLocal; return result; } public static object EvalStructInitializerExpression(InterpreterState s, StructInitializerExpression e) { var typename = GetTypename(e.Target); var type = (Namespace)s.Top.Members[typename]; var inst = CreateInstance(s, type); if (e.Args.Count == 0) { return inst; } var result = (Dictionary<string, object>)inst; foreach (var fie in e.Args) { result.Update(fie.FieldName.Value, EvalExpression(s, fie.Expr)); } return result; } public static object EvalIndexExpression(InterpreterState s, IndexExpression e) { var seq = EvalExpression(s, e.Target); var index = (int)(long)EvalExpression(s, e.Arg); switch (seq) { case string a: return a[index]; case object[] a: return a[index]; case List<object> a: return a[index]; default: throw new InvalidOperationException(); } } public static object ResolveCallTarget(InterpreterState s, object expr) { switch (expr) { case Token t: { var local = GetLocalVar(s, t.Value); if (local != null) { return local.Value; } if (!s.Current.Ns.Members.TryGetValue(t.Value, out object member) || (member is FieldDef)) { s.Top.Members.TryGetValue(t.Value, out member); } if (member is Namespace) { var ns = (Namespace)member; if (ns.Kind == NamespaceKind.TaggedPointerEnum) { return BuiltinFunction.Identity; } else { return GetConstructor(ns); } } else if (member != null) { return member; } if (t.Value == "assert") { return BuiltinFunction.Assert; } else if (t.Value == "format") { return BuiltinFunction.Format; } else if (t.Value == "transmute") { return BuiltinFunction.Transmute; } else if (t.Value == "min") { return BuiltinFunction.Min; } else if (t.Value == "max") { return BuiltinFunction.Max; } else if (t.Value == "cast") { return BuiltinFunction.Cast; } throw new InvalidOperationException(); } case DotExpression e: { var lhs = EvalExpression(s, e.Lhs); var memberName = e.Rhs.Value; if (lhs is Namespace) { return ((Namespace)lhs).Members[memberName]; } if (memberName == "as") { return new BoundBuiltinFunction { Func = BuiltinFunction.As, Instance = lhs }; } else if (memberName == "is") { return new BoundBuiltinFunction { Func = BuiltinFunction.Is, Instance = lhs }; } var type = GetTypeOfInstance(s, lhs); var func = (FunctionDef)type.Members[memberName]; return new BoundFunction { Instance = lhs, Func = func }; } case TypeArgsExpression e: { if (e.Target is DotExpression) { var func = (FunctionDef)ResolveCallTarget(s, e.Target); return new FunctionWithTypeArgs { Func = func, TypeArgs = e }; } var typename = GetTypename(e.Target); var type = (Namespace)s.Top.Members[typename]; return new FunctionWithTypeArgs { Func = GetConstructor(type), TypeArgs = e }; } default: throw new InvalidOperationException(); } } public static FunctionDef GetConstructor(Namespace type) { if (type.Kind != NamespaceKind.Struct) { throw new InvalidOperationException(); } return (FunctionDef)type.Members["cons"]; } public static object ResolveAssignTarget(InterpreterState s, object expr) { switch (expr) { case Token t: { var local = GetLocalVar(s, t.Value); if (local != null) { return local; } if (s.Current.Ns.Members.TryGetValue(t.Value, out object member) && !(member is FieldDef)) { return member; } return s.Top.Members[t.Value]; } case TypeModifierExpression e: { if (e.Modifier.Value != "::") { throw new InvalidOperationException(); } return s.Top.Members[((Token)e.Arg).Value]; } case DotExpression e: { var lhs = EvalExpression(s, e.Lhs); if (lhs is Namespace) { return ((Namespace)lhs).Members[e.Rhs.Value]; } var type = GetTypeOfInstance(s, lhs); var field = (FieldDef)type.Members[e.Rhs.Value]; return new BoundField { Instance = lhs, Field = field }; } case IndexExpression e: { var target = EvalExpression(s, e.Target); var index = (long)EvalExpression(s, e.Arg); return new BoundElement { Instance = target, Index = index }; } default: throw new InvalidOperationException(); } } public static void Assign(InterpreterState s, string op, object target, object val) { switch (target) { case LocalVariable local: { switch (op) { case "=": { local.Value = val; break; } case "+=": { local.Value = (long)local.Value + (long)val; break; } case "-=": { local.Value = (long)local.Value - (long)val; break; } case "*=": { local.Value = (long)local.Value * (long)val; break; } case "/=": { local.Value = (long)local.Value / (long)val; break; } case "%=": { local.Value = (long)local.Value % (long)val; break; } case "&=": { local.Value = (long)local.Value & (long)val; break; } case "|=": { local.Value = (long)local.Value | (long)val; break; } case "&&=": { local.Value = (bool)local.Value && (bool)val; break; } case "||=": { local.Value = (bool)local.Value || (bool)val; break; } default: throw new InvalidOperationException(); } break; } case BoundField bf: { var dict = (Dictionary<string, object>)bf.Instance; var fieldName = bf.Field.Name.Value; switch (op) { case "=": { dict.Update(fieldName, val); break; } case "+=": { dict.Update(fieldName, (long)dict[fieldName] + (long)val); break; } case "-=": { dict.Update(fieldName, (long)dict[fieldName] - (long)val); break; } case "*=": { dict.Update(fieldName, (long)dict[fieldName] * (long)val); break; } case "/=": { dict.Update(fieldName, (long)dict[fieldName] / (long)val); break; } case "%=": { dict.Update(fieldName, (long)dict[fieldName] % (long)val); break; } case "&=": { dict.Update(fieldName, (long)dict[fieldName] & (long)val); break; } case "|=": { dict.Update(fieldName, (long)dict[fieldName] | (long)val); break; } case "&&=": { dict.Update(fieldName, (bool)dict[fieldName] && (bool)val); break; } case "||=": { dict.Update(fieldName, (bool)dict[fieldName] || (bool)val); break; } default: throw new InvalidOperationException(); } break; } case BoundElement be: { var index = (int)be.Index; switch (be.Instance) { case object[] a: { switch (op) { case "=": { a[index] = val; break; } case "+=": { a[index] = (long)a[index] + (long)val; break; } case "-=": { a[index] = (long)a[index] - (long)val; break; } default: throw new InvalidOperationException(); } break; } case List<object> a: { switch (op) { case "=": { a[index] = val; break; } case "+=": { a[index] = (long)a[index] + (long)val; break; } case "-=": { a[index] = (long)a[index] - (long)val; break; } default: throw new InvalidOperationException(); } break; } default: throw new InvalidOperationException(); } break; } case StaticFieldDef sf: { sf.IsInitialized = true; switch (op) { case "=": { sf.Value = val; break; } default: throw new InvalidOperationException(); } break; } default: throw new InvalidOperationException(); } } public static Namespace GetTypeOfInstance(InterpreterState s, object value) { switch (value) { case long a: return (Namespace)s.Top.Members["long"]; case string a: return (Namespace)s.Top.Members["string"]; case char a: return (Namespace)s.Top.Members["char"]; case bool a: return (Namespace)s.Top.Members["bool"]; case Dictionary<string, object> a: return (Namespace)a["__type__"]; case StringBuilder a: return (Namespace)s.Top.Members["StringBuilder"]; case object[] a: return (Namespace)s.Top.Members["Array"]; case List<object> a: return (Namespace)s.Top.Members["List"]; case HashSet<object> a: return (Namespace)s.Top.Members["Set"]; case Map a: return (Namespace)s.Top.Members["Map"]; default: throw new InvalidOperationException(); } } public static object CreateInstance(InterpreterState s, Namespace type) { if (type.Name == "StringBuilder") { return new StringBuilder(); } if (type.Name == "Array") { throw new InvalidOperationException("Must use Array.cons to create an Array instance"); } if (type.Name == "List") { return new List<object>(); } if (type.Name == "Set") { throw new InvalidOperationException("Must use Set.create to create a Set instance"); } if (type.Name == "Map") { throw new InvalidOperationException("Must use Map.create to create a Map instance"); } var result = new Dictionary<string, object>(); result["__type__"] = type; foreach (var p in type.Members) { if (p.Value is FieldDef) { var fd = (FieldDef)p.Value; result[fd.Name.Value] = GetDefaultValue(s, GetTypename(fd.Type)); } } return result; } public static string GetTypename(object typeExpr) { switch (typeExpr) { case Token t: return t.Value; case TypeModifierExpression tme: return ((Token)tme.Arg).Value; case TypeArgsExpression tae: return ((Token)tae.Target).Value; default: throw new InvalidOperationException(); } } public static object GetDefaultValue(InterpreterState s, string typename) { switch (typename) { case "int": return (long)0; case "uint": return (long)0; case "long": return (long)0; case "ulong": return (ulong)0; case "string": return ""; case "pointer": return null; case "fun": return null; case "double": return (double)0; case "bool": return false; case "char": return '\0'; default: { if (s.Top.Members.TryGetValue(typename, out object typeObject)) { var type = (Namespace)typeObject; if (type.Kind == NamespaceKind.Struct) { if (!type.IsRefType) { return CreateInstance(s, type); } else { return null; } } else if (type.Kind == NamespaceKind.Enum) { return (long)0; } else if (type.Kind == NamespaceKind.TaggedPointerEnum) { return null; } else { throw new InvalidOperationException(); } } else if (typename.Length == 1 && char.IsUpper(typename[0])) { return null; // Generic type, just return null and hope for the best. } else { throw new InvalidOperationException(); } } } } public static void EnsureStaticFieldInitialized(InterpreterState s, StaticFieldDef sf) { if (sf.IsInitialized) { return; } if (sf.InitializerExpr != null) { var pushedFrame = false; var sfNs = sf.Parent != null ? sf.Parent.Ns : s.Top; if (s.Current.Ns != sfNs) { s.Frames.Push(s.Current); s.Current = new Frame { Ns = sfNs }; pushedFrame = true; } sf.Value = EvalExpression(s, sf.InitializerExpr); if (pushedFrame) { s.Current = s.Frames.Pop(); } } else if (sf.Type != null) { sf.Value = GetDefaultValue(s, GetTypename(sf.Type)); } sf.IsInitialized = true; } public static LocalVariable AddLocalVar(InterpreterState s, string name, object value) { for (var i = s.FirstLocalIndex; i < s.Locals.Count; i++) { if (s.Locals[i].Name == name) { throw new InvalidOperationException("Variable is already defined"); } } var local = new LocalVariable { Name = name, Value = value }; s.Locals.Add(local); return local; } public static LocalVariable GetLocalVar(InterpreterState s, string name) { for (var i = s.FirstLocalIndex; i < s.Locals.Count; i++) { if (s.Locals[i].Name == name) { return s.Locals[i]; } } return null; } public static object EvalInternalFunction(InterpreterState s, FunctionDef func, TypeArgsExpression typeArgs) { switch (func.InternalName) { case "int.parse": { return (long)int.Parse((string)s.Locals[s.FirstLocalIndex].Value); } case "long.toString": { return ((long)s.Locals[s.FirstLocalIndex].Value).ToString(); } case "char.toString": { return ((char)s.Locals[s.FirstLocalIndex].Value).ToString(); } case "string.slice": { var str = (string)s.Locals[s.FirstLocalIndex].Value; var from = (int)(long)(s.Locals[s.FirstLocalIndex + 1].Value); var to = (int)(long)(s.Locals[s.FirstLocalIndex + 2].Value); return str.Slice(from, to); } case "Stdout.writeLine": { Console.WriteLine((string)s.Locals[s.FirstLocalIndex].Value); return null; } case "Environment.getCommandLineArgs": { return s.FakeCommandLineArgs.Select(a => (object)a).ToArray(); } case "Environment.runCommandSync": { // TODO: Fix extremely hacky code var cmd = (string)s.Locals[s.FirstLocalIndex].Value; if (cmd[0] == '"' && cmd[cmd.Length - 1] == '"') { cmd = cmd.Slice(1, cmd.Length - 1); } var p = new System.Diagnostics.Process(); var exeIndex = cmd.IndexOf(".exe"); if (exeIndex < 0) { throw new InvalidOperationException(); } exeIndex += 4; if (cmd[exeIndex] == '"') { exeIndex += 1; } p.StartInfo.FileName = cmd.Slice(0, exeIndex); p.StartInfo.Arguments = cmd.Slice(exeIndex, cmd.Length); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); if (!p.Start()) { throw new InvalidOperationException(); } p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); return (long)p.ExitCode; } case "Environment.exit": { var exitCode = (long)s.Locals[s.FirstLocalIndex].Value; Environment.Exit((int)exitCode); return null; } case "Debug.break": { System.Diagnostics.Debugger.Break(); return null; } case "File.tryReadToStringBuilder": { var path = (string)s.Locals[s.FirstLocalIndex].Value; var out_ = (StringBuilder)s.Locals[s.FirstLocalIndex + 1].Value; using (var reader = new System.IO.StreamReader(path)) { out_.Append(reader.ReadToEnd()); } return true; } case "File.tryWriteString": { var path = (string)s.Locals[s.FirstLocalIndex].Value; var contents = (string)s.Locals[s.FirstLocalIndex + 1].Value; using (var writer = new System.IO.StreamWriter(path)) { writer.Write(contents); } return true; } case "StringBuilder.write": { var self = (StringBuilder)s.Locals[s.FirstLocalIndex].Value; var value = (string)s.Locals[s.FirstLocalIndex + 1].Value; self.Append(value); return null; } case "StringBuilder.writeChar": { var self = (StringBuilder)s.Locals[s.FirstLocalIndex].Value; var value = (char)s.Locals[s.FirstLocalIndex + 1].Value; self.Append(value); return null; } case "StringBuilder.toString": { var self = (StringBuilder)s.Locals[s.FirstLocalIndex].Value; return self.ToString(); } case "StringBuilder.compactToString": { var self = (StringBuilder)s.Locals[s.FirstLocalIndex].Value; return self.ToString(); } case "StringBuilder.clear": { var self = (StringBuilder)s.Locals[s.FirstLocalIndex].Value; self.Clear(); return null; } case "Array.cons": { if (typeArgs.Args.Count != 1) { throw new InvalidOperationException(); } var elementTypename = GetTypename(typeArgs.Args[0]); var result = new object[(int)(long)s.Locals[s.FirstLocalIndex].Value]; for (int i = 0; i < result.Length; i++) { result[i] = GetDefaultValue(s, elementTypename); } return result; } case "Array.stableSort": { var self = (object[])s.Locals[s.FirstLocalIndex].Value; // Ignore return null; } case "List.add": { var self = (List<object>)s.Locals[s.FirstLocalIndex].Value; var item = s.Locals[s.FirstLocalIndex + 1].Value; self.Add(item); return null; } case "List.setCountChecked": { var self = (List<object>)s.Locals[s.FirstLocalIndex].Value; var count = (int)(long)(s.Locals[s.FirstLocalIndex + 1].Value); self.RemoveRange(count, self.Count - count); return null; } case "List.clear": { var self = (List<object>)s.Locals[s.FirstLocalIndex].Value; self.Clear(); return null; } case "List.slice": { var self = (List<object>)s.Locals[s.FirstLocalIndex].Value; var from = (int)(long)(s.Locals[s.FirstLocalIndex + 1].Value); var to = (int)(long)(s.Locals[s.FirstLocalIndex + 2].Value); var result = new object[to - from]; for (int i = 0; i < result.Length; i++) { result[i] = self[i - from]; } return result; } case "Set.create": case "CustomSet.create": { if (typeArgs.Args.Count != 1) { throw new InvalidOperationException(); } var valueTypename = GetTypename(typeArgs.Args[0]); if (valueTypename == "string") { return new HashSet<object>(new StringComparer()); } else if (valueTypename == "int") { return new HashSet<object>(new LongComparer()); } else if (valueTypename == "Tag") { return new HashSet<object>(new TagComparer()); } else if (valueTypename == "Array") { // This is really just a huge hack return new HashSet<object>(new TagArgsComparer()); } else { return new HashSet<object>(); } } case "Set.add": case "CustomSet.add": { var self = (HashSet<object>)s.Locals[s.FirstLocalIndex].Value; var value = s.Locals[s.FirstLocalIndex + 1].Value; if (!self.Add(value)) { throw new InvalidOperationException("Already present"); } return null; } case "Set.tryAdd": case "CustomSet.tryAdd": { var self = (HashSet<object>)s.Locals[s.FirstLocalIndex].Value; var value = s.Locals[s.FirstLocalIndex + 1].Value; return self.Add(value); } case "Set.contains": case "CustomSet.contains": { var self = (HashSet<object>)s.Locals[s.FirstLocalIndex].Value; var value = s.Locals[s.FirstLocalIndex + 1].Value; return self.Contains(value); } case "Set.remove": case "CustomSet.remove": { var self = (HashSet<object>)s.Locals[s.FirstLocalIndex].Value; var value = s.Locals[s.FirstLocalIndex + 1].Value; if (!self.Remove(value)) { throw new InvalidOperationException("Not found"); } return null; } case "Set.clear": case "CustomSet.clear": { var self = (HashSet<object>)s.Locals[s.FirstLocalIndex].Value; self.Clear(); return null; } case "Map.create": { if (typeArgs.Args.Count != 2) { throw new InvalidOperationException(); } var keyTypename = GetTypename(typeArgs.Args[0]); var valueTypename = GetTypename(typeArgs.Args[1]); if (keyTypename == "string") { return new Map { Dict = new Dictionary<object, object>(new StringComparer()), ValueTypename = valueTypename }; } else if (keyTypename == "int") { return new Map { Dict = new Dictionary<object, object>(new LongComparer()), ValueTypename = valueTypename }; } else { return new Map { Dict = new Dictionary<object, object>(), ValueTypename = valueTypename }; } } case "Map.add": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; var value = s.Locals[s.FirstLocalIndex + 2].Value; self.Dict.Add(key, value); return null; } case "Map.tryAdd": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; var value = s.Locals[s.FirstLocalIndex + 2].Value; if (!self.Dict.ContainsKey(key)) { self.Dict.Add(key, value); return true; } else { return false; } } case "Map.addOrUpdate": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; var value = s.Locals[s.FirstLocalIndex + 2].Value; self.Dict[key] = value; return null; } case "Map.update": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; var value = s.Locals[s.FirstLocalIndex + 2].Value; if (!self.Dict.ContainsKey(key)) { throw new InvalidOperationException(); } self.Dict[key] = value; return null; } case "Map.get": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; if (!self.Dict.TryGetValue(key, out object value)) { throw new InvalidOperationException(); } return value; } case "Map.getOrDefault": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; if (!self.Dict.TryGetValue(key, out object value)) { switch (self.ValueTypename) { case "string": return ""; case "int": case "long": { return (long)0; } default: return null; } } return value; } case "Map.maybeGet": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; var maybe = (Dictionary<string, object>)CreateInstance(s, (Namespace)s.Top.Members["Maybe"]); if (self.Dict.TryGetValue(key, out object value)) { maybe["value"] = value; maybe["hasValue"] = true; } return maybe; } case "Map.remove": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; var key = s.Locals[s.FirstLocalIndex + 1].Value; if (!self.Dict.Remove(key)) { throw new InvalidOperationException("Not found"); } return null; } case "Map.clear": { var self = (Map)s.Locals[s.FirstLocalIndex].Value; self.Dict.Clear(); return null; } case "Memory.newArenaAllocator": { return null; } case "CpuTimeStopwatch.start": { return null; } case "CpuTimeStopwatch.elapsed": { return (double)0; } default: throw new ArgumentException(); } } public class StringComparer : IEqualityComparer<object> { public new bool Equals(object x, object y) { return string.Equals((string)x, (string)y); } public int GetHashCode(object obj) { return ((string)obj).GetHashCode(); } } public class LongComparer : IEqualityComparer<object> { public new bool Equals(object x, object y) { return (long)x == (long)y; } public int GetHashCode(object obj) { return ((long)obj).GetHashCode(); } } public class TagComparer : IEqualityComparer<object> { public new bool Equals(object x, object y) { return Static_Equals(x, y); } public static bool Static_Equals(object x, object y) { var a = (Dictionary<string, object>)x; var b = (Dictionary<string, object>)y; if (a["ti"] != b["ti"]) { return false; } return Static_ArgsEquals(a["args"], b["args"]); } public static bool Static_ArgsEquals(object x, object y) { var aArgs = (object[])x; var bArgs = (object[])y; if (aArgs == null && bArgs == null) { return true; } if (aArgs == null || bArgs == null) { return false; } if (aArgs.Length != bArgs.Length) { return false; } for (int i = 0; i < aArgs.Length; i++) { if (!Static_Equals(aArgs[i], bArgs[i])) { return false; } } return true; } public int GetHashCode(object obj) { return Static_GetHashCode(obj); } public static int Static_GetHashCode(object obj) { var x = (Dictionary<string, object>)obj; var ti = (Dictionary<string, object>)x["ti"]; return ((string)ti["name"]).GetHashCode(); } } public class TagArgsComparer : IEqualityComparer<object> { public new bool Equals(object x, object y) { return TagComparer.Static_ArgsEquals(x, y); } public int GetHashCode(object obj) { var args = (object[])obj; int hash = 0; foreach (var tag in args) { hash ^= TagComparer.Static_GetHashCode(tag); hash <<= 5; } return hash; } } public static object EvalIdentity(InterpreterState s, CallExpression e) { if (e.Args.Count != 1) { throw new InvalidOperationException(); } return EvalExpression(s, e.Args[0]); } public static object EvalAssert(InterpreterState s, CallExpression e) { if (e.Args.Count != 1) { throw new InvalidOperationException(); } if (!(bool)EvalExpression(s, e.Args[0])) { throw new InvalidOperationException("Assertion failed"); } return null; } public static object EvalAs(InterpreterState s, object lhs, CallExpression e) { if (e.Args.Count != 1) { throw new InvalidOperationException(); } var lhsType = GetTypeOfInstance(s, lhs); var rhsType = (Namespace)EvalExpression(s, e.Args[0]); if (lhsType != rhsType) { throw new InvalidOperationException("Invalid cast"); } return lhs; } public static object EvalIs(InterpreterState s, object lhs, CallExpression e) { if (e.Args.Count != 1) { throw new InvalidOperationException(); } if (lhs == null) { return false; } var lhsType = GetTypeOfInstance(s, lhs); var rhsType = (Namespace)EvalExpression(s, e.Args[0]); return lhsType == rhsType; } public static object EvalFormat(InterpreterState s, CallExpression e) { if (e.Args.Count < 1) { throw new InvalidOperationException(); } var rb = new StringBuilder(); var formatString = (string)EvalExpression(s, e.Args[0]); var arg = 1; var i = 0; while (i < formatString.Length) { var ch = formatString[i]; if (ch == '{') { i += 1; ch = formatString[i]; if (ch == '}') { var val = EvalExpression(s, e.Args[arg]); switch (val) { case char a: { rb.Append(a); break; } case bool a: { rb.Append(a ? "true" : "false"); break; } case long a: { rb.Append(a); break; } case ulong a: { rb.Append(a); break; } case string a: { rb.Append(a); break; } default: throw new InvalidOperationException(); } arg += 1; } else if (ch == '{') { rb.Append('{'); } else { throw new InvalidOperationException("Invalid format string"); } } else if (ch == '}') { i += 1; ch = formatString[i]; if (ch == '}') { rb.Append(ch); } else { throw new InvalidOperationException("Invalid format string"); } } else { rb.Append(ch); } i += 1; } if (arg < e.Args.Count) { throw new InvalidOperationException("Too many arguments"); } return rb.ToString(); } public static object EvalTransmute(InterpreterState s, CallExpression e) { if (e.Args.Count != 2) { throw new InvalidOperationException(); } var value = EvalExpression(s, e.Args[0]); var targetType = (Namespace)EvalExpression(s, e.Args[1]); switch (targetType.Name) { case "int": return (long)(char)value; case "char": return (char)(long)value; case "long": return value; case "ulong": return value; default: throw new InvalidOperationException(); } } public static object EvalMin(InterpreterState s, CallExpression e) { if (e.Args.Count != 2) { throw new InvalidOperationException(); } var lhs = (long)EvalExpression(s, e.Args[0]); var rhs = (long)EvalExpression(s, e.Args[1]); return Math.Min(lhs, rhs); } public static object EvalMax(InterpreterState s, CallExpression e) { if (e.Args.Count != 2) { throw new InvalidOperationException(); } var lhs = (long)EvalExpression(s, e.Args[0]); var rhs = (long)EvalExpression(s, e.Args[1]); return Math.Max(lhs, rhs); } public static object EvalCast(InterpreterState s, CallExpression e) { if (e.Args.Count != 2) { throw new InvalidOperationException(); } return EvalExpression(s, e.Args[0]); } } public class Map { public Dictionary<object, object> Dict; public string ValueTypename; } }
{ "pile_set_name": "Github" }
ENTRY(ota_2ndboot_image_entry) INCLUDE "platform/mcu/rtl8710bn/script/export-rom_symbol_v01.txt" GROUP ( libc.a libnosys.a ) MEMORY { ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */ ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */ BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */ BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 228 */ ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */ MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */ RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */ XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 32k, 32 Bytes resvd for header*/ XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0x6000-0x20 /* XIP1: 968k, 32 Bytes resvd for header */ } SECTIONS { .rom.text : { } > ROM .rom.rodata : { } > ROM .ARM.exidx : { __exidx_start = .; *(.ARM.exidx*) *(.gnu.linkonce.armexidx.*) __exidx_end = .; } > ROM .hal.rom.bss : { } > ROMBSS_RAM /* image1 entry, this section should in RAM and fixed address for ROM */ .ram_image1.entry : { __ram_image1_text_start__ = .; __ram_start_table_start__ = .; KEEP(*(SORT(.image1.entry.data*))) __ram_start_table_end__ = .; __image1_validate_code__ = .; KEEP(*(.image1.validate.rodata*)) KEEP(*(.image1.export.symb*)) } > BOOTLOADER_RAM /* Add . to assign the start address of the section */ /* to prevent the change of the start address by ld doing section alignment */ .ram_image1.text . : { /* image1 text */ *(.boot.ram.text*) *(.boot.rodata*) } > BOOTLOADER_RAM .ram_image1.data . : { __ram_image1_data_start__ = .; KEEP(*(.boot.ram.data*)) __ram_image1_data_end__ = .; __ram_image1_text_end__ = .; } > BOOTLOADER_RAM .ram_image1.bss . : { __image1_bss_start__ = .; KEEP(*(.boot.ram.bss*)) KEEP(*(.boot.ram.end.bss*)) __image1_bss_end__ = .; } > BOOTLOADER_RAM .ram_image2.entry : { __ram_image2_text_start__ = .; __image2_entry_func__ = .; KEEP(*(SORT(.image2.entry.data*))) __image2_validate_code__ = .; KEEP(*(.image2.validate.rodata*)) } > BD_RAM .ram_image2.text : { KEEP(*(.image2.ram.text*)) } > BD_RAM .ram_image2.data : { __data_start__ = .; *(.data*) __data_end__ = .; __ram_image2_text_end__ = .; . = ALIGN(16); } > BD_RAM .ram_image2.bss : { __bss_start__ = .; *(.bss*) *(COMMON) } > BD_RAM .ram_image2.skb.bss : { *(.bdsram.data*) __bss_end__ = .; } > BD_RAM .ram_heap.data : { *(.bfsram.data*) } > BD_RAM . = ALIGN(8); PROVIDE(_rec_heap_start = .); PROVIDE(_rec_heap_end = 0x1003CFFF); PROVIDE(_rec_heap_len = _rec_heap_end - _rec_heap_start); PROVIDE(end = 0x1003d000); .rom.bss : { *(.heap.stdlib*) } > ROM_BSS_RAM .ram_rdp.text : { __rom_top_4k_start_ = .; __rdp_text_start__ = .; KEEP(*(.rdp.ram.text*)) KEEP(*(.rdp.ram.data*)) __rdp_text_end__ = .; . = ALIGN(16); } > RDP_RAM .xip_image1.text : { __flash_boot_text_start__ = .; *(.flashboot.text*) __flash_boot_text_end__ = .; . = ALIGN(16); } > XIPBOOT .xip_image2.text : { __flash_text_start__ = .; *(.img2_custom_signature*) *(.text) *(.text*) *(.rodata) *(.rodata*) *(.debug_trace*) __flash_text_end__ = .; . = ALIGN (16); } > XIP1 } SECTIONS { /* Bootloader symbol list */ boot_export_symbol = 0x10002020; }
{ "pile_set_name": "Github" }
:107E000001C0B7C0112484B790E89093610010922C :107E10006100882361F0982F9A70923041F081FFC1 :107E200002C097EF94BF282E80E0C6D0E9C085E05D :107E30008093810082E08093C80088E18093C9002C :107E40008FEE8093CC0086E08093CA008EE0B4D0A1 :107E5000209A84E02BE93BEF91E03093850020935A :107E6000840096BBB09BFECF189AA8954091C8009D :107E700047FD02C0815089F793D0813479F490D0C6 :107E8000182FA0D0123811F480E004C088E0113817 :107E900009F083E07ED080E17CD0EECF823419F40B :107EA00084E198D0F8CF853411F485E0FACF853598 :107EB00041F476D0C82F74D0D82FCC0FDD1F82D0DC :107EC000EACF863519F484E085D0DECF843691F58B :107ED00067D066D0F82E64D0D82E00E011E05801AB :107EE0008FEFA81AB80A5CD0F80180838501FA10D8 :107EF000F6CF68D0F5E4DF1201C0FFCF50E040E0DC :107F000063E0CE0136D08E01E0E0F1E06F0182E067 :107F1000C80ED11C4081518161E0C8012AD00E5F9A :107F20001F4FF601FC10F2CF50E040E065E0CE01BB :107F300020D0B1CF843771F433D032D0F82E30D086 :107F400041D08E01F80185918F0123D0FA94F11070 :107F5000F9CFA1CF853739F435D08EE11AD085E934 :107F600018D081E197CF813509F0A9CF88E024D0DE :107F7000A6CFFC010A0167BFE895112407B600FCF3 :107F8000FDCF667029F0452B19F481E187BFE89594 :107F900008959091C80095FFFCCF8093CE0008957E :107FA0008091C80087FFFCCF8091C80084FD01C08C :107FB000A8958091CE000895E0E6F0E098E19083E6 :107FC00080830895EDDF803219F088E0F5DFFFCF80 :107FD00084E1DFCFCF93C82FE3DFC150E9F7CF9122 :027FE000F1CFDF :027FFE00000879 :0400000300007E007B :00000001FF
{ "pile_set_name": "Github" }
/* Five-color theme from a single blue hue. */ .hljs { display: block; padding: 0.5em; background: #EAEEF3; color: #00193A; } .hljs-keyword, .hljs-title, .hljs-important, .hljs-request, .hljs-header, .hljs-javadoctag { font-weight: bold; } .hljs-comment, .hljs-chunk, .hljs-template_comment { color: #738191; } .hljs-string, .hljs-title, .hljs-parent, .hljs-built_in, .hljs-literal, .hljs-filename, .hljs-value, .hljs-addition, .hljs-tag, .hljs-argument, .hljs-link_label, .hljs-blockquote, .hljs-header { color: #0048AB; } .hljs-decorator, .hljs-prompt, .hljs-yardoctag, .hljs-subst, .hljs-symbol, .hljs-doctype, .hljs-regexp, .hljs-preprocessor, .hljs-pragma, .hljs-pi, .hljs-attribute, .hljs-attr_selector, .hljs-javadoc, .hljs-xmlDocTag, .hljs-deletion, .hljs-shebang, .hljs-string .hljs-variable, .hljs-link_url, .hljs-bullet, .hljs-sqbracket, .hljs-phony { color: #4C81C9; }
{ "pile_set_name": "Github" }
var fs = require('graceful-fs') var path = require('path') var mkdirp = require('mkdirp') var mr = require('npm-registry-mock') var osenv = require('osenv') var rimraf = require('rimraf') var test = require('tap').test var common = require('../common-tap') var pkg = path.resolve(__dirname, 'ls-depth') var EXEC_OPTS = { cwd: pkg } var json = { name: 'ls-env', version: '0.0.0', dependencies: { 'test-package-with-one-dep': '0.0.0', 'test-repo-url-ssh': '0.0.1' }, devDependencies: { 'test-package-with-one-dep': '0.0.0', 'test-repo-url-https': '0.0.1' } } test('setup', function (t) { cleanup() mkdirp.sync(pkg) fs.writeFileSync( path.join(pkg, 'package.json'), JSON.stringify(json, null, 2) ) mr({port: common.port}, function (er, s) { common.npm( [ '--registry', common.registry, 'install' ], EXEC_OPTS, function (er, c) { t.ifError(er, 'install ran without issue') t.equal(c, 0) s.close() t.end() } ) }) }) test('npm ls --dev', function (t) { common.npm(['ls', '--dev'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --dev ran without issue') t.equal(code, 0) t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.has( stdout, /test-repo-url-https@0\.0\.1/, 'output contains [email protected]' ) t.doesNotHave( stdout, /test-repo-url-ssh@0\.0\.1/, 'output does NOT contain [email protected]' ) t.end() }) }) test('npm ls --only=development', function (t) { common.npm(['ls', '--only=development'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --only=development ran without issue') t.equal(code, 0) t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.end() }) }) test('npm ls --only=dev', function (t) { common.npm(['ls', '--only=dev'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --only=dev ran without issue') t.equal(code, 0) t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.end() }) }) test('npm ls --production', function (t) { common.npm(['ls', '--production'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --production ran without issue') t.notOk(code, 'npm exited ok') t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.has( stdout, /test-repo-url-ssh@0\.0\.1/, 'output contains [email protected]' ) t.doesNotHave( stdout, /test-repo-url-https@0\.0\.1/, 'output does NOT contain [email protected]' ) t.end() }) }) test('npm ls --prod', function (t) { common.npm(['ls', '--prod'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --prod ran without issue') t.notOk(code, 'npm exited ok') t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.end() }) }) test('npm ls --only=production', function (t) { common.npm(['ls', '--only=production'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --only=production ran without issue') t.notOk(code, 'npm exited ok') t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.end() }) }) test('npm ls --only=prod', function (t) { common.npm(['ls', '--only=prod'], EXEC_OPTS, function (er, code, stdout) { t.ifError(er, 'ls --only=prod ran without issue') t.notOk(code, 'npm exited ok') t.has( stdout, /test-package-with-one-dep@0\.0\.0/, 'output contains [email protected]' ) t.end() }) }) test('cleanup', function (t) { cleanup() t.end() }) function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(pkg) }
{ "pile_set_name": "Github" }
//===--- ThreadsafeFS.h ------------------------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_SUPPORT_THREADSAFEFS_H #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SUPPORT_THREADSAFEFS_H #include "Path.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/Support/VirtualFileSystem.h" #include <memory> namespace clang { namespace clangd { /// Wrapper for vfs::FileSystem for use in multithreaded programs like clangd. /// As FileSystem is not threadsafe, concurrent threads must each obtain one. /// Implementations may choose to depend on Context::current() e.g. to implement /// snapshot semantics. clangd will not create vfs::FileSystems for use in /// different contexts, so either ThreadsafeFS::view or the returned FS may /// contain this logic. class ThreadsafeFS { public: virtual ~ThreadsafeFS() = default; /// Obtain a vfs::FileSystem with an arbitrary initial working directory. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> view(llvm::NoneType CWD) const { return viewImpl(); } /// Obtain a vfs::FileSystem with a specified working directory. /// If the working directory can't be set (e.g. doesn't exist), logs and /// returns the FS anyway. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> view(PathRef CWD) const; private: /// Overridden by implementations to provide a vfs::FileSystem. /// This is distinct from view(NoneType) to avoid GCC's -Woverloaded-virtual. virtual llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const = 0; }; class RealThreadsafeFS : public ThreadsafeFS { private: llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override; }; } // namespace clangd } // namespace clang #endif
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y 5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ 4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
# created by tools/loadICU.tcl -- do not edit namespace eval ::tcl::clock { ::msgcat::mcset en_BW DATE_FORMAT "%d %B %Y" ::msgcat::mcset en_BW TIME_FORMAT_12 "%l:%M:%S %P" ::msgcat::mcset en_BW DATE_TIME_FORMAT "%d %B %Y %l:%M:%S %P %z" }
{ "pile_set_name": "Github" }
const p = require('../patterns.service.js') const y = require('yup') module.exports = y.object({ name: y .string() .required() .trim() .matches(p.isTitle, p.messages.isTitle), value: y.mixed().required() })
{ "pile_set_name": "Github" }
<?php namespace Concrete\Controller\SinglePage\Dashboard; use Concrete\Core\Page\Controller\DashboardPageController; class Extend extends DashboardPageController { public function view() { return $this->buildRedirectToFirstAccessibleChildPage(); } }
{ "pile_set_name": "Github" }
{ stdenv, fetchurl, fetchpatch, pkgconfig, gtk2, gettext, libxml2, intltool, libart_lgpl , libgnomecups, bison, flex }: stdenv.mkDerivation rec { name = "libgnomeprint-2.18.8"; src = fetchurl { url = "mirror://gnome/sources/libgnomeprint/2.18/${name}.tar.bz2"; sha256 = "1034ec8651051f84d2424e7a1da61c530422cc20ce5b2d9e107e1e46778d9691"; }; patches = [ ./bug653388.patch # Fix compatibility with bison 3 (fetchpatch { url = "https://github.com/pld-linux/libgnomeprint/raw/54c0f9c3675b86c53f6d77a5bc526ce9ef0e38cd/bison3.patch"; sha256 = "1sp04jbv34i1gcwf377hhmwdsmqzig70dd06rjz1isb6zwh4y01l"; }) ]; nativeBuildInputs = [ pkgconfig ]; buildInputs = [ gtk2 gettext intltool libart_lgpl libgnomecups bison flex ]; propagatedBuildInputs = [ libxml2 ]; meta = with stdenv.lib; { platforms = platforms.linux; }; }
{ "pile_set_name": "Github" }
# # This is a project Makefile. It is assumed the directory this Makefile resides in is a # project subdirectory. # PROJECT_NAME := lvgl_example #If IOT_SOLUTION_PATH is not defined, use relative path as default value IOT_SOLUTION_PATH ?= $(abspath $(shell pwd)/../../../) include $(IOT_SOLUTION_PATH)/Makefile include $(IDF_PATH)/make/project.mk
{ "pile_set_name": "Github" }
angular.module( 'ripplecharts.manage-currencies', [ 'ui.state', 'ui.bootstrap' ]) .config(function config( $stateProvider ) { $stateProvider.state( 'manage-currency', { url: '/manage-currency', views: { "main": { controller: 'ManageCurrenciesCtrl', templateUrl: 'manage-currencies/manage-currencies.tpl.html' } }, data:{ pageTitle: 'Manage Currencies' }, resolve : { gateInit : function (gateways) { return gateways.promise; } } }); }) .controller( 'ManageCurrenciesCtrl', function ManageCurrenciesCtrl( $scope, gateways) { var currencyWrapper, name; var currencies = gateways.getCurrencies('all'); var curr_col1 = d3.select('#curr_list .first_column'); var curr_col2 = d3.select('#curr_list .second_column'); var other_col = d3.select('#currencyList'); //load settings from session, local storage, options, or defaults $scope.base = store.session.get('base') || store.get('base') || Options.base || {currency:"XRP", issuer:""}; $scope.trade = store.session.get('trade') || store.get('trade') || Options.trade || {currency:"USD", issuer:"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"}; //Add standard currency boxes currencies.forEach(function(currency, i) { var checkbox; var self; if (!currency.custom && i <= currencies.length/2) { currencyWrapper = curr_col1.append('div').attr('class', 'currency strd'); } else if (!currency.custom){ currencyWrapper = curr_col2.append('div').attr('class', 'currency strd'); } else if (currency.custom) { currencyWrapper = other_col.append('div').attr('class', 'currency custom inputWrapper'); } checkbox = currencyWrapper.append('input').attr('type', 'checkbox').property('checked', currency.include) .on('change', function() { self = this; changeStatus(self, currency.currency); }); if (currency.currency === "XRP") checkbox.property('disabled', true); if (!currency.custom) currencyWrapper.append('img').attr('class', 'curr_symb').attr('src', currency.icon); currencyWrapper.append('text').text(currency.currency); if (currency.custom) currencyWrapper.append('a').attr('class', 'removeBtn').text('remove') .on('click', function() { removeCustom(d3.select(this.parentNode), currency.currency); checkLocal(currency.currency, 'base'); checkLocal(currency.currency, 'trade'); }); }); //Add custom currencies var addButton = d3.select('#btnAdd').on('click', function() { add(); }); var saved = d3.select('.saved'); function flashSaved() { saved.transition() .duration(500) .style('opacity', 1); saved.transition() .delay(1500) .duration(500) .style('opacity', 0); } $('#txtName').keypress(function(event) { if (event.keyCode == 13) { add(); } }); function add() { var addBox = d3.select('#txtName'); var newCurr = addBox.property('value').toUpperCase(); var description = d3.select('.description'); for (var i=0; i<currencies.length; i++) { if (currencies[i].currency === newCurr) { description.html('Currency already added.'); return; } } if (newCurr.length !== 3) { description.html('Please enter a valid currency code.'); } else { addCheckbox(newCurr); description.html('Please select or add a gateway in the <a href="#/manage-gateway">"Manage Gateways"</a> tab.'); flashSaved(); currencies = gateways.getCurrencies(true); } addBox.property('value', ''); } function changeStatus(self, currency) { var checked = !!d3.select(self).property('checked'); gateways.updateCurrency({ exclude : !checked, include : checked, currency : currency }); if (!checked) { checkLocal(currency, 'base'); checkLocal(currency, 'trade'); } flashSaved(); } //Add checkbox function addCheckbox (currency) { var container = d3.select('#currencyList'); var inputWrapper = container.append('div').attr('class', 'inputWrapper'); gateways.updateCurrency({ add : true, currency : currency }); inputWrapper.append('input') .attr('type', 'checkbox') .property('checked', true) .on('change', function() { changeStatus(this, currency); }); inputWrapper.append('label').text(currency); inputWrapper.append('a') .attr('class', 'removeBtn').text('remove') .on('click', function() { removeCustom(inputWrapper, currency); checkLocal(currency, 'base'); checkLocal(currency, 'trade'); }); flashSaved(); } function removeCustom(selection, currency) { selection.transition() .duration(300) .style('opacity', 0) .each('end', function(){ d3.select(this).remove(); }); gateways.updateCurrency({ remove : true, currency : currency }); flashSaved(); currencies = gateways.getCurrencies(true); } function checkLocal(currency, select) { if ($scope[select].currency === currency){ var clist = gateways.getCurrencies(); for(var j=0; j<clist.length; j++) { if (clist[j].include && clist[j].currency !== "XRP") { var list = gateways.getIssuers(clist[j].currency); for(var i=0; i<list.length; i++) { gateway = list[i]; if (gateway.include) { $scope[select] = {currency: clist[j].currency, issuer: gateway.account}; store.set(select, $scope[select]); store.session.set(select, $scope[select]); return; } } } } $scope[select] = {currency: 'XRP'}; store.set(select, $scope[select]); store.session.set(select, $scope[select]); } } });
{ "pile_set_name": "Github" }
import Vue from 'vue' import todo from './todo.vue' new Vue({ el: '#app', render: h => h(todo) })
{ "pile_set_name": "Github" }
/** * Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin which shows the Styles drop-down // list containing all styles in the editor toolbar. Other plugins, like // the "div" plugin, use a subset of the styles for their features. // // If you do not have plugins that depend on this file in your editor build, you can simply // ignore it. Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. // // For more information refer to: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_styles.html#style-rules CKEDITOR.stylesSet.add( 'default', [ /* Block styles */ // These styles are already available in the "Format" drop-down list ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles drop-down list, removing them from the toolbar. // (This requires the "stylescombo" plugin.) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object styles */ { name: 'Styled Image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled Image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact Table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }, /* Widget styles */ { name: 'Clean Image', type: 'widget', widget: 'image', attributes: { 'class': 'image-clean' } }, { name: 'Grayscale Image', type: 'widget', widget: 'image', attributes: { 'class': 'image-grayscale' } }, { name: 'Featured Snippet', type: 'widget', widget: 'codeSnippet', attributes: { 'class': 'code-featured' } }, { name: 'Featured Formula', type: 'widget', widget: 'mathjax', attributes: { 'class': 'math-featured' } }, { name: '240p', type: 'widget', widget: 'embedSemantic', attributes: { 'class': 'embed-240p' }, group: 'size' }, { name: '360p', type: 'widget', widget: 'embedSemantic', attributes: { 'class': 'embed-360p' }, group: 'size' }, { name: '480p', type: 'widget', widget: 'embedSemantic', attributes: { 'class': 'embed-480p' }, group: 'size' }, { name: '720p', type: 'widget', widget: 'embedSemantic', attributes: { 'class': 'embed-720p' }, group: 'size' }, { name: '1080p', type: 'widget', widget: 'embedSemantic', attributes: { 'class': 'embed-1080p' }, group: 'size' }, // Adding space after the style name is an intended workaround. For now, there // is no option to create two styles with the same name for different widget types. See https://dev.ckeditor.com/ticket/16664. { name: '240p ', type: 'widget', widget: 'embed', attributes: { 'class': 'embed-240p' }, group: 'size' }, { name: '360p ', type: 'widget', widget: 'embed', attributes: { 'class': 'embed-360p' }, group: 'size' }, { name: '480p ', type: 'widget', widget: 'embed', attributes: { 'class': 'embed-480p' }, group: 'size' }, { name: '720p ', type: 'widget', widget: 'embed', attributes: { 'class': 'embed-720p' }, group: 'size' }, { name: '1080p ', type: 'widget', widget: 'embed', attributes: { 'class': 'embed-1080p' }, group: 'size' } ] );
{ "pile_set_name": "Github" }
/* * Copyright 2019 New Vector Ltd * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.api.pushrules.rest import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * All push rulesets for a user. * Ref: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushrules */ @JsonClass(generateAdapter = true) internal data class GetPushRulesResponse( /** * Global rules, account level applying to all devices */ @Json(name = "global") val global: RuleSet, /** * Device specific rules, apply only to current device */ @Json(name = "device") val device: RuleSet? = null )
{ "pile_set_name": "Github" }
using Castle.DynamicProxy; using System; namespace ChangeTracking { internal class ChangeTrackingInterceptorSelector : IInterceptorSelector { IInterceptor[] IInterceptorSelector.SelectInterceptors(Type type, System.Reflection.MethodInfo method, IInterceptor[] interceptors) => interceptors; } }
{ "pile_set_name": "Github" }
=============== listCollections =============== .. default-domain:: mongodb .. contents:: On this page :local: :backlinks: none :depth: 1 :class: singlecol Definition ---------- .. dbcommand:: listCollections Retrieve information, i.e. the name and options, about the collections and :doc:`views </core/views>` in a database. Specifically, the command returns a document that contains information with which to create a cursor to the collection information. The :binary:`~bin.mongo` shell provides the :method:`db.getCollectionInfos()` and the :method:`db.getCollectionNames()` helper methods. The command has the following form: .. code-block:: javascript { listCollections: 1, filter: <document>, nameOnly: <boolean>, authorizedCollections: <boolean>, comment: <any> } The :dbcommand:`listCollections` command can take the following optional field: .. list-table:: :header-rows: 1 :widths: 20 20 80 * - Field - Type - Description * - ``filter`` - document - Optional. A query expression to filter the list of collections. You can specify a query expression on any of the :ref:`fields returned <list-collection-output>` by :samp:`listCollections`. * - ``nameOnly`` - boolean - Optional. A flag to indicate whether the command should return just the collection/view names and type or return both the name and other information. Returning just the name and type (``view`` or ``collection``) does not take collection-level locks whereas returning full collection information locks each collection in the database. The default value is ``false``. .. note:: When ``nameOnly`` is ``true``, your ``filter`` expression can only filter based on a collection's name and type. No other fields are available. .. versionadded:: 4.0 * - ``authorizedCollections`` - boolean - Optional. A flag, when set to ``true`` and used with ``nameOnly: true``, that allows a user without the required privilege (i.e. :authaction:`listCollections` action on the database) to run the command when access control is enforced. When both ``authorizedCollections`` and ``nameOnly`` options are set to true, the command returns only those collections for which the user has privileges. For example, if a user has :authaction:`find` action on specific collections, the command returns only those collections; or, if a user has :authaction:`find` or any other action, on the database resource, the command lists all collections in the database. The default value is ``false``. That is, the user must have :authaction:`listCollections` action on the database to run the command. For a user who has :authaction:`listCollections` action on the database, this option has no effect since the user has privileges to list the collections in the database. When used without ``nameOnly: true``, this option has no effect. That is, the user must have the required privileges to run the command when access control is enforced. Otherwise, the user is unauthorized to run the command. .. versionadded:: 4.0 * - ``comment`` - any - .. include:: /includes/extracts/comment-content.rst .. versionadded:: 4.4 .. _listCollections-behavior: Behavior -------- Filter ~~~~~~ Use a filter to limit the results of :dbcommand:`listCollections`. You can specify a ``filter`` on any of the :ref:`fields returned <list-collection-output>` in the :dbcommand:`listCollections` result set. Locks ~~~~~ .. versionchanged:: 4.0 The :dbcommand:`listCollection` command takes Intent Shared lock on the database. In previous versions, the command takes Shared lock on the database. Unless the ``nameOnly`` option is specified, the command also takes an Intent Shared lock on each of the collections in turn while holding the Intent Shared lock on the database. Client Disconnection ~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/extracts/4.2-changes-disconnect.rst .. |operation| replace:: :dbcommand:`listCollections` Replica Set Member State Restriction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/extracts/4.4-changes-repl-state-restrictions-operation.rst .. |operations| replace:: :dbcommand:`listCollections` Required Access --------------- .. include:: /includes/extracts/listCollections-auth-required-access.rst ``show collections`` ~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/extracts/listCollections-auth-show-collections.rst Earlier MongoDB Versions ~~~~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/extracts/listCollections-auth-show-collections-earlier-versions.rst .. _list-collection-output: Output ------ .. data:: listCollections.cursor A document that contains information with which to create a cursor to documents that contain collection names and options. The cursor information includes the cursor id, the full namespace for the command, as well as the first batch of results. Each document in the batch output contains the following fields: .. list-table:: :header-rows: 1 :widths: 15 15 30 * - Field - Type - Description * - name - String - Name of the collection. * - type - String - Type of data store. Returns ``collection`` for :manual:`collections </core/databases-and-collections/#collections>` and ``view`` for :manual:`views </core/views/>`. * - options - Document - Collection options. These options correspond directly to the options available in :method:`db.createCollection()`. For the descriptions on the options, see :method:`db.createCollection()`. * - info - Document - Lists the following fields related to the collection: readOnly ``boolean``. If ``true`` the data store is read only. uuid :abbr:`UUID (Universally unique identifier)`. Once established, the collection UUID does not change. The collection UUID remains the same across replica set members and shards in a sharded cluster. .. versionadded:: 3.6 * - idIndex - Document - Provides information on the ``_id`` index for the collection. .. data:: listCollections.ok The return value for the command. A value of ``1`` indicates success. Example ------- List All Collections ~~~~~~~~~~~~~~~~~~~~ The following example uses the :method:`db.getCollectionInfos()` helper to return information for all collections in the ``records`` database: .. code-block:: javascript use records db.getCollectionInfos(); .. seealso:: :method:`db.getCollectionInfos()`
{ "pile_set_name": "Github" }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageService.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Services { using System; using System.Threading.Tasks; using IoC; #if ANDROID using Android.App; #elif IOS #elif NETFX_CORE using global::Windows.UI.Popups; #else using System.Windows; using Windows; #endif /// <summary> /// Message service that implements the <see cref="IMessageService"/>. /// </summary> public partial class MessageService : ViewModelServiceBase, IMessageService { private readonly IDispatcherService _dispatcherService; private readonly ILanguageService _languageService; /// <summary> /// Initializes a new instance of the <see cref="MessageService"/> class. /// </summary> /// <param name="dispatcherService">The dispatcher service.</param> /// <param name="languageService">The language service.</param> /// <exception cref="ArgumentNullException">The <paramref name="dispatcherService"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="languageService"/> is <c>null</c>.</exception> public MessageService(IDispatcherService dispatcherService, ILanguageService languageService) { Argument.IsNotNull("dispatcherService", dispatcherService); Argument.IsNotNull("languageService", languageService); _dispatcherService = dispatcherService; _languageService = languageService; Initialize(); } #region Methods /// <summary> /// /// </summary> partial void Initialize(); #if !XAMARIN && !XAMARIN_FORMS /// <summary> /// Translates the message box result. /// </summary> /// <param name="result">The result.</param> /// <returns> /// Corresponding <see cref="MessageResult"/>. /// </returns> protected static MessageResult TranslateMessageBoxResult(MessageBoxResult result) { return Enum<MessageResult>.ConvertFromOtherEnumValue(result); } /// <summary> /// Translates the message button. /// </summary> /// <param name="button">The button.</param> /// <returns> /// Corresponding <see cref="MessageBoxButton"/>. /// </returns> protected static MessageBoxButton TranslateMessageButton(MessageButton button) { try { return Enum<MessageBoxButton>.ConvertFromOtherEnumValue(button); } catch (Exception) { throw new NotSupportedInPlatformException($"MessageBox class does not support MessageButton '{Enum<MessageButton>.ToString(button)}'"); } } #endif #endregion #region IMessageService Members /// <summary> /// Shows an error message to the user and allows a callback operation when the message is completed. /// </summary> /// <param name="exception">The exception.</param> /// <exception cref="ArgumentNullException">The <paramref name="exception"/> is <c>null</c>.</exception> public virtual Task<MessageResult> ShowErrorAsync(Exception exception) { Argument.IsNotNull("exception", exception); return ShowErrorAsync(exception.Message, string.Empty); } /// <summary> /// Shows an error message to the user and allows a callback operation when the message is completed. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> public virtual Task<MessageResult> ShowErrorAsync(string message, string caption = "") { if (string.IsNullOrEmpty(caption)) { caption = Catel.ResourceHelper.GetString("ErrorTitle"); } const MessageButton button = MessageButton.OK; const MessageImage icon = MessageImage.Error; return ShowAsync(message, caption, button, icon); } /// <summary> /// Shows a warning message to the user and allows a callback operation when the message is completed. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> public virtual Task<MessageResult> ShowWarningAsync(string message, string caption = "") { if (string.IsNullOrEmpty(caption)) { caption = Catel.ResourceHelper.GetString("WarningTitle"); } const MessageButton button = MessageButton.OK; const MessageImage icon = MessageImage.Warning; return ShowAsync(message, caption, button, icon); } /// <summary> /// Shows an information message to the user and allows a callback operation when the message is completed. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> public virtual Task<MessageResult> ShowInformationAsync(string message, string caption = "") { if (string.IsNullOrEmpty(caption)) { caption = Catel.ResourceHelper.GetString("InfoTitle"); } const MessageButton button = MessageButton.OK; const MessageImage icon = MessageImage.Information; return ShowAsync(message, caption, button, icon); } /// <summary> /// Shows an information message to the user and allows a callback operation when the message is completed. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <param name="button">The button.</param> /// <param name="icon">The icon.</param> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> public virtual Task<MessageResult> ShowAsync(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None) { return ShowMessageBoxAsync(message, caption, button, icon); } #endregion } }
{ "pile_set_name": "Github" }
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserResponse do @moduledoc """ Response message for cancelling an unfinished user account wipe. ## Attributes * `deviceUser` (*type:* `GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser.t`, *default:* `nil`) - Resultant DeviceUser object for the action. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :deviceUser => GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser.t() } field(:deviceUser, as: GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser ) end defimpl Poison.Decoder, for: GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserResponse do def decode(value, options) do GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
{ "pile_set_name": "Github" }
import Foundation extension Array where Element == Double { func average() -> Double { reduce(0, +) / Double(count) } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/sodium-battle.iml" filepath="$PROJECT_DIR$/sodium-battle.iml" /> </modules> </component> </project>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015-2020 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Driver_CAN.h" #define ARM_CAN_DRV_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(1,0) // CAN driver version // Driver Version static const ARM_DRIVER_VERSION can_driver_version = { ARM_CAN_API_VERSION, ARM_CAN_DRV_VERSION }; // Driver Capabilities static const ARM_CAN_CAPABILITIES can_driver_capabilities = { 32U, // Number of CAN Objects available 0U, // Does not support reentrant calls to ARM_CAN_MessageSend, ARM_CAN_MessageRead, ARM_CAN_ObjectConfigure and abort message sending used by ARM_CAN_Control. 0U, // Does not support CAN with Flexible Data-rate mode (CAN_FD) 0U, // Does not support restricted operation mode 0U, // Does not support bus monitoring mode 0U, // Does not support internal loopback mode 0U, // Does not support external loopback mode 0U // Reserved (must be zero) }; // Object Capabilities static const ARM_CAN_OBJ_CAPABILITIES can_object_capabilities = { 1U, // Object supports transmission 1U, // Object supports reception 0U, // Object does not support RTR reception and automatic Data transmission 0U, // Object does not support RTR transmission and automatic Data reception 0U, // Object does not allow assignment of multiple filters to it 0U, // Object does not support exact identifier filtering 0U, // Object does not support range identifier filtering 0U, // Object does not support mask identifier filtering 0U, // Object can not buffer messages 0U // Reserved (must be zero) }; static uint8_t can_driver_powered = 0U; static uint8_t can_driver_initialized = 0U; static ARM_CAN_SignalUnitEvent_t CAN_SignalUnitEvent = NULL; static ARM_CAN_SignalObjectEvent_t CAN_SignalObjectEvent = NULL; // // Functions // static ARM_DRIVER_VERSION ARM_CAN_GetVersion (void) { // Return driver version return can_driver_version; } static ARM_CAN_CAPABILITIES ARM_CAN_GetCapabilities (void) { // Return driver capabilities return can_driver_capabilities; } static int32_t ARM_CAN_Initialize (ARM_CAN_SignalUnitEvent_t cb_unit_event, ARM_CAN_SignalObjectEvent_t cb_object_event) { if (can_driver_initialized != 0U) { return ARM_DRIVER_OK; } CAN_SignalUnitEvent = cb_unit_event; CAN_SignalObjectEvent = cb_object_event; // Add code for pin, memory, RTX objects initialization // .. can_driver_initialized = 1U; return ARM_DRIVER_OK; } static int32_t ARM_CAN_Uninitialize (void) { // Add code for pin, memory, RTX objects de-initialization // .. can_driver_initialized = 0U; return ARM_DRIVER_OK; } static int32_t ARM_CAN_PowerControl (ARM_POWER_STATE state) { switch (state) { case ARM_POWER_OFF: can_driver_powered = 0U; // Add code to disable interrupts and put peripheral into reset mode, // and if possible disable clock // .. break; case ARM_POWER_FULL: if (can_driver_initialized == 0U) { return ARM_DRIVER_ERROR; } if (can_driver_powered != 0U) { return ARM_DRIVER_OK; } // Add code to enable clocks, reset variables enable interrupts // and put peripheral into operational // .. can_driver_powered = 1U; break; case ARM_POWER_LOW: return ARM_DRIVER_ERROR_UNSUPPORTED; } return ARM_DRIVER_OK; } static uint32_t ARM_CAN_GetClock (void) { // Add code to return peripheral clock frequency // .. } static int32_t ARM_CAN_SetBitrate (ARM_CAN_BITRATE_SELECT select, uint32_t bitrate, uint32_t bit_segments) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } // Add code to setup peripheral parameters to generate specified bitrate // with specified bit segments // .. return ARM_DRIVER_OK; } static int32_t ARM_CAN_SetMode (ARM_CAN_MODE mode) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } switch (mode) { case ARM_CAN_MODE_INITIALIZATION: // Add code to put peripheral into initialization mode // .. break; case ARM_CAN_MODE_NORMAL: // Add code to put peripheral into normal operation mode // .. break; case ARM_CAN_MODE_RESTRICTED: // Add code to put peripheral into restricted operation mode // .. break; case ARM_CAN_MODE_MONITOR: // Add code to put peripheral into bus monitoring mode // .. break; case ARM_CAN_MODE_LOOPBACK_INTERNAL: // Add code to put peripheral into internal loopback mode // .. break; case ARM_CAN_MODE_LOOPBACK_EXTERNAL: // Add code to put peripheral into external loopback mode // .. break; } return ARM_DRIVER_OK; } static ARM_CAN_OBJ_CAPABILITIES ARM_CAN_ObjectGetCapabilities (uint32_t obj_idx) { // Return object capabilities return can_object_capabilities; } static int32_t ARM_CAN_ObjectSetFilter (uint32_t obj_idx, ARM_CAN_FILTER_OPERATION operation, uint32_t id, uint32_t arg) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } switch (operation) { case ARM_CAN_FILTER_ID_EXACT_ADD: // Add code to setup peripheral to receive messages with specified exact ID break; case ARM_CAN_FILTER_ID_MASKABLE_ADD: // Add code to setup peripheral to receive messages with specified maskable ID break; case ARM_CAN_FILTER_ID_RANGE_ADD: // Add code to setup peripheral to receive messages within specified range of IDs break; case ARM_CAN_FILTER_ID_EXACT_REMOVE: // Add code to remove specified exact ID from being received by peripheral break; case ARM_CAN_FILTER_ID_MASKABLE_REMOVE: // Add code to remove specified maskable ID from being received by peripheral break; case ARM_CAN_FILTER_ID_RANGE_REMOVE: // Add code to remove specified range of IDs from being received by peripheral break; } return ARM_DRIVER_OK; } static int32_t ARM_CAN_ObjectConfigure (uint32_t obj_idx, ARM_CAN_OBJ_CONFIG obj_cfg) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } switch (obj_cfg) { case ARM_CAN_OBJ_INACTIVE: // Deactivate object // .. break; case ARM_CAN_OBJ_RX_RTR_TX_DATA: // Setup object to automatically return data when RTR with it's ID is received // .. break; case ARM_CAN_OBJ_TX_RTR_RX_DATA: // Setup object to send RTR and receive data response // .. break; case ARM_CAN_OBJ_TX: // Setup object to be used for sending messages // .. break; case ARM_CAN_OBJ_RX: // Setup object to be used for receiving messages // .. break; } return ARM_DRIVER_OK; } static int32_t ARM_CAN_MessageSend (uint32_t obj_idx, ARM_CAN_MSG_INFO *msg_info, const uint8_t *data, uint8_t size) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } // Add code to send requested message // .. return ((int32_t)size); } static int32_t ARM_CAN_MessageRead (uint32_t obj_idx, ARM_CAN_MSG_INFO *msg_info, uint8_t *data, uint8_t size) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } // Add code to read previously received message // (reception was started when object was configured for reception) // .. return ((int32_t)size); } static int32_t ARM_CAN_Control (uint32_t control, uint32_t arg) { if (can_driver_powered == 0U) { return ARM_DRIVER_ERROR; } switch (control & ARM_CAN_CONTROL_Msk) { case ARM_CAN_ABORT_MESSAGE_SEND: // Add code to abort message pending to be sent // .. break; case ARM_CAN_SET_FD_MODE: // Add code to enable Flexible Data-rate mode // .. break; case ARM_CAN_SET_TRANSCEIVER_DELAY: // Add code to set transceiver delay // .. break; default: // Handle unknown control code return ARM_DRIVER_ERROR_UNSUPPORTED; } return ARM_DRIVER_OK; } static ARM_CAN_STATUS ARM_CAN_GetStatus (void) { // Add code to return device bus and error status // .. } // IRQ handlers // Add interrupt routines to handle transmission, reception, error and status interrupts // .. // CAN driver functions structure extern \ ARM_DRIVER_CAN Driver_CAN0; ARM_DRIVER_CAN Driver_CAN0 = { ARM_CAN_GetVersion, ARM_CAN_GetCapabilities, ARM_CAN_Initialize, ARM_CAN_Uninitialize, ARM_CAN_PowerControl, ARM_CAN_GetClock, ARM_CAN_SetBitrate, ARM_CAN_SetMode, ARM_CAN_ObjectGetCapabilities, ARM_CAN_ObjectSetFilter, ARM_CAN_ObjectConfigure, ARM_CAN_MessageSend, ARM_CAN_MessageRead, ARM_CAN_Control, ARM_CAN_GetStatus };
{ "pile_set_name": "Github" }
# This Makefile compiles a library containing the C++ runtime for the TensorFlow # library. It's designed for use on platforms with limited resources where # running a full Bazel build would be prohibitive, or for cross-compilation onto # embedded systems. It includes only a bare-bones set of functionality. # # The default setup below is aimed at Unix-like devices, and should work on # modern Linux and OS X distributions without changes. # # If you have another platform, you'll need to take a careful look at the # compiler flags and folders defined below. They're separated into two sections, # the first for the host (the machine you're compiling on) and the second for # the target (the machine you want the program to run on). # Host compilation settings # Find where we're running from, so we can store generated files here. MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) HAS_GEN_HOST_PROTOC := \ $(shell test -f $(MAKEFILE_DIR)/gen/protobuf-host/bin/protoc && echo "true" ||\ echo "false") # Hexagon integration ifdef HEXAGON_LIBS LIBGEMM_WRAPPER := $(HEXAGON_LIBS)/libgemm_wrapper.so ifeq ($(shell test -f $(LIBGEMM_WRAPPER) 2> /dev/null; echo $$?), 0) $(info "Use hexagon libs at " $(LIBGEMM_WRAPPER)) else $(error "hexagon libs not found at " $(LIBGEMM_WRAPPER)) endif ifdef HEXAGON_INCLUDE ifeq ($(shell test -d $(HEXAGON_INCLUDE) 2> /dev/null; echo $$?), 0) $(info "Use hexagon libs at " $(HEXAGON_INCLUDE)) else $(error "hexagon libs not found at " $(HEXAGON_INCLUDE)) endif else $(error "HEXAGON_INCLUDE is not set.") endif ifneq ($(TARGET),ANDROID) $(error "hexagon is only supported on Android") endif endif # HEXAGON_LIBS # Try to figure out the host system HOST_OS := ifeq ($(OS),Windows_NT) HOST_OS = WINDOWS else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Linux) HOST_OS := LINUX endif ifeq ($(UNAME_S),Darwin) HOST_OS := OSX endif endif # Where compiled objects are stored. HOST_OBJDIR := $(MAKEFILE_DIR)/gen/host_obj/ HOST_BINDIR := $(MAKEFILE_DIR)/gen/host_bin/ HOST_GENDIR := $(MAKEFILE_DIR)/gen/host_obj/ # Settings for the host compiler. HOST_CXX := $(CC_PREFIX) gcc HOST_CXXFLAGS := --std=c++11 HOST_LDOPTS := ifeq ($(HAS_GEN_HOST_PROTOC),true) HOST_LDOPTS += -L$(MAKEFILE_DIR)/gen/protobuf-host/lib endif HOST_LDOPTS += -L/usr/local/lib HOST_INCLUDES := \ -I. \ -I$(MAKEFILE_DIR)/downloads/ \ -I$(MAKEFILE_DIR)/downloads/eigen \ -I$(MAKEFILE_DIR)/downloads/gemmlowp \ -I$(HOST_GENDIR) ifeq ($(HAS_GEN_HOST_PROTOC),true) HOST_INCLUDES += -I$(MAKEFILE_DIR)/gen/protobuf-host/include endif # This is at the end so any globally-installed frameworks like protobuf don't # override local versions in the source tree. HOST_INCLUDES += -I/usr/local/include HOST_LIBS := \ -lstdc++ \ -lprotobuf \ -lpthread \ -lm \ -lz # If we're on Linux, also link in the dl library. ifeq ($(HOST_OS),LINUX) HOST_LIBS += -ldl -lpthread endif # If we're on a Pi, link in pthreads and dl ifeq ($(HOST_OS),PI) HOST_LIBS += -ldl -lpthread endif # proto_text is a tool that converts protobufs into a form we can use more # compactly within TensorFlow. It's a bit like protoc, but is designed to # produce a much more minimal result so we can save binary space. # We have to build it on the host system first so that we can create files # that are needed for the runtime building. PROTO_TEXT := $(HOST_BINDIR)proto_text # The list of dependencies is derived from the Bazel build file by running # the gen_file_lists.sh script on a system with a working Bazel setup. PROTO_TEXT_CC_FILES := $(shell cat $(MAKEFILE_DIR)/proto_text_cc_files.txt) PROTO_TEXT_PB_CC_LIST := $(shell cat $(MAKEFILE_DIR)/proto_text_pb_cc_files.txt) PROTO_TEXT_PB_H_LIST := $(shell cat $(MAKEFILE_DIR)/proto_text_pb_h_files.txt) # Locations of the intermediate files proto_text generates. PROTO_TEXT_PB_H_FILES := $(addprefix $(HOST_GENDIR), $(PROTO_TEXT_PB_H_LIST)) PROTO_TEXT_CC_OBJS := $(addprefix $(HOST_OBJDIR), $(PROTO_TEXT_CC_FILES:.cc=.o)) PROTO_TEXT_PB_OBJS := $(addprefix $(HOST_OBJDIR), $(PROTO_TEXT_PB_CC_LIST:.cc=.o)) PROTO_TEXT_OBJS := $(PROTO_TEXT_CC_OBJS) $(PROTO_TEXT_PB_OBJS) # Target device settings. # Default to running on the same system we're compiling on. # You should override TARGET on the command line if you're cross-compiling, e.g. # make -f tensorflow/contrib/makefile/Makefile TARGET=ANDROID TARGET := $(HOST_OS) # Where compiled objects are stored. GENDIR := $(MAKEFILE_DIR)/gen/ OBJDIR := $(GENDIR)obj/ LIBDIR := $(GENDIR)lib/ BINDIR := $(GENDIR)bin/ PBTGENDIR := $(GENDIR)proto_text/ PROTOGENDIR := $(GENDIR)proto/ DEPDIR := $(GENDIR)dep/ $(shell mkdir -p $(DEPDIR) >/dev/null) # Settings for the target compiler. CXX := $(CC_PREFIX) gcc OPTFLAGS := -O2 CXXFLAGS := --std=c++11 -DIS_SLIM_BUILD -fno-exceptions -DNDEBUG $(OPTFLAGS) LDFLAGS := \ -L/usr/local/lib DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td INCLUDES := \ -I. \ -I$(MAKEFILE_DIR)/downloads/ \ -I$(MAKEFILE_DIR)/downloads/eigen \ -I$(MAKEFILE_DIR)/downloads/gemmlowp \ -I$(PROTOGENDIR) \ -I$(PBTGENDIR) ifeq ($(HAS_GEN_HOST_PROTOC),true) INCLUDES += -I$(MAKEFILE_DIR)/gen/protobuf-host/include endif # This is at the end so any globally-installed frameworks like protobuf don't # override local versions in the source tree. INCLUDES += -I/usr/local/include LIBS := \ -lstdc++ \ -lprotobuf \ -lz \ -lm ifeq ($(HAS_GEN_HOST_PROTOC),true) PROTOC := $(MAKEFILE_DIR)/gen/protobuf-host/bin/protoc else PROTOC := protoc endif $(info PROTOC = "$(PROTOC)") $(info CC_PREFIX = "$(CC_PREFIX)") PROTOCFLAGS := AR := ar ARFLAGS := -r LIBFLAGS := # If we're on OS X, make sure that globals aren't stripped out. ifeq ($(TARGET),OSX) LDFLAGS += -all_load endif # Make sure that we don't strip global constructors on Linux. ifeq ($(TARGET),LINUX) ifeq ($(HAS_GEN_HOST_PROTOC),true) LIBFLAGS += -L$(MAKEFILE_DIR)/gen/protobuf-host/lib export LD_LIBRARY_PATH=$(MAKEFILE_DIR)/gen/protobuf-host/lib endif CXXFLAGS += -fPIC LIBFLAGS += -Wl,--allow-multiple-definition -Wl,--whole-archive LDFLAGS := -Wl,--no-whole-archive endif # If we're on Linux, also link in the dl library. ifeq ($(TARGET),LINUX) LIBS += -ldl -lpthread endif # If we're cross-compiling for the Raspberry Pi, use the right gcc. ifeq ($(TARGET),PI) CXXFLAGS += -D__ANDROID_TYPES_SLIM__ LDFLAGS := -Wl,--no-whole-archive LIBS += -ldl -lpthread LIBFLAGS += -Wl,--allow-multiple-definition -Wl,--whole-archive endif # Set up Android building ifeq ($(TARGET),ANDROID) # Override NDK_ROOT on the command line with your own NDK location, e.g. # make -f tensorflow/contrib/makefile/Makefile TARGET=ANDROID \ # NDK_ROOT=/path/to/your/ndk # You need to have an Android version of the protobuf libraries compiled to link # in. The compile_android_protobuf.sh script may help. # TODO(satok): Support all CPU architectures (Currently only armv7 is supported) OS_PATH := ifeq ($(HOST_OS),LINUX) OS_PATH=linux endif ifeq ($(HOST_OS),OSX) OS_PATH=darwin endif ifeq ($(HOST_OS),WINDOWS) $(error "windows is not supported.") endif ifndef NDK_ROOT $(error "NDK_ROOT is not defined.") endif CXX := $(CC_PREFIX) $(NDK_ROOT)/toolchains/arm-linux-androideabi-4.9/prebuilt/$(OS_PATH)-x86_64/bin/arm-linux-androideabi-g++ CXXFLAGS +=\ --sysroot $(NDK_ROOT)/platforms/android-21/arch-arm \ -Wno-narrowing \ -march=armv7-a \ -mfloat-abi=softfp \ -mfpu=neon \ -fPIE INCLUDES = \ -I$(NDK_ROOT)/sources/android/support/include \ -I$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.9/include \ -I$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/include \ -I. \ -I$(MAKEFILE_DIR)/downloads/ \ -I$(MAKEFILE_DIR)/downloads/eigen \ -I$(MAKEFILE_DIR)/downloads/gemmlowp \ -I$(MAKEFILE_DIR)/gen/protobuf/include \ -I$(PROTOGENDIR) \ -I$(PBTGENDIR) LIBS := \ -lgnustl_static \ -lprotobuf \ -llog \ -lz \ -lm LD := $(NDK_ROOT)/toolchains/arm-linux-androideabi-4.9/prebuilt/$(OS_PATH)-x86_64/arm-linux-androideabi/bin/ld LDFLAGS := \ -march=armv7-a \ -L$(MAKEFILE_DIR)/gen/protobuf/lib \ -L$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a \ -fPIE \ -pie \ -v AR := $(NDK_ROOT)/toolchains/arm-linux-androideabi-4.9/prebuilt/$(OS_PATH)-x86_64/bin/arm-linux-androideabi-ar ARFLAGS := r LIBFLAGS += -Wl,--allow-multiple-definition -Wl,--whole-archive ifdef HEXAGON_LIBS INCLUDES += -I$(HEXAGON_INCLUDE) LIBS += -lgemm_wrapper LDFLAGS += -L$(HEXAGON_LIBS) CXXFLAGS += -DUSE_HEXAGON_LIBS endif endif # ANDROID # Settings for iOS. ifeq ($(TARGET),IOS) IPHONEOS_PLATFORM := $(shell xcrun --sdk iphoneos --show-sdk-platform-path) IPHONEOS_SYSROOT := $(shell xcrun --sdk iphoneos --show-sdk-path) IPHONESIMULATOR_PLATFORM := $(shell xcrun --sdk iphonesimulator \ --show-sdk-platform-path) IPHONESIMULATOR_SYSROOT := $(shell xcrun --sdk iphonesimulator \ --show-sdk-path) IOS_SDK_VERSION := $(shell xcrun --sdk iphoneos --show-sdk-version) MIN_SDK_VERSION := 8.2 # Override IOS_ARCH with ARMV7, ARMV7S, ARM64, or I386. IOS_ARCH := X86_64 ifeq ($(IOS_ARCH),ARMV7) CXXFLAGS += -miphoneos-version-min=$(MIN_SDK_VERSION) \ -arch armv7 \ -D__thread= \ -DUSE_GEMM_FOR_CONV \ -Wno-c++11-narrowing \ -mno-thumb \ -DTF_LEAN_BINARY \ -D__ANDROID_TYPES_SLIM__ \ -fno-exceptions \ -isysroot \ ${IPHONEOS_SYSROOT} LDFLAGS := -arch armv7 \ -miphoneos-version-min=${MIN_SDK_VERSION} \ -framework Accelerate \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -all_load \ -L$(GENDIR)protobuf_ios/lib \ -lz endif ifeq ($(IOS_ARCH),ARMV7S) CXXFLAGS += -miphoneos-version-min=$(MIN_SDK_VERSION) \ -arch armv7s \ -D__thread= \ -DUSE_GEMM_FOR_CONV \ -Wno-c++11-narrowing \ -mno-thumb \ -DTF_LEAN_BINARY \ -D__ANDROID_TYPES_SLIM__ \ -fno-exceptions \ -isysroot \ ${IPHONEOS_SYSROOT} LDFLAGS := -arch armv7s \ -miphoneos-version-min=${MIN_SDK_VERSION} \ -framework Accelerate \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -all_load \ -L$(GENDIR)protobuf_ios/lib \ -lz endif ifeq ($(IOS_ARCH),ARM64) CXXFLAGS += -miphoneos-version-min=$(MIN_SDK_VERSION) \ -arch arm64 \ -D__thread= \ -DUSE_GEMM_FOR_CONV \ -Wno-c++11-narrowing \ -DTF_LEAN_BINARY \ -D__ANDROID_TYPES_SLIM__ \ -fno-exceptions \ -isysroot \ ${IPHONEOS_SYSROOT} LDFLAGS := -arch arm64 \ -miphoneos-version-min=${MIN_SDK_VERSION} \ -framework Accelerate \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -all_load \ -L$(GENDIR)protobuf_ios/lib \ -lz endif ifeq ($(IOS_ARCH),I386) CXXFLAGS += -mios-simulator-version-min=$(MIN_SDK_VERSION) \ -arch i386 \ -D__thread= \ -DUSE_GEMM_FOR_CONV \ -Wno-c++11-narrowing \ -DTF_LEAN_BINARY \ -D__ANDROID_TYPES_SLIM__ \ -fno-exceptions \ -isysroot \ ${IPHONESIMULATOR_SYSROOT} LDFLAGS := -arch i386 \ -mios-simulator-version-min=${MIN_SDK_VERSION} \ -framework Accelerate \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -all_load \ -L$(GENDIR)protobuf_ios/lib \ -lz endif ifeq ($(IOS_ARCH),X86_64) CXXFLAGS += -mios-simulator-version-min=$(MIN_SDK_VERSION) \ -arch x86_64 \ -D__thread= \ -DUSE_GEMM_FOR_CONV \ -Wno-c++11-narrowing \ -DTF_LEAN_BINARY \ -D__ANDROID_TYPES_SLIM__ \ -fno-exceptions \ -isysroot \ ${IPHONESIMULATOR_SYSROOT} LDFLAGS := -arch x86_64 \ -mios-simulator-version-min=${MIN_SDK_VERSION} \ -framework Accelerate \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -all_load \ -L$(GENDIR)protobuf_ios/lib \ -lz endif OBJDIR := $(OBJDIR)ios_$(IOS_ARCH)/ LIBDIR := $(LIBDIR)ios_$(IOS_ARCH)/ BINDIR := $(BINDIR)ios_$(IOS_ARCH)/ DEPDIR := $(DEPDIR)ios_$(IOS_ARCH)/ endif # This library is the main target for this makefile. It will contain a minimal # runtime that can be linked in to other programs. LIB_NAME := libtensorflow-core.a LIB_PATH := $(LIBDIR)$(LIB_NAME) # A small example program that shows how to link against the library. BENCHMARK_NAME := $(BINDIR)benchmark # What sources we want to compile, derived from the main Bazel build using the # gen_file_lists.sh script. CORE_CC_ALL_SRCS := \ $(wildcard tensorflow/core/*.cc) \ $(wildcard tensorflow/core/common_runtime/*.cc) \ $(wildcard tensorflow/core/debug/*.cc) \ $(wildcard tensorflow/core/framework/*.cc) \ $(wildcard tensorflow/core/graph/*.cc) \ $(wildcard tensorflow/core/lib/*/*.cc) \ $(wildcard tensorflow/core/platform/*.cc) \ $(wildcard tensorflow/core/platform/*/*.cc) \ $(wildcard tensorflow/core/platform/*/*/*.cc) \ $(wildcard tensorflow/core/util/*.cc) \ $(wildcard tensorflow/core/util/*/*.cc) \ tensorflow/core/util/version_info.cc # Remove duplicates (for version_info.cc) CORE_CC_ALL_SRCS := $(sort $(CORE_CC_ALL_SRCS)) CORE_CC_EXCLUDE_SRCS := \ $(wildcard tensorflow/core/*/*test.cc) \ $(wildcard tensorflow/core/*/*testutil*) \ $(wildcard tensorflow/core/*/*testlib*) \ $(wildcard tensorflow/core/*/*main.cc) \ $(wildcard tensorflow/core/*/*/*test.cc) \ $(wildcard tensorflow/core/*/*/*testutil*) \ $(wildcard tensorflow/core/*/*/*testlib*) \ $(wildcard tensorflow/core/*/*/*main.cc) \ $(wildcard tensorflow/core/graph/dot.*) \ $(wildcard tensorflow/core/lib/gif/*) \ $(wildcard tensorflow/core/lib/io/zlib*) \ $(wildcard tensorflow/core/lib/io/record*) \ $(wildcard tensorflow/core/lib/jpeg/*) \ $(wildcard tensorflow/core/lib/png/*) \ $(wildcard tensorflow/core/util/events_writer.*) \ $(wildcard tensorflow/core/util/reporter.*) \ $(wildcard tensorflow/core/platform/default/stream_executor.*) \ $(wildcard tensorflow/core/platform/default/test_benchmark.*) \ $(wildcard tensorflow/core/platform/cuda.h) \ $(wildcard tensorflow/core/platform/cloud/*) \ $(wildcard tensorflow/core/platform/google/*) \ $(wildcard tensorflow/core/platform/google/*/*) \ $(wildcard tensorflow/core/platform/jpeg.*) \ $(wildcard tensorflow/core/platform/png.*) \ $(wildcard tensorflow/core/platform/stream_executor.*) \ $(wildcard tensorflow/core/platform/windows/*) \ $(wildcard tensorflow/core/user_ops/*.cu.cc) \ $(wildcard tensorflow/core/common_runtime/gpu/*) \ $(wildcard tensorflow/core/common_runtime/gpu_device_factory.*) # Filter out all the excluded files. TF_CC_SRCS := $(filter-out $(CORE_CC_EXCLUDE_SRCS), $(CORE_CC_ALL_SRCS)) # Add in any extra files that don't fit the patterns easily TF_CC_SRCS += tensorflow/core/common_runtime/gpu/gpu_tracer.cc # Also include the op and kernel definitions. TF_CC_SRCS += $(shell cat $(MAKEFILE_DIR)/tf_op_files.txt) PBT_CC_SRCS := $(shell cat $(MAKEFILE_DIR)/tf_pb_text_files.txt) PROTO_SRCS := $(shell cat $(MAKEFILE_DIR)/tf_proto_files.txt) BENCHMARK_SRCS := \ tensorflow/core/util/reporter.cc \ tensorflow/tools/benchmark/benchmark_model.cc \ tensorflow/tools/benchmark/benchmark_model_main.cc # File names of the intermediate files target compilation generates. TF_CC_OBJS := $(addprefix $(OBJDIR), $(TF_CC_SRCS:.cc=.o)) PBT_GEN_FILES := $(addprefix $(PBTGENDIR), $(PBT_CC_SRCS)) PBT_OBJS := $(addprefix $(OBJDIR), $(PBT_CC_SRCS:.cc=.o)) PROTO_CC_SRCS := $(addprefix $(PROTOGENDIR), $(PROTO_SRCS:.proto=.pb.cc)) PROTO_OBJS := $(addprefix $(OBJDIR), $(PROTO_SRCS:.proto=.pb.o)) LIB_OBJS := $(PROTO_OBJS) $(TF_CC_OBJS) $(PBT_OBJS) BENCHMARK_OBJS := $(addprefix $(OBJDIR), $(BENCHMARK_SRCS:.cc=.o)) .PHONY: clean cleantarget # The target that's compiled if there's no command-line arguments. all: $(LIB_PATH) $(BENCHMARK_NAME) # Rules for target compilation. .phony_version_info: tensorflow/core/util/version_info.cc: .phony_version_info tensorflow/tools/git/gen_git_source.sh $@ # Gathers together all the objects we've compiled into a single '.a' archive. $(LIB_PATH): $(LIB_OBJS) @mkdir -p $(dir $@) $(AR) $(ARFLAGS) $(LIB_PATH) $(LIB_OBJS) $(BENCHMARK_NAME): $(BENCHMARK_OBJS) $(LIB_PATH) @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) \ -o $(BENCHMARK_NAME) $(BENCHMARK_OBJS) \ $(LIBFLAGS) $(LIB_PATH) $(LDFLAGS) $(LIBS) # Matches on the normal hand-written TensorFlow C++ source files. $(OBJDIR)%.o: %.cc | $(PBT_GEN_FILES) @mkdir -p $(dir $@) @mkdir -p $(dir $(DEPDIR)$*) $(CXX) $(CXXFLAGS) $(DEPFLAGS) $(INCLUDES) -c $< -o $@ @mv -f $(DEPDIR)/$*.Td $(DEPDIR)/$*.d # Compiles C++ source files that have been generated by protoc. $(OBJDIR)%.pb.o: $(PROTOGENDIR)%.pb.cc @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ # Builds C++ code from proto files using protoc. $(PROTOGENDIR)%.pb.cc $(PROTOGENDIR)%.pb.h: %.proto @mkdir -p $(dir $@) $(PROTOC) $(PROTOCFLAGS) $< --cpp_out $(PROTOGENDIR) # Uses proto_text to generate minimal pb_text C++ files from protos. $(PBTGENDIR)%.pb_text.cc $(PBTGENDIR)%.pb_text.h $(PBTGENDIR)%.pb_text-impl.h: %.proto | $(PROTO_TEXT) @mkdir -p $(dir $@) $(PROTO_TEXT) \ $(PBTGENDIR)tensorflow/core \ tensorflow/core/ \ tensorflow/tools/proto_text/placeholder.txt \ $< # Compiles the C++ source files created by proto_text. $(OBJDIR)%.pb_text.o: $(PBTGENDIR)%.pb_text.cc @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ # Makes sure that we don't compile the protoc-generated C++ sources before they # and the proto_text files have been created. $(PROTO_OBJS): $(PROTO_CC_SRCS) $(PBT_GEN_FILES) # Host compilation rules. # For normal manually-created TensorFlow C++ source files. $(HOST_OBJDIR)%.o: %.cc @mkdir -p $(dir $@) $(HOST_CXX) $(HOST_CXXFLAGS) $(HOST_INCLUDES) -c $< -o $@ # Compiles object code from protoc-built C++ source files. $(HOST_OBJDIR)%.pb.o: $(HOST_GENDIR)%.pb.cc @mkdir -p $(dir $@) $(HOST_CXX) $(HOST_CXXFLAGS) $(HOST_INCLUDES) -c $< -o $@ # Ensures we wait until proto_text has generated the .h files from protos before # we compile the C++. $(PROTO_TEXT_OBJS) : $(PROTO_TEXT_PB_H_FILES) # Runs proto_text to generate C++ source files from protos. $(PROTO_TEXT): $(PROTO_TEXT_OBJS) $(PROTO_TEXT_PB_H_FILES) @mkdir -p $(dir $@) $(HOST_CXX) $(HOST_CXXFLAGS) $(HOST_INCLUDES) \ -o $(PROTO_TEXT) $(PROTO_TEXT_OBJS) $(HOST_LDOPTS) $(HOST_LIBS) # Compiles the C++ source files from protos using protoc. $(HOST_GENDIR)%.pb.cc $(HOST_GENDIR)%.pb.h: %.proto @mkdir -p $(dir $@) $(PROTOC) $(PROTOCFLAGS) $< --cpp_out $(HOST_GENDIR) # Gets rid of all generated files. clean: rm -rf $(MAKEFILE_DIR)/gen rm -rf tensorflow/core/util/version_info.cc # Gets rid of all generated files except protobuf libs generated # before calling make. This allows users not to recompile proto libs everytime. clean_except_protobuf_libs: find $(MAKEFILE_DIR)/gen -mindepth 1 -maxdepth 1 ! -name "protobuf" ! -name "protobuf-host" -exec rm -r "{}" \; rm -rf tensorflow/core/util/version_info.cc # Gets rid of target files only, leaving the host alone. Also leaves the lib # directory untouched deliberately, so we can persist multiple architectures # across builds for iOS. cleantarget: rm -rf $(OBJDIR) rm -rf $(BINDIR) $(DEPDIR)/%.d: ; .PRECIOUS: $(DEPDIR)/%.d -include $(patsubst %,$(DEPDIR)/%.d,$(basename $(TF_CC_SRCS))) ifdef SUB_MAKEFILES $(warning "include sub makefiles, must not contain white spaces in the path:" $(SUB_MAKEFILES)) include $(SUB_MAKEFILES) endif
{ "pile_set_name": "Github" }
package ct; public abstract interface n { public abstract void b(); } /* Location: * Qualified Name: ct.n * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
{ "pile_set_name": "Github" }
/* * FreeRTOS WiFi V1.4.7 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. If you wish to use our Amazon * FreeRTOS name, please do so in a fair use way that does not cause confusion. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /** * This file contains the CLI commands. */ #include <stdio.h> #include <stdint.h> #include <os.h> #include "FreeRTOS.h" #include "FreeRTOSIPConfig.h" #include "task.h" #include "cli.h" #include "toi.h" #include "io_def.h" #include "iot_wifi.h" #include "lwip/inet.h" #include "syslog.h" #include "task_def.h" /*-----------------------------------------------------------*/ /* the length of a line of remembered history command line. */ #define HISTORY_LINE_MAX (256) /*-----------------------------------------------------------*/ /* the lines of remembered CLI commands. */ #define HISTORY_LINES (5) /*-----------------------------------------------------------*/ //#define MINICLI_TASK_NAME "cli" /*-----------------------------------------------------------*/ //#define MINICLI_TASK_STACKSIZE (4096) /*-----------------------------------------------------------*/ //#define MINICLI_TASK_PRIO (1) /*-----------------------------------------------------------*/ static const char *_aws_wifi_strerror( WIFIReturnCode_t r ) { switch( r ) { case eWiFiSuccess: return "eWiFiSuccess"; case eWiFiFailure: return "eWiFiFailure"; case eWiFiTimeout: return "eWiFiTimeout"; case eWiFiNotSupported: return "eWiFiNotSupported"; } return "UNKNOWN CODE"; } /*-----------------------------------------------------------*/ static WIFISecurity_t _str_to_aws_security(const char *str) { if ( 0 == strcmp( str, "open" ) ) return eWiFiSecurityOpen; if ( 0 == strcmp( str, "wep" ) ) return eWiFiSecurityWEP; if ( 0 == strcmp( str, "wpa" ) ) return eWiFiSecurityWPA; if ( 0 == strcmp( str, "wpa2" ) ) return eWiFiSecurityWPA2; return eWiFiSecurityNotSupported; } /*-----------------------------------------------------------*/ static const char *_device_mode_to_str( WIFIDeviceMode_t xDeviceMode ) { switch( xDeviceMode ) { case eWiFiModeStation: return "station"; case eWiFiModeAP: return "ap"; case eWiFiModeP2P: return "p2p"; case eWiFiModeNotSupported: return "not-supported-mode"; default: return "unknown-mode"; } } /*-----------------------------------------------------------*/ #define HANDLE_STATUS(_statement_) \ do \ { \ WIFIReturnCode_t _r = ( _statement_ ); \ printf( "%s\n", _aws_wifi_strerror( _r ) ); \ } while ( 0 ) /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_On( uint8_t len, char *param[] ) { HANDLE_STATUS( WIFI_On() ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_Off( uint8_t len, char *param[] ) { HANDLE_STATUS( WIFI_Off() ); return 0; } /*-----------------------------------------------------------*/ static int _parse_aws_net_params( WIFINetworkParams_t * pxNetworkParams, uint8_t len, char * param [] ) { if( len < 2 || len > 3 ) { printf("params: <ssid> [ <open|wep|wpa|wpa2> [ <password/key> ] ]\n"); return 1; } pxNetworkParams->pcSSID = param[0]; pxNetworkParams->ucSSIDLength = os_strlen( param[0] ); pxNetworkParams->xSecurity = _str_to_aws_security( param[1] ); if( eWiFiSecurityNotSupported == pxNetworkParams->xSecurity ) { printf( "support security: open/wep/wpa/wpa2\n" ); return 2; } if( eWiFiSecurityOpen != pxNetworkParams->xSecurity ) { if( len < 3 ) { printf( "security %s require a key\n", param[1] ); return 3; } pxNetworkParams->pcPassword = param[2]; pxNetworkParams->ucPasswordLength = os_strlen( param[2] ); } return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_ConnectAP( uint8_t len, char *param[] ) { WIFINetworkParams_t xNetworkParams; if( _parse_aws_net_params( &xNetworkParams, len, param ) ) { return 1; } HANDLE_STATUS( WIFI_ConnectAP( &xNetworkParams ) ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_Disconnect( uint8_t len, char *param[] ) { HANDLE_STATUS( WIFI_Disconnect() ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_Reset( uint8_t len, char *param[] ) { HANDLE_STATUS( WIFI_Reset() ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_SetMode( uint8_t len, char *param[] ) { WIFIDeviceMode_t xDeviceMode; if( len > 0 ) { if( !os_strcmp( param[ 0 ], "sta" ) ) { xDeviceMode = eWiFiModeStation; } else if( !os_strcmp( param[ 0 ], "ap" ) ) { xDeviceMode = eWiFiModeAP; } else if( !os_strcmp( param[ 0 ], "p2p" ) ) { xDeviceMode = eWiFiModeP2P; } else { xDeviceMode = eWiFiModeNotSupported; } } else { xDeviceMode = eWiFiModeStation; printf( "use default mode\n" ); } printf( "set device mode to %s\n", _device_mode_to_str( xDeviceMode ) ); HANDLE_STATUS( WIFI_SetMode( xDeviceMode ) ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_GetMode( uint8_t len, char *param[] ) { WIFIDeviceMode_t xDeviceMode; HANDLE_STATUS( WIFI_GetMode( &xDeviceMode ) ); printf( "device mode is %s\n", _device_mode_to_str( xDeviceMode ) ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_NetworkAdd( uint8_t len, char *param[] ) { printf( "not supported\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_NetworkGet( uint8_t len, char *param[] ) { printf( "not supported\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_NetworkDelete( uint8_t len, char *param[] ) { printf( "not supported\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_Ping( uint8_t len, char *param[] ) { uint8_t addr[ 4 ]; int32_t count; int32_t interval; ip4_addr_t ip_addr; WIFIReturnCode_t r = eWiFiFailure; if( len == 0 ) { addr[0] = 127; addr[1] = 0; addr[2] = 0; addr[3] = 1; printf( "use default ip address\n" ); } else { if( inet_aton( param[ 0 ], &ip_addr ) == 1 ) { addr[ 0 ] = ( ntohl( ip_addr.addr ) >> 24 ) & 0xFF; addr[ 1 ] = ( ntohl( ip_addr.addr ) >> 16 ) & 0xFF; addr[ 2 ] = ( ntohl( ip_addr.addr ) >> 8 ) & 0xFF; addr[ 3 ] = ( ntohl( ip_addr.addr ) ) & 0xFF; } else { printf( "invalid ip addr\n" ); return 1; } } if( len > 1 ) { uint8_t err; count = toi( param[ 1 ], &err ); if( err == TOI_ERR || count > 65535 || count < 0) { printf( "invalid packet count\n" ); return 2; } } else { count = 5; } if( len > 2 ) { uint8_t err; interval = toi( param[ 2 ], &err ); if( err == TOI_ERR || interval < 0 ) { printf( "invalid interval\n" ); return 3; } } else { interval = 1000; } printf( "ping %d.%d.%d.%d\n", addr[ 0 ] & 0xFF, addr[ 1 ] & 0xFF, addr[ 2 ] & 0xFF, addr[ 3 ] & 0xFF ); HANDLE_STATUS( ( r = WIFI_Ping( addr, (uint16_t)count, (uint32_t)interval ) ) ); if( r == eWiFiSuccess ) { printf( "host ping is in good health\n" ); } else { printf( "host ping packet lost\n" ); } return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_GetIP( uint8_t len, char *param[] ) { uint8_t ucIPAddr[ 4 ]; HANDLE_STATUS( WIFI_GetIP( &ucIPAddr[ 0 ] ) ); printf("ip addr %u.%u.%u.%u\n", ucIPAddr[ 0 ] & 0xFF, ucIPAddr[ 1 ] & 0xFF, ucIPAddr[ 2 ] & 0xFF, ucIPAddr[ 3 ] & 0xFF ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_GetMAC( uint8_t len, char *param[] ) { uint8_t ucMacAddressVal[ wificonfigMAX_BSSID_LEN ]; HANDLE_STATUS( WIFI_GetMAC( &ucMacAddressVal[0] ) ); printf("mac addr %02x:%02x:%02x:%02x:%02x:%02x\n", ucMacAddressVal[ 0 ] & 0xFF, ucMacAddressVal[ 1 ] & 0xFF, ucMacAddressVal[ 2 ] & 0xFF, ucMacAddressVal[ 3 ] & 0xFF, ucMacAddressVal[ 4 ] & 0xFF, ucMacAddressVal[ 5 ] & 0xFF ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_GetHostIP( uint8_t len, char *param[] ) { uint8_t ucIPAddr[ 4 ]; char *pcHost; WIFIReturnCode_t r = eWiFiFailure; if( len > 0 ) { pcHost = param[0]; } else { pcHost = "localhost"; printf( "use default host\n" ); } printf( "resolve host: %s\n", pcHost ); HANDLE_STATUS( r = WIFI_GetHostIP( pcHost, &ucIPAddr[ 0 ] ) ); if( r == eWiFiSuccess ) { printf( "ip addr %u.%u.%u.%u\n", ucIPAddr[ 0 ] & 0xFF, ucIPAddr[ 1 ] & 0xFF, ucIPAddr[ 2 ] & 0xFF, ucIPAddr[ 3 ] & 0xFF ); } else { printf( "dns query failed\n" ); } return 0; } /*-----------------------------------------------------------*/ static const char * _security_to_str(WIFISecurity_t security) { switch( security ) { case eWiFiSecurityOpen: return "open"; case eWiFiSecurityWEP: return "wep"; case eWiFiSecurityWPA: return "wpa"; case eWiFiSecurityWPA2: return "wpa2"; case eWiFiSecurityNotSupported: return "not-supported"; default: return "unknown-security"; } } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_Scan( uint8_t len, char *param[] ) { const uint8_t ucNumNetworks = 10; //Get 10 scan results WIFIScanResult_t * xScanResults; xScanResults = pvPortMalloc( sizeof( WIFIScanResult_t ) * ucNumNetworks ); if( NULL == xScanResults ) { printf( "Not enough memory\n" ); return 1; } HANDLE_STATUS( WIFI_Scan( xScanResults, ucNumNetworks ) ); vTaskDelay( 1000 ); for( int i = 0; i < ucNumNetworks; i++ ) { WIFIScanResult_t *p = &xScanResults[ i ]; for( int j = 0; j < strlen( p->cSSID ); j++ ) p->cSSID[ j ] &= 0x7F; printf( "ssid %s\n", p->cSSID ); printf( "bssid %02x:%02x:%02x:%02x:%02x:%02x:\n", p->ucBSSID[ 0 ], p->ucBSSID[ 1 ], p->ucBSSID[ 2 ], p->ucBSSID[ 3 ], p->ucBSSID[ 4 ], p->ucBSSID[ 5 ] ); printf( "security %s\n", _security_to_str( p->xSecurity ) ); printf( "rssi %d\n", (int)p->cRSSI ); printf( "channel %d\n", (int)p->cChannel ); printf( "visibility %s\n", (int)p->ucHidden ? "hidden" : "visible" ); } vPortFree( xScanResults ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_StartAP( uint8_t len, char *param[] ) { printf( "not supported\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_StopAP( uint8_t len, char *param[] ) { printf( "not supported\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_ConfigureAP( uint8_t len, char *param[] ) { WIFINetworkParams_t xNetworkParams; uint32_t val; uint8_t err; if( len < 1 ) { printf("missing channel number\n"); return 1; } val = toi( param[0], &err ); if( err == TOI_ERR || val < 1 || val > 14 ) { printf( "invalid channel number: %s\n", param[0] ); return 2; } xNetworkParams.cChannel = (int8_t)val; if( _parse_aws_net_params( &xNetworkParams, len - 1, &param[1] ) ) { return 2; } HANDLE_STATUS( WIFI_ConfigureAP( &xNetworkParams ) ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_SetPMMode( uint8_t len, char *param[] ) { printf( "TBD\n" ); return 0; } /*-----------------------------------------------------------*/ static uint8_t _do_WIFI_GetPMMode( uint8_t len, char *param[] ) { printf( "TBD\n" ); return 0; } /*-----------------------------------------------------------*/ static void _cli_def_task(void *param) { while (1) { cli_task(); } } /*-----------------------------------------------------------*/ static void vCliHistoryInitialize( cli_history_t *hist ) { static char s_history_lines[ HISTORY_LINES ][ HISTORY_LINE_MAX ]; static char *s_history_ptrs[ HISTORY_LINES ]; static char s_history_input[ HISTORY_LINE_MAX ]; static char s_history_parse_token[ HISTORY_LINE_MAX ]; hist->history = &s_history_ptrs[0]; for ( int i = 0; i < HISTORY_LINES; i++ ) { s_history_ptrs[i] = s_history_lines[i]; } hist->input = s_history_input; hist->parse_token = s_history_parse_token; hist->history_max = HISTORY_LINES; hist->line_max = HISTORY_LINE_MAX; hist->index = 0; hist->position = 0; hist->full = 0; } /*-----------------------------------------------------------*/ static uint8_t _do_MQTT_demo_task( uint8_t len, char *param[] ) { extern int vStartMQTTEchoDemo( bool awsIotMqttMode, const char * pIdentifier, void * pNetworkServerInfo, void * pNetworkCredentialInfo, const IotNetworkInterface_t * pNetworkInterface ); vStartMQTTEchoDemo(false, NULL, NULL, NULL, NULL); return 0; } /*-----------------------------------------------------------*/ void vCliTaskStartup( void ) { static cmd_t root[] = { { "a", "turn Wi-Fi on", _do_WIFI_On, NULL }, { "b", "turn Wi-Fi off", _do_WIFI_Off, NULL }, { "c", "connect to AP", _do_WIFI_ConnectAP, NULL }, { "d", "disconnect from AP", _do_WIFI_Disconnect, NULL }, { "e", "reset Wi-Fi", _do_WIFI_Reset, NULL }, { "f", "set mode (sta/ap/p2p (not N/A)", _do_WIFI_SetMode, NULL }, { "g", "get mode", _do_WIFI_GetMode, NULL }, { "h", "add network", _do_WIFI_NetworkAdd, NULL }, { "i", "get network", _do_WIFI_NetworkGet, NULL }, { "j", "del network", _do_WIFI_NetworkDelete, NULL }, { "k", "ping <ip addr>", _do_WIFI_Ping, NULL }, { "l", "get ip", _do_WIFI_GetIP, NULL }, { "m", "get mac", _do_WIFI_GetMAC, NULL }, { "n", "get host ip addr", _do_WIFI_GetHostIP, NULL }, { "o", "scan and show result", _do_WIFI_Scan, NULL }, { "p", "start AP running", _do_WIFI_StartAP, NULL }, { "q", "stop AP running", _do_WIFI_StopAP, NULL }, { "r", "config AP", _do_WIFI_ConfigureAP, NULL }, { "s", "set power save mode <norm/lp/aon>", _do_WIFI_SetPMMode, NULL }, { "t", "get power save mode", _do_WIFI_GetPMMode, NULL }, { "z", "MQTT demo task", _do_MQTT_demo_task, NULL }, { NULL, NULL, NULL, NULL } }; static cli_t cb = { .state = 1, .echo = 0, .get = __io_getchar, .put = __io_putchar, .cmd = &root[0] }; vCliHistoryInitialize( &cb.history ); cli_init (&cb ); if ( xTaskCreate( _cli_def_task, MINICLI_TASK_NAME, MINICLI_TASK_STACKSIZE / sizeof( portSTACK_TYPE ), NULL, MINICLI_TASK_PRIO, NULL ) != pdPASS ) { configPRINTF( ( "CLI task create failed\n" ) ); } }
{ "pile_set_name": "Github" }
<A HREF = "http://www.ed.ac.uk/"> <IMG align=right BORDER=0 SRC = "edcrest.gif"></A> <P Align=left><I>This page is part of the <A HREF="http://www.cstr.ed.ac.uk/projects/festival.html"> Festival Text to Speech System</A> documentation <br> Copyright <A HREF="http://www.ed.ac.uk"> University of Edinburgh</A> 1997 <br> Contact: <A HREF="mailto:[email protected]"> [email protected] </a> </P> <br clear=right>
{ "pile_set_name": "Github" }
#import <TargetConditionals.h> #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #import <Cocoa/Cocoa.h> #endif #define USE_CUSTOM_ASSERTION_HANDLER \ { \ NSThread *__currentThread = [NSThread currentThread]; \ NSDictionary *__threadDict = (__currentThread==nil) ? nil : [__currentThread threadDictionary]; \ if (__threadDict != nil) { \ VVAssertionHandler *__newAH = [[VVAssertionHandler alloc] init]; \ if (__newAH != nil) { \ [__threadDict setValue:__newAH forKey:@"NSAssertionHandler"]; \ [__newAH release]; \ __newAH = nil; \ } \ } \ } @interface VVAssertionHandler : NSAssertionHandler { } @end
{ "pile_set_name": "Github" }
CLASS net/minecraft/class_2258 net/minecraft/block/BubbleColumnBlock FIELD field_10680 DRAG Lnet/minecraft/class_2746; METHOD method_9656 calculateDrag (Lnet/minecraft/class_1922;Lnet/minecraft/class_2338;)Z ARG 0 world ARG 1 pos METHOD method_9657 update (Lnet/minecraft/class_1936;Lnet/minecraft/class_2338;Z)V ARG 0 world ARG 1 pos ARG 2 drag METHOD method_9658 isStillWater (Lnet/minecraft/class_1936;Lnet/minecraft/class_2338;)Z ARG 0 world ARG 1 pos
{ "pile_set_name": "Github" }
package com.crashinvaders.texturepackergui.views.canvas.widgets.preview; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Widget; import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup; import com.crashinvaders.common.scene2d.ScrollFocusCaptureInputListener; import com.crashinvaders.texturepackergui.views.canvas.model.AtlasModel; public class PreviewHolder extends WidgetGroup { private static final float SAVE_PADDING = 24f; private static final Rectangle TMP_RECT = new Rectangle(); private static final int[] ZOOM_LEVELS = {5, 10, 16, 25, 33, 50, 66, 100, 150, 200, 300, 400, 600, 800, 1000}; private static final int DEFAULT_ZOOM_INDEX = 7; private final Skin skin; private final NoPageHint noPageHint; private PageGroup pageGroup; private boolean pageMoved; private int zoomIndex = DEFAULT_ZOOM_INDEX; private Listener listener; public PreviewHolder(Skin skin) { this.skin = skin; noPageHint = new NoPageHint(skin); addActor(noPageHint); addActor(new OuterFade(skin)); addListener(new PanZoomListener()); addListener(new ScrollFocusCaptureInputListener()); } @Override protected void setStage(Stage stage) { super.setStage(stage); if (stage != null) { stage.setScrollFocus(this); } } @Override protected void sizeChanged() { super.sizeChanged(); if (!pageMoved) { fitPageAtCenter(); } fixPagePosition(); } public void setPage(AtlasModel atlas, int pageIndex) { if (atlas == null) throw new IllegalArgumentException("atlas cannot be null"); if (pageGroup != null && pageGroup.getPage().getPageIndex() == pageIndex) return; if (pageGroup != null) { removeActor(pageGroup); } pageGroup = new PageGroup(skin, atlas.getPages().get(pageIndex)); addActor(pageGroup); pageMoved = false; noPageHint.setVisible(false); fitPageAtCenter(); fixPagePosition(); } public void setListener(Listener listener) { this.listener = listener; } public void reset() { setZoomIndex(DEFAULT_ZOOM_INDEX); pageMoved = false; if (pageGroup != null) { removeActor(pageGroup); pageGroup = null; } noPageHint.setVisible(true); } private void setZoomIndex(int zoomIndex) { if (pageGroup == null) return; this.zoomIndex = zoomIndex; int zoomPercentage = ZOOM_LEVELS[zoomIndex]; float pageScale = (float)zoomPercentage / 100f; pageGroup.setScale(pageScale); if (listener != null) { listener.onZoomChanged(ZOOM_LEVELS[zoomIndex]); } } private boolean isHitPage(float x, float y) { if (pageGroup == null) return false; return TMP_RECT.set( pageGroup.getX(), pageGroup.getY(), pageGroup.getWidth() * pageGroup.getScaleX(), pageGroup.getHeight() * pageGroup.getScaleY()) .contains(x, y); } private void fixPagePosition() { if (pageGroup == null) return; float x = pageGroup.getX(); float y = pageGroup.getY(); float width = pageGroup.getWidth() * pageGroup.getScaleX(); float height = pageGroup.getHeight() * pageGroup.getScaleY(); float availableWidth = getWidth(); float availableHeight = getHeight(); if (x < -width + SAVE_PADDING) pageGroup.setX(-width + SAVE_PADDING); if (x > availableWidth - SAVE_PADDING) pageGroup.setX(availableWidth - SAVE_PADDING); if (y < -height + SAVE_PADDING) pageGroup.setY(-height + SAVE_PADDING); if (y > availableHeight - SAVE_PADDING) pageGroup.setY(availableHeight - SAVE_PADDING); } private void fitPageAtCenter() { if (pageGroup == null) return; if (getWidth() <= 0f || getHeight() <= 0f) return; for (int i = ZOOM_LEVELS.length - 1; i >= 0; i--) { float zoomScale = (float)ZOOM_LEVELS[i] / 100f; float width = pageGroup.getWidth() * zoomScale; float height = pageGroup.getHeight() * zoomScale; if (width <= getWidth() && height <= getHeight()) { setZoomIndex(i); break; } } pageGroup.setPosition( (getWidth() - pageGroup.getWidth() * pageGroup.getScaleX()) * 0.5f, (getHeight() - pageGroup.getHeight() * pageGroup.getScaleY()) * 0.5f); } public interface Listener { void onZoomChanged(int percentage); } private class PanZoomListener extends InputListener { private final Vector2 tmpCoords = new Vector2(); private final Vector2 lastPos = new Vector2(); private boolean dragging = false; @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { getStage().setScrollFocus(PreviewHolder.this); if (pageGroup == null) return false; if (button != 0) return false; // if (!isHitPage(x, y)) return false; dragging = true; lastPos.set(x, y); return true; } @Override public void touchDragged(InputEvent event, float x, float y, int pointer) { if (dragging) { pageGroup.setPosition( pageGroup.getX() - lastPos.x + x, pageGroup.getY() - lastPos.y + y); fixPagePosition(); lastPos.set(x, y); pageMoved = true; } } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (button != 0) return; dragging = false; } @Override public boolean scrolled(InputEvent event, float x, float y, int amount) { if (pageGroup == null) return false; float preWidth = pageGroup.getWidth() * pageGroup.getScaleX(); float preHeight = pageGroup.getHeight() * pageGroup.getScaleY(); float xNormalized = x < pageGroup.getX() ? 0f : x > pageGroup.getX()+preWidth ? 1f : (x- pageGroup.getX())/preWidth; float yNormalized = y < pageGroup.getY() ? 0f : y > pageGroup.getY()+preHeight ? 1f : (y- pageGroup.getY())/preHeight; setZoomIndex(Math.max(0, Math.min(ZOOM_LEVELS.length-1, zoomIndex - amount))); float postWidth = pageGroup.getWidth() * pageGroup.getScaleX(); float postHeight = pageGroup.getHeight() * pageGroup.getScaleY(); pageGroup.setPosition( pageGroup.getX() + (preWidth - postWidth) * xNormalized, pageGroup.getY() + (preHeight - postHeight) * yNormalized); fixPagePosition(); return true; } } /** Draws fade outside of page (when page is present) */ private class OuterFade extends Widget { private final Color COLOR_DIM = new Color(0x00000040); private final TextureRegion whiteTexture; public OuterFade(Skin skin) { whiteTexture = skin.getRegion("white"); setFillParent(true); } @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); if (pageGroup == null) return; Color col; float x = pageGroup.getX(); float y = pageGroup.getY(); float width = pageGroup.getWidth() * pageGroup.getScaleX(); float height = pageGroup.getHeight() * pageGroup.getScaleY(); // Fading all around page col = COLOR_DIM; batch.setColor(col.r, col.g, col.b, col.a * getColor().a * parentAlpha); batch.draw(whiteTexture, getX() + 0f, getY() + y + height, getWidth(), getHeight()); batch.draw(whiteTexture, getX() + 0f, getY() + y - getHeight(), getWidth(), getHeight()); batch.draw(whiteTexture, getX() + 0f, getY() + y, x, height); batch.draw(whiteTexture, getX() + x + width, getY() + y, getWidth(), height); } } }
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////// // modifier.hpp // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XPRESSIVE_DETAIL_STATIC_MODIFIER_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_STATIC_MODIFIER_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once # pragma warning(push) # pragma warning(disable : 4510) // default constructor could not be generated # pragma warning(disable : 4610) // user defined constructor required #endif #include <boost/xpressive/detail/detail_fwd.hpp> #include <boost/proto/traits.hpp> #include <boost/xpressive/regex_constants.hpp> namespace boost { namespace xpressive { namespace detail { /////////////////////////////////////////////////////////////////////////////// // modifier template<typename Modifier> struct modifier_op { typedef regex_constants::syntax_option_type opt_type; template<typename Expr> struct apply { typedef typename proto::binary_expr< modifier_tag , typename proto::terminal<Modifier>::type , typename proto::result_of::as_child<Expr const>::type >::type type; }; template<typename Expr> typename apply<Expr>::type const operator ()(Expr const &expr) const { typename apply<Expr>::type that = {{this->mod_}, proto::as_child(expr)}; return that; } operator opt_type() const { return this->opt_; } Modifier mod_; opt_type opt_; }; }}} #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma warning(pop) #endif #endif
{ "pile_set_name": "Github" }
body { font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; } .jasmine_reporter a:visited, .jasmine_reporter a { color: #303; } .jasmine_reporter a:hover, .jasmine_reporter a:active { color: blue; } .run_spec { float:right; padding-right: 5px; font-size: .8em; text-decoration: none; } .jasmine_reporter { margin: 0 5px; } .banner { color: #303; background-color: #fef; padding: 5px; } .logo { float: left; font-size: 1.1em; padding-left: 5px; } .logo .version { font-size: .6em; padding-left: 1em; } .runner.running { background-color: yellow; } .options { text-align: right; font-size: .8em; } .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } .suite .suite { margin: 5px; } .suite.passed { background-color: #dfd; } .suite.failed { background-color: #fdd; } .spec { margin: 5px; padding-left: 1em; clear: both; } .spec.failed, .spec.passed, .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } .spec.failed { background-color: #fbb; border-color: red; } .spec.passed { background-color: #bfb; border-color: green; } .spec.skipped { background-color: #bbb; } .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } .passed { background-color: #cfc; display: none; } .failed { background-color: #fbb; } .skipped { color: #777; background-color: #eee; display: none; } /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ .resultMessage span.result { display: block; line-height: 2em; color: black; } .resultMessage .mismatch { color: black; } .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } .finished-at { padding-left: 1em; font-size: .6em; } .show-passed .passed, .show-skipped .skipped { display: block; } #jasmine_content { position:fixed; right: 100%; } .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; }
{ "pile_set_name": "Github" }
<template name="announcement"> {{#if announcement}} {{#with announcement}} <div class="ui {{type}} message"> <div class="header"> {{header}} </div> <p class="date"> {{time}} </p> <p> {{content}} </p> <p class="float right"> - {{name}} </p> </div> {{/with}} {{/if}} </template>
{ "pile_set_name": "Github" }
# Prints tmux session info. # Assuems that [ -n "$TMUX"]. run_segment() { tmux display-message -p '#S:#I.#P' return 0 }
{ "pile_set_name": "Github" }
// +build windows package lib import ( "fmt" "syscall" . "gopkg.in/check.v1" ) func (s *OssutilCommandSuite) TestGetOsLang(c *C) { var mod = syscall.NewLazyDLL("kernel32.dll") var proc = mod.NewProc("GetUserDefaultUILanguage") err := proc.Find() if err != nil { fmt.Printf("%s", err.Error()) return } var sproc = mod.NewProc("SetUserDefaultUILanguage") err = sproc.Find() if err != nil { fmt.Printf("%s", err.Error()) return } oriLang, _, _ := proc.Call() sproc.Call(1033) c.Assert(getOsLang(), Equals, EnglishLanguage) sproc.Call(2052) c.Assert(getOsLang(), Equals, ChineseLanguage) sproc.Call(oriLang) }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018, NVIDIA CORPORATION. * * 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. */ #pragma once #include <common/cudart_utils.h> #include <cuda_utils.cuh> #include <linalg/add.cuh> #include <linalg/eltwise.cuh> #include <linalg/norm.cuh> #include <matrix/math.cuh> #include <matrix/matrix.cuh> #include "sign.cuh" namespace MLCommon { namespace Functions { enum penalty { NONE, L1, L2, ELASTICNET, }; template <typename math_t> void lasso(math_t *out, const math_t *coef, const int len, const math_t alpha, cudaStream_t stream) { LinAlg::rowNorm(out, coef, len, 1, LinAlg::NormType::L1Norm, true, stream); LinAlg::scalarMultiply(out, out, alpha, 1, stream); } template <typename math_t> void lassoGrad(math_t *grad, const math_t *coef, const int len, const math_t alpha, cudaStream_t stream) { sign(grad, coef, alpha, len, stream); } template <typename math_t> void ridge(math_t *out, const math_t *coef, const int len, const math_t alpha, cudaStream_t stream) { LinAlg::rowNorm(out, coef, len, 1, LinAlg::NormType::L2Norm, true, stream); LinAlg::scalarMultiply(out, out, alpha, 1, stream); } template <typename math_t> void ridgeGrad(math_t *grad, const math_t *coef, const int len, const math_t alpha, cudaStream_t stream) { LinAlg::scalarMultiply(grad, coef, math_t(2) * alpha, len, stream); } template <typename math_t> void elasticnet(math_t *out, const math_t *coef, const int len, const math_t alpha, const math_t l1_ratio, cudaStream_t stream) { math_t *out_lasso = NULL; allocate(out_lasso, 1); ridge(out, coef, len, alpha * (math_t(1) - l1_ratio), stream); lasso(out_lasso, coef, len, alpha * l1_ratio, stream); LinAlg::add(out, out, out_lasso, 1, stream); if (out_lasso != NULL) { CUDA_CHECK(cudaFree(out_lasso)); } } template <typename math_t> void elasticnetGrad(math_t *grad, const math_t *coef, const int len, const math_t alpha, const math_t l1_ratio, cudaStream_t stream) { math_t *grad_lasso = NULL; allocate(grad_lasso, len); ridgeGrad(grad, coef, len, alpha * (math_t(1) - l1_ratio), stream); lassoGrad(grad_lasso, coef, len, alpha * l1_ratio, stream); LinAlg::add(grad, grad, grad_lasso, len, stream); if (grad_lasso != NULL) { CUDA_CHECK(cudaFree(grad_lasso)); } } }; // namespace Functions }; // namespace MLCommon // end namespace ML
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * EPSON TOYOCOM RTC-7301SF/DG Driver * * Copyright (c) 2016 Akinobu Mita <[email protected]> * * Based on rtc-rp5c01.c * * Datasheet: http://www5.epsondevice.com/en/products/parallel/rtc7301sf.html */ #include <linux/io.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mod_devicetable.h> #include <linux/delay.h> #include <linux/regmap.h> #include <linux/platform_device.h> #include <linux/rtc.h> #define DRV_NAME "rtc-r7301" #define RTC7301_1_SEC 0x0 /* Bank 0 and Band 1 */ #define RTC7301_10_SEC 0x1 /* Bank 0 and Band 1 */ #define RTC7301_AE BIT(3) #define RTC7301_1_MIN 0x2 /* Bank 0 and Band 1 */ #define RTC7301_10_MIN 0x3 /* Bank 0 and Band 1 */ #define RTC7301_1_HOUR 0x4 /* Bank 0 and Band 1 */ #define RTC7301_10_HOUR 0x5 /* Bank 0 and Band 1 */ #define RTC7301_DAY_OF_WEEK 0x6 /* Bank 0 and Band 1 */ #define RTC7301_1_DAY 0x7 /* Bank 0 and Band 1 */ #define RTC7301_10_DAY 0x8 /* Bank 0 and Band 1 */ #define RTC7301_1_MONTH 0x9 /* Bank 0 */ #define RTC7301_10_MONTH 0xa /* Bank 0 */ #define RTC7301_1_YEAR 0xb /* Bank 0 */ #define RTC7301_10_YEAR 0xc /* Bank 0 */ #define RTC7301_100_YEAR 0xd /* Bank 0 */ #define RTC7301_1000_YEAR 0xe /* Bank 0 */ #define RTC7301_ALARM_CONTROL 0xe /* Bank 1 */ #define RTC7301_ALARM_CONTROL_AIE BIT(0) #define RTC7301_ALARM_CONTROL_AF BIT(1) #define RTC7301_TIMER_CONTROL 0xe /* Bank 2 */ #define RTC7301_TIMER_CONTROL_TIE BIT(0) #define RTC7301_TIMER_CONTROL_TF BIT(1) #define RTC7301_CONTROL 0xf /* All banks */ #define RTC7301_CONTROL_BUSY BIT(0) #define RTC7301_CONTROL_STOP BIT(1) #define RTC7301_CONTROL_BANK_SEL_0 BIT(2) #define RTC7301_CONTROL_BANK_SEL_1 BIT(3) struct rtc7301_priv { struct regmap *regmap; int irq; spinlock_t lock; u8 bank; }; static const struct regmap_config rtc7301_regmap_config = { .reg_bits = 32, .val_bits = 8, .reg_stride = 4, }; static u8 rtc7301_read(struct rtc7301_priv *priv, unsigned int reg) { int reg_stride = regmap_get_reg_stride(priv->regmap); unsigned int val; regmap_read(priv->regmap, reg_stride * reg, &val); return val & 0xf; } static void rtc7301_write(struct rtc7301_priv *priv, u8 val, unsigned int reg) { int reg_stride = regmap_get_reg_stride(priv->regmap); regmap_write(priv->regmap, reg_stride * reg, val); } static void rtc7301_update_bits(struct rtc7301_priv *priv, unsigned int reg, u8 mask, u8 val) { int reg_stride = regmap_get_reg_stride(priv->regmap); regmap_update_bits(priv->regmap, reg_stride * reg, mask, val); } static int rtc7301_wait_while_busy(struct rtc7301_priv *priv) { int retries = 100; while (retries-- > 0) { u8 val; val = rtc7301_read(priv, RTC7301_CONTROL); if (!(val & RTC7301_CONTROL_BUSY)) return 0; udelay(300); } return -ETIMEDOUT; } static void rtc7301_stop(struct rtc7301_priv *priv) { rtc7301_update_bits(priv, RTC7301_CONTROL, RTC7301_CONTROL_STOP, RTC7301_CONTROL_STOP); } static void rtc7301_start(struct rtc7301_priv *priv) { rtc7301_update_bits(priv, RTC7301_CONTROL, RTC7301_CONTROL_STOP, 0); } static void rtc7301_select_bank(struct rtc7301_priv *priv, u8 bank) { u8 val = 0; if (bank == priv->bank) return; if (bank & BIT(0)) val |= RTC7301_CONTROL_BANK_SEL_0; if (bank & BIT(1)) val |= RTC7301_CONTROL_BANK_SEL_1; rtc7301_update_bits(priv, RTC7301_CONTROL, RTC7301_CONTROL_BANK_SEL_0 | RTC7301_CONTROL_BANK_SEL_1, val); priv->bank = bank; } static void rtc7301_get_time(struct rtc7301_priv *priv, struct rtc_time *tm, bool alarm) { int year; tm->tm_sec = rtc7301_read(priv, RTC7301_1_SEC); tm->tm_sec += (rtc7301_read(priv, RTC7301_10_SEC) & ~RTC7301_AE) * 10; tm->tm_min = rtc7301_read(priv, RTC7301_1_MIN); tm->tm_min += (rtc7301_read(priv, RTC7301_10_MIN) & ~RTC7301_AE) * 10; tm->tm_hour = rtc7301_read(priv, RTC7301_1_HOUR); tm->tm_hour += (rtc7301_read(priv, RTC7301_10_HOUR) & ~RTC7301_AE) * 10; tm->tm_mday = rtc7301_read(priv, RTC7301_1_DAY); tm->tm_mday += (rtc7301_read(priv, RTC7301_10_DAY) & ~RTC7301_AE) * 10; if (alarm) { tm->tm_wday = -1; tm->tm_mon = -1; tm->tm_year = -1; tm->tm_yday = -1; tm->tm_isdst = -1; return; } tm->tm_wday = (rtc7301_read(priv, RTC7301_DAY_OF_WEEK) & ~RTC7301_AE); tm->tm_mon = rtc7301_read(priv, RTC7301_10_MONTH) * 10 + rtc7301_read(priv, RTC7301_1_MONTH) - 1; year = rtc7301_read(priv, RTC7301_1000_YEAR) * 1000 + rtc7301_read(priv, RTC7301_100_YEAR) * 100 + rtc7301_read(priv, RTC7301_10_YEAR) * 10 + rtc7301_read(priv, RTC7301_1_YEAR); tm->tm_year = year - 1900; } static void rtc7301_write_time(struct rtc7301_priv *priv, struct rtc_time *tm, bool alarm) { int year; rtc7301_write(priv, tm->tm_sec % 10, RTC7301_1_SEC); rtc7301_write(priv, tm->tm_sec / 10, RTC7301_10_SEC); rtc7301_write(priv, tm->tm_min % 10, RTC7301_1_MIN); rtc7301_write(priv, tm->tm_min / 10, RTC7301_10_MIN); rtc7301_write(priv, tm->tm_hour % 10, RTC7301_1_HOUR); rtc7301_write(priv, tm->tm_hour / 10, RTC7301_10_HOUR); rtc7301_write(priv, tm->tm_mday % 10, RTC7301_1_DAY); rtc7301_write(priv, tm->tm_mday / 10, RTC7301_10_DAY); /* Don't care for alarm register */ rtc7301_write(priv, alarm ? RTC7301_AE : tm->tm_wday, RTC7301_DAY_OF_WEEK); if (alarm) return; rtc7301_write(priv, (tm->tm_mon + 1) % 10, RTC7301_1_MONTH); rtc7301_write(priv, (tm->tm_mon + 1) / 10, RTC7301_10_MONTH); year = tm->tm_year + 1900; rtc7301_write(priv, year % 10, RTC7301_1_YEAR); rtc7301_write(priv, (year / 10) % 10, RTC7301_10_YEAR); rtc7301_write(priv, (year / 100) % 10, RTC7301_100_YEAR); rtc7301_write(priv, year / 1000, RTC7301_1000_YEAR); } static void rtc7301_alarm_irq(struct rtc7301_priv *priv, unsigned int enabled) { rtc7301_update_bits(priv, RTC7301_ALARM_CONTROL, RTC7301_ALARM_CONTROL_AF | RTC7301_ALARM_CONTROL_AIE, enabled ? RTC7301_ALARM_CONTROL_AIE : 0); } static int rtc7301_read_time(struct device *dev, struct rtc_time *tm) { struct rtc7301_priv *priv = dev_get_drvdata(dev); unsigned long flags; int err; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 0); err = rtc7301_wait_while_busy(priv); if (!err) rtc7301_get_time(priv, tm, false); spin_unlock_irqrestore(&priv->lock, flags); return err; } static int rtc7301_set_time(struct device *dev, struct rtc_time *tm) { struct rtc7301_priv *priv = dev_get_drvdata(dev); unsigned long flags; spin_lock_irqsave(&priv->lock, flags); rtc7301_stop(priv); udelay(300); rtc7301_select_bank(priv, 0); rtc7301_write_time(priv, tm, false); rtc7301_start(priv); spin_unlock_irqrestore(&priv->lock, flags); return 0; } static int rtc7301_read_alarm(struct device *dev, struct rtc_wkalrm *alarm) { struct rtc7301_priv *priv = dev_get_drvdata(dev); unsigned long flags; u8 alrm_ctrl; if (priv->irq <= 0) return -EINVAL; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 1); rtc7301_get_time(priv, &alarm->time, true); alrm_ctrl = rtc7301_read(priv, RTC7301_ALARM_CONTROL); alarm->enabled = !!(alrm_ctrl & RTC7301_ALARM_CONTROL_AIE); alarm->pending = !!(alrm_ctrl & RTC7301_ALARM_CONTROL_AF); spin_unlock_irqrestore(&priv->lock, flags); return 0; } static int rtc7301_set_alarm(struct device *dev, struct rtc_wkalrm *alarm) { struct rtc7301_priv *priv = dev_get_drvdata(dev); unsigned long flags; if (priv->irq <= 0) return -EINVAL; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 1); rtc7301_write_time(priv, &alarm->time, true); rtc7301_alarm_irq(priv, alarm->enabled); spin_unlock_irqrestore(&priv->lock, flags); return 0; } static int rtc7301_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct rtc7301_priv *priv = dev_get_drvdata(dev); unsigned long flags; if (priv->irq <= 0) return -EINVAL; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 1); rtc7301_alarm_irq(priv, enabled); spin_unlock_irqrestore(&priv->lock, flags); return 0; } static const struct rtc_class_ops rtc7301_rtc_ops = { .read_time = rtc7301_read_time, .set_time = rtc7301_set_time, .read_alarm = rtc7301_read_alarm, .set_alarm = rtc7301_set_alarm, .alarm_irq_enable = rtc7301_alarm_irq_enable, }; static irqreturn_t rtc7301_irq_handler(int irq, void *dev_id) { struct rtc_device *rtc = dev_id; struct rtc7301_priv *priv = dev_get_drvdata(rtc->dev.parent); unsigned long flags; irqreturn_t ret = IRQ_NONE; u8 alrm_ctrl; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 1); alrm_ctrl = rtc7301_read(priv, RTC7301_ALARM_CONTROL); if (alrm_ctrl & RTC7301_ALARM_CONTROL_AF) { ret = IRQ_HANDLED; rtc7301_alarm_irq(priv, false); rtc_update_irq(rtc, 1, RTC_IRQF | RTC_AF); } spin_unlock_irqrestore(&priv->lock, flags); return ret; } static void rtc7301_init(struct rtc7301_priv *priv) { unsigned long flags; spin_lock_irqsave(&priv->lock, flags); rtc7301_select_bank(priv, 2); rtc7301_write(priv, 0, RTC7301_TIMER_CONTROL); spin_unlock_irqrestore(&priv->lock, flags); } static int __init rtc7301_rtc_probe(struct platform_device *dev) { void __iomem *regs; struct rtc7301_priv *priv; struct rtc_device *rtc; int ret; priv = devm_kzalloc(&dev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; regs = devm_platform_ioremap_resource(dev, 0); if (IS_ERR(regs)) return PTR_ERR(regs); priv->regmap = devm_regmap_init_mmio(&dev->dev, regs, &rtc7301_regmap_config); if (IS_ERR(priv->regmap)) return PTR_ERR(priv->regmap); priv->irq = platform_get_irq(dev, 0); spin_lock_init(&priv->lock); priv->bank = -1; rtc7301_init(priv); platform_set_drvdata(dev, priv); rtc = devm_rtc_device_register(&dev->dev, DRV_NAME, &rtc7301_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) return PTR_ERR(rtc); if (priv->irq > 0) { ret = devm_request_irq(&dev->dev, priv->irq, rtc7301_irq_handler, IRQF_SHARED, dev_name(&dev->dev), rtc); if (ret) { priv->irq = 0; dev_err(&dev->dev, "unable to request IRQ\n"); } else { device_set_wakeup_capable(&dev->dev, true); } } return 0; } #ifdef CONFIG_PM_SLEEP static int rtc7301_suspend(struct device *dev) { struct rtc7301_priv *priv = dev_get_drvdata(dev); if (device_may_wakeup(dev)) enable_irq_wake(priv->irq); return 0; } static int rtc7301_resume(struct device *dev) { struct rtc7301_priv *priv = dev_get_drvdata(dev); if (device_may_wakeup(dev)) disable_irq_wake(priv->irq); return 0; } #endif static SIMPLE_DEV_PM_OPS(rtc7301_pm_ops, rtc7301_suspend, rtc7301_resume); static const struct of_device_id rtc7301_dt_match[] = { { .compatible = "epson,rtc7301sf" }, { .compatible = "epson,rtc7301dg" }, {} }; MODULE_DEVICE_TABLE(of, rtc7301_dt_match); static struct platform_driver rtc7301_rtc_driver = { .driver = { .name = DRV_NAME, .of_match_table = rtc7301_dt_match, .pm = &rtc7301_pm_ops, }, }; module_platform_driver_probe(rtc7301_rtc_driver, rtc7301_rtc_probe); MODULE_AUTHOR("Akinobu Mita <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("EPSON TOYOCOM RTC-7301SF/DG Driver"); MODULE_ALIAS("platform:rtc-r7301");
{ "pile_set_name": "Github" }
// // Prefix header for all source files of the 'PhoenixUtil' target in the 'PhoenixUtil' project // #ifdef __OBJC__ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #endif #define DEBUG 1 #ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif
{ "pile_set_name": "Github" }
/*- * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static char sccsid[] = "@(#)subr.c 8.2 (Berkeley) 4/28/95"; #endif /* not lint */ #include <sys/param.h> #include <sys/file.h> #include <sys/user.h> #include <sys/proc.h> #include <sys/time.h> #include <sys/ktrace.h> #include <stdio.h> #include "ktrace.h" getpoints(s) char *s; { int facs = 0; while (*s) { switch(*s) { case 'c': facs |= KTRFAC_SYSCALL | KTRFAC_SYSRET; break; case 'n': facs |= KTRFAC_NAMEI; break; case 'i': facs |= KTRFAC_GENIO; break; case 's': facs |= KTRFAC_PSIG; break; case 'w': facs |= KTRFAC_CSW; break; case '+': facs |= DEF_POINTS; break; default: return (-1); } s++; } return (facs); } timevaladd(t1, t2) struct timeval *t1, *t2; { t1->tv_sec += t2->tv_sec; t1->tv_usec += t2->tv_usec; timevalfix(t1); } timevalsub(t1, t2) struct timeval *t1, *t2; { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; timevalfix(t1); } timevalfix(t1) struct timeval *t1; { if (t1->tv_usec < 0) { t1->tv_sec--; t1->tv_usec += 1000000; } if (t1->tv_usec >= 1000000) { t1->tv_sec++; t1->tv_usec -= 1000000; } }
{ "pile_set_name": "Github" }
{ "name": "SlideshowPro Player", "description": "A customisable media player.", "url": "http://slideshowpro.net/" }
{ "pile_set_name": "Github" }
defmodule Util.ColorsTest do @colors_file "css-color-names.json" use ExUnit.Case, async: true alias Cog.Util.Colors test "look up hex code by name" do assert Colors.name_to_hex("lightblue") == "#add8e6" end test "look up name by hex code" do assert Colors.hex_to_name("#add8e6") == "lightblue" end test "hex codes are passed thru" do assert Colors.name_to_hex("#add8e6") == "#add8e6" end test "unknown name returns :unknown_color" do assert Colors.name_to_hex("superultramarine") == :unknown_color end test "unknown hex code returns :unknown_color" do assert Colors.hex_to_name("#add8e0") == :unknown_color end test "accurate code is generated from JSON file" do hex_codes = File.read!(Path.join(String.Chars.to_string(:code.priv_dir(:cog)), @colors_file)) |> Poison.decode! names = Enum.reduce(hex_codes, %{}, fn({name, code}, acc) -> Map.put(acc, code, name) end) Enum.each(hex_codes, fn({name, code}) -> assert Colors.name_to_hex(name) == code assert Colors.hex_to_name(code) == Map.get(names, code) end) assert Colors.names() == Enum.sort(Map.keys(hex_codes)) end end
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>JTable.DropLocation (Java SE 12 &amp; JDK 12 )</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="keywords" content="javax.swing.JTable.DropLocation class"> <meta name="keywords" content="getRow()"> <meta name="keywords" content="getColumn()"> <meta name="keywords" content="isInsertRow()"> <meta name="keywords" content="isInsertColumn()"> <meta name="keywords" content="toString()"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> <script type="text/javascript" src="../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="JTable.DropLocation (Java SE 12 & JDK 12 )"; } } catch(err) { } //--> var data = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; var pathtoroot = "../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../index.html">Overview</a></li> <li><a href="../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JTable.DropLocation.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> </div> <a id="skip.navbar.top"> <!-- --> </a> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <!-- ======== START OF CLASS DATA ======== --> <main role="main"> <div class="header"> <div class="subTitle"><span class="moduleLabelInType">Module</span>&nbsp;<a href="../../module-summary.html">java.desktop</a></div> <div class="subTitle"><span class="packageLabelInType">Package</span>&nbsp;<a href="package-summary.html">javax.swing</a></div> <h2 title="Class JTable.DropLocation" class="title">Class JTable.DropLocation</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="../../../java.base/java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li><a href="TransferHandler.DropLocation.html" title="class in javax.swing">javax.swing.TransferHandler.DropLocation</a></li> <li> <ul class="inheritance"> <li>javax.swing.JTable.DropLocation</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="JTable.html" title="class in javax.swing">JTable</a></dd> </dl> <hr> <pre>public static final class <span class="typeNameLabel">JTable.DropLocation</span> extends <a href="TransferHandler.DropLocation.html" title="class in javax.swing">TransferHandler.DropLocation</a></pre> <div class="block">A subclass of <code>TransferHandler.DropLocation</code> representing a drop location for a <code>JTable</code>.</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>1.6</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="JTable.html#getDropLocation()"><code>JTable.getDropLocation()</code></a></dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <div class="memberSummary"> <div role="tablist" aria-orientation="horizontal"><button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t4" class="tableTab" onclick="show(8);">Concrete Methods</button></div> <div id="memberSummary_tabpanel" role="tabpanel"> <table aria-labelledby="t0"> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Method</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor" id="i0"> <td class="colFirst"><code>int</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getColumn()">getColumn</a></span>()</code></th> <td class="colLast"> <div class="block">Returns the column index where a dropped item should be placed in the table.</div> </td> </tr> <tr class="rowColor" id="i1"> <td class="colFirst"><code>int</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getRow()">getRow</a></span>()</code></th> <td class="colLast"> <div class="block">Returns the row index where a dropped item should be placed in the table.</div> </td> </tr> <tr class="altColor" id="i2"> <td class="colFirst"><code>boolean</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#isInsertColumn()">isInsertColumn</a></span>()</code></th> <td class="colLast"> <div class="block">Returns whether or not this location represents an insert of a column.</div> </td> </tr> <tr class="rowColor" id="i3"> <td class="colFirst"><code>boolean</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#isInsertRow()">isInsertRow</a></span>()</code></th> <td class="colLast"> <div class="block">Returns whether or not this location represents an insert of a row.</div> </td> </tr> <tr class="altColor" id="i4"> <td class="colFirst"><code><a href="../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#toString()">toString</a></span>()</code></th> <td class="colLast"> <div class="block">Returns a string representation of this drop location.</div> </td> </tr> </tbody> </table> </div> </div> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.javax.swing.TransferHandler.DropLocation"> <!-- --> </a> <h3>Methods declared in class&nbsp;javax.swing.<a href="TransferHandler.DropLocation.html" title="class in javax.swing">TransferHandler.DropLocation</a></h3> <code><a href="TransferHandler.DropLocation.html#getDropPoint()">getDropPoint</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods declared in class&nbsp;java.lang.<a href="../../../java.base/java/lang/Object.html" title="class in java.lang">Object</a></h3> <code><a href="../../../java.base/java/lang/Object.html#clone()">clone</a>, <a href="../../../java.base/java/lang/Object.html#equals(java.lang.Object)">equals</a>, <a href="../../../java.base/java/lang/Object.html#finalize()">finalize</a>, <a href="../../../java.base/java/lang/Object.html#getClass()">getClass</a>, <a href="../../../java.base/java/lang/Object.html#hashCode()">hashCode</a>, <a href="../../../java.base/java/lang/Object.html#notify()">notify</a>, <a href="../../../java.base/java/lang/Object.html#notifyAll()">notifyAll</a>, <a href="../../../java.base/java/lang/Object.html#wait()">wait</a>, <a href="../../../java.base/java/lang/Object.html#wait(long)">wait</a>, <a href="../../../java.base/java/lang/Object.html#wait(long,int)">wait</a></code></li> </ul> </li> </ul> </section> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a id="getRow()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRow</h4> <pre class="methodSignature">public&nbsp;int&nbsp;getRow()</pre> <div class="block">Returns the row index where a dropped item should be placed in the table. Interpretation of the value depends on the return of <code>isInsertRow()</code>. If that method returns <code>true</code> this value indicates the index where a new row should be inserted. Otherwise, it represents the value of an existing row on which the data was dropped. This index is in terms of the view. <p> <code>-1</code> indicates that the drop occurred over empty space, and no row could be calculated.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the drop row</dd> </dl> </li> </ul> <a id="getColumn()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getColumn</h4> <pre class="methodSignature">public&nbsp;int&nbsp;getColumn()</pre> <div class="block">Returns the column index where a dropped item should be placed in the table. Interpretation of the value depends on the return of <code>isInsertColumn()</code>. If that method returns <code>true</code> this value indicates the index where a new column should be inserted. Otherwise, it represents the value of an existing column on which the data was dropped. This index is in terms of the view. <p> <code>-1</code> indicates that the drop occurred over empty space, and no column could be calculated.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the drop row</dd> </dl> </li> </ul> <a id="isInsertRow()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isInsertRow</h4> <pre class="methodSignature">public&nbsp;boolean&nbsp;isInsertRow()</pre> <div class="block">Returns whether or not this location represents an insert of a row.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>whether or not this is an insert row</dd> </dl> </li> </ul> <a id="isInsertColumn()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isInsertColumn</h4> <pre class="methodSignature">public&nbsp;boolean&nbsp;isInsertColumn()</pre> <div class="block">Returns whether or not this location represents an insert of a column.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>whether or not this is an insert column</dd> </dl> </li> </ul> <a id="toString()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>toString</h4> <pre class="methodSignature">public&nbsp;<a href="../../../java.base/java/lang/String.html" title="class in java.lang">String</a>&nbsp;toString()</pre> <div class="block">Returns a string representation of this drop location. This method is intended to be used for debugging purposes, and the content and format of the returned string may vary between implementations.</div> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="TransferHandler.DropLocation.html#toString()">toString</a></code>&nbsp;in class&nbsp;<code><a href="TransferHandler.DropLocation.html" title="class in javax.swing">TransferHandler.DropLocation</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>a string representation of this drop location</dd> </dl> </li> </ul> </li> </ul> </section> </li> </ul> </div> </div> </main> <!-- ========= END OF CLASS DATA ========= --> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../index.html">Overview</a></li> <li><a href="../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JTable.DropLocation.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> </div> <a id="skip.navbar.bottom"> <!-- --> </a> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small><a href="https://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> For further API reference and developer documentation see the <a href="https://docs.oracle.com/pls/topic/lookup?ctx=javase12.0.2&amp;id=homepage" target="_blank">Java SE Documentation</a>, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.<br> <a href="../../../../legal/copyright.html">Copyright</a> &copy; 1993, 2019, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.<br>All rights reserved. Use is subject to <a href="https://www.oracle.com/technetwork/java/javase/terms/license/java12.0.2speclicense.html">license terms</a> and the <a href="https://www.oracle.com/technetwork/java/redist-137594.html">documentation redistribution policy</a>. <!-- Version 12.0.2+10 --></small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
using System.Collections.Generic; using Shouldly; using Xunit; namespace Volo.Abp.Cli.Build { public class GitRepository_Tests : AbpCliTestBase { [Fact] public void GetUniqueName_Test() { var gitRepository = new GitRepository("repo-1", "dev", "") { DependingRepositories = new List<GitRepository> { new GitRepository("repo-2", "dev", ""), new GitRepository("repo-3", "dev", "") { DependingRepositories = new List<GitRepository>() { new GitRepository("repo-4", "dev", "") } } } }; gitRepository.GetUniqueName("").ShouldBe("B25C935F97D7B3375530A96B392B7644"); gitRepository.GetUniqueName("production").ShouldBe("production_B25C935F97D7B3375530A96B392B7644"); } [Fact] public void FindRepositoryOf_Test() { var gitRepository = new GitRepository("repo-1", "dev", "/repo-1/dev/") { DependingRepositories = new List<GitRepository> { new GitRepository("repo-2", "dev", "/repo-2/dev/"), new GitRepository("repo-3", "dev", "/repo-3/dev/") { DependingRepositories = new List<GitRepository>() { new GitRepository("repo-4", "dev", "/repo-4/dev/") } } } }; gitRepository.FindRepositoryOf("/repo-4/dev/A.csproj").ShouldBe("repo-4"); } } }
{ "pile_set_name": "Github" }
package home.smart.fly.animations.customview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import home.smart.fly.animations.R; /** * Created by Rookie on 2017/10/30. */ public class BitmapMeshView extends View { private Bitmap mBitmap; //定义两个常量,这两个常量指定该图片横向,纵向上都被划分为20格 private final int WIDTH = 20; private final int HEIGHT = 20; //记录该图片上包含441个顶点 private final int COUNT = (WIDTH + 1) * (HEIGHT + 1); //定义一个数组,记录Bitmap上的21*21个点的坐标 private final float[] verts = new float[COUNT * 2]; //定义一个数组,记录Bitmap上的21*21个点经过扭曲后的坐标 //对图片扭曲的关键就是修改该数组里元素的值 private final float[] orig = new float[COUNT * 2]; public BitmapMeshView(Context context) { super(context); init(); } public BitmapMeshView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public BitmapMeshView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yuanyuan); //获取图片宽度和高度 float bitmapWidth = mBitmap.getWidth(); float bitmapHeight = mBitmap.getHeight(); int index = 0; for (int y = 0; y <= HEIGHT; y++) { float fy = bitmapHeight * y / HEIGHT; for (int x = 0; x <= WIDTH; x++) { float fx = bitmapWidth * x / WIDTH; //初始化orig,verts数组 //初始化,orig,verts两个数组均匀地保存了21 * 21个点的x,y坐标  orig[index * 2 + 0] = verts[index * 2 + 0] = fx; orig[index * 2 + 1] = verts[index * 2 + 1] = fy; index += 1; } } //设置背景色 setBackgroundColor(Color.WHITE); } @Override protected void onDraw(Canvas canvas) { //对bitmap按verts数组进行扭曲 //从第一个点(由第5个参数0控制)开始扭曲 canvas.drawBitmapMesh(mBitmap, WIDTH, HEIGHT, verts, 0, null, 0, null); } /** * 工具方法,用于根据触摸事件的位置计算verts数组里各元素的值 */ private void warp(float cx, float cy) { for (int i = 0; i < COUNT * 2; i += 2) { float dx = cx - orig[i + 0]; float dy = cy - orig[i + 1]; float dd = dx * dx + dy * dy; //计算每个坐标点与当前点(cx,cy)之间的距离 float d = (float) Math.sqrt(dd); //计算扭曲度,距离当前点(cx,cy)越远,扭曲度越小 float pull = 80000 / ((float) (dd * d)); //对verts数组(保存bitmap 上21 * 21个点经过扭曲后的坐标)重新赋值 if (pull >= 1) { verts[i + 0] = cx; verts[i + 1] = cy; } else { //控制各顶点向触摸事件发生点偏移 verts[i + 0] = orig[i + 0] + dx * pull; verts[i + 1] = orig[i + 1] + dx * pull; } } //通知View组件重绘 invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { //调用warp方法根据触摸屏事件的坐标点来扭曲verts数组 warp(event.getX(), event.getY()); return true; } }
{ "pile_set_name": "Github" }
# -*- mode: snippet -*- # key: imp # name: simple import # condition: (= (length "imp") (current-column)) # contributor: Luke Hoersten <[email protected]> # -- import ${1:Module} ${2:(${3:f})}
{ "pile_set_name": "Github" }
#!/usr/bin/env bash valgrind --tool=massif ./unit-tests $* valgrind --leak-check=full --suppressions=./valgrind_suppressions.txt ./unit-tests $*
{ "pile_set_name": "Github" }
Sample and benchmark scripts for pktgen (packet generator) ========================================================== This directory contains some pktgen sample and benchmark scripts, that can easily be copied and adjusted for your own use-case. General doc is located in kernel: Documentation/networking/pktgen.txt Helper include files ==================== This directory contains two helper shell files, that can be "included" by shell source'ing. Namely "functions.sh" and "parameters.sh". Common parameters ----------------- The parameters.sh file support easy and consistant parameter parsing across the sample scripts. Usage example is printed on errors:: Usage: ./pktgen_sample01_simple.sh [-vx] -i ethX -i : ($DEV) output interface/device (required) -s : ($PKT_SIZE) packet size -d : ($DEST_IP) destination IP -m : ($DST_MAC) destination MAC-addr -t : ($THREADS) threads to start -c : ($SKB_CLONE) SKB clones send before alloc new SKB -b : ($BURST) HW level bursting of SKBs -v : ($VERBOSE) verbose -x : ($DEBUG) debug The global variable being set is also listed. E.g. the required interface/device parameter "-i" sets variable $DEV. Common functions ---------------- The functions.sh file provides; Three different shell functions for configuring the different components of pktgen: pg_ctrl(), pg_thread() and pg_set(). These functions correspond to pktgens different components. * pg_ctrl() control "pgctrl" (/proc/net/pktgen/pgctrl) * pg_thread() control the kernel threads and binding to devices * pg_set() control setup of individual devices See sample scripts for usage examples.
{ "pile_set_name": "Github" }
// // Licensed under the terms in License.txt // // Copyright 2010 Allen Ding. All rights reserved. // #import "Carrier.h" #import "Cruiser.h" #import "Engine.h" #import "Fighter.h" #import "JumpCapable.h" #import "OrbitCapable.h" #import "SpaceShip.h" #import "TestReporter.h" #import "TestSpy.h" #import "TestVerifier.h" #import "Robot.h" #import "Galaxy.h" #import "StringPrefixMatcher.h"
{ "pile_set_name": "Github" }