repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
zhangyin2088/Teamcat
teamcat_service/docker_build/target/one_step_build/teamcat/doraemon/project/urlrouter/project_dashboard_urls.py
<reponame>zhangyin2088/Teamcat #coding=utf-8 # coding=utf-8 ''' Created on 2014-1-5 @author: ETHAN ''' from django.conf.urls import url from doraemon.project.views.project_dashboard_view import index_list,more_activites dashboard_router=[url(r"(\d{1,6})/dashboard/$",index_list), url(r"(\d{1,6})/dashboard/more_activites",more_activites)]
jcleng/nix-kangle-3.5.13.2
src/src/KReplaceIPMark.h
<filename>src/src/KReplaceIPMark.h #ifndef KREPLACEIPMARK_H #define KREPLACEIPMARK_H #include "KMark.h" class KReplaceIPMark : public KMark { public: KReplaceIPMark() { header = "X-Real-Ip"; val = NULL; } ~KReplaceIPMark() { if (val) { delete val; } } bool mark(KHttpRequest *rq, KHttpObject *obj, const int chainJumpType, int &jumpType) { KHttpHeader *h = rq->parser.headers; KHttpHeader *prev = NULL; while (h) { if (strcasecmp(h->attr, header.c_str()) == 0) { KRegSubString *sub = NULL; if (val) { sub = val->matchSubString(h->val, strlen(h->val), 0); } if (val == NULL || sub) { if (prev) { prev->next = h->next; } else { rq->parser.headers = h->next; } if (rq->client_ip) { free(rq->client_ip); } if (val == NULL) { rq->client_ip = h->val; } else { free(h->val); char *ip = sub->getString(1); if (ip) { rq->client_ip = strdup(ip); } } free(h->attr); free(h); if (TEST(rq->raw_url.flags,KGL_URL_ORIG_SSL)) { SET(rq->raw_url.flags,KGL_URL_SSL); } else { CLR(rq->raw_url.flags,KGL_URL_SSL); } return true; } } prev = h; h = h->next; } return true; } KMark *newInstance() { return new KReplaceIPMark; } const char *getName() { return "replace_ip"; } std::string getHtml(KModel *model) { std::stringstream s; s << "header:<input name='header' value='"; KReplaceIPMark *m = (KReplaceIPMark *)model; if (m) { s << m->header; } else { s << "X-Real-Ip"; } s << "'>"; s << "val(regex):<input name='val' value='"; if (m && m->val) { s << m->val->getModel(); } s << "'>"; return s.str(); } std::string getDisplay() { std::stringstream s; s << header; if (val) { s << ":" << val->getModel(); } return s.str(); } void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException) { header = attribute["header"]; std::string val = attribute["val"]; if (this->val) { delete this->val; this->val = NULL; } if (!val.empty()) { this->val = new KReg; this->val->setModel(val.c_str(), PCRE_CASELESS); } } void buildXML(std::stringstream &s) { s << " header='" << header << "' "; if (val) { s << "val='" << KXml::param(val->getModel()) << "' "; } s << "> "; } private: std::string header; KReg *val; }; class KParentMark : public KMark { public: KParentMark() { memset(&upstream_sign, 0, sizeof(upstream_sign)); } ~KParentMark() { for (int i = 0; i < 2; i++) { if (upstream_sign[i].data) { free(upstream_sign[i].data); } } } bool mark(KHttpRequest *rq, KHttpObject *obj, const int chainJumpType, int &jumpType) { KHttpHeader *h = rq->parser.removeHeader("x-real-ip-sign"); if (h == NULL) { return false; } char *sign = strchr(h->val, '|'); if (sign == NULL) { free(h->attr); free(h->val); free(h); return false; } *sign = '\0'; bool matched = false; KMD5_CTX context; unsigned char digest[17]; char buf[33]; KMD5Init(&context); KMD5Update(&context, (unsigned char *)h->val, sign - h->val); for (int i = 0; i < 2; i++) { if (upstream_sign[i].data == NULL) { continue; } KMD5_CTX ctx2 = context; KMD5Update(&ctx2, (unsigned char *)upstream_sign[i].data, upstream_sign[i].len); KMD5Final(digest, &ctx2); make_digest(buf, digest); if (strcmp(buf, sign + 1) == 0) { matched = true; break; } } if (matched) { rq->ctx->parent_signed = true; char *hot = h->val; for (;;) { char *p = strchr(hot, ','); if (p) { *p = '\0'; } char *val = strchr(hot, '='); if (val) { *val = '\0'; val++; if (strcmp(hot, "ip") == 0) { if (rq->client_ip) { free(rq->client_ip); } rq->client_ip = strdup(val); } else if (strcmp(hot, "p") == 0) { if (strcmp(val, "https") == 0) { SET(rq->raw_url.flags, KGL_URL_SSL); } else { CLR(rq->raw_url.flags, KGL_URL_SSL); } } } if (p == NULL) { break; } hot = p + 1; } } free(h->attr); free(h->val); free(h); return matched; } KMark *newInstance() { return new KParentMark; } const char *getName() { return "parent"; } std::string getHtml(KModel *model) { std::stringstream s; s << "sign:<input name='sign' value='"; KParentMark *m = (KParentMark *)model; if (m) { for (int i = 0; i < 2; i++) { if (m->upstream_sign[i].data) { s.write(m->upstream_sign[i].data, m->upstream_sign[i].len); if (i == 0) { s << "|"; } } } } s << "'>"; return s.str(); } std::string getDisplay() { std::stringstream s; for (int i = 0; i < 2; i++) { if (upstream_sign[i].data) { s.write(upstream_sign[i].data, upstream_sign[i].len); if (i == 0) { s << "|"; } } } return s.str(); } void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException) { for (int i = 0; i < 2; i++) { if (this->upstream_sign[i].data) { free(this->upstream_sign[i].data); this->upstream_sign[i].data = NULL; } } char *upstream_sign = strdup(attribute["sign"].c_str()); char *hot = upstream_sign; for (int i = 0; i < 2; i++) { char *p = strchr(hot, '|'); if (p) { *p = '\0'; } this->upstream_sign[i].len = strlen(hot); if (this->upstream_sign[i].len > 0) { this->upstream_sign[i].data = strdup(hot); } if (p == NULL) { break; } hot = p + 1; } free(upstream_sign); } void buildXML(std::stringstream &s) { s << " sign='"; for (int i = 0; i < 2; i++) { if (upstream_sign[i].data) { s.write(upstream_sign[i].data, upstream_sign[i].len); if (i == 0) { s << "|"; } } } s << "'> "; } private: kgl_str_t upstream_sign[2]; }; class KSelfIPMark : public KMark { public: KSelfIPMark() { } bool mark(KHttpRequest *rq, KHttpObject *obj, const int chainJumpType, int &jumpType) { if (rq->bind_ip) { free(rq->bind_ip); rq->bind_ip = NULL; } if (ip.empty()) { char ip[MAXIPLEN]; rq->c->socket->get_self_ip(ip,sizeof(ip)); rq->bind_ip = strdup(ip); } else if (ip[0] == '$') { rq->bind_ip = strdup(rq->getClientIp()); } else if (ip[0] != '-') { rq->bind_ip = strdup(ip.c_str()); } return true; } KMark *newInstance() { return new KSelfIPMark; } const char *getName() { return "self_ip"; } std::string getHtml(KModel *model) { std::stringstream s; s << "ip:<input name='ip' value='"; KSelfIPMark *m = (KSelfIPMark *)model; if (m) { s << m->ip; } s << "'>"; return s.str(); } std::string getDisplay() { return ip; } void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException) { ip = attribute["ip"]; } void buildXML(std::stringstream &s) { s << " ip='" << ip << "'>"; } private: std::string ip; }; #endif
ShenQianwithC/HistomicsTK
packages/girder_worker/examples/plugin_example/gwexample/__init__.py
from girder_worker import GirderWorkerPluginABC class GWExamplePlugin(GirderWorkerPluginABC): def __init__(self, app, *args, **kwargs): self.app = app # Here we can also change application settings. E.g. # changing the task time limit: # # self.app.config.update({ # 'TASK_TIME_LIMIT': 300 # }) def task_imports(self): # Return a list of python importable paths to the # plugin's path directory return ['gwexample.analyses.tasks']
SoftReaper/Mesa-Renoir-deb
src/compiler/clc/clc.c
/* * Copyright © Microsoft Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "nir/nir.h" #include "nir/nir_serialize.h" #include "glsl_types.h" #include "nir_types.h" #include "clc.h" #include "clc_helpers.h" #include "spirv/nir_spirv.h" #include "util/u_debug.h" #include <stdlib.h> enum clc_debug_flags { CLC_DEBUG_DUMP_SPIRV = 1 << 0, CLC_DEBUG_VERBOSE = 1 << 1, }; static const struct debug_named_value clc_debug_options[] = { { "dump_spirv", CLC_DEBUG_DUMP_SPIRV, "Dump spirv blobs" }, { "verbose", CLC_DEBUG_VERBOSE, NULL }, DEBUG_NAMED_VALUE_END }; DEBUG_GET_ONCE_FLAGS_OPTION(debug_clc, "CLC_DEBUG", clc_debug_options, 0) static void clc_print_kernels_info(const struct clc_parsed_spirv *obj) { fprintf(stdout, "Kernels:\n"); for (unsigned i = 0; i < obj->num_kernels; i++) { const struct clc_kernel_arg *args = obj->kernels[i].args; bool first = true; fprintf(stdout, "\tvoid %s(", obj->kernels[i].name); for (unsigned j = 0; j < obj->kernels[i].num_args; j++) { if (!first) fprintf(stdout, ", "); else first = false; switch (args[j].address_qualifier) { case CLC_KERNEL_ARG_ADDRESS_GLOBAL: fprintf(stdout, "__global "); break; case CLC_KERNEL_ARG_ADDRESS_LOCAL: fprintf(stdout, "__local "); break; case CLC_KERNEL_ARG_ADDRESS_CONSTANT: fprintf(stdout, "__constant "); break; default: break; } if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_VOLATILE) fprintf(stdout, "volatile "); if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_CONST) fprintf(stdout, "const "); if (args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_RESTRICT) fprintf(stdout, "restrict "); fprintf(stdout, "%s %s", args[j].type_name, args[j].name); } fprintf(stdout, ");\n"); } } static void clc_libclc_optimize(nir_shader *s) { bool progress; do { progress = false; NIR_PASS(progress, s, nir_split_var_copies); NIR_PASS(progress, s, nir_opt_copy_prop_vars); NIR_PASS(progress, s, nir_lower_var_copies); NIR_PASS(progress, s, nir_lower_vars_to_ssa); NIR_PASS(progress, s, nir_copy_prop); NIR_PASS(progress, s, nir_opt_remove_phis); NIR_PASS(progress, s, nir_opt_dce); NIR_PASS(progress, s, nir_opt_if, true); NIR_PASS(progress, s, nir_opt_dead_cf); NIR_PASS(progress, s, nir_opt_cse); NIR_PASS(progress, s, nir_opt_peephole_select, 8, true, true); NIR_PASS(progress, s, nir_opt_algebraic); NIR_PASS(progress, s, nir_opt_constant_folding); NIR_PASS(progress, s, nir_opt_undef); NIR_PASS(progress, s, nir_lower_undef_to_zero); NIR_PASS(progress, s, nir_opt_deref); } while (progress); } struct clc_libclc { const nir_shader *libclc_nir; }; struct clc_libclc * clc_libclc_new(const struct clc_logger *logger, const struct clc_libclc_options *options) { struct clc_libclc *ctx = rzalloc(NULL, struct clc_libclc); if (!ctx) { clc_error(logger, "D3D12: failed to allocate a clc_libclc"); return NULL; } const struct spirv_to_nir_options libclc_spirv_options = { .environment = NIR_SPIRV_OPENCL, .create_library = true, .constant_addr_format = nir_address_format_32bit_index_offset_pack64, .global_addr_format = nir_address_format_32bit_index_offset_pack64, .shared_addr_format = nir_address_format_32bit_offset_as_64bit, .temp_addr_format = nir_address_format_32bit_offset_as_64bit, .float_controls_execution_mode = FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP32, .caps = { .address = true, .float64 = true, .int8 = true, .int16 = true, .int64 = true, .kernel = true, }, }; glsl_type_singleton_init_or_ref(); nir_shader *s = nir_load_libclc_shader(64, NULL, &libclc_spirv_options, options->nir_options); if (!s) { clc_error(logger, "D3D12: spirv_to_nir failed on libclc blob"); ralloc_free(ctx); return NULL; } if (options && options->optimize) clc_libclc_optimize(s); ralloc_steal(ctx, s); ctx->libclc_nir = s; return ctx; } void clc_free_libclc(struct clc_libclc *ctx) { ralloc_free(ctx); glsl_type_singleton_decref(); } const nir_shader *clc_libclc_get_clc_shader(struct clc_libclc *ctx) { return ctx->libclc_nir; } void clc_libclc_serialize(struct clc_libclc *context, void **serialized, size_t *serialized_size) { struct blob tmp; blob_init(&tmp); nir_serialize(&tmp, context->libclc_nir, true); blob_finish_get_buffer(&tmp, serialized, serialized_size); } void clc_libclc_free_serialized(void *serialized) { free(serialized); } struct clc_libclc * clc_libclc_deserialize(const void *serialized, size_t serialized_size) { struct clc_libclc *ctx = rzalloc(NULL, struct clc_libclc); if (!ctx) { return NULL; } glsl_type_singleton_init_or_ref(); struct blob_reader tmp; blob_reader_init(&tmp, serialized, serialized_size); nir_shader *s = nir_deserialize(NULL, NULL, &tmp); if (!s) { ralloc_free(ctx); return NULL; } ralloc_steal(ctx, s); ctx->libclc_nir = s; return ctx; } bool clc_compile_c_to_spir(const struct clc_compile_args *args, const struct clc_logger *logger, struct clc_binary *out_spir) { return clc_c_to_spir(args, logger, out_spir) >= 0; } void clc_free_spir(struct clc_binary *spir) { clc_free_spir_binary(spir); } bool clc_compile_spir_to_spirv(const struct clc_binary *in_spir, const struct clc_logger *logger, struct clc_binary *out_spirv) { if (clc_spir_to_spirv(in_spir, logger, out_spirv) < 0) return false; if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV) clc_dump_spirv(out_spirv, stdout); return true; } void clc_free_spirv(struct clc_binary *spirv) { clc_free_spirv_binary(spirv); } bool clc_compile_c_to_spirv(const struct clc_compile_args *args, const struct clc_logger *logger, struct clc_binary *out_spirv) { if (clc_c_to_spirv(args, logger, out_spirv) < 0) return false; if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV) clc_dump_spirv(out_spirv, stdout); return true; } bool clc_link_spirv(const struct clc_linker_args *args, const struct clc_logger *logger, struct clc_binary *out_spirv) { if (clc_link_spirv_binaries(args, logger, out_spirv) < 0) return false; if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV) clc_dump_spirv(out_spirv, stdout); return true; } bool clc_parse_spirv(const struct clc_binary *in_spirv, const struct clc_logger *logger, struct clc_parsed_spirv *out_data) { if (!clc_spirv_get_kernels_info(in_spirv, &out_data->kernels, &out_data->num_kernels, &out_data->spec_constants, &out_data->num_spec_constants, logger)) return false; if (debug_get_option_debug_clc() & CLC_DEBUG_VERBOSE) clc_print_kernels_info(out_data); return true; } void clc_free_parsed_spirv(struct clc_parsed_spirv *data) { clc_free_kernels_info(data->kernels, data->num_kernels); } bool clc_specialize_spirv(const struct clc_binary *in_spirv, const struct clc_parsed_spirv *parsed_data, const struct clc_spirv_specialization_consts *consts, struct clc_binary *out_spirv) { if (!clc_spirv_specialize(in_spirv, parsed_data, consts, out_spirv)) return false; if (debug_get_option_debug_clc() & CLC_DEBUG_DUMP_SPIRV) clc_dump_spirv(out_spirv, stdout); return true; }
frochet/pquic
picoquic/protoop.c
<reponame>frochet/pquic #include "protoop.h" protoop_id_t PROTOOP_PARAM_PARSE_FRAME = { .id = PROTOOPID_PARAM_PARSE_FRAME }; protoop_id_t PROTOOP_PARAM_PROCESS_FRAME = { .id = PROTOOPID_PARAM_PROCESS_FRAME }; protoop_id_t PROTOOP_PARAM_WRITE_FRAME = { .id = PROTOOPID_PARAM_WRITE_FRAME }; protoop_id_t PROTOOP_PARAM_NOTIFY_FRAME = { .id = PROTOOPID_PARAM_NOTIFY_FRAME }; protoop_id_t PROTOOP_PARAM_WRITE_TRANSPORT_PARAMETER = { .id = PROTOOPID_PARAM_WRITE_TRANSPORT_PARAMETER }; protoop_id_t PROTOOP_PARAM_PROCESS_TRANSPORT_PARAMETER = { .id = PROTOOPID_PARAM_PROCESS_TRANSPORT_PARAMETER }; protoop_id_t PROTOOP_NOPARAM_UPDATE_RTT = { .id = PROTOOPID_NOPARAM_UPDATE_RTT }; protoop_id_t PROTOOP_NOPARAM_SCHEDULE_FRAMES_ON_PATH = { .id = PROTOOPID_NOPARAM_SCHEDULE_FRAMES_ON_PATH }; protoop_id_t PROTOOP_NOPARAM_SCHEDULER_WRITE_NEW_FRAMES = { .id = PROTOOPID_NOPARAM_SCHEDULER_WRITE_NEW_FRAMES }; protoop_id_t PROTOOP_NOPARAM_PROCESS_ACK_RANGE = { .id = PROTOOPID_NOPARAM_PROCESS_ACK_RANGE }; protoop_id_t PROTOOP_NOPARAM_CHECK_SPURIOUS_RETRANSMISSION = { .id = PROTOOPID_NOPARAM_CHECK_SPURIOUS_RETRANSMISSION }; protoop_id_t PROTOOP_NOPARAM_PROCESS_POSSIBLE_ACK_OF_ACK_FRAME = { .id = PROTOOPID_NOPARAM_PROCESS_POSSIBLE_ACK_OF_ACK_FRAME }; protoop_id_t PROTOOP_NOPARAM_PROCESS_ACK_OF_ACK_RANGE = { .id = PROTOOPID_NOPARAM_PROCESS_ACK_OF_ACK_RANGE }; protoop_id_t PROTOOP_NOPARAM_PROCESS_ACK_OF_STREAM_FRAME = { .id = PROTOOPID_NOPARAM_PROCESS_ACK_OF_STREAM_FRAME }; protoop_id_t PROTOOP_NOPARAM_FIND_READY_STREAM = { .id = PROTOOPID_NOPARAM_FIND_READY_STREAM }; protoop_id_t PROTOOP_NOPARAM_SCHEDULE_NEXT_STREAM = { .id = PROTOOPID_NOPARAM_SCHEDULE_NEXT_STREAM }; protoop_id_t PROTOOP_NOPARAM_FIND_READY_PLUGIN_STREAM = { .id = PROTOOPID_NOPARAM_FIND_READY_PLUGIN_STREAM }; protoop_id_t PROTOOP_NOPARAM_IS_ACK_NEEDED = { .id = PROTOOPID_NOPARAM_IS_ACK_NEEDED }; protoop_id_t PROTOOP_NOPARAM_IS_TLS_STREAM_READY = { .id = PROTOOPID_NOPARAM_IS_TLS_STREAM_READY }; protoop_id_t PROTOOP_NOPARAM_CHECK_STREAM_FRAME_ALREADY_ACKED = { .id = PROTOOPID_NOPARAM_CHECK_STREAM_FRAME_ALREADY_ACKED }; protoop_id_t PROTOOP_NOPARAM_INCOMING_ENCRYPTED = { .id = PROTOOPID_NOPARAM_INCOMING_ENCRYPTED }; protoop_id_t PROTOOP_NOPARAM_GET_INCOMING_PATH = { .id = PROTOOPID_NOPARAM_GET_INCOMING_PATH }; protoop_id_t PROTOOP_NOPARAM_CONGESTION_ALGORITHM_NOTIFY = { .id = PROTOOPID_NOPARAM_CONGESTION_ALGORITHM_NOTIFY }; protoop_id_t PROTOOP_NOPARAM_ESTIMATE_PATH_BANDWIDTH = { .id = PROTOOPID_NOPARAM_ESTIMATE_PATH_BANDWIDTH }; protoop_id_t PROTOOP_NOPARAM_CALLBACK_FUNCTION = { .id = PROTOOPID_NOPARAM_CALLBACK_FUNCTION }; protoop_id_t PROTOOP_NOPARAM_PRINTF = { .id = PROTOOPID_NOPARAM_PRINTF }; protoop_id_t PROTOOP_NOPARAM_SNPRINTF = { .id = PROTOOPID_NOPARAM_SNPRINTF }; protoop_id_t PROTOOP_NOPARAM_CONNECTION_ERROR = { .id = PROTOOPID_NOPARAM_CONNECTION_ERROR }; protoop_id_t PROTOOP_NOPARAM_GET_DESTINATION_CONNECTION_ID = { .id = PROTOOPID_NOPARAM_GET_DESTINATION_CONNECTION_ID }; protoop_id_t PROTOOP_NOPARAM_SET_NEXT_WAKE_TIME = { .id = PROTOOPID_NOPARAM_SET_NEXT_WAKE_TIME }; protoop_id_t PROTOOP_NOPARAM_HAS_CONGESTION_CONTROLLED_PLUGIN_FRAMEMS_TO_SEND = { .id = PROTOOPID_NOPARAM_HAS_CONGESTION_CONTROLLED_PLUGIN_FRAMEMS_TO_SEND }; protoop_id_t PROTOOP_NOPARAM_RETRANSMIT_NEEDED = { .id = PROTOOPID_NOPARAM_RETRANSMIT_NEEDED }; protoop_id_t PROTOOP_NOPARAM_RETRANSMIT_NEEDED_BY_PACKET = { .id = PROTOOPID_NOPARAM_RETRANSMIT_NEEDED_BY_PACKET }; protoop_id_t PROTOOP_NOPARAM_PREDICT_PACKET_HEADER_LENGTH = { .id = PROTOOPID_NOPARAM_PREDICT_PACKET_HEADER_LENGTH }; protoop_id_t PROTOOP_NOPARAM_GET_CHECKSUM_LENGTH = { .id = PROTOOPID_NOPARAM_GET_CHECKSUM_LENGTH }; protoop_id_t PROTOOP_NOPARAM_DEQUEUE_RETRANSMIT_PACKET = { .id = PROTOOPID_NOPARAM_DEQUEUE_RETRANSMIT_PACKET }; protoop_id_t PROTOOP_NOPARAM_DEQUEUE_RETRANSMITTED_PACKET = { .id = PROTOOPID_NOPARAM_DEQUEUE_RETRANSMITTED_PACKET }; protoop_id_t PROTOOP_NOPARAM_PREPARE_PACKET_OLD_CONTEXT = { .id = PROTOOPID_NOPARAM_PREPARE_PACKET_OLD_CONTEXT }; protoop_id_t PROTOOP_NOPARAM_PREPARE_MTU_PROBE = { .id = PROTOOPID_NOPARAM_PREPARE_MTU_PROBE }; protoop_id_t PROTOOP_NOPARAM_PREPARE_STREAM_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_STREAM_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_PLUGIN_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_PLUGIN_FRAME }; protoop_id_t PROTOOP_NOPARAM_STREAM_BYTES_MAX = { .id = PROTOOPID_NOPARAM_STREAM_BYTES_MAX }; protoop_id_t PROTOOP_NOPARAM_STREAM_ALWAYS_ENCODE_LENGTH = { .id = PROTOOPID_NOPARAM_STREAM_ALWAYS_ENCODE_LENGTH }; protoop_id_t PROTOOP_NOPARAM_PREPARE_CRYPTO_HS_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_CRYPTO_HS_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_HANDSHAKE_DONE_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_HANDSHAKE_DONE_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_ACK_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_ACK_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_ACK_ECN_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_ACK_ECN_FRAME }; protoop_id_t PROTOOP_NOPARAM_PARSE_ECN_BLOCK = { .id = PROTOOPID_NOPARAM_PARSE_ECN_BLOCK }; protoop_id_t PROTOOP_NOPARAM_PROCESS_ECN_BLOCK = { .id = PROTOOPID_NOPARAM_PROCESS_ECN_BLOCK }; protoop_id_t PROTOOP_NOPARAM_WRITE_ECN_BLOCK = { .id = PROTOOPID_NOPARAM_WRITE_ECN_BLOCK }; protoop_id_t PROTOOP_NOPARAM_PREPARE_MAX_DATA_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_MAX_DATA_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_REQUIRED_MAX_STREAM_DATA_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_REQUIRED_MAX_STREAM_DATA_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_PATH_CHALLENGE_FRAME = { .id = PROTOOPID_NOPARAM_PREPARE_PATH_CHALLENGE_FRAME }; protoop_id_t PROTOOP_NOPARAM_SKIP_FRAME = { .id = PROTOOPID_NOPARAM_SKIP_FRAME }; protoop_id_t PROTOOP_NOPARAM_PREPARE_PACKET_READY = { .id = PROTOOPID_NOPARAM_PREPARE_PACKET_READY }; protoop_id_t PROTOOP_NOPARAM_RECEIVED_PACKET = { .id = PROTOOPID_NOPARAM_RECEIVED_PACKET }; protoop_id_t PROTOOP_NOPARAM_BEFORE_SENDING_PACKET = { .id = PROTOOPID_NOPARAM_BEFORE_SENDING_PACKET }; protoop_id_t PROTOOP_NOPARAM_RECEIVED_SEGMENT = { .id = PROTOOPID_NOPARAM_RECEIVED_SEGMENT }; protoop_id_t PROTOOP_NOPARAM_SEGMENT_PREPARED = { .id = PROTOOPID_NOPARAM_SEGMENT_PREPARED }; protoop_id_t PROTOOP_NOPARAM_SEGMENT_ABORTED = { .id = PROTOOPID_NOPARAM_SEGMENT_ABORTED }; protoop_id_t PROTOOP_NOPARAM_HEADER_PARSED = { .id = PROTOOPID_NOPARAM_HEADER_PARSED }; protoop_id_t PROTOOP_NOPARAM_HEADER_PREPARED = { .id = PROTOOPID_NOPARAM_HEADER_PREPARED }; protoop_id_t PROTOOP_NOPARAM_FINALIZE_AND_PROTECT_PACKET = { .id = PROTOOPID_NOPARAM_FINALIZE_AND_PROTECT_PACKET }; protoop_id_t PROTOOP_NOPARAM_PACKET_WAS_LOST = { .id = PROTOOPID_NOPARAM_PACKET_WAS_LOST }; protoop_id_t PROTOOP_NOPARAM_CONNECTION_STATE_CHANGED = { .id = PROTOOPID_NOPARAM_CONNECTION_STATE_CHANGED }; protoop_id_t PROTOOP_NOPARAM_STREAM_OPENED = { .id = PROTOOPID_NOPARAM_STREAM_OPENED }; protoop_id_t PROTOOP_NOPARAM_PLUGIN_STREAM_OPENED = { .id = PROTOOPID_NOPARAM_PLUGIN_STREAM_OPENED }; protoop_id_t PROTOOP_NOPARAM_STREAM_FLAGS_CHANGED = { .id = PROTOOPID_NOPARAM_STREAM_FLAGS_CHANGED }; protoop_id_t PROTOOP_NOPARAM_STREAM_CLOSED = { .id = PROTOOPID_NOPARAM_STREAM_CLOSED }; protoop_id_t PROTOOP_NOPARAM_FAST_RETRANSMIT = { .id = PROTOOPID_NOPARAM_FAST_RETRANSMIT }; protoop_id_t PROTOOP_NOPARAM_RETRANSMISSION_TIMEOUT = { .id = PROTOOPID_NOPARAM_RETRANSMISSION_TIMEOUT }; protoop_id_t PROTOOP_NOPARAM_TAIL_LOSS_PROBE = { .id = PROTOOPID_NOPARAM_TAIL_LOSS_PROBE }; protoop_id_t PROTOOP_NOPARAM_SELECT_SENDING_PATH = { .id = PROTOOPID_NOPARAM_SELECT_SENDING_PATH }; protoop_id_t PROTOOP_NOPARAM_NOPARAM_UNKNOWN_TP_RECEIVED = { .id = PROTOOPID_NOPARAM_UNKNOWN_TP_RECEIVED }; protoop_id_t PROTOOP_NOPARAM_UPDATE_ACK_DELAY = { .id = PROTOOPID_NOPARAM_UPDATE_ACK_DELAY }; protoop_id_t PROTOOP_NOPARAM_LOG_EVENT = { .id = PROTOOPID_NOPARAM_LOG_EVENT }; protoop_id_t PROTOOP_NOPARAM_LOG_FRAME = { .id = PROTOOPID_NOPARAM_LOG_FRAME }; protoop_id_t PROTOOP_NOPARAM_PUSH_LOG_CONTEXT = { .id = PROTOOPID_NOPARAM_PUSH_LOG_CONTEXT }; protoop_id_t PROTOOP_NOPARAM_POP_LOG_CONTEXT = { .id = PROTOOPID_NOPARAM_POP_LOG_CONTEXT }; protoop_id_t PROTOOP_NOPARAM_PEER_ADDRESS_CHANGED = { .id = PROTOOPID_NOPARAM_PEER_ADDRESS_CHANGED };
doits/mobility
spec/database.rb
<filename>spec/database.rb module Mobility module Test class Database class << self def connect(orm) case orm when 'active_record' ::ActiveRecord::Base.establish_connection config[driver] ::ActiveRecord::Migration.verbose = false if in_memory? # don't really need this, but let's return something relevant ::ActiveRecord::Base.connection when 'sequel' adapter = config[driver]['adapter'].gsub(/^sqlite3$/,'sqlite') user = config[driver]['username'] database = config[driver]['database'] ::Sequel.connect(adapter: adapter, database: database, username: user) end end def auto_migrate Schema.migrate :up if in_memory? end def config @config ||= YAML::load(File.open(File.expand_path("../databases.yml", __FILE__))) end def driver (ENV["DB"] or "sqlite3").downcase end def in_memory? config[driver]["database"] == ":memory:" end end end end end
MiccWan/dbux
samples/case-studies/async/producer_consumer/producer_consumer_cb.js
import { ConsumerBase, ProducerBase } from './producer_consumer_base'; const sleep = setTimeout; /** * */ function foreverCb(task) { function next() { return task(next); } return next(); } // ########################################################################### // Consumer // ########################################################################### class Consumer extends ConsumerBase { forever = foreverCb; sleep = sleep; consumeOrIdle = (next) => { if (this.canConsume()) { const idx = this.startConsume(); this.doWork(() => { this.finishConsume(idx); next(); }); } else { sleep(next); } } } // ########################################################################### // Producer // ########################################################################### class Producer extends ProducerBase { forever = foreverCb; sleep = sleep; produceOrIdle = (next) => { if (this.canProduce()) { this.startProduce(); this.doWork(() => { this.finishProduce(); next(); }); } else { sleep(next); } } } // main // start all producers + consumers new Producer().run(); new Producer().run(); new Consumer().run(); new Consumer().run();
Neusoft-Technology-Solutions/aws-sdk-cpp
aws-cpp-sdk-appflow/include/aws/appflow/model/ConnectionMode.h
<filename>aws-cpp-sdk-appflow/include/aws/appflow/model/ConnectionMode.h /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/appflow/Appflow_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Appflow { namespace Model { enum class ConnectionMode { NOT_SET, Public, Private }; namespace ConnectionModeMapper { AWS_APPFLOW_API ConnectionMode GetConnectionModeForName(const Aws::String& name); AWS_APPFLOW_API Aws::String GetNameForConnectionMode(ConnectionMode value); } // namespace ConnectionModeMapper } // namespace Model } // namespace Appflow } // namespace Aws
inepex/ineform
ineframe/src/main/java/com/inepex/ineFrame/server/di/guice/DefaultApplicationLangs.java
<reponame>inepex/ineform<filename>ineframe/src/main/java/com/inepex/ineFrame/server/di/guice/DefaultApplicationLangs.java<gh_stars>1-10 package com.inepex.ineFrame.server.di.guice; import java.util.Arrays; import java.util.Collection; import com.google.inject.Inject; import com.inepex.ineFrame.client.i18n.IneFrameI18n; import com.inepex.inei18n.server.ApplicationLangs; import com.inepex.inei18n.server.I18nModuleConverter; public class DefaultApplicationLangs implements ApplicationLangs { private final Collection<String> langs; @Inject DefaultApplicationLangs() { langs = Arrays.asList(new I18nModuleConverter(IneFrameI18n.class).getModuleLanguages()); } @Override public Collection<String> getLangs() { return langs; } }
aulonm/okr-tracker
src/router/router-guards/user.js
<gh_stars>10-100 import { db } from '@/config/firebaseConfig'; import store from '@/store'; const { state } = store; export default async function RouterGuardUser(to, from, next) { const { id } = to.params; if (!id) { next(); } else { try { const { exists } = await db.collection('users').doc(id).get(); if (!exists) throw new Error(); next(); } catch (e) { if (!state.user) { next({ name: 'Login', query: { redirectFrom: to.fullPath }, }); } else { next({ name: 'Not found' }); } } } }
atviriduomenys/spinta
spinta/types/object/link.py
<reponame>atviriduomenys/spinta from spinta import commands from spinta.components import Context from spinta.types.datatype import Object from spinta.types.helpers import set_dtype_backend @commands.link.register(Context, Object) def link(context: Context, dtype: Object) -> None: set_dtype_backend(dtype) for prop in dtype.properties.values(): commands.link(context, prop.dtype)
BKJang/YourHome
front/src/redux/modules/releaseList.js
import { createAction, handleActions } from 'redux-actions'; import { pender } from 'redux-pender'; import * as releaseAPI from '../../lib/api/releaseList'; import { Map, List } from 'immutable'; const CHANGE_CURRENTID = 'orderList/CHANGE_CURRENTID'; //Nav 위치 변경 const CHANGE_CUSTNO = 'orderList/CHANGE_CURRENTNO'; //RELEAST 리스트 위치변경 const CHANGE_STARTDATE = 'orderList/CHANGE_STARTDATE'; //STARTDATE 변경 const CHANGE_ENDDATE = 'orderList/CHANGE_ENDDATE'; //ENDDATE 변경 const GET_STORE_LIST = 'release/GET_STORE_LIST'; // 매장 목록 가져오기 const GET_ORDER_LIST = 'release/GET_ORDER_LIST'; // 해당 매장의 전체 주문 목록 가져오기 const GET_ORDER_DATA = 'release/GET_ORDER_DATA'; // 해당 매장의 주문 상세 정보 가져오기 const DELETE_ORDER_DATA = 'release/DELETE_ORDER_DATA'; export const updateCurrentId = createAction(CHANGE_CURRENTID); export const updateCustNo = createAction(CHANGE_CUSTNO); export const updateStartDate = createAction(CHANGE_STARTDATE); export const updateEndDate = createAction(CHANGE_ENDDATE); export const getStoreList = createAction(GET_STORE_LIST, releaseAPI.getStoreList); export const getOrderList = createAction(GET_ORDER_LIST, releaseAPI.getOrderList); export const getOrderData = createAction(GET_ORDER_DATA, releaseAPI.getOrderData); export const deleteOrderData = createAction(DELETE_ORDER_DATA, releaseAPI.deleteOrderData); // 초기값 설정 const initialState = Map({ releaseList: Map({ init: Map({ _id: '', branchCode: '', branchName: '', name: '', id: '', cName: '', bNumber: '', bAddress: '', email: '', pNumber: '' }), form: Map({ _id: '', branchCode: '', branchName: '', name: '', id: '', cName: '', bNumber: '', bAddress: '', email: '', pNumber: '' }), error: null, store: [], currentId: '', custNo: '', startDate: new Date(), endDate: new Date(), list: List([ Map({ _id: '', branchCode: '', branchName: '', items: List([ Map({ itemCode: '', itemName: '', itemCount: '', itemCost: '', itemVolume: '', itemDepth: '' }) ]), updateAt: '' }) ]) }), result: Map({}) }); export default handleActions( { [CHANGE_CURRENTID]: (state, action) => { return state.setIn(['releaseList', 'currentId'], action.payload); }, [CHANGE_CUSTNO]: (state, action) => { return state.setIn(['releaseList', 'custNo'], action.payload); }, [CHANGE_STARTDATE]: (state, action) => { return state.setIn(['releaseList', 'startDate'], action.payload); }, [CHANGE_ENDDATE]: (state, action) => { return state.setIn(['releaseList', 'endDate'], action.payload); }, ...pender({ type: GET_STORE_LIST, onSuccess: (state, action) => { console.log(action.payload.data); return state .setIn(['releaseList', 'store'], action.payload.data) .setIn(['releaseList', 'currentId'], action.payload.data[0].branchCode); } }), ...pender({ type: GET_ORDER_LIST, onSuccess: (state, action) => state .setIn(['releaseList', 'list'], action.payload.data) .setIn(['releaseList', 'custNo'], action.payload.data[0]._id) }), ...pender({ type: GET_ORDER_DATA, onSuccess: (state, action) => state.setIn(['releaseList', 'form'], Map(action.payload.data)) }), ...pender({ type: DELETE_ORDER_DATA, onSuccess: (state, action) => state.set('result', Map(action.payload.data)) }) }, initialState );
pavaniuriti2000/python_files
challenge.py
#challenge in making_complex_decisions tax = 0 total = 0 country = input("Enter what country you are from :") country = country.lower() total = float(input("Enter total ")) if country == "canada": province = input("Enter your province ") province = province.lower() if province == "alberta": tax = (0.05 * total) elif province == "ontaria" or province == "nova scotia": tax = (0.13 * total) else: tax = (0.05 * total) + (0.06 * total) else : tax = 0 total = total +tax print("Your tax amount is $%.2f" %tax) print("Your total amount is $%.2f" %total)
WarpCloud/WALM
pkg/models/release/metainfo_resource_types.go
package release import ( "github.com/tidwall/gjson" "github.com/sirupsen/logrus" "strconv" "fmt" "encoding/json" "WarpCloud/walm/pkg/k8s/utils" ) type MetaResourceMemoryConfig struct { IntConfig } func (config *MetaResourceMemoryConfig) BuildDefaultValue(jsonStr string) { config.DefaultValue = config.BuildMemoryConfigValue(jsonStr) } func (config *MetaResourceMemoryConfig) BuildMemoryConfigValue(jsonStr string) int64 { strValue := getResourceStr(jsonStr, config.MapKey) if strValue == "" { return 0 } return utils.ParseK8sResourceMemory(strValue) } func getResourceStr(jsonStr, mapKey string) string { if jsonStr == "" || mapKey == "" { return "" } return gjson.Get(jsonStr, mapKey).String() } type MetaResourceCpuConfig struct { FloatConfig } func (config *MetaResourceCpuConfig) BuildDefaultValue(jsonStr string) { config.DefaultValue = config.BuildCpuConfigValue(jsonStr) } func (config *MetaResourceCpuConfig) BuildCpuConfigValue(jsonStr string) float64 { strValue := getResourceStr(jsonStr, config.MapKey) if strValue == "" { return 0 } return utils.ParseK8sResourceCpu(strValue) } type ResourceStorage struct { AccessModes []string `json:"accessModes, omitempty" description:"storage access modes"` StorageClass string `json:"storageClass" description:"storage class"` } type MetaResourceStorage struct { ResourceStorage Size int64 `json:"size" description:"storage size"` } type MetaResourceStorageWithStringSize struct { ResourceStorage Size string `json:"size" description:"storage size"` } type MetaResourceStorageConfig struct { Name string `json:"name" description:"config name"` MapKey string `json:"mapKey" description:"config map values.yaml key"` DefaultValue *MetaResourceStorage `json:"defaultValue" description:"default value of mapKey"` Description string `json:"description" description:"config description"` Type string `json:"type" description:"config type"` Required bool `json:"required" description:"required"` } type MetaConfigTestSet struct { MapKey string `json:"mapKey" description:"config map values.yaml key"` Type string `json:"type" description:"config type"` Required bool `json:"required" description:"required"` } func (config *MetaResourceStorageConfig) BuildDefaultValue(jsonStr string) { config.DefaultValue = config.BuildStorageConfigValue(jsonStr).Value } func (config *MetaResourceStorageConfig) BuildStorageConfigValue(jsonStr string) *MetaResourceStorageConfigValue { resourceStorageConfigValue := &MetaResourceStorageConfigValue{ Name: config.Name, } resourceStorageWithStringSize := parseResourceStorageWithStringSize(jsonStr, config.MapKey) if resourceStorageWithStringSize != nil { resourceStorageConfigValue.Value = &MetaResourceStorage{ ResourceStorage: resourceStorageWithStringSize.ResourceStorage, } if resourceStorageWithStringSize.Size != "" { resourceStorageConfigValue.Value.Size = utils.ParseK8sResourceStorage(resourceStorageWithStringSize.Size) } } return resourceStorageConfigValue } func parseResourceStorageWithStringSize(jsonStr, mapKey string) *MetaResourceStorageWithStringSize { rawMsg := gjson.Get(jsonStr, mapKey).Raw if rawMsg == "" { return nil } resourceStorage := &MetaResourceStorageWithStringSize{} err := json.Unmarshal([]byte(rawMsg), resourceStorage) if err != nil { logrus.Warnf("failed to unmarshal %s : %s", rawMsg, err.Error()) return nil } return resourceStorage } func convertResourceBinaryIntByUnit(i *int64, unit string) string { return strconv.FormatInt(*i, 10) + unit } func convertResourceDecimalFloat(f *float64) string { return fmt.Sprintf("%g", *f) }
veriKami/ePF_API_doc
ePF_API_doxy-0.2.x-dev/html/classep___senator.js
<filename>ePF_API_doxy-0.2.x-dev/html/classep___senator.js var classep___senator = [ [ "__toString", "classep___senator.html#a7516ca30af0db3cdbf9a7739b48ce91d", null ], [ "getDataStruct", "classep___senator.html#a79dabf680e30ee6e62508a8df24ed243", null ], [ "komisje", "classep___senator.html#a66895e14014726b555618e5b409771bd", null ], [ "oswiadczenia_majatkowe", "classep___senator.html#ab7a97df64d38268bc2d006b6666d0275", null ], [ "rejestr_korzysci", "classep___senator.html#a6c022f0121768edc931338ecb59e0dca", null ], [ "wystapienia", "classep___senator.html#a18b1bf1c04262c23e5edc5c81a4f897c", null ], [ "zespoly_parlamentarne", "classep___senator.html#acf90e2692da0f334ab0dfce03e3a9e7a", null ], [ "zespoly_senackie", "classep___senator.html#ae0fd986698b921926b3d3f6f3c6fd674", null ], [ "$_aliases", "classep___senator.html#ab4e31d75f0bc5d512456911e5d01366b", null ], [ "$_field_init_lookup", "classep___senator.html#a4a4d54ae35428077a7c61ec8a5139af3", null ] ];
ehsk/CHF-TopoResolver
src/main/java/tr/util/db/BatchExecutor.java
package tr.util.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.function.Consumer; /** * Created with IntelliJ IDEA. * User: user * Date: 11/11/2016 * Time: 2:26 PM */ public class BatchExecutor { private final String sql; private final int maxBatchSize; private final ConnectionSupplier connectionSupplier; private PreparedStatement pstmt = null; private int batchSize = 0; public BatchExecutor(ConnectionSupplier connectionSupplier, int maxBatchSize, String sql) { this.connectionSupplier = connectionSupplier; this.maxBatchSize = maxBatchSize; this.sql = sql; } public void addBatch(Consumer<PreparedStatement> parameterConsumer) throws SQLException { if (pstmt == null) { initPreparedStatement(connectionSupplier); } parameterConsumer.accept(pstmt); pstmt.addBatch(); if (++batchSize % maxBatchSize == 0) { executeBatch(); initPreparedStatement(connectionSupplier); } } private void executeBatch() throws SQLException { if (pstmt != null) { pstmt.executeBatch(); pstmt.getConnection().commit(); pstmt.close(); pstmt.getConnection().close(); } } private void initPreparedStatement(ConnectionSupplier connectionSupplier) throws SQLException { final Connection conn = connectionSupplier.get(); pstmt = conn.prepareStatement(sql); } public void finalizeBatch() throws SQLException { executeBatch(); } public interface ConnectionSupplier { Connection get() throws SQLException; } }
NASA-AMMOS/MGViz
scripts/essence/Tools/FileManager/FileManagerTool.js
<gh_stars>1-10 define([ 'Layers_', 'jquery', 'd3', 'Formulae_', 'Map_', 'Globe_', 'Login', 'CursorInfo', 'shp', 'mark', ], function(L_, $, d3, F_, Map_, Globe_, Login, CursorInfo, shp) { var userfiles = {} // prettier-ignore var markup = [ "<div id='fileManagerTool' style='display: inline-flex; white-space: nowrap; justify-content: flex-start; padding: 5px;'>", "<div id='fileManagerToolBar' style='width: 30px;'>", "<div id='fileManagerToolBarTools' class='mmgisRadioBarVertical'>", "<div id='fileManagerToolBarAllFiles' title='All Files' class='active'><i class='mdi mdi-folder mdi-24px' style='position: absolute;'></i></div>", "<div id='fileManagerToolBarMyFiles' title='My Files'><i class='mdi mdi-folder-account mdi-24px' style='position: absolute;'></i></div>", "</div>", "<div id='fileManagerToolBarTools' class='mmgisRadioBarVertical' style='padding-top: 25px;'>", "<div id='fileManagerToolBarAdd' title='New File'><i class='mdi mdi-file-plus mdi-24px' style='position: absolute;'></i></div>", "<div id='fileManagerToolBarUpload' title='Upload'><i class='mdi mdi-upload mdi-24px' style='position: absolute;'></i></div>", "<input id='fileManagerUpload' title='Upload' type=file name='files[]' size=30 style='opacity: 0; height: 27px; width: 30px; position: relative; top: -33px;' multiple>", "<div id='fileManagerToolDownload' title='Download'><i class='mdi mdi-download mdi-24px' style='position: relative; top: -33px;'></i></div>", "</div>", "<div id='fileManagerToolBarTools' class='mmgisRadioBarVertical' style='margin-top: -13px;'>", "<div id='fileManagerToolBarRefresh' title='Refresh'><i class='mdi mdi-refresh mdi-24px' style='position: absolute;'></i></div>", "<div id='fileManagerToolBarAllOff' title='All Off'><i class='mdi mdi-layers-off mdi-24px' style='position: absolute;'></i></div>", "</div>", "</div>", "<div id='fileManagerContent' style='padding: 0px 5px; display: inline-flex;'>", "<div id='fileManagerContentFiles' style='width: 250px;'>", "<div id='fmcfHeader' class='ui action inverted input'>", "<input id='fileManagerContentSearch' type='text' placeholder='Search' style='padding: 0px 0px 6px 0px; font-size: 14px; background-color: transparent; color: white;' value=''></input>", "</div>", "<ul id='fmcfList' class='mmgisScrollbar' style='list-style-type: none; padding: 0; margin: 0; height: 220px; overflow-y: auto;'></ul>", "</div>", "<div id='fileManagerContentProperties' style='width: 250px; margin-left: 7px;'>", "</div>", "</div>", "</div>" ]; var FileManagerTool = { height: 250, width: 293, widths: [293, 552], lastShowUserFiles: true, filterString: '', activeFileId: null, container: null, buttonCont: null, userCont: null, fileCont: null, optionCont: null, activeoptions: { user: null, filename: null }, init: function() { markup = markup.join('\n') }, make: function(TC_) { this.T_ = TC_ var tools = d3.select('#tools') tools.selectAll('*').remove() tools = tools .append('div') .attr('class', 'ui padded grid mmgisScrollbar') .style('height', '100%') tools.html(markup) setupInterface() //setupInterfaceOLD(); $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/getalluserswithfiles.php', data: { master: L_.masterdb, mission: L_.mission, username: Login.username, }, success: function(data) { userfiles = JSON.parse(data) if (Array.isArray(userfiles)) { userfiles = {} } if ( Login.username && !userfiles.hasOwnProperty(Login.username) ) { userfiles[Login.username] = {} } //buildFromUserFiles(); showUsersFiles(true) }, }) }, destroy: function() {}, moveTo: function(div) {}, } function setupInterface() { FileManagerTool.fileCont = d3.select('#fmcfList') FileManagerTool.optionCont = d3.select('#fileManagerContentProperties') //All Files $('#fileManagerToolBarAllFiles').on('click', function() { $(this).addClass('active') $('#fileManagerToolBarMyFiles').removeClass('active') showUsersFiles(true) }) //My Files $('#fileManagerToolBarMyFiles').on('click', function() { if (Login.username) { $(this).addClass('active') $('#fileManagerToolBarAllFiles').removeClass('active') showUsersFiles(Login.username) } else CursorInfo.update("You're not logged in.", 2500, true) }) //Search $('#fileManagerContentSearch').on('input', function() { FileManagerTool.filterString = $(this).val() showUsersFiles(FileManagerTool.lastShowUserFiles) }) //Upload $('#fileManagerUpload').on('change', function(evt) { var files = evt.target.files // FileList object // use the 1st file from the list var f = files[0] var ext = F_.getExtension(f.name).toLowerCase() switch (ext) { case 'shp': case 'dbf': var shpFile var dbfFile for (var i = 0; i < files.length; i++) { if ( F_.getExtension(files[i].name).toLowerCase() == 'shp' ) shpFile = files[i] if ( F_.getExtension(files[i].name).toLowerCase() == 'dbf' ) dbfFile = files[i] } if (shpFile && dbfFile) { var shpBuffer var dbfBuffer var readerSHP = new FileReader() readerSHP.onload = function(e) { shpBuffer = e.target.result var readerDBF = new FileReader() readerSHP.onload = function(e) { dbfBuffer = e.target.result bothLoaded() } readerSHP.readAsArrayBuffer(dbfFile) } readerSHP.readAsArrayBuffer(shpFile) function bothLoaded() { var featureArray = [] shp.open(shpBuffer, dbfBuffer) .then(source => source.read().then(function log(result) { if (result.done) { var geojsonResult = F_.getBaseGeoJSON() geojsonResult.Features = featureArray createFile(f.name, geojsonResult) return } featureArray.push( F_.geoJSONFeatureMetersToDegrees( result.value ) ) return source.read().then(log) }) ) .catch(error => console.error(error.stack)) } } else { console.warn( 'Warning! FileManager - missing .shp or .dbf' ) } break default: var reader = new FileReader() // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { createFile(theFile.name, e.target.result) } })(f) // Read in the image file as a data URL. reader.readAsText(f) } }) //Other $('#fileManagerToolBarAdd').on('click', createFile) $('#fileManagerToolDownload').on('click', downloadThisFile) $('#fileManagerToolBarRefresh').on('click', refreshAllFiles) $('#fileManagerToolBarAllOff').on('click', removeAllFiles) } function setupInterfaceOLD() { FileManagerTool.container = d3 .select('#tools') .append('div') .attr('class', 'ui padded grid unselectable') .style('padding-bottom', '12px') .style('height', '100%') FileManagerTool.buttonCont = FileManagerTool.container .append('div') .attr('class', 'two wide column') .style('border-right', '2px solid #00A3CC') .style('padding', '0px 7px 14px 7px') FileManagerTool.buttonCont = FileManagerTool.buttonCont .append('div') .style('text-align', 'center') FileManagerTool.buttonCont .append('div') .attr('id', 'fmMyFiles') .attr('class', 'mmgisButton') .style('width', '90%') .html('My Files') FileManagerTool.buttonCont .append('div') .attr('id', 'fmCreate') .attr('class', 'mmgisButton') .style('width', '90%') .html('Create') FileManagerTool.buttonCont .append('div') .attr('id', 'fmRefresh') .attr('class', 'mmgisButton') .style('width', '90%') .html('Refresh') FileManagerTool.buttonCont .append('div') .attr('id', 'fmRemoveAll') .attr('class', 'mmgisButton') .style('width', '90%') .html('Remove All') FileManagerTool.userCont = FileManagerTool.container .append('div') .attr('class', 'five wide column') .style('padding', '0px 7px 14px 7px') FileManagerTool.userCont .append('div') .style('font-size', '18px') .style('border-bottom', '2px solid #1f7493') .style('color', '#EEE') .html('Users') FileManagerTool.userCont = FileManagerTool.userCont .append('div') .attr('id', 'fmUserList') .attr('class', 'ui middle aligned selection list mmgisScrollbar') .style('margin-top', '0px') .style('overflow-y', 'auto') .style('height', '100%') FileManagerTool.fileCont = FileManagerTool.container .append('div') .attr('class', 'five wide column') .style('padding', '0px 7px 14px 7px') FileManagerTool.fileCont .append('div') .style('font-size', '18px') .style('border-bottom', '2px solid #1f7493') .style('color', '#EEE') .html('Files') FileManagerTool.fileCont = FileManagerTool.fileCont .append('div') .attr('id', 'fmFileList') .attr('class', 'ui middle aligned selection list mmgisScrollbar') .style('margin-top', '0px') .style('overflow-y', 'auto') .style('height', '100%') FileManagerTool.optionCont = FileManagerTool.container .append('div') .attr('class', 'four wide column') .style('padding', '0px 7px 14px 7px') FileManagerTool.optionCont .append('div') .style('font-size', '18px') .style('border-bottom', '2px solid #1f7493') .style('color', '#EEE') .html('Properties') FileManagerTool.optionCont = FileManagerTool.optionCont .append('div') .attr('class', 'mmgisScrollbar') .style('overflow-y', 'auto') .style('height', '100%') $('#fmCreate').on('click', createFile) $('#fmRefresh').on('click', refreshAllFiles) $('#fmRemoveAll').on('click', removeAllFiles) } function buildFromUserFiles() { for (var u in userfiles) { FileManagerTool.userCont .append('div') .attr('id', 'fmUser_' + u.replace(/[^\w\s]/gi, '_')) .attr('class', 'item customColor1') .style('border-bottom', '1px solid #666') .style('box-shadow', function() { return u == Login.username ? 'inset 0px 0px 0px 2px rgb(0, 163, 204)' : 'none' }) .style('background-color', '#171717') .style('border-radius', '0px') .on( 'click', (function(u) { return function() { $('#fmUserList .item').css({ 'background-color': '#171717', }) $( '#fmUserList #fmUser_' + u.replace(/[^\w\s]/gi, '_') ).css({ 'background-color': 'rgba(18, 66, 84, 0.9)', }) hideFilesOptions() showUsersFiles(u) } })(u) ) .append('div') .attr('class', 'content') .append('div') .attr('class', 'header') .style('color', '#CCC') .html(u) } $('#fmMyFiles').on('click', function() { if (Login.username) { $('#fmUser_' + Login.username.replace(/[^\w\s]/gi, '_')).click() } else { CursorInfo.update("You're not logged in.", 2500, true) } }) } //user is a user or is true for all users function showUsersFiles(user) { FileManagerTool.lastShowUserFiles = user FileManagerTool.fileCont.selectAll('*').remove() var subsetUserfiles = userfiles if (user !== true) { if (userfiles.hasOwnProperty(user)) { subsetUserfiles = [subsetUserfiles[user]] } else { subsetUserfiles = [] console.warn('User ' + user + ' not found!') } } for (var u in subsetUserfiles) { for (var f in subsetUserfiles[u]) { if ( FileManagerTool.filterString.length == 0 || subsetUserfiles[u][f].match( new RegExp(FileManagerTool.filterString, 'i') ) ) { var safeId = 'fmFile_' + (u + f).replace(/\w\s/gi, '_') var c = FileManagerTool.fileCont .append('li') .attr('id', safeId) .attr('class', 'item customColor1') .style('display', 'flex') .style('border-bottom', '1px solid #333') .style('background-color', 'rgba(0,0,0,0.25)') .style('border-radius', '0px') .style('height', '24px') .style('line-height', '24px') .style('cursor', 'pointer') c.append('div') .attr('class', 'content') .style('float', 'left') .style('flex', '1') .append('div') .attr('class', 'header') .style('max-width', '181px') .attr('title', u) .style('color', '#CCC') .html(subsetUserfiles[u][f]) .on( 'click', (function(u, f, safeId) { return function() { $('#fmcfList .item').css({ 'background-color': 'rgba(0,0,0,0.25)', }) if ( FileManagerTool.activeFileId != safeId ) { $('#fmcfList #' + safeId).css({ 'background-color': 'rgba(7,144,173,0.55)', }) getFileOptions(u, f) FileManagerTool.activeFileId = safeId } else { FileManagerTool.T_.setToolWidth( FileManagerTool.widths[0] ) hideFilesOptions() FileManagerTool.activeFileId = null } } })(user !== true ? user : u, f, safeId) ) //Mark $('#' + safeId).unmark({ done: function() { if (FileManagerTool.filterString.length > 0) $('#' + safeId).markRegExp( new RegExp( FileManagerTool.filterString, 'i' ), {} ) }, }) var b = c .append('div') .attr('class', 'mmgisRadioBar') .style('height', '16px') .style('float', 'right') b.append('div') .attr('id', 'fmFileAdd_' + f.replace(/\w\s/gi, '_')) .style('margin', '0') .style('margin-top', '3px') .style('height', '16px') .style('line-height', '16px') .style( 'background-color', L_.addedfiles.hasOwnProperty(f) && L_.addedfiles[f]['layer'] != null ? '#dfebef' : '#111' ) .html( L_.addedfiles.hasOwnProperty(f) && L_.addedfiles[f]['layer'] != null ? 'on' : 'off' ) .on( 'click', (function(u, f) { return function() { if ( L_.addedfiles.hasOwnProperty(f) && L_.addedfiles[f]['layer'] != null ) { removeFile(u, f) } else { addFile(u, f) } } })(user !== true ? user : u, f) ) } } } } function getFileOptions(u, f) { $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/getproperties.php', data: { master: L_.masterdb, mission: L_.mission, filename: f }, success: function(data) { data = JSON.parse(data)[0] if (Login.username == u) userfiles[Login.username][data['filename']] = data['name'] showFilesOptions(u, f, data) }, }) } function showFilesOptions(u, f, data) { hideFilesOptions() FileManagerTool.T_.setToolWidth(FileManagerTool.widths[1]) FileManagerTool.activeoptions.user = u FileManagerTool.activeoptions.filename = f var defaultName = userfiles[u][f] var nameChanged = false var defaultPublicity = data['public'] var publicityChanged = false var defaultDescription = data['description'] var descriptionChanged = false var c = FileManagerTool.optionCont .append('div') .style('display', 'flex') .style('flex-flow', 'column') .style('width', '100%') var name = c .append('div') .attr('class', 'ui inverted input') .style('position', 'inherit') //.style( 'margin', function() { return ( u == Login.username ) ? '8px 0px 8px 0px' : '8px auto 8px auto'; } ) .style('width', '100%') .style('display', 'inline-flex') .style('white-space', 'nowrap') .style('text-align', 'left') name.append('input') .attr('id', 'fmName') .attr('type', 'text') .attr('value', defaultName) .style('background-color', 'transparent') .style('width', '140px') .style('padding', '0px 0px 6px 0px') .style('font-size', '14px') .style('margin', '0') .style('color', 'white') name.append('div') .style('width', 'calc( 100% - 140px )') .style('padding', '0px 0px 6px 0px') .style('white-space', 'nowrap') .style('display', 'block') .style('overflow', 'hidden') .style('text-overflow', 'ellipsis') .style('text-align', 'right') .style('font-style', 'italic') .style('color', '#ddd') .attr('title', u) .html('by ' + u) var desc = c .append('div') .attr('class', 'field') .style('text-align', 'center') desc.append('textarea') .attr('id', 'fmDescription') .attr('class', 'mmgisScrollbar') .attr('rows', '7') .style('resize', 'vertical') .style('width', '100%') .style('background-color', '#111') .style('margin', '0') .style('border', '1px solid #666') .style('color', '#CCC') .html(defaultDescription) if (u == Login.username) { var pubdown = c.append('div').style('display', 'inline-block') var publicity = pubdown .append('div') .attr('id', 'fmPublicity') .attr('class', 'mmgisRadioBar') .style('display', 'inline-block') .style('white-space', 'nowrap') .style('margin', '0px 0px 4px 0px') .style('text-align', 'center') publicity .append('div') .attr('class', function() { return data['public'] == '1' ? 'active' : '' }) .html('Public') publicity .append('div') .attr('class', function() { return data['public'] == '0' ? 'active' : '' }) .html('Private') var savedel = c.append('div').style('display', 'inline-block') var save = savedel .append('div') .attr('id', 'fmSaveChanges') .attr('class', 'mmgisButton') .style('display', 'inline-block') .style('white-space', 'nowrap') .style('margin-left', '0px') .style('margin-right', '0px') .style('width', '180px') .style('text-align', 'center') .html('Save Changes') $('#fmSaveChanges').on('click', saveProperties) var del = savedel .append('div') .attr('id', 'fmDelete') .attr('class', 'mmgisButton') .style('display', 'inline-block') .style('white-space', 'nowrap') .style('margin-left', '0px') .style('margin-right', '0px') .style('width', 'calc( 100% - 184px )') .style('text-align', 'center') .html('Delete') var areyousure = c .append('div') .attr('id', 'fmDeletePopup') .attr('class', 'ui inverted popup transition hidden') .attr('data-variation', 'basic') .style( 'background', 'linear-gradient( to right, #5E1824, #1B1C1D )' ) .html('Are you sure? ') areyousure .append('div') .attr('class', 'mmgisButton') .html('yes') .on('click', deleteFile) areyousure .append('div') .attr('class', 'mmgisButton') .html('no') .on('click', function() { $('#fmDelete').popup('hide') }) $('#fmDelete').popup({ popup: $('#fmDeletePopup'), on: 'click', hoverable: true, position: 'left center', }) } //highlight save changes if values are different than defaults $('#fmName').on('input', function() { if ($(this).val() != defaultName) { $('#fmSaveChanges').css({ 'border-color': '#33cc66', color: '#26d962', }) nameChanged = true } else { nameChanged = false resetSaveColor() } }) $('#fmDescription').on('input', function() { if ($(this).val() != defaultDescription) { $('#fmSaveChanges').css({ 'border-color': '#33cc66', color: '#26d962', }) descriptionChanged = true } else { descriptionChanged = false resetSaveColor() } }) $('.mmgisRadioBar#fmPublicity div').click(function() { $('.mmgisRadioBar#fmPublicity div').removeClass('active') $(this).addClass('active') if ( $(this) .html() .toLowerCase() == 'public' ) { if (defaultPublicity == '0') { $('#fmSaveChanges').css({ 'border-color': '#33cc66', color: '#26d962', }) publicityChanged = true } else { publicityChanged = false resetSaveColor() } } else { if (defaultPublicity == '0') { publicityChanged = false resetSaveColor() } else { $('#fmSaveChanges').css({ 'border-color': '#33cc66', color: '#26d962', }) publicityChanged = true } } }) function resetSaveColor() { if (!(nameChanged || descriptionChanged || publicityChanged)) { $('#fmSaveChanges').css({ 'border-color': '#666', color: '#999', }) } } } function hideFilesOptions() { FileManagerTool.optionCont.selectAll('*').remove() } function saveProperties() { var propname = $('#fmName').val() var propdescription = $('#fmDescription').val() var proppublic = $('#fmPublicity .active').html() if (proppublic.toLowerCase() == 'private') proppublic = 0 else proppublic = 1 $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/saveproperties.php', data: { master: L_.masterdb, mission: L_.mission, username: Login.username, filename: FileManagerTool.activeoptions.filename, name: propname, description: propdescription, public: proppublic, }, success: function(data) { if (data.toLowerCase().substring(0, 7) == 'success') { userfiles[Login.username][ FileManagerTool.activeoptions.filename ] = propname showUsersFiles(Login.username) $( '#fmFileList #fmFile_' + ( Login.username + FileManagerTool.activeoptions.filename ).replace(/ /g, '_') ).css({ 'background-color': 'rgba(18, 66, 84, 0.9)' }) getFileOptions( Login.username, FileManagerTool.activeoptions.filename ) } }, }) } //optional name, filedata function createFile(name, filedata) { if (typeof name !== 'string') name = undefined name = name || 'New File' filedata = filedata || '' if (filedata != '') { if (typeof filedata == 'string') filedata = JSON.parse(filedata) //Force features if (filedata.hasOwnProperty('Features')) { filedata.features = filedata.Features delete filedata.Features } //Add initial feature filedata.features.unshift({ type: 'Feature', properties: { boundingbox: [0, 0, 0, 0], fill: '#000' }, geometry: { type: 'Polygon', coordinates: [] }, }) filedata = F_.GeoJSONStringify(filedata) } if (!Login.username) { CursorInfo.update( 'You must be logged in to create files.', 2500, true ) return } if (canUserCreate(Login.username, name)) { $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/createfile.php', data: { master: L_.masterdb, mission: L_.mission, username: Login.username, name: name, filedata: filedata, }, success: function(data) { data = JSON.parse(data) if (data['status'] == 'success') { userfiles[Login.username][data['filename']] = name showUsersFiles(Login.username) $( '#fmFileList #fmFile_' + (Login.username + data['filename']).replace( / /g, '_' ) ).css({ 'background-color': 'rgba(18, 66, 84, 0.9)' }) getFileOptions(Login.username, data['filename']) } else { CursorInfo.update( 'Failed to create a new file.', 2500, true ) } }, }) } else { CursorInfo.update("You already have a '" + name + ".'", 2500, true) } } function downloadThisFile() { if ( !FileManagerTool.activeoptions.user || !FileManagerTool.activeoptions.filename ) { CursorInfo.update('Select a file before downloading.', 2500, true) return } var name = userfiles[FileManagerTool.activeoptions.user][ FileManagerTool.activeoptions.filename ] if (Login.username == FileManagerTool.activeoptions.user) $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/getfiledata.php', data: { master: L_.masterdb, mission: L_.mission, filename: FileManagerTool.activeoptions.filename, }, success: function(data) { if (data.length < 3) { delete L_.addedfiles[f] CursorInfo.update('No file data found.', 2500, true) return } //fine data = JSON.parse(JSON.parse(data)) if (data.hasOwnProperty('Features')) { Object.defineProperty( data, 'features', Object.getOwnPropertyDescriptor(data, 'Features') ) delete data['Features'] } F_.downloadObject(data, name) }, error: function(XMLHttpRequest, textStatus, errorThrown) { delete L_.addedfiles[f] CursorInfo.update('Failed to get file data.', 2500, true) }, }) else CursorInfo.update( 'You can only download your own files.', 2500, true ) } function canUserCreate(u, name) { if (userfiles.hasOwnProperty(u)) { for (f in userfiles[u]) { if (userfiles[u][f].toLowerCase() == name.toLowerCase()) { return false } } } return true } function deleteFile() { $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/deletefile.php', data: { master: L_.masterdb, mission: L_.mission, filename: FileManagerTool.activeoptions.filename, }, success: function(data) { data = JSON.parse(data) if (data['status'] == 'success') { delete userfiles[Login.username][ FileManagerTool.activeoptions.filename ] hideFilesOptions() $('#fmDelete').popup('hide') showUsersFiles(Login.username) } else { CursorInfo.update('Failed to delete file.', 2500, true) } }, }) } function addFile(u, f) { L_.addedfiles[f] = {} L_.addedfiles[f]['layer'] = 0 //0 means were trying to add L_.addedfiles[f]['name'] = userfiles[u][f] L_.addedfiles[f]['username'] = u $.ajax({ type: 'POST', url: 'scripts/essence/Tools/FileManager/getfiledata.php', data: { master: L_.masterdb, mission: L_.mission, filename: f }, success: function(data) { if (data.length < 3) { delete L_.addedfiles[f] CursorInfo.update('No file data found.', 2500, true) return } //fine data = JSON.parse(JSON.parse(data)) if (data.hasOwnProperty('Features')) { Object.defineProperty( data, 'features', Object.getOwnPropertyDescriptor(data, 'Features') ) delete data['Features'] } $('#fmFileAdd_' + f.replace(/ /g, '_')) .css({ 'background-color': '#dfebef' }) .html('on') //sort data so point features are always on top of lines and lines always on top of polygons F_.sortGeoJSONFeatures(data) L_.addedfiles[f]['layer'] = L.geoJson(data, { style: function(feature) { var props = feature.properties if (!props) props = {} return { color: 'black', radius: 6, opacity: props.opacity || 1, fillColor: props.fill || 'black', fillOpacity: props.fillOpacity || 0.5, color: props.stroke || 'black', weight: props.weight || 2, className: 'spePolygonLayer', pointerEvents: null, } }, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng) }, onEachFeature: function(feature, layer) { var props = feature.properties if (!props) props = {} var list = '<dl><dt><b>' + (props.name || '') + '</b></dt><dt>' + (props.description || '') + "</dt><hr style='border: 1px solid #666; margin-bottom: 2px;'><dt style='color: #888; font-size: 14px;'><i>" + userfiles[u][f] + "</i></dt><dt style='color: #888; font-size: 12px; text-align: right;'>–<i>" + u + '</i></dt></dl>' layer.bindPopup(list) }, }) L_.addedfiles[f]['layer'].addTo(Map_.map) Globe_.removeVectorTileLayer('addedfiles_' + f) Globe_.addVectorTileLayer({ id: 'addedfiles_' + f, layers: L_.addedfiles[f]['layer']._layers, }) }, error: function(XMLHttpRequest, textStatus, errorThrown) { delete L_.addedfiles[f] CursorInfo.update('Failed to get file data.', 2500, true) }, }) } function refreshAllFiles() { var addedfilesClone = {} for (f in L_.addedfiles) { addedfilesClone[f] = L_.addedfiles[f].username } for (f in addedfilesClone) { removeFile(addedfilesClone[f], f) addFile(addedfilesClone[f], f) } } function removeFile(u, f) { if (L_.addedfiles[f]['layer'] != 0) { $('#fmFileAdd_' + f.replace(/ /g, '_')) .css({ 'background-color': '#111' }) .html('off') if (Map_.map.hasLayer(L_.addedfiles[f]['layer'])) { Map_.map.removeLayer(L_.addedfiles[f]['layer']) } Globe_.removeVectorTileLayer('addedfiles_' + f) delete L_.addedfiles[f] } } function removeAllFiles() { for (f in L_.addedfiles) { if (L_.addedfiles[f]['layer'] != 0) { $('#fmFileAdd_' + f.replace(/ /g, '_')) .css({ 'background-color': '#111' }) .html('off') if (Map_.map.hasLayer(L_.addedfiles[f]['layer'])) { Map_.map.removeLayer(L_.addedfiles[f]['layer']) } delete L_.addedfiles[f] } } } FileManagerTool.init() return FileManagerTool })
dosisod/skull
test/skull/common/errors.c
#include <stdbool.h> #include <stdlib.h> #include <string.h> #include "skull/common/str.h" #include "skull/common/errors.c" #include "skull/semantic/variable.h" #include "test/skull/common/errors.h" #include "test/testing.h" static bool message_stringify_wrapper(Message *error, const char *expected) { message_stringify(error); if (!error->real) { return !expected; } const bool pass = strcmp(error->real, expected) == 0; free(error->real); return pass; } bool test_fmt_error_stringify() { Token *tok = tokenize(U"xxx"); Message err_tok = { .tok = tok }; Variable *var = make_variable(TYPE_INT, U"var_name", true); Message err_var = { .var = var }; Message err_type = { .type = TYPE_INT }; const char32_t *str = U"some string"; Message err_str = { .str32 = str }; ASSERT_TRUTHY(message_stringify_wrapper(&err_tok, "xxx")); ASSERT_TRUTHY(message_stringify_wrapper(&err_var, "var_name")); ASSERT_TRUTHY(message_stringify_wrapper(&err_str, "some string")); ASSERT_TRUTHY(message_stringify_wrapper(&err_type, "Int")); free_tokens(tok); free_variable(var); PASS } void error_test_self(bool *pass) { RUN_ALL( test_fmt_error_stringify ) }
schinmayee/nimbus
applications/physbam/physbam-lib/External_Libraries/src/fltk/src/fl_symbols.cxx
<reponame>schinmayee/nimbus<filename>applications/physbam/physbam-lib/External_Libraries/src/fltk/src/fl_symbols.cxx // // "$Id: fl_symbols.cxx,v 1.1 2011/12/10 04:53:51 rbsheth Exp $" // // Symbol drawing code for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2010 by <NAME> and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // // These are small graphics drawn by the normal label-drawing // code when the string starts with an '@' sign. // Adapted from original code written by: // Written by <NAME> // Version 2.1 a // Date: Oct 2, 1992 #include <FL/Fl.H> #include <FL/fl_draw.H> #include <FL/math.h> #include "flstring.h" typedef struct { const char *name; void (*drawit)(Fl_Color); char scalable; char notempty; } SYMBOL; #define MAXSYMBOL 211 /* Maximal number of symbols in table. Only half of them are used. Should be prime. */ static SYMBOL symbols[MAXSYMBOL]; /* The symbols */ static int symbnumb = -1; /* Their number */ static int find(const char *name) { // returns hash entry if it exists, or first empty slot: int pos = name[0] ? ( name[1] ? ( name[2] ? 71*name[0]+31*name[1]+name[2] : 31*name[0]+name[1] ) : name[0] ) : 0; pos %= MAXSYMBOL; int hh2 = name[0] ? ( (name[1]) ? 51*name[0]+3*name[1] : 3*name[0] ) : 1; hh2 %= MAXSYMBOL; if (!hh2) hh2 = 1; for (;;) { if (!symbols[pos].notempty) return pos; if (!strcmp(symbols[pos].name,name)) return pos; pos = (pos + hh2) % MAXSYMBOL; } } static void fl_init_symbols(void); /**************** The routines seen by the user *************************/ /** Adds a symbol to the system. \param[in] name name of symbol (without the "@") \param[in] drawit function to draw symbol \param[in] scalable set to 1 if \p drawit uses scalable vector drawing \returns 1 on success, 0 on failure */ int fl_add_symbol(const char *name, void (*drawit)(Fl_Color), int scalable) { fl_init_symbols(); int pos; if (symbnumb > MAXSYMBOL / 2) return 0; // table is full pos = find(name); symbols[pos].name = name; symbols[pos].drawit = drawit; symbols[pos].notempty = 1; symbols[pos].scalable = scalable; symbnumb++; return 1; } int fl_return_arrow(int x,int y,int w,int h); /** Draw the named symbol in the given rectangle using the given color \param[in] label name of symbol \param[in] x,y position of symbol \param[in] w,h size of symbol \param[in] col color of symbox \returns 1 on success, 0 on failure */ // provided for back compatibility: int fl_draw_symbol(const char *label,int x,int y,int w,int h,Fl_Color col) { const char *p = label; if (*p++ != '@') return 0; fl_init_symbols(); int equalscale = 0; if (*p == '#') {equalscale = 1; p++;} if (*p == '-' && p[1]>='1' && p[1]<='9') { int n = p[1]-'0'; x += n; y += n; w -= 2*n; h -= 2*n; p += 2; } else if (*p == '+' && p[1]>='1' && p[1]<='9') { int n = p[1]-'0'; x -= n; y -= n; w += 2*n; h += 2*n; p += 2; } if (w < 10) {x -= (10-w)/2; w = 10;} if (h < 10) {y -= (10-h)/2; h = 10;} w = (w-1)|1; h = (h-1)|1; char flip_x = 0, flip_y = 0; if (*p=='$') { flip_x = 1; p++; } if (*p=='%') { flip_y = 1; p++; } int rotangle; switch (*p++) { case '0': rotangle = 1000*(p[1]-'0') + 100*(p[2]-'0') + 10*(p[3]-'0'); p += 4; break; case '1': rotangle = 2250; break; case '2': rotangle = 2700; break; case '3': rotangle = 3150; break; case '4': rotangle = 1800; break; case '5': case '6': rotangle = 0; break; case '7': rotangle = 1350; break; case '8': rotangle = 900; break; case '9': rotangle = 450; break; default: rotangle = 0; p--; break; } int pos = find(p); if (!symbols[pos].notempty) return 0; if (symbols[pos].scalable == 3) { // kludge to detect return arrow fl_return_arrow(x,y,w,h); return 1; } fl_push_matrix(); fl_translate(x+w/2,y+h/2); if (symbols[pos].scalable) { if (equalscale) {if (w<h) h = w; else w = h;} fl_scale(0.5*w, 0.5*h); fl_rotate(rotangle/10.0); if (flip_x) fl_scale(-1.0, 1.0); if (flip_y) fl_scale(1.0, -1.0); } (symbols[pos].drawit)(col); fl_pop_matrix(); return 1; } /******************** THE DEFAULT SYMBOLS ****************************/ /* Some help stuff */ #define BP fl_begin_polygon() #define EP fl_end_polygon() #define BCP fl_begin_complex_polygon() #define ECP fl_end_complex_polygon() #define BL fl_begin_line() #define EL fl_end_line() #define BC fl_begin_loop() #define EC fl_end_loop() #define vv(x,y) fl_vertex(x,y) //for the outline color static void set_outline_color(Fl_Color c) { fl_color(fl_darker(c)); } static void rectangle(double x,double y,double x2,double y2,Fl_Color col) { fl_color(col); BP; vv(x,y); vv(x2,y); vv(x2,y2); vv(x,y2); EP; set_outline_color(col); BC; vv(x,y); vv(x2,y); vv(x2,y2); vv(x,y2); EC; } /* The drawing routines */ static void draw_fltk(Fl_Color col) { fl_color(col); // F fill BCP; vv(-2.0, -0.5); vv(-1.0, -0.5); vv(-1.0, -0.3); vv(-1.8, -0.3); vv(-1.8, -0.1); vv(-1.2, -0.1); vv(-1.2, 0.1); vv(-1.8, 0.1); vv(-1.8, 0.5); vv(-2.0, 0.5); ECP; // L fill BCP; vv(-1.0, -0.5); vv(-0.8, -0.5); vv(-0.8, 0.3); vv(0.0, 0.3); vv(0.0, 0.5); vv(-1.0, 0.5); ECP; // T outline BCP; vv(-0.1, -0.5); vv(1.1, -0.5); vv(1.1, -0.3); vv(0.6, -0.3); vv(0.6, 0.5); vv(0.4, 0.5); vv(0.4, -0.3); vv(-0.1, -0.3); ECP; // K outline BCP; vv(1.1, -0.5); vv(1.3, -0.5); vv(1.3, -0.15); vv(1.70, -0.5); vv(2.0, -0.5); vv(1.43, 0.0); vv(2.0, 0.5); vv(1.70, 0.5); vv(1.3, 0.15); vv(1.3, 0.5); vv(1.1, 0.5); ECP; set_outline_color(col); // F outline BC; vv(-2.0, -0.5); vv(-1.0, -0.5); vv(-1.0, -0.3); vv(-1.8, -0.3); vv(-1.8, -0.1); vv(-1.2, -0.1); vv(-1.2, 0.1); vv(-1.8, 0.1); vv(-1.8, 0.5); vv(-2.0, 0.5); EC; // L outline BC; vv(-1.0, -0.5); vv(-0.8, -0.5); vv(-0.8, 0.3); vv(0.0, 0.3); vv(0.0, 0.5); vv(-1.0, 0.5); EC; // T outline BC; vv(-0.1, -0.5); vv(1.1, -0.5); vv(1.1, -0.3); vv(0.6, -0.3); vv(0.6, 0.5); vv(0.4, 0.5); vv(0.4, -0.3); vv(-0.1, -0.3); EC; // K outline BC; vv(1.1, -0.5); vv(1.3, -0.5); vv(1.3, -0.15); vv(1.70, -0.5); vv(2.0, -0.5); vv(1.43, 0.0); vv(2.0, 0.5); vv(1.70, 0.5); vv(1.3, 0.15); vv(1.3, 0.5); vv(1.1, 0.5); EC; } static void draw_search(Fl_Color col) { fl_color(col); BP; vv(-.4, .13); vv(-1.0, .73); vv(-.73, 1.0); vv(-.13, .4); EP; set_outline_color(col); fl_line_style(FL_SOLID, 3, 0); BC; fl_circle(.2, -.2, .6); EC; fl_line_style(FL_SOLID, 1, 0); BC; vv(-.4, .13); vv(-1.0, .73); vv(-.73, 1.0); vv(-.13, .4); EC; } static void draw_arrow1(Fl_Color col) { fl_color(col); BP; vv(-0.8,-0.4); vv(-0.8,0.4); vv(0.0,0.4); vv(0.0,-0.4); EP; BP; vv(0.0,0.8); vv(0.8,0.0); vv(0.0,-0.8); vv(0.0,-0.4); vv(0.0,0.4); EP; set_outline_color(col); BC; vv(-0.8,-0.4); vv(-0.8,0.4); vv(0.0,0.4); vv(0.0,0.8); vv(0.8,0.0); vv(0.0,-0.8); vv(0.0,-0.4); EC; } static void draw_arrow1bar(Fl_Color col) { draw_arrow1(col); rectangle(.6,-.8,.9,.8,col); } static void draw_arrow2(Fl_Color col) { fl_color(col); BP; vv(-0.3,0.8); vv(0.50,0.0); vv(-0.3,-0.8); EP; set_outline_color(col); BC; vv(-0.3,0.8); vv(0.50,0.0); vv(-0.3,-0.8); EC; } static void draw_arrow3(Fl_Color col) { fl_color(col); BP; vv(0.1,0.8); vv(0.9,0.0); vv(0.1,-0.8); EP; BP; vv(-0.7,0.8); vv(0.1,0.0); vv(-0.7,-0.8); EP; set_outline_color(col); BC; vv(0.1,0.8); vv(0.9,0.0); vv(0.1,-0.8); EC; BC; vv(-0.7,0.8); vv(0.1,0.0); vv(-0.7,-0.8); EC; } static void draw_arrowbar(Fl_Color col) { fl_color(col); BP; vv(0.2,0.8); vv(0.6,0.8); vv(0.6,-0.8); vv(0.2,-0.8); EP; BP; vv(-0.6,0.8); vv(0.2,0.0); vv(-0.6,-0.8); EP; set_outline_color(col); BC; vv(0.2,0.8); vv(0.6,0.8); vv(0.6,-0.8); vv(0.2,-0.8); EC; BC; vv(-0.6,0.8); vv(0.2,0.0); vv(-0.6,-0.8); EC; } static void draw_arrowbox(Fl_Color col) { fl_color(col); BP; vv(-0.6,0.8); vv(0.2,0.0); vv(-0.6,-0.8); EP; BC; vv(0.2,0.8); vv(0.6,0.8); vv(0.6,-0.8); vv(0.2,-0.8); EC; set_outline_color(col); BC; vv(0.2,0.8); vv(0.6,0.8); vv(0.6,-0.8); vv(0.2,-0.8); EC; BC; vv(-0.6,0.8); vv(0.2,0.0); vv(-0.6,-0.8); EC; } static void draw_bararrow(Fl_Color col) { fl_color(col); BP; vv(0.1,0.8); vv(0.9,0.0); vv(0.1,-0.8); EP; BP; vv(-0.5,0.8); vv(-0.1,0.8); vv(-0.1,-0.8); vv(-0.5,-0.8); EP; set_outline_color(col); BC; vv(0.1,0.8); vv(0.9,0.0); vv(0.1,-0.8); EC; BC; vv(-0.5,0.8); vv(-0.1,0.8); vv(-0.1,-0.8); vv(-0.5,-0.8); EC; } static void draw_doublebar(Fl_Color col) { rectangle(-0.6,-0.8,-.1,.8,col); rectangle(.1,-0.8,.6,.8,col); } static void draw_arrow01(Fl_Color col) { fl_rotate(180); draw_arrow1(col); } static void draw_arrow02(Fl_Color col) { fl_rotate(180); draw_arrow2(col); } static void draw_arrow03(Fl_Color col) { fl_rotate(180); draw_arrow3(col); } static void draw_0arrowbar(Fl_Color col) { fl_rotate(180); draw_arrowbar(col); } static void draw_0arrowbox(Fl_Color col) { fl_rotate(180); draw_arrowbox(col); } static void draw_0bararrow(Fl_Color col) { fl_rotate(180); draw_bararrow(col); } static void draw_doublearrow(Fl_Color col) { fl_color(col); BP; vv(-0.35,-0.4); vv(-0.35,0.4); vv(0.35,0.4); vv(0.35,-0.4); EP; BP; vv(0.15,0.8); vv(0.95,0.0); vv(0.15,-0.8); EP; BP; vv(-0.15,0.8); vv(-0.95,0.0); vv(-0.15,-0.8); EP; set_outline_color(col); BC; vv(-0.15,0.4); vv(0.15,0.4); vv(0.15,0.8); vv(0.95,0.0); vv(0.15,-0.8); vv(0.15,-0.4); vv(-0.15,-0.4); vv(-0.15,-0.8); vv(-0.95,0.0); vv(-0.15,0.8); EC; } static void draw_arrow(Fl_Color col) { fl_color(col); BP; vv(0.65,0.1); vv(1.0,0.0); vv(0.65,-0.1); EP; BL; vv(-1.0,0.0); vv(0.65,0.0); EL; set_outline_color(col); BL; vv(-1.0,0.0); vv(0.65,0.0); EL; BC; vv(0.65,0.1); vv(1.0,0.0); vv(0.65,-0.1); EC; } static void draw_square(Fl_Color col) { rectangle(-1,-1,1,1,col); } static void draw_circle(Fl_Color col) { fl_color(col); BP; fl_circle(0,0,1); EP; set_outline_color(col); BC; fl_circle(0,0,1); EC; } static void draw_line(Fl_Color col) { fl_color(col); BL; vv(-1.0,0.0); vv(1.0,0.0); EL; } static void draw_plus(Fl_Color col) { fl_color(col); BP; vv(-0.9,-0.15); vv(-0.9,0.15); vv(0.9,0.15); vv(0.9,-0.15); EP; BP; vv(-0.15,-0.9); vv(-0.15,0.9); vv(0.15,0.9); vv(0.15,-0.9); EP; set_outline_color(col); BC; vv(-0.9,-0.15); vv(-0.9,0.15); vv(-0.15,0.15); vv(-0.15,0.9); vv(0.15,0.9); vv(0.15,0.15); vv(0.9,0.15); vv(0.9,-0.15); vv(0.15,-0.15); vv(0.15,-0.9); vv(-0.15,-0.9); vv(-0.15,-0.15); EC; } static void draw_uparrow(Fl_Color) { fl_color(FL_LIGHT3); BL; vv(-.8,.8); vv(-.8,-.8); vv(.8,0); EL; fl_color(FL_DARK3); BL; vv(-.8,.8); vv(.8, 0); EL; } static void draw_downarrow(Fl_Color) { fl_color(FL_DARK3); BL; vv(-.8,.8); vv(-.8,-.8); vv(.8,0); EL; fl_color(FL_LIGHT3); BL; vv(-.8,.8); vv(.8, 0); EL; } static void draw_menu(Fl_Color col) { rectangle(-0.65, 0.85, 0.65, -0.25, col); rectangle(-0.65, -0.6, 0.65, -1.0, col); } // Standard UI icons... static void draw_filenew(Fl_Color c) { fl_color(c); BCP; vv(-0.7, -1.0); vv(0.1, -1.0); vv(0.1, -0.4); vv(0.7, -0.4); vv(0.7, 1.0); vv(-0.7, 1.0); ECP; fl_color(fl_lighter(c)); BP; vv(0.1, -1.0); vv(0.1, -0.4); vv(0.7, -0.4); EP; fl_color(fl_darker(c)); BC; vv(-0.7, -1.0); vv(0.1, -1.0); vv(0.1, -0.4); vv(0.7, -0.4); vv(0.7, 1.0); vv(-0.7, 1.0); EC; BL; vv(0.1, -1.0); vv(0.7, -0.4); EL; } static void draw_fileopen(Fl_Color c) { fl_color(c); BP; vv(-1.0, -0.7); vv(-0.9, -0.8); vv(-0.4, -0.8); vv(-0.3, -0.7); vv(0.6, -0.7); vv(0.6, 0.7); vv(-1.0, 0.7); EP; fl_color(fl_darker(c)); BC; vv(-1.0, -0.7); vv(-0.9, -0.8); vv(-0.4, -0.8); vv(-0.3, -0.7); vv(0.6, -0.7); vv(0.6, 0.7); vv(-1.0, 0.7); EC; fl_color(fl_lighter(c)); BP; vv(-1.0, 0.7); vv(-0.6, -0.3); vv(1.0, -0.3); vv(0.6, 0.7); EP; fl_color(fl_darker(c)); BC; vv(-1.0, 0.7); vv(-0.6, -0.3); vv(1.0, -0.3); vv(0.6, 0.7); EC; } static void draw_filesave(Fl_Color c) { fl_color(c); BP; vv(-0.9, -1.0); vv(0.9, -1.0); vv(1.0, -0.9); vv(1.0, 0.9); vv(0.9, 1.0); vv(-0.9, 1.0); vv(-1.0, 0.9); vv(-1.0, -0.9); EP; fl_color(fl_lighter(c)); BP; vv(-0.7, -1.0); vv(0.7, -1.0); vv(0.7, -0.4); vv(-0.7, -0.4); EP; BP; vv(-0.7, 0.0); vv(0.7, 0.0); vv(0.7, 1.0); vv(-0.7, 1.0); EP; fl_color(c); BP; vv(-0.5, -0.9); vv(-0.3, -0.9); vv(-0.3, -0.5); vv(-0.5, -0.5); EP; fl_color(fl_darker(c)); BC; vv(-0.9, -1.0); vv(0.9, -1.0); vv(1.0, -0.9); vv(1.0, 0.9); vv(0.9, 1.0); vv(-0.9, 1.0); vv(-1.0, 0.9); vv(-1.0, -0.9); EC; } static void draw_filesaveas(Fl_Color c) { draw_filesave(c); fl_color(fl_color_average(c, FL_WHITE, 0.25f)); BP; vv(0.6, -0.8); vv(1.0, -0.4); vv(0.0, 0.6); vv(-0.4, 0.6); vv(-0.4, 0.2); EP; fl_color(fl_darker(c)); BC; vv(0.6, -0.8); vv(1.0, -0.4); vv(0.0, 0.6); vv(-0.4, 0.6); vv(-0.4, 0.2); EC; BP; vv(-0.1, 0.6); vv(-0.4, 0.6); vv(-0.4, 0.3); EP; } static void draw_fileprint(Fl_Color c) { fl_color(c); BP; vv(-0.8, 0.0); vv(0.8, 0.0); vv(1.0, 0.2); vv(1.0, 1.0); vv(-1.0, 1.0); vv(-1.0, 0.2); EP; fl_color(fl_color_average(c, FL_WHITE, 0.25f)); BP; vv(-0.6, 0.0); vv(-0.6, -1.0); vv(0.6, -1.0); vv(0.6, 0.0); EP; fl_color(fl_lighter(c)); BP; vv(-0.6, 0.6); vv(0.6, 0.6); vv(0.6, 1.0); vv(-0.6, 1.0); EP; fl_color(fl_darker(c)); BC; vv(-0.8, 0.0); vv(-0.6, 0.0); vv(-0.6, -1.0); vv(0.6, -1.0); vv(0.6, 0.0); vv(0.8, 0.0); vv(1.0, 0.2); vv(1.0, 1.0); vv(-1.0, 1.0); vv(-1.0, 0.2); EC; BC; vv(-0.6, 0.6); vv(0.6, 0.6); vv(0.6, 1.0); vv(-0.6, 1.0); EC; } static void draw_round_arrow(Fl_Color c, float da=5.0) { double a, r, dr1=0.005, dr2=0.015; int i, j; for (j=0; j<2; j++) { if (j&1) { fl_color(c); set_outline_color(c); BC; } else { fl_color(c); BCP; } vv(-0.1, 0.0); vv(-1.0, 0.0); vv(-1.0, 0.9); for (i=27, a=140.0, r=1.0; i>0; i--, a-=da, r-=dr1) { double ar = a/180.0 * M_PI; vv(cos(ar)*r, sin(ar)*r); } for (i=27; i>=0; a+=da, i--, r-=dr2) { double ar = a/180.0 * M_PI; vv(cos(ar)*r, sin(ar)*r); } if (j&1) { EC; } else { ECP; } } } static void draw_refresh(Fl_Color c) { draw_round_arrow(c); fl_rotate(180.0); draw_round_arrow(c); fl_rotate(-180.0); } static void draw_reload(Fl_Color c) { fl_rotate(-135.0); draw_round_arrow(c, 10); fl_rotate(135.0); } static void draw_undo(Fl_Color c) { fl_translate(0.0, 0.2); fl_scale(1.0, -1.0); draw_round_arrow(c, 6); fl_scale(1.0, -1.0); fl_translate(0.0, -0.2); } static void draw_redo(Fl_Color c) { fl_scale(-1.0, 1.0); draw_undo(c); fl_scale(-1.0, 1.0); } static void fl_init_symbols(void) { static char beenhere; if (beenhere) return; beenhere = 1; symbnumb = 0; fl_add_symbol("", draw_arrow1, 1); fl_add_symbol("->", draw_arrow1, 1); fl_add_symbol(">", draw_arrow2, 1); fl_add_symbol(">>", draw_arrow3, 1); fl_add_symbol(">|", draw_arrowbar, 1); fl_add_symbol(">[]", draw_arrowbox, 1); fl_add_symbol("|>", draw_bararrow, 1); fl_add_symbol("<-", draw_arrow01, 1); fl_add_symbol("<", draw_arrow02, 1); fl_add_symbol("<<", draw_arrow03, 1); fl_add_symbol("|<", draw_0arrowbar, 1); fl_add_symbol("[]<", draw_0arrowbox, 1); fl_add_symbol("<|", draw_0bararrow, 1); fl_add_symbol("<->", draw_doublearrow, 1); fl_add_symbol("-->", draw_arrow, 1); fl_add_symbol("+", draw_plus, 1); fl_add_symbol("->|", draw_arrow1bar, 1); fl_add_symbol("arrow", draw_arrow, 1); fl_add_symbol("returnarrow", 0, 3); fl_add_symbol("square", draw_square, 1); fl_add_symbol("circle", draw_circle, 1); fl_add_symbol("line", draw_line, 1); fl_add_symbol("plus", draw_plus, 1); fl_add_symbol("menu", draw_menu, 1); fl_add_symbol("UpArrow", draw_uparrow, 1); fl_add_symbol("DnArrow", draw_downarrow, 1); fl_add_symbol("||", draw_doublebar, 1); fl_add_symbol("search", draw_search, 1); fl_add_symbol("FLTK", draw_fltk, 1); fl_add_symbol("filenew", draw_filenew, 1); fl_add_symbol("fileopen", draw_fileopen, 1); fl_add_symbol("filesave", draw_filesave, 1); fl_add_symbol("filesaveas", draw_filesaveas, 1); fl_add_symbol("fileprint", draw_fileprint, 1); fl_add_symbol("refresh", draw_refresh, 1); fl_add_symbol("reload", draw_reload, 1); fl_add_symbol("undo", draw_undo, 1); fl_add_symbol("redo", draw_redo, 1); // fl_add_symbol("file", draw_file, 1); } // // End of "$Id: fl_symbols.cxx,v 1.1 2011/12/10 04:53:51 rbsheth Exp $". //
igiant/connect
domains.go
package connect import "encoding/json" // DeliveryType - Delivery Type type DeliveryType string const ( Online DeliveryType = "Online" // deliver online, immediatelly OfflineScheduler DeliveryType = "OfflineScheduler" // delivery is started by scheduler OfflineEtrn DeliveryType = "OfflineEtrn" // delivery is started by ETRN command from remote host ) // Forwarding action // Forwarding - Note: all fields must be assigned if used in set methods type Forwarding struct { IsEnabled bool `json:"isEnabled"` // is forwarding enabled? Host string `json:"host"` // hostname or IP address to forward Port int `json:"port"` // host port How DeliveryType `json:"how"` // how to deliver PreventLoop bool `json:"preventLoop"` // do not deliver to domain alias (applicable when Domain.aliasList is not empty) } type DirectoryServiceType string const ( WindowsActiveDirectory DirectoryServiceType = "WindowsActiveDirectory" // Windows Active Directory AppleDirectoryKerberos DirectoryServiceType = "AppleDirectoryKerberos" // Apple Open Directory with Kerberos authentication AppleDirectoryPassword DirectoryServiceType = "AppleDirectoryPassword" // Apple Open Directory with Password Server authentication KerioDirectory DirectoryServiceType = "KerioDirectory" // Kerio Directory (reserved for future use) CustomLDAP DirectoryServiceType = "CustomLDAP" // Custom Generic LDAP ) // DirectoryAuthentication - Note: all fields must be assigned if used in set methods (except password) type DirectoryAuthentication struct { Username string `json:"username"` Password string `json:"password"` IsSecure bool `json:"isSecure"` // is used LDAPS? } // DirectoryServiceConfiguration - Directory service configuration type DirectoryServiceConfiguration struct { ServiceType DirectoryServiceType `json:"serviceType"` // type of the service Authentication DirectoryAuthentication `json:"authentication"` // authentication information DirectoryName string `json:"directoryName"` // Active Directory only: Directory name LdapSuffix string `json:"ldapSuffix"` // Apple Directory, Kerio Directory: LDAP Search Suffix } // DirectoryService - Directory service information type DirectoryService struct { IsEnabled bool `json:"isEnabled"` // directory service is in use / isEnabled must be always assigned if used in set methods ServiceType DirectoryServiceType `json:"serviceType"` // type of the service CustomMapFile string `json:"customMapFile"` // Custom Generic LDAP only: custom map filename Authentication DirectoryAuthentication `json:"authentication"` // authentication information Hostname string `json:"hostname"` // directory service hostname BackupHostname string `json:"backupHostname"` // directory service backup hostname DirectoryName string `json:"directoryName"` // Active Directory only: Directory name LdapSuffix string `json:"ldapSuffix"` // Apple Directory, Kerio Directory: LDAP Search Suffix } // Footer - Note: all fields must be assigned if used in set methods type Footer struct { IsUsed bool `json:"isUsed"` // is footer used Text string `json:"text"` // text that will be appended to every message sent from this domain IsHtml bool `json:"isHtml"` // if is value false the text is precessed as plaintext IsUsedInDomain bool `json:"isUsedInDomain"` // footer is used also for e-mails within domain } // WebmailLogo - Note: all fields must be assigned if used in set methods type WebmailLogo struct { IsUsed bool `json:"isUsed"` // has domain user defined logo? Url string `json:"url"` // user defined logo URL } type DomainRenameInfo struct { IsRenamed bool `json:"isRenamed"` OldName string `json:"oldName"` NewName string `json:"newName"` } type DomainQuota struct { DiskSizeLimit SizeLimit `json:"diskSizeLimit"` // max. disk usage ConsumedSize ByteValueWithUnits `json:"consumedSize"` // [READ-ONLY] current disk usage Notification QuotaNotification `json:"notification"` // option for notification WarningLimit int `json:"warningLimit"` // limit in per cent Email string `json:"email"` // if quota is exceeded the notification will be sent to this address Blocks bool `json:"blocks"` // if reaching the quota will block creation of a new items } // Domain - Domain details type Domain struct { Id KId `json:"id"` // [READ-ONLY] global identification of domain Name string `json:"name"` // [REQUIRED FOR CREATE] [WRITE-ONCE] name Description string `json:"description"` // description IsPrimary bool `json:"isPrimary"` // is this domain primary? UserMaxCount int `json:"userMaxCount"` // maximum users per domain, 'unlimited' constant can be used PasswordExpirationEnabled bool `json:"passwordExpirationEnabled"` // is password expiration enabled for this domain? PasswordExpirationDays int `json:"passwordExpirationDays"` // password expiration interval PasswordHistoryCount int `json:"passwordHistoryCount"` // lenght of password history PasswordComplexityEnabled bool `json:"passwordComplexityEnabled"` // is password complexity enabled for this domain? PasswordMinimumLength int `json:"passwordMinimumLength"` // minimum password length for complexity feature OutgoingMessageLimit SizeLimit `json:"outgoingMessageLimit"` // outgoing message size limit DeletedItems ActionAfterDays `json:"deletedItems"` // clean Deleted Items folder (AC maximum: 24855) JunkEmail ActionAfterDays `json:"junkEmail"` // clean Junk Email folder (AC maximum: 24855) SentItems ActionAfterDays `json:"sentItems"` // clean Sent Items folder (AC maximum: 24855) AutoDelete ActionAfterDays `json:"autoDelete"` // clean all folders (AC minimun:30, maximum: 24855) KeepForRecovery ActionAfterDays `json:"keepForRecovery"` // keep deleted messages for recovery AliasList StringList `json:"aliasList"` // list of domain alternative names ForwardingOptions Forwarding `json:"forwardingOptions"` // forwarding settings Service DirectoryService `json:"service"` // directory service configuration DomainFooter Footer `json:"domainFooter"` // domain footer setting KerberosRealm string `json:"kerberosRealm"` // Kerberos Realm name WinNtName string `json:"winNtName"` // Windows NT domain name - available on windows only PamRealm string `json:"pamRealm"` // PAM Realm name - available on linux only IpAddressBind OptionalString `json:"ipAddressBind"` // specific IP address bind Logo WebmailLogo `json:"logo"` // user defined logo CustomClientLogo CustomImage `json:"customClientLogo"` // Use custom logo in Kerio Connect Client (if not enabled global option from AdvancedOptionsSetting.webMail is used) CheckSpoofedSender bool `json:"checkSpoofedSender"` // RenameInfo DomainRenameInfo `json:"renameInfo"` // [READ-ONLY] if domain was renamed, contain old and new domain name DomainQuota DomainQuota `json:"domainQuota"` // domain's quota settings IsDistributed bool `json:"isDistributed"` // [READ-ONLY] if domain is distributed IsDkimEnabled bool `json:"isDkimEnabled"` // true if DKIM is used for this domain IsLdapManagementAllowed bool `json:"isLdapManagementAllowed"` // [READ-ONLY] true if directory service user/group can be created/deleted IsInstantMessagingEnabled bool `json:"isInstantMessagingEnabled"` // true if Instant Messaging is enabled for this domain UseRemoteArchiveAddress bool `json:"useRemoteArchiveAddress"` // if true emails are archived to remoteArchiveAddress RemoteArchiveAddress string `json:"remoteArchiveAddress"` // remote archiving address ArchiveLocalMessages bool `json:"archiveLocalMessages"` // if true emails from emails are archived to remoteArchiveAddress ArchiveIncomingMessages bool `json:"archiveIncomingMessages"` // if true emails are archived to remoteArchiveAddress ArchiveOutgoingMessages bool `json:"archiveOutgoingMessages"` // if true emails are archived to remoteArchiveAddress ArchiveBeforeFilter bool `json:"archiveBeforeFilter"` // if true emails are archived before content filter check } // DomainSetting - Identical settings for all domains type DomainSetting struct { Hostname string `json:"hostname"` // internet hostname - how this machine introduces itself in SMTP,POP3... PublicFoldersPerDomain bool `json:"publicFoldersPerDomain"` // true=public folders are unique per each domain / false=global for all domains ServerId KId `json:"serverId"` // id of server primary used in cluster } // DomainList - List of domains type DomainList []Domain // UserLimitType - Types of user amount limit type UserLimitType string const ( DomainLimit UserLimitType = "DomainLimit" // stricter limit for amount of users is on domain LicenseLimit UserLimitType = "LicenseLimit" // stricter limit for amount of users is on license ) // MaximumUsers - User limit information type MaximumUsers struct { IsUnlimited bool `json:"isUnlimited"` // is it a special case with no limit for users ? AllowedUsers int `json:"allowedUsers"` // number of allowed users (take minimum of server and domain limit) Limit int `json:"limit"` // max. user limit LimitType UserLimitType `json:"limitType"` // max. user limit type, if domain limit == license limit -> use license } // UserDomainCountInfo - User count information type UserDomainCountInfo struct { CurrentUsers int `json:"currentUsers"` // number of created users on domain AllowedUsers MaximumUsers `json:"allowedUsers"` // number of allowed users, take stricter limit from max. number for domain, max. number by license } // Domain management // DomainsCheckPublicFoldersIntegrity - If corrupted folder is found, try to fix it. func (s *ServerConnection) DomainsCheckPublicFoldersIntegrity() error { _, err := s.CallRaw("Domains.checkPublicFoldersIntegrity", nil) return err } // DomainsCreate - Create new domains. // domains - new domain entities // Return // errors - error message list // result - particular results for all items func (s *ServerConnection) DomainsCreate(domains DomainList) (ErrorList, CreateResultList, error) { params := struct { Domains DomainList `json:"domains"` }{domains} data, err := s.CallRaw("Domains.create", params) if err != nil { return nil, nil, err } errors := struct { Result struct { Errors ErrorList `json:"errors"` Result CreateResultList `json:"result"` } `json:"result"` }{} err = json.Unmarshal(data, &errors) return errors.Result.Errors, errors.Result.Result, err } // DomainsGeneratePassword - Generate password which meets current password policy of a given domain. // domainId - ID of the domain // Return // password - <PASSWORD> func (s *ServerConnection) DomainsGeneratePassword(domainId KId) (string, error) { params := struct { DomainId KId `json:"domainId"` }{domainId} data, err := s.CallRaw("Domains.generatePassword", params) if err != nil { return "", err } password := struct { Result struct { Password string `json:"password"` } `json:"result"` }{} err = json.Unmarshal(data, &password) return password.Result.Password, err } // DomainsGet - Obtain a list of domains. // query - query conditions and limits // Return // list - domains // totalItems - amount of domains for given search condition, useful when limit is defined in SearchQuery func (s *ServerConnection) DomainsGet(query SearchQuery) (DomainList, int, error) { query = addMissedParametersToSearchQuery(query) params := struct { Query SearchQuery `json:"query"` }{query} data, err := s.CallRaw("Domains.get", params) if err != nil { return nil, 0, err } list := struct { Result struct { List DomainList `json:"list"` TotalItems int `json:"totalItems"` } `json:"result"` }{} err = json.Unmarshal(data, &list) return list.Result.List, list.Result.TotalItems, err } // DomainsGetDkimDnsRecord - Returns DNS TXT record to be added into DNS. func (s *ServerConnection) DomainsGetDkimDnsRecord(domain string) (string, error) { params := struct { Domain string `json:"domain"` }{domain} data, err := s.CallRaw("Domains.getDkimDnsRecord", params) if err != nil { return "", err } detail := struct { Result struct { Detail string `json:"detail"` } `json:"result"` }{} err = json.Unmarshal(data, &detail) return detail.Result.Detail, err } // DomainsGetSettings - Get settings common in all domains. // Return // setting - domain global setting func (s *ServerConnection) DomainsGetSettings() (*DomainSetting, error) { data, err := s.CallRaw("Domains.getSettings", nil) if err != nil { return nil, err } setting := struct { Result struct { Setting DomainSetting `json:"setting"` } `json:"result"` }{} err = json.Unmarshal(data, &setting) return &setting.Result.Setting, err } // DomainsGetUserCountInfo - Get information about user count and limit for domain. Disabled users are not counted. // domainId - ID of the domain which will be renamed // Return // countInfo - structure with users count and limit func (s *ServerConnection) DomainsGetUserCountInfo(domainId KId) (*UserDomainCountInfo, error) { params := struct { DomainId KId `json:"domainId"` }{domainId} data, err := s.CallRaw("Domains.getUserCountInfo", params) if err != nil { return nil, err } countInfo := struct { Result struct { CountInfo UserDomainCountInfo `json:"countInfo"` } `json:"result"` }{} err = json.Unmarshal(data, &countInfo) return &countInfo.Result.CountInfo, err } // DomainsRemove - Remove domains. // domainIds - list of global identifiers of domains to be deleted // Return // errors - error message list func (s *ServerConnection) DomainsRemove(domainIds KIdList) (ErrorList, error) { params := struct { DomainIds KIdList `json:"domainIds"` }{domainIds} data, err := s.CallRaw("Domains.remove", params) if err != nil { return nil, err } errors := struct { Result struct { Errors ErrorList `json:"errors"` } `json:"result"` }{} err = json.Unmarshal(data, &errors) return errors.Result.Errors, err } // DomainsRename - Start domain renaming process. // domainId - ID of the domain which will be renamed // newName - new domain name // Return // error - error message func (s *ServerConnection) DomainsRename(domainId KId, newName string) (*ClusterError, error) { params := struct { DomainId KId `json:"domainId"` NewName string `json:"newName"` }{domainId, newName} data, err := s.CallRaw("Domains.rename", params) if err != nil { return nil, err } error := struct { Result struct { Error ClusterError `json:"error"` } `json:"result"` }{} err = json.Unmarshal(data, &error) return &error.Result.Error, err } // DomainsSaveFooterImage - Save a new footer's image. // fileId - id of uploaded file // Return // imgUrl - url to saved image func (s *ServerConnection) DomainsSaveFooterImage(fileId string) (string, error) { params := struct { FileId string `json:"fileId"` }{fileId} data, err := s.CallRaw("Domains.saveFooterImage", params) if err != nil { return "", err } imgUrl := struct { Result struct { ImgUrl string `json:"imgUrl"` } `json:"result"` }{} err = json.Unmarshal(data, &imgUrl) return imgUrl.Result.ImgUrl, err } // DomainsSaveWebMailLogo - Save a new logo. // fileId - ID of the uploaded file // domainId - global domain identifier // Return // logoUrl - path to the saved file func (s *ServerConnection) DomainsSaveWebMailLogo(fileId string, domainId KId) (string, error) { params := struct { FileId string `json:"fileId"` DomainId KId `json:"domainId"` }{fileId, domainId} data, err := s.CallRaw("Domains.saveWebMailLogo", params) if err != nil { return "", err } logoUrl := struct { Result struct { LogoUrl string `json:"logoUrl"` } `json:"result"` }{} err = json.Unmarshal(data, &logoUrl) return logoUrl.Result.LogoUrl, err } // DomainsSet - Set existing domains to given pattern. // domainIds - list of the domain's global identifier(s) // pattern - pattern to use for new values // Return // errors - error message list func (s *ServerConnection) DomainsSet(domainIds KIdList, pattern Domain) (ErrorList, error) { params := struct { DomainIds KIdList `json:"domainIds"` Pattern Domain `json:"pattern"` }{domainIds, pattern} data, err := s.CallRaw("Domains.set", params) if err != nil { return nil, err } errors := struct { Result struct { Errors ErrorList `json:"errors"` } `json:"result"` }{} err = json.Unmarshal(data, &errors) return errors.Result.Errors, err } // DomainsSetSettings - Set settings for all domains. // setting - domain global settings func (s *ServerConnection) DomainsSetSettings(setting DomainSetting) error { params := struct { Setting DomainSetting `json:"setting"` }{setting} _, err := s.CallRaw("Domains.setSettings", params) return err } // DomainsTestDomainController - Test connection between Kerio Connect and domain controller. // hostnames - directory server (primary and secondary if any) // config - directory service configuration. If password is empty then it is taken from domain by 'domainId'. // domainId - global domain identifier // Return // errors - error message func (s *ServerConnection) DomainsTestDomainController(hostnames StringList, config DirectoryServiceConfiguration, domainId KId) (ErrorList, error) { params := struct { Hostnames StringList `json:"hostnames"` Config DirectoryServiceConfiguration `json:"config"` DomainId KId `json:"domainId"` }{hostnames, config, domainId} data, err := s.CallRaw("Domains.testDomainController", params) if err != nil { return nil, err } errors := struct { Result struct { Errors ErrorList `json:"errors"` } `json:"result"` }{} err = json.Unmarshal(data, &errors) return errors.Result.Errors, err } // DomainsTestDkimDnsStatus - Tests DKIM DNS TXT status for domain list. // hostnames - hostnames checked for DKIM public key in DNS // Return // errors - error message func (s *ServerConnection) DomainsTestDkimDnsStatus(hostnames StringList) (ErrorList, error) { params := struct { Hostnames StringList `json:"hostnames"` }{hostnames} data, err := s.CallRaw("Domains.testDkimDnsStatus", params) if err != nil { return nil, err } errors := struct { Result struct { Errors ErrorList `json:"errors"` } `json:"result"` }{} err = json.Unmarshal(data, &errors) return errors.Result.Errors, err } // DomainsGetDomainFooterPlaceholders - Return all supported placeholders for domain footer func (s *ServerConnection) DomainsGetDomainFooterPlaceholders() (NamedConstantList, error) { data, err := s.CallRaw("Domains.getDomainFooterPlaceholders", nil) if err != nil { return nil, err } placeholders := struct { Result struct { Placeholders NamedConstantList `json:"placeholders"` } `json:"result"` }{} err = json.Unmarshal(data, &placeholders) return placeholders.Result.Placeholders, err }
dji-sdk/DJI-Cloud-API-Demo
src/main/java/com/dji/sample/common/error/CommonErrorEnum.java
<gh_stars>1-10 package com.dji.sample.common.error; /** * @author sean.zhou * @version 0.1 * @date 2021/11/25 */ public enum CommonErrorEnum implements IErrorInfo { SYSTEM_ERROR(600500, "system error"), SECRET_INVALID(600100, "secret invalid"), NO_TOKEN(600101, "accss_token is null"), TOKEN_EXPIRED(600102, "token is expired"), TOKEN_INVALID(600103, "token invalid"), SIGN_INVALID(600104, "sign invalid"); private String msg; private int code; CommonErrorEnum(int code, String msg) { this.code = code; this.msg = msg; } @Override public String getErrorMsg() { return this.msg; } @Override public Integer getErrorCode() { return this.code; } }
ggear/cloudera-framework
cloudera-framework-common/src/main/java/com/cloudera/framework/common/util/DfsUtil.java
<reponame>ggear/cloudera-framework<gh_stars>10-100 package com.cloudera.framework.common.util; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; /** * Provide DFS utility functions */ public class DfsUtil { private static final String FILE_METADATA_PREFIX = "_"; /** * Determine whether an action can be performed * * @param hdfs the {@link FileSystem file system} * @param user the user to test * @param groups the groups to test * @param path the {@link Path} to test * @param action the action to test * @return <code>true</code> if action is allowed, <code>false</code> * otherwise */ public static boolean canDoAction(FileSystem hdfs, String user, String[] groups, Path path, FsAction action) throws IOException { FileStatus status = hdfs.getFileStatus(path); FsPermission permission = status.getPermission(); if (permission.getOtherAction().implies(action)) { return true; } for (String group : groups) { if (group.equals(status.getGroup()) && permission.getGroupAction().implies(action)) { return true; } } return user.equals(status.getOwner()) && permission.getUserAction().implies(action); } /** * List files. * * @param hdfs the {@link FileSystem file system} * @param path the root {@link Path path} * @param recurse whether to recurse from <code>path</code> * @param filterMetaData if <code>true</code> filter out files named with suffix * {@link #FILE_METADATA_PREFIX} * @return the {@link Set set} of file {@link Path paths} */ public static Set<Path> listFiles(FileSystem hdfs, Path path, boolean recurse, boolean filterMetaData) throws IOException { Set<Path> files = new HashSet<>(); try { RemoteIterator<LocatedFileStatus> filesIterator = hdfs.listFiles(path, recurse); while (filesIterator.hasNext()) { Path file = filesIterator.next().getPath(); if (!filterMetaData || !file.getName().startsWith(FILE_METADATA_PREFIX)) { files.add(file); } } } catch (FileNotFoundException exception) { // ignore } return files; } /** * List directories. * * @param hdfs the {@link FileSystem file system} * @param path the root {@link Path path} * @param recurse whether to recurse from <code>path</code> * @param filterMetaData if <code>true</code> filter out directories either named or with a * containing file named with suffix {@link #FILE_METADATA_PREFIX} * @return the {@link Set set} of directory {@link Path paths} */ public static Set<Path> listDirs(FileSystem hdfs, Path path, boolean recurse, boolean filterMetaData) throws IOException { Map<Path, Boolean> dirs = new HashMap<>(); try { RemoteIterator<LocatedFileStatus> filesIterator = hdfs.listFiles(path, recurse); while (filesIterator.hasNext()) { Path file = filesIterator.next().getPath(); Path dir = file.getParent(); dirs.put(dir, (dirs.getOrDefault(dir, false)) || file.getName().startsWith(FILE_METADATA_PREFIX)); } } catch (FileNotFoundException exception) { // ignore } Set<Path> dirsFiltered = dirs.keySet(); if (filterMetaData) { dirsFiltered = new HashSet<>(); for (Path dir : dirs.keySet()) { if (!dirs.get(dir) && !dir.getName().startsWith(FILE_METADATA_PREFIX)) { dirsFiltered.add(dir); } } } return dirsFiltered; } }
sajiok/beanio
test/org/beanio/parser/json/segment/JsonSegmentParserTest.java
package org.beanio.parser.json.segment; import static org.junit.Assert.*; import java.io.*; import java.util.*; import org.beanio.*; import org.beanio.beans.Person; import org.beanio.parser.ParserTest; import org.junit.*; /** * JUnit test cases for JSON segments. * * @author <NAME> * @since 2.0 */ public class JsonSegmentParserTest extends ParserTest { private StreamFactory factory; @Before public void setup() throws Exception { factory = newStreamFactory("jsonSegment_mapping.xml"); } @Test @SuppressWarnings("rawtypes") public void testSegment_JsonTypeObject() { BeanReader in = factory.createReader("stream1", new InputStreamReader( getClass().getResourceAsStream("js1.txt"))); try { Map map = (Map) in.read(); assertEquals("1234", map.get("account")); Person person = (Person) map.get("customer"); assertEquals("Jen", person.getFirstName()); assertEquals("Jones", person.getLastName()); StringWriter text = new StringWriter(); factory.createWriter("stream1", text).write(map); assertEquals(load("js1.txt"), text.toString()); } finally { in.close(); } } @Test @SuppressWarnings("rawtypes") public void testSegment_JsonTypeObjectList() { BeanReader in = factory.createReader("stream2", new InputStreamReader( getClass().getResourceAsStream("js2.txt"))); try { Map map = (Map) in.read(); assertEquals(new Integer(2), map.get("count")); List list = (List) map.get("friends"); Person person = (Person) list.get(0); assertEquals("Jen", person.getFirstName()); assertEquals("Jones", person.getLastName()); person = (Person) list.get(1); assertEquals("Mary", person.getFirstName()); assertEquals("Smith", person.getLastName()); StringWriter text = new StringWriter(); factory.createWriter("stream2", text).write(map); assertEquals(load("js2.txt"), text.toString()); } finally { in.close(); } } @Test @SuppressWarnings("rawtypes") public void testSegment_JsonTypeArray() { BeanReader in = factory.createReader("stream3", new InputStreamReader( getClass().getResourceAsStream("js3.txt"))); try { Map map = (Map) in.read(); assertArrayEquals(new Integer[] { 1, 2, 3 }, ((List)map.get("numbers")).toArray()); Person person = (Person) map.get("person"); assertEquals("Jen", person.getFirstName()); assertEquals("Jones", person.getLastName()); StringWriter text = new StringWriter(); factory.createWriter("stream3", text).write(map); assertEquals(load("js3.txt"), text.toString()); } finally { in.close(); } } @Test @SuppressWarnings("rawtypes") public void testSegment_JsonTypeNone() { BeanReader in = factory.createReader("stream4", new InputStreamReader( getClass().getResourceAsStream("js4.txt"))); try { Map map = (Map) in.read(); Person person = (Person) map.get("person"); assertEquals("Jen", person.getFirstName()); assertEquals("Jones", person.getLastName()); assertEquals("1234", map.get("account")); StringWriter text = new StringWriter(); BeanWriter out = factory.createWriter("stream4", text); out.write(map); map = (Map) in.read(); person = (Person) map.get("person"); assertEquals("Jason", person.getFirstName()); assertEquals("Jones", person.getLastName()); assertEquals("5678", map.get("account")); out.write(map); assertEquals(load("js4.txt"), text.toString()); } finally { in.close(); } } }
IncompleteWorlds/01_gs4cubesat
C++Server/Common/include/CxxUtilities/FitsUtility.hh
/* * FitsFile.hh * * Created on: Jun 18, 2014 * Author: yuasa */ #ifndef CXXUTILITIES_FITSFILE_HH_ #define CXXUTILITIES_FITSFILE_HH_ #include "CxxUtilities/String.hh" namespace CxxUtilities { class FitsUtility { #ifndef TBIT public: // DATATYPE TFORM CODE static const int TBIT = 1; // 'X' static const int TBYTE = 11; // 8-bit unsigned byte, 'B' static const int TLOGICAL = 14; // logicals (int for keywords and char for table cols 'L' static const int TSTRING = 16; // ASCII string, 'A' static const int TSHORT = 21; // signed short, 'I' static const int TLONG = 41; // signed long, static const int TLONGLONG = 81; // 64-bit long signed integer 'K' static const int TFLOAT = 42; // single precision float, 'E' static const int TDOUBLE = 82; // double precision float, 'D' static const int TCOMPLEX = 83; // complex (pair of floats) 'C' static const int TDBLCOMPLEX = 163; // double complex (2 doubles) 'M' static const int TINT = 31; // int static const int TSBYTE = 12; // 8-bit signed byte, 'S' static const int TUINT = 30; // unsigned int 'V' static const int TUSHORT = 20; // unsigned short 'U' static const int TULONG = 40; // unsigned long #endif public: static std::string convertSIB2StyleDataTypeNameToCfitsioStyleTFORM(std::string dataTypeName) { dataTypeName = CxxUtilities::String::downCase(dataTypeName); if (CxxUtilities::String::include(dataTypeName, "byte")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "B"; } else { return "S"; } } else if (CxxUtilities::String::include(dataTypeName, "short")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "U"; } else { return "I"; } } else if (CxxUtilities::String::include(dataTypeName, "int")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "V"; } else { return "J"; } } else if (CxxUtilities::String::include(dataTypeName, "long")) { return "K"; } else if (CxxUtilities::String::include(dataTypeName, "float")) { return "E"; } else if (CxxUtilities::String::include(dataTypeName, "double")) { return "D"; } else if (CxxUtilities::String::include(dataTypeName, "x") || CxxUtilities::String::include(dataTypeName, "bits") || CxxUtilities::String::include(dataTypeName, "bit")) { std::string dataTypeWidth = CxxUtilities::String::replace(dataTypeName, "x", ""); dataTypeWidth = CxxUtilities::String::replace(dataTypeWidth, "bits", ""); dataTypeWidth = CxxUtilities::String::replace(dataTypeWidth, "bit", ""); dataTypeWidth = CxxUtilities::String::replace(dataTypeWidth, " ", ""); return dataTypeWidth + "X"; } else { using namespace std; cerr << "CxxUtilities::FitsUtility::convertSIB2StyleDataTypeNameToCfitsioStyleTFORM(): Unrecognizable data type name " << dataTypeName << " provided." << endl; return ""; } } // end of convertSIB2StyleDataTypeNameToCfitsioStyleTFORM() static int getCfitsioStyleDataTypeNumber(std::string dataTypeName) { dataTypeName = CxxUtilities::String::downCase(dataTypeName); if (CxxUtilities::String::include(dataTypeName, "byte")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return TBYTE; } else { return TSBYTE; } } else if (CxxUtilities::String::include(dataTypeName, "short")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return TUSHORT; } else { return TSHORT; } } else if (CxxUtilities::String::include(dataTypeName, "int")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return TUINT; } else { return TINT; } } else if (CxxUtilities::String::include(dataTypeName, "long")) { return TLONG; } else if (CxxUtilities::String::include(dataTypeName, "float")) { return TFLOAT; } else if (CxxUtilities::String::include(dataTypeName, "double")) { return TDOUBLE; } else if (CxxUtilities::String::include(dataTypeName, "x") || CxxUtilities::String::include(dataTypeName, "bits") || CxxUtilities::String::include(dataTypeName, "bit")) { return TBIT; } else { using namespace std; cerr << "CxxUtilities::FitsUtility::getCfitsioStyleDataTypeNumber(): Unrecognizable data type name " << dataTypeName << " provided." << endl; return 0; } } static std::string getCfitsioStyleDataTypeNumberAsString(std::string dataTypeName) { dataTypeName = CxxUtilities::String::downCase(dataTypeName); if (CxxUtilities::String::include(dataTypeName, "byte")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "TBYTE"; } else { return "TSBYTE"; } } else if (CxxUtilities::String::include(dataTypeName, "short")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "TUSHORT"; } else { return "TSHORT"; } } else if (CxxUtilities::String::include(dataTypeName, "int")) { if (CxxUtilities::String::include(dataTypeName, "unsigned")) { return "TUINT"; } else { return "TINT"; } } else if (CxxUtilities::String::include(dataTypeName, "long")) { return "TLONG"; } else if (CxxUtilities::String::include(dataTypeName, "float")) { return "TFLOAT"; } else if (CxxUtilities::String::include(dataTypeName, "double")) { return "TDOUBLE"; } else if (CxxUtilities::String::include(dataTypeName, "x") || CxxUtilities::String::include(dataTypeName, "bits") || CxxUtilities::String::include(dataTypeName, "bit")) { return "TBIT"; } else { using namespace std; cerr << "CxxUtilities::FitsUtility::getCfitsioStyleDataTypeNumber(): Unrecognizable data type name " << dataTypeName << " provided." << endl; return "INVALID"; } } /** * SIB2-style data type names are: * byte,unsignedByte * short,unsignedShort * int,unsignedInt * long,unsignedLong * float * double * hexBinary */ static void getTZEROAndTSCALForSIB2StyleDataTypeName(std::string dataTypeName, double& resultingTZERO, double& resultingTSCAL) { char type = convertSIB2StyleDataTypeNameToCfitsioStyleTFORM(dataTypeName)[0]; dataTypeName = CxxUtilities::String::downCase(dataTypeName); if (CxxUtilities::String::include(dataTypeName, "float") || CxxUtilities::String::include(dataTypeName, "double") || CxxUtilities::String::include(dataTypeName, "x") || CxxUtilities::String::include(dataTypeName, "bit")) { //nothing to do return; } if (CxxUtilities::String::include(dataTypeName, "unsigned")) { //unsigned switch (type) { case 'B': //unsiged byte resultingTSCAL = 1; resultingTZERO = 0; break; case 'I': //unsigned short case 'U': resultingTSCAL = 1; resultingTZERO = 32768; break; case 'J': //unsigned int case 'V': resultingTSCAL = 1; resultingTZERO = 2147483648; break; case 'K': //unsigned long resultingTSCAL = 1; resultingTZERO = 9223372036854775808; break; default: break; } } else { //signed switch (type) { case 'B': //signed byte case 'S': resultingTSCAL = 1; resultingTZERO = -128; break; case 'I': //signed short resultingTSCAL = 1; resultingTZERO = 0; break; case 'J': //signed int resultingTSCAL = 1; resultingTZERO = 0; break; case 'K': //signed long resultingTSCAL = 1; resultingTZERO = 0; break; default: using namespace std; cerr << "CxxUtilities::FitsUtility::getTZEROAndTSCALForSIB2StyleDataTypeName(): Unrecognizable data type name " << dataTypeName << " provided." << endl; break; } } } //end of getTZEROAndTSCALForSIB2StyleDataTypeName() }; class FitsColumnDefinition { public: /** Column name. */ std::string TTYPE; public: /** Column data type. */ std::string TFORM; public: std::string dataTypeName; public: /** Unit. */ std::string TUNIT; public: /** Column display format. */ std::string TDISP; public: /** Scaling factor. */ double TSCAL = 0; public: /** Offset used in the scaling. */ double TZERO = 0; public: /** Comment. */ std::string comment; private: bool isUnitSet_ = false; bool isDisplayFormatSet_ = false; public: FitsColumnDefinition(std::string columnName, std::string columnDataType, std::string comment = "") { this->TTYPE = columnName; this->dataTypeName = columnDataType; std::string cfitsioStyleTFORM = FitsUtility::convertSIB2StyleDataTypeNameToCfitsioStyleTFORM(columnDataType); if (CxxUtilities::String::containsNumber(cfitsioStyleTFORM)) { this->TFORM = cfitsioStyleTFORM; } else { this->TFORM = "1" + cfitsioStyleTFORM; } this->comment = comment; setTZEROAndTSCAL(); } public: void setTZEROAndTSCAL() { FitsUtility::getTZEROAndTSCALForSIB2StyleDataTypeName(this->dataTypeName, this->TZERO, this->TSCAL); } public: void setUnit(std::string unit) { this->TUNIT = unit; this->isUnitSet_ = true; } public: bool isUnitSet() { return isUnitSet_; } public: void setDisplayFormat(std::string format) { this->TDISP = format; this->isDisplayFormatSet_ = true; } public: bool isDisplayFormatSet() { return isDisplayFormatSet_; } }; class FitsExtensionDefinition { public: std::string extensionName; public: std::vector<FitsColumnDefinition> columnDefinitions; public: FitsExtensionDefinition(std::string extensionName) { this->extensionName = extensionName; } public: FitsExtensionDefinition(std::string extensionName, std::vector<FitsColumnDefinition> columnDefinitions) { this->extensionName = extensionName; this->columnDefinitions = columnDefinitions; } public: void push(const FitsColumnDefinition& columnDefinition) { this->columnDefinitions.push_back(columnDefinition); } public: FitsColumnDefinition& at(size_t index) { return this->columnDefinitions.at(index); } public: size_t nColumns() { return this->columnDefinitions.size(); } public: size_t size() { return this->columnDefinitions.size(); } public: static FitsExtensionDefinition* constructFromListOfColumnNameDataTypeAndComment(std::string extensionName, std::string listOfColumnNamesAndDataTypeNames, std::string delimiter = " ") { FitsExtensionDefinition* extensionDefinition = new FitsExtensionDefinition(extensionName); auto lines = CxxUtilities::String::splitIntoLines(listOfColumnNamesAndDataTypeNames); for (auto& line : lines) { std::vector<std::string> array = CxxUtilities::String::split(line, delimiter); if (array.size() < 2) { using namespace std; cerr << "CxxUtilities::FitsExtensionDefinition::constructFromListOfColumnNameDataTypeAndComment(): " << "invalid entry in the column definition list (" << line << ")" << endl; continue; } std::string columnName = array[0]; std::string columnDataType = array[1]; std::string comment = ""; if (array.size() >= 3) { std::stringstream ss; for (size_t i = 2; i < array.size(); i++) { ss << array[i]; if (i != array.size() - 1) { ss << " "; } } comment = ss.str(); } FitsColumnDefinition columnDefinition(columnName, columnDataType, comment); extensionDefinition->push(columnDefinition); } return extensionDefinition; } public: char** createTTYPEs() { char** ttypes = new char*[this->columnDefinitions.size()]; for (size_t i = 0; i < this->columnDefinitions.size(); i++) { ttypes[i] = new char[this->columnDefinitions.at(i).TTYPE.size() + 1]; strcpy(ttypes[i], this->columnDefinitions.at(i).TTYPE.c_str()); } return ttypes; } public: void deleteTTYPEs(char** ttypes) { for (size_t i = 0; i < this->columnDefinitions.size(); i++) { delete ttypes[i]; } delete ttypes; } public: char** createTFORMs() { char** tforms = new char*[this->columnDefinitions.size()]; for (size_t i = 0; i < this->columnDefinitions.size(); i++) { tforms[i] = new char[this->columnDefinitions.at(i).TFORM.size() + 1]; strcpy(tforms[i], this->columnDefinitions.at(i).TFORM.c_str()); } return tforms; } public: void deleteTFORMs(char** tforms) { for (size_t i = 0; i < this->columnDefinitions.size(); i++) { delete tforms[i]; } delete tforms; } public: char** createTUNITs() { char** tunits = new char*[this->columnDefinitions.size()]; for (size_t i = 0; i < this->columnDefinitions.size(); i++) { tunits[i] = new char[this->columnDefinitions.at(i).TUNIT.size() + 1]; strcpy(tunits[i], this->columnDefinitions.at(i).TUNIT.c_str()); } return tunits; } public: void deleteTUNITs(char** tunits) { for (size_t i = 0; i < this->columnDefinitions.size(); i++) { delete tunits[i]; } delete tunits; } public: const std::string& getExtensionName() const { return extensionName; } public: void setExtensionName(const std::string& extensionName) { this->extensionName = extensionName; } private: std::vector<std::string> columnNames; std::map<std::string, size_t> columnNameAndColumnIndexMap; std::vector<std::tuple<std::string/*column name*/, int/*column index*/, int/*data type number*/>> columnNameAndColumnIndexVector; public: std::vector<std::string>& getColumnNames() { if (this->columnNames.size() != this->columnDefinitions.size()) { this->columnNames.clear(); for (auto& e : this->columnDefinitions) { this->columnNames.push_back(e.TTYPE); } } return columnNames; } public: size_t getColumnIndex(std::string columnName) { if (this->columnNameAndColumnIndexMap.size() != this->columnDefinitions.size()) { this->columnNameAndColumnIndexMap.clear(); for (size_t i = 0; i < this->columnDefinitions.size(); i++) { auto columnName = this->columnDefinitions[i].TTYPE; this->columnNameAndColumnIndexMap[columnName] = i; } } if (columnNameAndColumnIndexMap.count(columnName) != 0) { return columnNameAndColumnIndexMap[columnName]; } else { using namespace std; cerr << "CxxUtilities::FitsExtensionDefinition::getColumnIndex(): invalid column name " << columnName << endl; exit(-1); } } public: std::vector< // std::tuple<std::string/*column name*/, int/*column index*/, int/*data type number*/> // >& getColumnNameAndColumnIndexTupleVector() { if (this->columnNameAndColumnIndexVector.size() != this->columnDefinitions.size()) { this->columnNameAndColumnIndexVector.clear(); for (size_t i = 0; i < this->columnDefinitions.size(); i++) { auto columnName = this->columnDefinitions[i].TTYPE; auto columnIndex = i; auto dataTypeNumber = FitsUtility::getCfitsioStyleDataTypeNumber(this->columnDefinitions[i].dataTypeName); std::tuple<std::string, int, int> entry = std::make_tuple(columnName, columnIndex, dataTypeNumber); this->columnNameAndColumnIndexVector.push_back(entry); } } return this->columnNameAndColumnIndexVector; } public: std::string toString() { using namespace std; std::stringstream ss; size_t i = 0; for (auto& e : this->columnDefinitions) { ss << left << setw(3) << i << " TTYPE=" << setw(32) << e.TTYPE << " TFORM=" << setw(4) << e.TFORM << " TUNIT=" << setw(5) << e.TUNIT << " TZERO=" << setw(12) << e.TZERO << " TSCAL=" << setw(12) << e.TSCAL << " " << setw(15) << e.dataTypeName << " " << setw(8) << FitsUtility::getCfitsioStyleDataTypeNumberAsString(e.dataTypeName) << endl; i++; } return ss.str(); } }; } #endif /* CXXUTILITIES_FITSFILE_HH_ */
open-hand/hzero-front
packages/hzero-front/src/components/Tips/index.js
<reponame>open-hand/hzero-front<gh_stars>10-100 import React, { Component } from 'react'; import { Bind } from 'lodash-decorators'; import { Tooltip } from 'hzero-ui'; import { queryToolTip } from '../../services/api'; import StaticTextEditor from './StaticTextEditor'; import styles from './index.less'; export default class Tips extends Component { constructor(props) { super(props); this.staticTextEditor = React.createRef(); this.state = { prevContent: '', prevTitle: '', visible: false }; } componentDidMount() { const { code, lang } = this.props; queryToolTip({ textCode: code, lang }).then(res => { if (res) { this.setState({ prevContent: res.text, prevTitle: res.title }); } else { this.setState({ prevContent: '', prevTitle: '' }); } }); } @Bind() handleVisible() { const { visible } = this.state; this.setState({ visible }); } @Bind() renderRichEditor() { const { prevContent, prevTitle } = this.state; const { title } = this.props; return ( <> <div style={{ textAlign: 'center' }}>{title || prevTitle}</div> <StaticTextEditor content={prevContent} readOnly onRef={staticTextEditor => { this.staticTextEditor = staticTextEditor; }} /> </> ); } render() { const { children, title, code, lang, ...others } = this.props; return ( <Tooltip trigger="click" overlayClassName={styles['editor-tooltip']} {...others} title={this.renderRichEditor()} > {children} </Tooltip> ); } }
Intel-EPID-SDK/epid-sdk
epid/internal/ippmath/test/tatepairing-test.cc
/*############################################################################ # Copyright 2016-2019 Intel 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. ############################################################################*/ /// Intel(R) EPID 1.1 Pairing unit tests. /*! \file */ #include <cstring> #include "gtest/gtest.h" #include "testhelper/1.1/epid_params-testhelper.h" #include "testhelper/epid_gtest-testhelper.h" #include "testhelper/errors-testhelper.h" #include "testhelper/ffelement_wrapper-testhelper.h" extern "C" { #include "ippmath/tatepairing.h" } /// compares Epid11GtElemStr values bool operator==(Epid11GtElemStr const& lhs, Epid11GtElemStr const& rhs) { return 0 == std::memcmp(&lhs, &rhs, sizeof(lhs)); } namespace { class Epid11PairingTest : public ::testing::Test { public: virtual void SetUp() { params = new Epid11ParamsObj(); } virtual void TearDown() { delete params; } static const Epid11G1ElemStr kGaElemStr; static const Epid11G2ElemStr kGbElemStr; Epid11ParamsObj* params; }; const Epid11G1ElemStr Epid11PairingTest::kGaElemStr = { 0x02, 0x5A, 0xC4, 0xC5, 0xCD, 0x7D, 0xAA, 0xFD, 0x26, 0xE5, 0x0B, 0xA9, 0xB4, 0xE1, 0x72, 0xA1, 0x65, 0x2D, 0x84, 0xAD, 0x34, 0x34, 0xF8, 0x62, 0x98, 0x6A, 0x15, 0xBE, 0xEA, 0xE3, 0xCC, 0x56, 0x05, 0x70, 0x5F, 0x4F, 0x11, 0xAF, 0x45, 0xCF, 0x04, 0x1B, 0x96, 0xAD, 0xEB, 0x26, 0xEE, 0x95, 0x65, 0x4B, 0xD3, 0xD6, 0x5C, 0x13, 0x76, 0xB7, 0x7A, 0xA1, 0xC6, 0xDA, 0xED, 0x5A, 0x40, 0xCE}; const Epid11G2ElemStr Epid11PairingTest::kGbElemStr = { 0x02, 0x10, 0x9A, 0xF4, 0x06, 0x32, 0x30, 0x89, 0xCB, 0x95, 0xE9, 0x55, 0x0E, 0x9D, 0xAF, 0x0E, 0x98, 0xCD, 0xCA, 0xDC, 0xB1, 0xFF, 0xFC, 0xD1, 0x45, 0x66, 0xBB, 0x86, 0x46, 0x1E, 0x8C, 0x30, 0x04, 0x78, 0x53, 0xE1, 0x3F, 0x96, 0xC5, 0xE4, 0x15, 0x23, 0x7B, 0x1F, 0x3F, 0x2C, 0xD3, 0x95, 0x40, 0xBC, 0x7A, 0x31, 0x1F, 0x14, 0x38, 0x9E, 0x1A, 0xA5, 0xD6, 0x63, 0x10, 0x91, 0xE4, 0xD3, 0x00, 0xB4, 0x02, 0xBC, 0x47, 0xFA, 0xA6, 0x29, 0x82, 0x0B, 0xB1, 0xD5, 0xFF, 0xF2, 0xE6, 0xB0, 0xC6, 0xAE, 0xE8, 0x7B, 0x91, 0xD9, 0xEE, 0x66, 0x07, 0x1F, 0xFD, 0xA2, 0xE7, 0x02, 0x66, 0xDD, 0x05, 0x2E, 0xF8, 0xC6, 0xC1, 0x6A, 0xEF, 0x3C, 0xC1, 0x95, 0xF6, 0x26, 0xCE, 0x5E, 0x55, 0xD1, 0x64, 0x13, 0x28, 0xB1, 0x18, 0x57, 0xD8, 0x1B, 0x84, 0xFA, 0xEC, 0x7E, 0x5D, 0x99, 0x06, 0x49, 0x05, 0x73, 0x35, 0xA9, 0xA7, 0xF2, 0xA1, 0x92, 0x5F, 0x3E, 0x7C, 0xDF, 0xAC, 0xFE, 0x0F, 0xF5, 0x08, 0xD0, 0x3C, 0xAE, 0xCD, 0x58, 0x00, 0x5F, 0xD0, 0x84, 0x7E, 0xEA, 0x63, 0x57, 0xFE, 0xC6, 0x01, 0x56, 0xDA, 0xF3, 0x72, 0x61, 0xDA, 0xC6, 0x93, 0xB0, 0xAC, 0xEF, 0xAA, 0xD4, 0x51, 0x6D, 0xCA, 0x71, 0x1E, 0x06, 0x73, 0xEA, 0x83, 0xB2, 0xB1, 0x99, 0x4A, 0x4D, 0x4A, 0x0D, 0x35, 0x07}; /////////////////////////////////////////////////////////////////////// // NewEpid11PairingState / DeleteEpid11PairingState // test that delete works in a "normal" valid case. TEST_F(Epid11PairingTest, DeleteWorksGivenNewlyCreatedPairingState) { Epid11PairingState* ps = nullptr; THROW_ON_EPIDERR(NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); EXPECT_NO_THROW(DeleteEpid11PairingState(&ps)); } // test that delete works if there is nothing to do TEST_F(Epid11PairingTest, DeleteWorksGivenNullPointer) { EXPECT_NO_THROW(DeleteEpid11PairingState(nullptr)); Epid11PairingState* ps = nullptr; EXPECT_NO_THROW(DeleteEpid11PairingState(&ps)); } // test that new succeeds with valid parameters TEST_F(Epid11PairingTest, NewSucceedsGivenValidParameters) { Epid11PairingState* ps = nullptr; EXPECT_EQ(kEpidNoErr, NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); DeleteEpid11PairingState(&ps); } // test that new fails if any options are NULL TEST_F(Epid11PairingTest, NewFailsGivenNullParameters) { Epid11PairingState* ps = nullptr; EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(nullptr, this->params->G2, this->params->GT, &ps)); DeleteEpid11PairingState(&ps); EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(this->params->G1, nullptr, this->params->GT, &ps)); DeleteEpid11PairingState(&ps); EXPECT_EQ( kEpidBadArgErr, NewEpid11PairingState(this->params->G1, this->params->G2, nullptr, &ps)); DeleteEpid11PairingState(&ps); EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, nullptr)); } // test that new checks that G1 is valid TEST_F(Epid11PairingTest, NewFailsGivenInvalidG1) { Epid11PairingState* ps = nullptr; EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(this->params->G2, this->params->G2, this->params->GT, &ps)); DeleteEpid11PairingState(&ps); } // test that new checks that G2 is valid TEST_F(Epid11PairingTest, NewFailsGivenInvalidG2) { Epid11PairingState* ps = nullptr; EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(this->params->G1, this->params->G1, this->params->GT, &ps)); DeleteEpid11PairingState(&ps); } // test that new checks that GT is valid TEST_F(Epid11PairingTest, NewFailsGivenInvalidGT) { FiniteFieldObj GFp; Epid11PairingState* ps = nullptr; EXPECT_EQ(kEpidBadArgErr, NewEpid11PairingState(this->params->G1, this->params->G2, GFp, &ps)); DeleteEpid11PairingState(&ps); } /////////////////////////////////////////////////////////////////////// // Pairing TEST_F(Epid11PairingTest, PairingWorksFromG1AndG2ToGt) { Epid11GtElemStr r_expected_str = { 0x02, 0xE1, 0x84, 0x16, 0x53, 0x10, 0x0E, 0xEC, 0xFB, 0xDE, 0xF3, 0x5E, 0x2E, 0x26, 0xEE, 0x45, 0x0C, 0xD7, 0x97, 0xA7, 0x35, 0x43, 0x08, 0x5E, 0x03, 0xB9, 0xFE, 0x91, 0x8A, 0x02, 0x14, 0xB4, 0x07, 0x7F, 0x8A, 0x5E, 0xFD, 0xE1, 0x83, 0xC9, 0xCE, 0x1C, 0xC9, 0xF1, 0xCC, 0xB0, 0x52, 0x81, 0xAD, 0x80, 0x2D, 0x13, 0x1C, 0x32, 0xEC, 0xAF, 0xA0, 0x8B, 0x66, 0x05, 0x0A, 0x89, 0x26, 0xAD, 0x06, 0x75, 0x3B, 0x3B, 0xE5, 0xFB, 0x62, 0x20, 0xA8, 0xC3, 0x91, 0xC6, 0x26, 0xC6, 0x58, 0x71, 0xB1, 0x85, 0x06, 0xBD, 0xAE, 0x06, 0x51, 0xF9, 0x86, 0x2A, 0xC1, 0x5A, 0x11, 0xBA, 0x17, 0xE1, 0x01, 0x4B, 0x22, 0x66, 0xEB, 0xCF, 0x7E, 0x2B, 0xE7, 0x0A, 0xF2, 0x77, 0x1C, 0xE6, 0x48, 0x8F, 0x3E, 0xD8, 0x7D, 0x71, 0xF1, 0x78, 0x4C, 0x80, 0x93, 0xF8, 0x08, 0xB7, 0xCB, 0xAF, 0x04, 0xDF, 0x04, 0x5C, 0x19, 0x3C, 0xD3, 0x29, 0x11, 0xE7, 0xC5, 0x58, 0x68, 0xEA, 0x65, 0xBB, 0x48, 0x5F, 0x3A, 0x62, 0xD9, 0x62, 0x40, 0x57, 0x53, 0x19, 0x9B, 0xB5, 0x6C, 0x52, 0x0C, 0x33, 0x27, 0x14, 0x06, 0x6A, 0xAD, 0xB0, 0x38, 0x41, 0xD0, 0xA5, 0x37, 0x54, 0xC5, 0x3E, 0x3B, 0x5F, 0x1A, 0xAF, 0x75, 0x8F, 0xCA, 0x42, 0xB9, 0xA6, 0x1E, 0x18, 0xB2, 0x6B, 0x31, 0x7D, 0x5C, 0xC6, 0xE8, 0xDC}; Epid11GtElemStr r_str = {0}; FfElementObj r(&this->params->GT); EcPointObj ga_elem(&this->params->G1, this->kGaElemStr); EcPointObj gb_elem(&this->params->G2, this->kGbElemStr); Epid11PairingState* ps = nullptr; THROW_ON_EPIDERR(NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); EXPECT_EQ(kEpidNoErr, Epid11Pairing(ps, ga_elem, gb_elem, r)); DeleteEpid11PairingState(&ps); THROW_ON_EPIDERR(WriteFfElement(this->params->GT, r, &r_str, sizeof(r_str))); EXPECT_EQ(r_expected_str, r_str); } TEST_F(Epid11PairingTest, PairingGivenPointAtInfinityReturns1) { Epid11GtElemStr r_expected_str = {0}; r_expected_str.a[0].a[0].data.data[31] = 1; Epid11GtElemStr r_str = {0}; FfElementObj r(&this->params->GT); EcPointObj ga_elem(&this->params->G1); EcPointObj gb_elem(&this->params->G2, this->kGbElemStr); Epid11PairingState* ps = nullptr; THROW_ON_EPIDERR(NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); EXPECT_EQ(kEpidNoErr, Epid11Pairing(ps, ga_elem, gb_elem, r)); DeleteEpid11PairingState(&ps); THROW_ON_EPIDERR(WriteFfElement(this->params->GT, r, &r_str, sizeof(r_str))); EXPECT_EQ(r_expected_str, r_str); } TEST_F(Epid11PairingTest, PairingFailsOnPointMismatch) { FfElementObj r(&this->params->GT); EcPointObj ga_elem(&this->params->G1, this->kGaElemStr); EcPointObj gb_elem(&this->params->G2, this->kGbElemStr); Epid11PairingState* ps = nullptr; THROW_ON_EPIDERR(NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); EXPECT_EQ(kEpidBadArgErr, Epid11Pairing(ps, gb_elem, ga_elem, r)); DeleteEpid11PairingState(&ps); } TEST_F(Epid11PairingTest, PairingFailsOnInvalidPointInG1) { FfElementObj r(&this->params->GT); EcPointObj ga_elem(&this->params->G3); EcPointObj gb_elem(&this->params->G2, this->kGbElemStr); Epid11PairingState* ps = nullptr; THROW_ON_EPIDERR(NewEpid11PairingState(this->params->G1, this->params->G2, this->params->GT, &ps)); EXPECT_EQ(kEpidBadArgErr, Epid11Pairing(ps, gb_elem, ga_elem, r)); DeleteEpid11PairingState(&ps); } } // namespace
reactjsguru/atom-settings
packages/ide-typescript/node_modules/bufrw/test/atoms.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var testRW = require('../test_rw'); var test = require('tape'); var atoms = require('../atoms'); test('atoms.Int8', testRW.cases(atoms.Int8, [ [-0x12, [0xee]], [ 0, [0x00]], [ 0x12, [0x12]], // value validation { writeTest: { value: null, error: { type: 'bufrw.invalid-argument', message: 'invalid argument, expected a number' } } }, { writeTest: { value: 1000, error: { type: 'bufrw.range-error', message: 'value 1000 out of range, min: -128 max: 127' } } }, // truncation { writeTest: { value: 0, length: 0, error: { type: 'bufrw.short-buffer', name: 'BufrwShortBufferError', message: 'expected at least 1 bytes, only have 0 @0', actual: 0, expected: 1, offset: 0 } }, readTest: { bytes: [], error: { name: 'BufrwShortBufferError', type: 'bufrw.short-buffer', message: 'expected at least 1 bytes, only have 0 @0', actual: 0, expected: 1, offset: 0 } } } ])); test('atoms.Int16BE', testRW.cases(atoms.Int16BE, [ [-0x1234, [0xed, 0xcc]], [ 0, [0x00, 0x00]], [ 0x1234, [0x12, 0x34]] ])); test('atoms.Int32BE', testRW.cases(atoms.Int32BE, [ [-0x12345678, [0xed, 0xcb, 0xa9, 0x88]], [ 0x00000000, [0x00, 0x00, 0x00, 0x00]], [ 0x12345678, [0x12, 0x34, 0x56, 0x78]] ])); test('atoms.Int16LE', testRW.cases(atoms.Int16LE, [ [-0x1234, [0xcc, 0xed]], [ 0, [0x00, 0x00]], [ 0x1234, [0x34, 0x12]] ])); test('atoms.Int32LE', testRW.cases(atoms.Int32LE, [ [-0x12345678, [0x88, 0xa9, 0xcb, 0xed]], [ 0x00000000, [0x00, 0x00, 0x00, 0x00]], [ 0x12345678, [0x78, 0x56, 0x34, 0x12]] ])); test('atoms.UInt8', testRW.cases(atoms.UInt8, [ [ 0, [0x00]], [0x12, [0x12]], [0xee, [0xee]] ])); test('atoms.UInt16BE', testRW.cases(atoms.UInt16BE, [ [ 0, [0x00, 0x00]], [0x1234, [0x12, 0x34]], [0xedcc, [0xed, 0xcc]] ])); test('atoms.UInt32BE', testRW.cases(atoms.UInt32BE, [ [0x00000000, [0x00, 0x00, 0x00, 0x00]], [0x12345678, [0x12, 0x34, 0x56, 0x78]], [0xedcba988, [0xed, 0xcb, 0xa9, 0x88]] ])); test('atoms.UInt16LE', testRW.cases(atoms.UInt16LE, [ [ 0, [0x00, 0x00]], [0x1234, [0x34, 0x12]], [0xedcc, [0xcc, 0xed]] ])); test('atoms.UInt32LE', testRW.cases(atoms.UInt32LE, [ [ 0x00000000, [0x00, 0x00, 0x00, 0x00]], [ 0x12345678, [0x78, 0x56, 0x34, 0x12]], [ 0xedcba988, [0x88, 0xa9, 0xcb, 0xed]] ])); test('atoms.FloatLE', testRW.cases(atoms.FloatLE, [ [-1, [0x00, 0x00, 0x80, 0xbf]], [ 0, [0x00, 0x00, 0x00, 0x00]], [ 1, [0x00, 0x00, 0x80, 0x3f]] ])); test('atoms.FloatBE', testRW.cases(atoms.FloatBE, [ [-1, [0xbf, 0x80, 0x00, 0x00]], [ 0, [0x00, 0x00, 0x00, 0x00]], [ 1, [0x3f, 0x80, 0x00, 0x00]] ])); test('atoms.DoubleLE', testRW.cases(atoms.DoubleLE, [ [-1, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xbf]], [ 0, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]], [ 1, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]] ])); test('atoms.DoubleBE', testRW.cases(atoms.DoubleBE, [ [-1, [0xbf, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]], [ 0, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]], [ 1, [0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]] ]));
aimldl/coding
c++/en/dropbox/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp
<filename>c++/en/dropbox/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp<gh_stars>0  #include "pch.h" // Uncomment this in Visual Studio #include <iostream> #include <set> using namespace std; int main() { auto x = 2; auto y = 3.141592; auto z = &x; // Show the typeid of each variable cout << typeid(x).name() << endl; // int cout << typeid(y).name() << endl; // double cout << typeid(z).name() << endl; // int * return 0; }
AsahiOS/gate
usr/src/prototypes/prototype.h
<filename>usr/src/prototypes/prototype.h /* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2021 <contributor> */ #ifndef _PROTOTYPE_H #define _PROTOTYPE_H /* * Describe the purpose of the file here. */ #ifdef __cplusplus extern "C" { #endif /* Put your definitions in here */ #ifdef __cplusplus } #endif #endif /* _PROTOTYPE_H */
eccles/lnxproc
lnxproc/pidfd.py
<reponame>eccles/lnxproc ''' Contains PidFd() class Reads the /proc/<pid>/fd directory and resolves symbolic links NB requires sudo ''' from contextlib import suppress from logging import getLogger from os import listdir, readlink, path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class PidFd(ReadFile): ''' PidFd handling ''' FILENAME = ospath.join('proc', '%s', 'fd') KEY = 'pidfd' def read(self): ''' The <pid>/fd is a directory so we make the dictionary here in case the pid goes away ''' LOGGER.debug("Read") ret = {} with suppress(FileNotFoundError): for line in listdir(self.filename): if line: try: ret[int(line)] = readlink( ospath.join(self.filename, line) ) except OSError: pass self.data = ret def normalize(self): ''' Returns data ''' LOGGER.debug("Normalize") return self.data.copy()
TigerBSD/FreeBSD-Custom-ThinkPad
FreeBSD/sys/security/mac/mac_inet6.c
<gh_stars>10-100 /*- * Copyright (c) 2007-2009 <NAME> * All rights reserved. * * This software was developed by <NAME> for the TrustedBSD Project. * * This software was developed at the University of Cambridge Computer * Laboratory with support from a grant from Google, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include "opt_mac.h" #include <sys/param.h> #include <sys/kernel.h> #include <sys/lock.h> #include <sys/malloc.h> #include <sys/mutex.h> #include <sys/sbuf.h> #include <sys/systm.h> #include <sys/mount.h> #include <sys/file.h> #include <sys/namei.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/if_var.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <netinet6/ip6_var.h> #include <security/mac/mac_framework.h> #include <security/mac/mac_internal.h> #include <security/mac/mac_policy.h> static struct label * mac_ip6q_label_alloc(int flag) { struct label *label; int error; label = mac_labelzone_alloc(flag); if (label == NULL) return (NULL); if (flag & M_WAITOK) MAC_POLICY_CHECK(ip6q_init_label, label, flag); else MAC_POLICY_CHECK_NOSLEEP(ip6q_init_label, label, flag); if (error) { MAC_POLICY_PERFORM_NOSLEEP(ip6q_destroy_label, label); mac_labelzone_free(label); return (NULL); } return (label); } int mac_ip6q_init(struct ip6q *q6, int flag) { if (mac_labeled & MPC_OBJECT_IP6Q) { q6->ip6q_label = mac_ip6q_label_alloc(flag); if (q6->ip6q_label == NULL) return (ENOMEM); } else q6->ip6q_label = NULL; return (0); } static void mac_ip6q_label_free(struct label *label) { MAC_POLICY_PERFORM_NOSLEEP(ip6q_destroy_label, label); mac_labelzone_free(label); } void mac_ip6q_destroy(struct ip6q *q6) { if (q6->ip6q_label != NULL) { mac_ip6q_label_free(q6->ip6q_label); q6->ip6q_label = NULL; } } void mac_ip6q_reassemble(struct ip6q *q6, struct mbuf *m) { struct label *label; if (mac_policy_count == 0) return; label = mac_mbuf_to_label(m); MAC_POLICY_PERFORM_NOSLEEP(ip6q_reassemble, q6, q6->ip6q_label, m, label); } void mac_ip6q_create(struct mbuf *m, struct ip6q *q6) { struct label *label; if (mac_policy_count == 0) return; label = mac_mbuf_to_label(m); MAC_POLICY_PERFORM_NOSLEEP(ip6q_create, m, label, q6, q6->ip6q_label); } int mac_ip6q_match(struct mbuf *m, struct ip6q *q6) { struct label *label; int result; if (mac_policy_count == 0) return (1); label = mac_mbuf_to_label(m); result = 1; MAC_POLICY_BOOLEAN_NOSLEEP(ip6q_match, &&, m, label, q6, q6->ip6q_label); return (result); } void mac_ip6q_update(struct mbuf *m, struct ip6q *q6) { struct label *label; if (mac_policy_count == 0) return; label = mac_mbuf_to_label(m); MAC_POLICY_PERFORM_NOSLEEP(ip6q_update, m, label, q6, q6->ip6q_label); } void mac_netinet6_nd6_send(struct ifnet *ifp, struct mbuf *m) { struct label *mlabel; if (mac_policy_count == 0) return; mlabel = mac_mbuf_to_label(m); MAC_POLICY_PERFORM_NOSLEEP(netinet6_nd6_send, ifp, ifp->if_label, m, mlabel); }
impedimentToProgress/UCI-BlueChip
snapgear_linux/user/microwin/src/include/windef.h
<reponame>impedimentToProgress/UCI-BlueChip /* windef.h*/ /* * Copyright (c) 1999 <NAME> <<EMAIL>> * * Win32 API base type definitions */ #define _WINDEF_H #ifdef VXWORKS /* Don't include the internal Tornado header file <ntcontext.h>, ** ** as the definitions in it conflict with these definitions. */ #define __INCntcontexth /* Bring in the core VxWorks definitions as they could conflict ** ** with the ones below if they are brought in later. */ #include <vxWorks.h> #endif #ifndef NULL #define NULL ((void *)0) #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef NOMINMAX #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #endif /* NOMINMAX */ #define CALLBACK #define WINAPI #define WINAPIV #define APIENTRY WINAPI #define APIPRIVATE #define PASCAL #define FAR #define NEAR #define CONST const #define CDECL #define VOID void typedef void *PVOID; typedef char CHAR; typedef short SHORT; typedef long LONG; typedef SHORT *PSHORT; typedef LONG *PLONG; #ifndef VXWORKS typedef unsigned char UCHAR; typedef unsigned short USHORT; typedef unsigned long ULONG; typedef unsigned int UINT; #ifndef __ITRON_TYPES_h_ /* FIXME RTEMS hack*/ #ifndef COMMON_H /* MiniGUI hack*/ typedef int BOOL; #endif #endif #endif /* !VXWORKS*/ typedef ULONG * PULONG; typedef USHORT * PUSHORT; typedef UCHAR * PUCHAR; typedef char * PSZ; typedef int INT; typedef unsigned int *PUINT; typedef unsigned long DWORD; typedef unsigned char BYTE; typedef unsigned short WORD; typedef float FLOAT; typedef FLOAT *PFLOAT; typedef BOOL NEAR *PBOOL; typedef BOOL FAR *LPBOOL; typedef BYTE NEAR *PBYTE; typedef BYTE FAR *LPBYTE; typedef int NEAR *PINT; typedef int FAR *LPINT; typedef WORD NEAR *PWORD; typedef WORD FAR *LPWORD; typedef long FAR *LPLONG; typedef DWORD NEAR *PDWORD; typedef DWORD FAR *LPDWORD; typedef void FAR *LPVOID; typedef CONST void FAR *LPCVOID; typedef unsigned short WCHAR; typedef WCHAR *PWCHAR; typedef WCHAR *LPWCH, *PWCH; typedef CONST WCHAR *LPCWCH, *PCWCH; typedef WCHAR *NWPSTR; typedef WCHAR *LPWSTR, *PWSTR; typedef CONST WCHAR *LPCWSTR, *PCWSTR; typedef CHAR *PCHAR; typedef CHAR *LPCH, *PCH; typedef CONST CHAR *LPCCH, *PCCH; typedef CHAR *NPSTR; typedef CHAR *LPSTR, *PSTR; typedef CONST CHAR *LPCSTR, *PCSTR; typedef char TCHAR, *PTCHAR; typedef unsigned char TBYTE , *PTBYTE ; typedef LPSTR LPTCH, PTCH; typedef LPSTR PTSTR, LPTSTR; typedef LPCSTR LPCTSTR; #define __TEXT(quote) quote #define TEXT(quote) __TEXT(quote) typedef int (FAR WINAPI *FARPROC)(); typedef int (NEAR WINAPI *NEARPROC)(); typedef int (WINAPI *PROC)(); typedef UINT WPARAM; typedef LONG LPARAM; typedef LONG LRESULT; typedef LONG HRESULT; #define MAKEWORD(a, b) ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) << 8)) #define MAKELONG(a, b) ((LONG)(((WORD)(a)) | ((DWORD)((WORD)(b))) << 16)) #define LOWORD(l) ((WORD)(l)) #define HIWORD(l) ((WORD)(((DWORD)(l) >> 16) & 0xFFFF)) #define LOBYTE(w) ((BYTE)(w)) #define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF)) #define PALETTEINDEX(i) ((COLORREF)(0x01000000 | (DWORD)(WORD)(i))) typedef DWORD COLORREF; typedef DWORD *LPCOLORREF; /* handle typedef*/ typedef PVOID HANDLE; typedef HANDLE *PHANDLE; typedef HANDLE NEAR *SPHANDLE; typedef HANDLE FAR *LPHANDLE; typedef HANDLE HGLOBAL; typedef HANDLE HLOCAL; typedef HANDLE GLOBALHANDLE; typedef HANDLE LOCALHANDLE; typedef WORD ATOM; typedef struct hwnd * HWND; typedef struct hdc * HDC; typedef struct hcursor *HCURSOR; typedef struct hgdiobj *HGDIOBJ; typedef struct hgdiobj *HBRUSH; typedef struct hgdiobj *HPEN; typedef struct hgdiobj *HFONT; typedef struct hgdiobj *HBITMAP; typedef struct hgdiobj *HRGN; typedef struct hgdiobj *HPALETTE; typedef HANDLE HICON; typedef HANDLE HINSTANCE; typedef HANDLE HMENU; /* moved to winuser.h for resource compiler*/ /*typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);*/
HendrylNogueira/CursoPython3
pythonMundoTres/ex074.py
<gh_stars>0 ''' Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que está na tupla. ''' import random num = (random.randint(1, 10), random.randint(1, 10), random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)) print(f'Os valores sorteados foram: {num}') print(f'O maior valor é {max(num)}') print(f'O menor valor é {min(num)}')
rbkmoney/woody_java
woody-thrift/src/main/java/com/rbkmoney/woody/thrift/impl/http/interceptor/ext/THSExtensionContext.java
package com.rbkmoney.woody.thrift.impl.http.interceptor.ext; import com.rbkmoney.woody.api.interceptor.ext.ExtensionContext; import com.rbkmoney.woody.api.trace.ContextUtils; import com.rbkmoney.woody.api.trace.TraceData; import com.rbkmoney.woody.thrift.impl.http.THMetadataProperties; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class THSExtensionContext extends ExtensionContext { public THSExtensionContext(TraceData traceData, Object providerContext, Object[] contextParameters) { super(traceData, providerContext, contextParameters); } public HttpServletRequest getProviderRequest() { Object providerContext = getProviderContext(); if (providerContext instanceof HttpServletRequest) { return (HttpServletRequest) providerContext; } throw new IllegalArgumentException("Unknown type:" + providerContext.getClass()); } public HttpServletResponse getProviderResponse() { HttpServletResponse response = null; Object providerContext = getProviderContext(); if (providerContext instanceof HttpServletResponse) { response = (HttpServletResponse) providerContext; } if (response == null) { response = ContextUtils.getContextValue(HttpServletResponse.class, getContextParameters(), 0); } if (response == null) { response = ContextUtils.getMetadataValue(getTraceData().getServiceSpan(), HttpServletResponse.class, THMetadataProperties.TH_TRANSPORT_RESPONSE); } if (response == null) { throw new IllegalArgumentException("Unknown type:" + providerContext.getClass() + "|" + ContextUtils.getContextValue(Object.class, getContextParameters(), 0)); } return response; } public void setResponseHeader(String key, String value) { if (key != null && value != null) { getProviderResponse().setHeader(key, value); } } }
praneethgb/rasa
rasa/nlu/extractors/spacy_entity_extractor.py
<gh_stars>1-10 import typing from typing import Any, Dict, List, Text from rasa.engine.graph import ExecutionContext, GraphComponent from rasa.engine.storage.resource import Resource from rasa.engine.storage.storage import ModelStorage from rasa.shared.nlu.constants import ENTITIES, TEXT from rasa.nlu.utils.spacy_utils import SpacyModel from rasa.nlu.extractors.extractor import EntityExtractorMixin from rasa.shared.nlu.training_data.message import Message from rasa.nlu.extractors._spacy_entity_extractor import SpacyEntityExtractor if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc # This is a workaround around until we have all components migrated to `GraphComponent`. SpacyEntityExtractor = SpacyEntityExtractor class SpacyEntityExtractorGraphComponent(GraphComponent, EntityExtractorMixin): """Entity extractor which uses SpaCy.""" @staticmethod def get_default_config() -> Dict[Text, Any]: """The component's default config (see parent class for full docstring).""" return { # by default all dimensions recognized by spacy are returned # dimensions can be configured to contain an array of strings # with the names of the dimensions to filter for "dimensions": None } def __init__(self, config: Dict[Text, Any]) -> None: """Initialize SpacyEntityExtractorGraphComponent.""" self._config = config @classmethod def create( cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, ) -> GraphComponent: """Creates a new component (see parent class for full docstring).""" return cls(config) @classmethod def required_packages(cls) -> List[Text]: """Lists required dependencies (see parent class for full docstring).""" return ["spacy"] def process(self, messages: List[Message], model: SpacyModel) -> List[Message]: """Extract entities using SpaCy. Args: messages: List of messages to process. model: Container holding a loaded spacy nlp model. Returns: The processed messages. """ for message in messages: # can't use the existing doc here (spacy_doc on the message) # because tokens are lower cased which is bad for NER spacy_nlp = model.model doc = spacy_nlp(message.get(TEXT)) all_extracted = self.add_extractor_name(self._extract_entities(doc)) dimensions = self._config["dimensions"] extracted = self.filter_irrelevant_entities(all_extracted, dimensions) message.set( ENTITIES, message.get(ENTITIES, []) + extracted, add_to_output=True ) return messages @staticmethod def _extract_entities(doc: "Doc") -> List[Dict[Text, Any]]: entities = [ { "entity": ent.label_, "value": ent.text, "start": ent.start_char, "confidence": None, "end": ent.end_char, } for ent in doc.ents ] return entities
neeldaveloper97/entraos
src/main/java/no/entra/entraos/api/repository/TemplateRepository.java
package no.entra.entraos.api.repository; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import io.helidon.common.reactive.Multi; import io.helidon.common.reactive.Single; import io.helidon.dbclient.DbClient; import io.helidon.dbclient.DbRow; import io.netty.util.ResourceLeakDetector.Level; import no.entra.entraos.api.exception.AppExceptionCode; import no.entra.entraos.api.model.PersonContract; import no.entra.entraos.api.model.Template; import no.entra.entraos.api.util.EntityUtils; import no.entra.entraos.api.util.StringUtils; public class TemplateRepository { private DbClient dbClient; public TemplateRepository(DbClient dbClient) { this.dbClient = dbClient; } public Multi<Template> all() { return this.dbClient .execute(exc -> exc.createQuery("SELECT * FROM template").execute()) .map(dbRow -> dbRow.as(Template.class)); } public Single<String> save(Template template) { if(template!=null) { final String id = StringUtils.ensureId(template.getId()); return this.dbClient .execute(exec -> exec .insert("INSERT INTO template(id, contract_name, contract_category_id, contract_type_id, description, contract_properties) VALUES (?, ?, ?, ?, ?, ?)", id, template.getContract_name(), template.getContract_category_id(), template.getContract_type_id(), template.getDescription(), EntityUtils.object_mapToJsonString(template.getContract_properties()) )).map(i -> i>0?id:null); } else { return Single.error(AppExceptionCode.COMMON_BADREQUESTEXCEPTION_400_9998.addMessageParams("Cannot parse the request content for template")); } } public Single<Template> getOne(String id) { return this.dbClient .execute(exec -> exec .createGet("SELECT * FROM template WHERE id=?") .addParam(id) .execute() ) .map(rowOptional -> rowOptional.map(dbRow -> dbRow.as(Template.class)).orElseThrow(() -> AppExceptionCode.COMMON_IDNOTFOUNDEXCEPTION_400_9999.addMessageParams(id)) ); } public Single<Long> update(String id, Template template) { if(template!=null) { template.setId(id); return this.dbClient.execute(exec -> exec.createUpdate("UPDATE template SET contract_name=:contractname , contract_category_id=:contractcategoryid, contract_type_id=:contracttypeid, description=:description, contract_properties=:contractproperties WHERE id=:id") .namedParam(template) .execute()); } else { return Single.error(AppExceptionCode.COMMON_BADREQUESTEXCEPTION_400_9998.addMessageParams("Cannot parse the request content for template")); } } public Single<Long> deleteById(String id) { return this.dbClient.execute(exec -> exec .createDelete("DELETE FROM template WHERE id = :id") .addParam("id", id) .execute() ); } public Template findById(String id) { Optional<DbRow> row = this.dbClient .execute(exec -> exec .createGet("SELECT * FROM template WHERE id=?") .addParam(id) .execute() ).await(); if(row.isPresent()) { return row.get().as(Template.class); } else { return null; } } }
cctvzd7/aliyun-openapi-java-sdk
aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/transform/v20190815/DeleteLinkeantcodeAntcodeDeleteprojectkeyResponseUnmarshaller.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.sofa.transform.v20190815; import com.aliyuncs.sofa.model.v20190815.DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse; import com.aliyuncs.transform.UnmarshallerContext; public class DeleteLinkeantcodeAntcodeDeleteprojectkeyResponseUnmarshaller { public static DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse unmarshall(DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse deleteLinkeantcodeAntcodeDeleteprojectkeyResponse, UnmarshallerContext _ctx) { deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setRequestId(_ctx.stringValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.RequestId")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setResultCode(_ctx.stringValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.ResultCode")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setResultMessage(_ctx.stringValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.ResultMessage")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setCreatedAt(_ctx.stringValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.CreatedAt")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setDeployKeyId(_ctx.longValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.DeployKeyId")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setId(_ctx.longValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.Id")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setProjectId(_ctx.longValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.ProjectId")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setResponseStatusCode(_ctx.longValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.ResponseStatusCode")); deleteLinkeantcodeAntcodeDeleteprojectkeyResponse.setUpdatedAt(_ctx.stringValue("DeleteLinkeantcodeAntcodeDeleteprojectkeyResponse.UpdatedAt")); return deleteLinkeantcodeAntcodeDeleteprojectkeyResponse; } }
ideacrew/opm_enroll
components/benefit_sponsors/config/routes.rb
BenefitSponsors::Engine.routes.draw do namespace :profiles do resources :registrations do post :counties_for_zip_code, on: :collection end namespace :broker_agencies do resources :broker_agency_profiles, only: [:new, :create, :show, :index, :edit, :update] do collection do get :family_index get :messages get :staff_index get :agency_messages get :commission_statements end member do post :clear_assign_for_employer get :assign post :update_assign post :family_datatable get :inbox get :download_commission_statement get :show_commission_statement end end resources :broker_applicants end namespace :employers do resources :employer_profiles, only: [:show] do get :export_census_employees post :bulk_employee_upload get :coverage_reports collection do get :generate_sic_tree get :show_pending end member do get :inbox get :download_invoice end resources :broker_agency, only: [:index, :show, :create] do collection do get :active_broker end get :terminate end end resources :employer_staff_roles do member do get :approve end end end end namespace :inboxes do resources :messages, only: [:show, :destroy] do get :msg_to_portal end end namespace :organizations do resource :office_locations do member do get :new end end end resources :benefit_sponsorships do resources :benefit_applications, controller: "benefit_applications/benefit_applications" do get 'late_rates_check', on: :collection post 'revert' post 'submit_application' post 'force_submit_application' resources :benefit_packages, controller: "benefit_packages/benefit_packages" do get :calculate_employer_contributions, on: :collection get :calculate_employer_contributions, on: :member get :calculate_employee_cost_details, on: :collection get :calculate_employee_cost_details, on: :member get :reference_product_summary, on: :collection resources :sponsored_benefits, controller: "sponsored_benefits/sponsored_benefits" do member do get :calculate_employee_cost_details get :calculate_employer_contributions end collection do get :calculate_employee_cost_details get :calculate_employer_contributions end end end end end end
kevinflaherty1/crnk-framework
crnk-gen/crnk-gen-openapi/src/test/java/io/crnk/gen/openapi/internal/operations/RelationshipGetTest.java
package io.crnk.gen.openapi.internal.operations; import io.crnk.gen.openapi.internal.OperationType; import io.swagger.v3.oas.models.Operation; import org.junit.Assert; import org.junit.jupiter.api.Test; class RelationshipGetTest extends NestedOperationsBaseTest { @Test void operationType() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals(OperationType.GET, RelationshipGet.operationType()); } @Test void isEnabledTrueWhenReadableAndFieldReadable() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResourceField.setReadable(true); Assert.assertTrue(RelationshipGet.isEnabled()); } @Test void isEnabledFalseWhenReadableAndFieldNotReadable() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); Assert.assertTrue(metaResource.isReadable()); metaResource.setReadable(false); Assert.assertFalse(RelationshipGet.isEnabled()); } @Test void isEnabledFalseWhenNotReadableAndFieldReadable() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setReadable(true); Assert.assertFalse(RelationshipGet.isEnabled()); } @Test void isEnabledFalseWhenNotReadableAndFieldNotReadable() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); metaResource.setReadable(false); metaResourceField.setReadable(false); Assert.assertFalse(RelationshipGet.isEnabled()); } @Test void getDescription() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("Retrieve RelatedResourceType references related to a ResourceType resource", RelationshipGet.getDescription()); } @Test void operation() { Operation operation = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource).operation(); Assert.assertTrue(operation.getResponses().containsKey("200")); } @Test void path() { RelationshipGet RelationshipGet = new RelationshipGet(metaResource, metaResourceField, relatedMetaResource); Assert.assertEquals("/ResourcePath/{id}/relationships/someRelatedResource", RelationshipGet.path()); } }
cybervisiontech/cdap
cdap-data-fabric/src/main/java/co/cask/cdap/data2/dataset2/lib/table/MetadataStoreDataset.java
/* * Copyright © 2014 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.data2.dataset2.lib.table; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.api.dataset.lib.AbstractDataset; import co.cask.cdap.api.dataset.table.Delete; import co.cask.cdap.api.dataset.table.Put; import co.cask.cdap.api.dataset.table.Row; import co.cask.cdap.api.dataset.table.Scanner; import co.cask.cdap.api.dataset.table.Table; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.util.List; import javax.annotation.Nullable; /** * Handy dataset to be used for managing metadata */ public class MetadataStoreDataset extends AbstractDataset { private static final Gson GSON = new Gson(); /** * All rows we store use single column of this name. */ private static final byte[] COLUMN = Bytes.toBytes("c"); private final Table table; public MetadataStoreDataset(Table table) { super("ignored", table); this.table = table; } protected <T> byte[] serialize(T value) { return Bytes.toBytes(GSON.toJson(value)); } protected <T> T deserialize(byte[] serialized, Class<T> classOfT) { return GSON.fromJson(Bytes.toString(serialized), classOfT); } // returns first that matches @Nullable public <T> T get(Key id, Class<T> classOfT) { try { Scanner scan = table.scan(id.getKey(), Bytes.stopKeyForPrefix(id.getKey())); Row row = scan.next(); if (row == null || row.isEmpty()) { return null; } byte[] value = row.get(COLUMN); if (value == null) { return null; } return deserialize(value, classOfT); } catch (Exception e) { throw Throwables.propagate(e); } } // lists all that has same first id parts public <T> List<T> list(Key id, Class<T> classOfT) { return list(id, classOfT, Integer.MAX_VALUE); } // lists all that has same first id parts public <T> List<T> list(Key id, Class<T> classOfT, int limit) { return list(id, null, classOfT, limit, Predicates.<T>alwaysTrue()); } // lists all that has first id parts in range of startId and stopId public <T> List<T> list(Key startId, @Nullable Key stopId, Class<T> classOfT, int limit, Predicate<T> filter) { byte[] startKey = startId.getKey(); byte[] stopKey = stopId == null ? Bytes.stopKeyForPrefix(startKey) : stopId.getKey(); try { List<T> list = Lists.newArrayList(); Scanner scan = table.scan(startKey, stopKey); Row next; while ((limit-- > 0) && (next = scan.next()) != null) { byte[] columnValue = next.get(COLUMN); if (columnValue == null) { continue; } T value = deserialize(columnValue, classOfT); if (filter.apply(value)) { list.add(value); } } return list; } catch (Exception e) { throw Throwables.propagate(e); } } public <T> void deleteAll(Key id) { byte[] prefix = id.getKey(); byte[] stopKey = Bytes.stopKeyForPrefix(prefix); try { Scanner scan = table.scan(prefix, stopKey); Row next; while ((next = scan.next()) != null) { String columnValue = next.getString(COLUMN); if (columnValue == null) { continue; } table.delete(new Delete(next.getRow()).add(COLUMN)); } } catch (Exception e) { throw Throwables.propagate(e); } } public <T> void write(Key id, T value) { try { table.put(new Put(id.getKey()).add(COLUMN, serialize(value))); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Metadata entry key */ public static final class Key { private final byte[] key; private Key(byte[] key) { this.key = key; } public byte[] getKey() { return key; } /** * Builds {@link Key}s. */ public static final class Builder { private byte[] key; public Builder() { key = new byte[0]; } public Builder(Key start) { this.key = start.getKey(); } public Builder add(String part) { byte[] b = Bytes.toBytes(part); key = Bytes.add(key, Bytes.toBytes(b.length), b); return this; } public Builder add(String... parts) { for (String part : parts) { add(part); } return this; } public Builder add(long part) { key = Bytes.add(key, Bytes.toBytes(part)); return this; } public Key build() { return new Key(key); } } } }
esean/stl_voro_fill
sw/3rd_party/VTK-7.1.0/Common/DataModel/vtkImplicitBoolean.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkImplicitBoolean.cxx Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImplicitBoolean.h" #include "vtkImplicitFunctionCollection.h" #include "vtkObjectFactory.h" #include <cmath> vtkStandardNewMacro(vtkImplicitBoolean); // Construct with union operation. vtkImplicitBoolean::vtkImplicitBoolean() { this->OperationType = VTK_UNION; this->FunctionList = vtkImplicitFunctionCollection::New(); } vtkImplicitBoolean::~vtkImplicitBoolean() { this->FunctionList->Delete(); } vtkMTimeType vtkImplicitBoolean::GetMTime() { vtkMTimeType fMtime; vtkMTimeType mtime = this->vtkImplicitFunction::GetMTime(); vtkImplicitFunction *f; vtkCollectionSimpleIterator sit; for (this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { fMtime = f->GetMTime(); if ( fMtime > mtime ) { mtime = fMtime; } } return mtime; } // Add another implicit function to the list of functions. void vtkImplicitBoolean::AddFunction(vtkImplicitFunction *f) { if ( ! this->FunctionList->IsItemPresent(f) ) { this->Modified(); this->FunctionList->AddItem(f); } } // Remove a function from the list of implicit functions to boolean. void vtkImplicitBoolean::RemoveFunction(vtkImplicitFunction *f) { if ( this->FunctionList->IsItemPresent(f) ) { this->Modified(); this->FunctionList->RemoveItem(f); } } // Evaluate boolean combinations of implicit function using current operator. double vtkImplicitBoolean::EvaluateFunction(double x[3]) { double value = 0; double v; vtkImplicitFunction *f; if (this->FunctionList->GetNumberOfItems() == 0) { return value; } vtkCollectionSimpleIterator sit; if ( this->OperationType == VTK_UNION ) { //take minimum value for (value = VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=f->FunctionValue(x)) < value ) { value = v; } } } else if ( this->OperationType == VTK_INTERSECTION ) { //take maximum value for (value=-VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=f->FunctionValue(x)) > value ) { value = v; } } } else if ( this->OperationType == VTK_UNION_OF_MAGNITUDES ) { //take minimum absolute value for (value = VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=fabs(f->FunctionValue(x))) < value ) { value = v; } } } else //difference { vtkImplicitFunction *firstF; this->FunctionList->InitTraversal(sit); if ( (firstF = this->FunctionList->GetNextImplicitFunction(sit)) != NULL ) { value = firstF->FunctionValue(x); } for (this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( f != firstF ) { if ( (v=(-1.0)*f->FunctionValue(x)) > value ) { value = v; } } } }//else return value; } // Evaluate gradient of boolean combination. void vtkImplicitBoolean::EvaluateGradient(double x[3], double g[3]) { double value = 0; double v; vtkImplicitFunction *f; vtkCollectionSimpleIterator sit; if (this->FunctionList->GetNumberOfItems() == 0) { g[0] = 0; g[1] = 0; g[2] = 0; return; } if ( this->OperationType == VTK_UNION ) { //take minimum value for (value = VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=f->FunctionValue(x)) < value ) { value = v; f->FunctionGradient(x,g); } } } else if ( this->OperationType == VTK_INTERSECTION ) { //take maximum value for (value=-VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=f->FunctionValue(x)) > value ) { value = v; f->FunctionGradient(x,g); } } } if ( this->OperationType == VTK_UNION_OF_MAGNITUDES ) { //take minimum value for (value = VTK_DOUBLE_MAX, this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( (v=fabs(f->FunctionValue(x))) < value ) { value = v; f->FunctionGradient(x,g); } } } else //difference { double gTemp[3]; vtkImplicitFunction *firstF; this->FunctionList->InitTraversal(sit); if ( (firstF = this->FunctionList->GetNextImplicitFunction(sit)) != NULL ) { value = firstF->FunctionValue(x); firstF->FunctionGradient(x,gTemp); g[0] = -1.0*gTemp[0]; g[1] = -1.0*gTemp[1]; g[2] = -1.0*gTemp[2]; } for (this->FunctionList->InitTraversal(sit); (f=this->FunctionList->GetNextImplicitFunction(sit)); ) { if ( f != firstF ) { if ( (v=(-1.0)*f->FunctionValue(x)) > value ) { value = v; f->FunctionGradient(x,gTemp); g[0] = -1.0*gTemp[0]; g[1] = -1.0*gTemp[1]; g[2] = -1.0*gTemp[2]; } } } }//else } void vtkImplicitBoolean::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Function List:\n"; this->FunctionList->PrintSelf(os,indent.GetNextIndent()); os << indent << "Operator Type: "; if ( this->OperationType == VTK_INTERSECTION ) { os << "VTK_INTERSECTION\n"; } else if ( this->OperationType == VTK_UNION ) { os << "VTK_UNION\n"; } else if ( this->OperationType == VTK_UNION_OF_MAGNITUDES ) { os << "VTK_UNION_OF_MAGNITUDES\n"; } else { os << "VTK_DIFFERENCE\n"; } }
crafterm/piccr
test/functional/commments_controller_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'commments_controller' # Re-raise errors caught by the controller. class CommmentsController; def rescue_action(e) raise e end; end class CommmentsControllerTest < Test::Unit::TestCase fixtures :commments def setup @controller = CommmentsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_get_index get :index assert_response :success assert assigns(:commments) end def test_should_get_new get :new assert_response :success end def test_should_create_commment assert_difference('Commment.count') do post :create, :commment => { } end assert_redirected_to commment_path(assigns(:commment)) end def test_should_show_commment get :show, :id => 1 assert_response :success end def test_should_get_edit get :edit, :id => 1 assert_response :success end def test_should_update_commment put :update, :id => 1, :commment => { } assert_redirected_to commment_path(assigns(:commment)) end def test_should_destroy_commment assert_difference('Commment.count', -1) do delete :destroy, :id => 1 end assert_redirected_to commments_path end end
tschaffter/apl-core-library
aplcore/src/component/corecomponent.cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 <yoga/YGNode.h> #include <cmath> #include "apl/common.h" #include "apl/component/componenteventsourcewrapper.h" #include "apl/component/componenteventtargetwrapper.h" #include "apl/component/componentpropdef.h" #include "apl/component/corecomponent.h" #include "apl/component/yogaproperties.h" #include "apl/content/rootconfig.h" #include "apl/engine/builder.h" #include "apl/engine/componentdependant.h" #include "apl/engine/contextwrapper.h" #include "apl/engine/hovermanager.h" #include "apl/engine/keyboardmanager.h" #include "apl/engine/layoutmanager.h" #include "apl/focus/focusmanager.h" #include "apl/livedata/layoutrebuilder.h" #include "apl/livedata/livearray.h" #include "apl/livedata/livearrayobject.h" #include "apl/primitives/accessibilityaction.h" #include "apl/primitives/keyboard.h" #include "apl/time/sequencer.h" #include "apl/time/timemanager.h" #include "apl/touch/pointerevent.h" #include "apl/utils/hash.h" #include "apl/utils/searchvisitor.h" #include "apl/utils/session.h" #include "apl/utils/stickyfunctions.h" #include "apl/utils/stickychildrentree.h" #include "apl/utils/tracing.h" namespace apl { const std::string VISUAL_CONTEXT_TYPE_MIXED = "mixed"; const std::string VISUAL_CONTEXT_TYPE_GRAPHIC = "graphic"; const std::string VISUAL_CONTEXT_TYPE_TEXT = "text"; const std::string VISUAL_CONTEXT_TYPE_VIDEO = "video"; const std::string VISUAL_CONTEXT_TYPE_EMPTY = "empty"; /*****************************************************************/ const static bool DEBUG_BOUNDS = false; const static bool DEBUG_ENSURE = false; const static bool DEBUG_LAYOUTDIRECTION = false; const static bool DEBUG_PADDING = false; const static bool DEBUG_MEASUREMENT = false; /** * A helper function to zero the insets for when a component's position is change to "sticky" */ static void zeroComponentInsets(const CoreComponentPtr &component) { auto nodeRef = component->getNode(); yn::setPosition<YGEdgeLeft>(nodeRef, NAN, *component->getContext()); yn::setPosition<YGEdgeBottom>(nodeRef, NAN, *component->getContext()); yn::setPosition<YGEdgeRight>(nodeRef, NAN, *component->getContext()); yn::setPosition<YGEdgeTop>(nodeRef, NAN, *component->getContext()); yn::setPosition<YGEdgeStart>(nodeRef, NAN, *component->getContext()); yn::setPosition<YGEdgeEnd>(nodeRef, NAN, *component->getContext()); component->setDirty(kPropertyBounds); } /** * A helper function to restore the zeroed insets for when a component's position is change from "sticky" * to something else */ static void restoreComponentInsets(const CoreComponentPtr &component) { auto nodeRef = component->getNode(); yn::setPosition<YGEdgeLeft>(nodeRef, component->getCalculated(kPropertyLeft), *component->getContext()); yn::setPosition<YGEdgeBottom>(nodeRef, component->getCalculated(kPropertyBottom), *component->getContext()); yn::setPosition<YGEdgeRight>(nodeRef, component->getCalculated(kPropertyRight), *component->getContext()); yn::setPosition<YGEdgeTop>(nodeRef, component->getCalculated(kPropertyTop), *component->getContext()); yn::setPosition<YGEdgeStart>(nodeRef, component->getCalculated(kPropertyStart), *component->getContext()); yn::setPosition<YGEdgeEnd>(nodeRef, component->getCalculated(kPropertyEnd), *component->getContext()); component->setDirty(kPropertyBounds); } CoreComponent::CoreComponent(const ContextPtr& context, Properties&& properties, const Path& path) : Component(context, properties.asLabel(*context, "id")), mInheritParentState(properties.asBoolean(*context, "inheritParentState", false)), mStyle(properties.asString(*context, "style", "")), mProperties(std::move(properties)), mParent(nullptr), mYGNodeRef(YGNodeNewWithConfig(context->ygconfig())), mPath(path), mDisplayedChildrenStale(true), mGlobalToLocalIsStale(true), mTextMeasurementHashStale(true), mVisualHashStale(true) { YGNodeSetContext(mYGNodeRef, this); } void CoreComponent::scheduleTickHandler(const Object& handler, double delay) { auto weak_ptr = std::weak_ptr<CoreComponent>(std::static_pointer_cast<CoreComponent>(shared_from_this())); // Lambda capture takes care of handler here as it's a copy. mContext->getRootConfig().getTimeManager()->setTimeout([weak_ptr, handler, delay]() { auto self = weak_ptr.lock(); if (!self) return; auto ctx = self->createEventContext("Tick"); if (propertyAsBoolean(*ctx, handler, "when", true)) { auto commands = Object(arrayifyProperty(*ctx, handler, "commands")); if (!commands.empty()) ctx->sequencer().executeCommands(commands, ctx, self, true); } self->scheduleTickHandler(handler, delay); }, delay); } void CoreComponent::processTickHandlers() { auto& tickHandlers = getCalculated(kPropertyHandleTick); if (tickHandlers.empty() || !tickHandlers.isArray()) return; for (const auto& handler : tickHandlers.getArray()) { auto delay = std::max(propertyAsDouble(*mContext, handler, "minimumDelay", 1000), mContext->getRootConfig().getTickHandlerUpdateLimit()); scheduleTickHandler(handler, delay); } } void CoreComponent::initialize() { APL_TRACE_BLOCK("CoreComponent:initialize"); // TODO: Would be nice to work this in with the regular properties more cleanly. mState.set(kStateChecked, mProperties.asBoolean(*mContext, "checked", false)); mState.set(kStateDisabled, mProperties.asBoolean(*mContext, "disabled", false)); mCalculated.set(kPropertyNotifyChildrenChanged, Object::EMPTY_MUTABLE_ARRAY()); // Fix up the state variables that can be assigned as a property if (mInheritParentState && mParent) mState = mParent->getState(); // Assign the built-in properties. assignProperties(propDefSet()); // Fix layout direction early to ensure correct hash calculation the first time fixLayoutDirection(false); // After all assigned calculate visual hash. fixVisualHash(false); // Mixed states always match their properties mState.set(kStateChecked, mCalculated.get(kPropertyChecked).asBoolean()); mState.set(kStateDisabled, mCalculated.get(kPropertyDisabled).asBoolean()); // Special handling for user properties - these are copied into an object map without evaluation auto user = std::make_shared<ObjectMap>(); for (const auto& p : mProperties) { if (!std::strncmp("-user-", p.first.c_str(), 6)) user->emplace(p.first.substr(6), p.second); } mCalculated.set(kPropertyUser, user); // Set notion of focusability. Here as we actually may need to know all other properties. mCalculated.set(kPropertyFocusable, isFocusable()); // The component property definition set returns an array of raw accessibility action objects. This code // processes the raw array, sets up dependancy relationships, and stores the processed array under the same key. ObjectArray actions; for (const auto& m : mCalculated.get(kPropertyAccessibilityActions).getArray() ) { auto aa = AccessibilityAction::create(shared_from_corecomponent(), m); if (aa) actions.emplace_back(std::move(aa)); } mCalculated.set(kPropertyAccessibilityActions, Object(std::move(actions))); // Process tick handlers here. Not same as onMount as it's a bad idea to go through every component on every tick // to collect handlers and run them on mass. processTickHandlers(); // Add this component to the list of pending onMount elements if it has the handler. auto commands = getCalculated(kPropertyOnMount); if (commands.isArray() && !commands.empty()) { mContext->pendingOnMounts().emplace(shared_from_corecomponent()); } } void CoreComponent::release() { // TODO: Must remove this component from any dirty lists mContext->layoutManager().remove(shared_from_corecomponent()); RecalculateTarget::removeUpstreamDependencies(); mParent = nullptr; for (auto& child : mChildren) child->release(); mChildren.clear(); } /** * Accept a visitor pattern * @param visitor */ void CoreComponent::accept(Visitor<CoreComponent>& visitor) const { visitor.visit(*this); visitor.push(); for (auto it = mChildren.begin(); !visitor.isAborted() && it != mChildren.end(); it++) (*it)->accept(visitor); visitor.pop(); } /** * Visitor pattern for walking the component hierarchy in reverse order. We are interested in the components * that the user can see/interact with. Child classes that have knowledge about which children are off screen or otherwise * invalid/unattached should use that knowledge to reduce the number of nodes walked or avoid walking otherwise invalid * components they may have stashed in their children. * @param visitor */ void CoreComponent::raccept(Visitor<CoreComponent>& visitor) const { visitor.visit(*this); visitor.push(); for (auto it = mChildren.rbegin(); !visitor.isAborted() && it != mChildren.rend(); it++) (*it)->raccept(visitor); visitor.pop(); } ComponentPtr CoreComponent::findComponentById(const std::string& id) const { if (id.empty()) return nullptr; if (mId == id || mUniqueId == id) return std::const_pointer_cast<CoreComponent>(shared_from_corecomponent()); for (auto& m : mChildren) { auto result = m->findComponentById(id); if (result) return result; } return nullptr; } ComponentPtr CoreComponent::findComponentAtPosition(const Point& position) const { auto visitor = TopAtPosition(position); raccept(visitor); return visitor.getResult(); } // Call this when a child has been attached to the parent void CoreComponent::attachedToParent(const CoreComponentPtr& parent) { assert(parent != nullptr); mParent = parent; // Can only be called after the yoga nodes are arranged. auto layoutPropDefSet = getLayoutPropDefSet(); if (layoutPropDefSet) assignProperties(*layoutPropDefSet); // Update our state. if (mInheritParentState) { updateMixedStateProperty(kPropertyChecked, mParent->getCalculated(kPropertyChecked).asBoolean()); updateMixedStateProperty(kPropertyDisabled, mParent->getCalculated(kPropertyDisabled).asBoolean()); updateInheritedState(); updateStyle(); } } void CoreComponent::update(UpdateType type, float value) { switch (type) { case kUpdateTakeFocus: { auto& fm = getContext()->focusManager(); if (value) fm.setFocus(shared_from_corecomponent(), false); else fm.releaseFocus(shared_from_corecomponent(), false); } break; case kUpdatePressState: setState(kStatePressed, value != 0); break; default: LOG(LogLevel::kWarn) << "Unexpected update command type " << type << " value=" << value; break; } } void CoreComponent::update(UpdateType type, const std::string& value) { if (type == kUpdateAccessibilityAction) { auto accessibilityActions = getCalculated(kPropertyAccessibilityActions); // Find the first accessibility action in the array that matches the requested name. const auto& array = accessibilityActions.getArray(); auto it = std::find_if(array.begin(), array.end(), [&](const Object& object) { return object.getAccessibilityAction()->getName() == value; }); if (it != array.end()) { const auto& aa = it->getAccessibilityAction(); if (aa->enabled()) { const auto& cmds = aa->getCommands(); if (cmds.isArray() && !cmds.empty()) executeEventHandler(value, cmds, false); else invokeStandardAccessibilityAction(value); } } } } /** * Add a child component. The child already has a reference to the parent. * @param child The component to add. */ bool CoreComponent::appendChild(const ComponentPtr& child, bool useDirtyFlag) { return insertChild(std::dynamic_pointer_cast<CoreComponent>(child), mChildren.size(), useDirtyFlag); } void CoreComponent::notifyChildChanged(size_t index, const std::string& uid, const std::string& action) { auto &changes = mCalculated.get(kPropertyNotifyChildrenChanged).getMutableArray(); auto change = std::make_shared<ObjectMap>(); change->emplace("index", index); change->emplace("uid", uid); change->emplace("action", action); changes.emplace_back(change); setDirty(kPropertyNotifyChildrenChanged); } void CoreComponent::attachYogaNodeIfRequired(const CoreComponentPtr& coreChild, int index) { // The default behavior is to attach the child. Override this for // Pager and MultiChildScrollableComponent YGNodeInsertChild(mYGNodeRef, coreChild->getNode(), index); } void CoreComponent::attachYogaNode(const CoreComponentPtr& child) { auto it = std::find(mChildren.begin(), mChildren.end(), child); assert(it != mChildren.end()); YGNodeInsertChild(mYGNodeRef, child->getNode(), std::distance(mChildren.begin(), it)); child->updateNodeProperties(); } void CoreComponent::markDisplayedChildrenStale(bool useDirtyFlag) { // Children visibility can't be stale if component can't have one. if (multiChild() || singleChild()) { mDisplayedChildrenStale = true; if (useDirtyFlag) setDirty(kPropertyNotifyChildrenChanged); } } size_t CoreComponent::getDisplayedChildCount() const { auto& mutableThis = const_cast<CoreComponent&>(*this); mutableThis.ensureDisplayedChildren(); return mDisplayedChildren.size(); } ComponentPtr CoreComponent::getDisplayedChildAt(size_t drawIndex) const { auto& mutableThis = const_cast<CoreComponent&>(*this); mutableThis.ensureDisplayedChildren(); return mDisplayedChildren.at(drawIndex); } bool CoreComponent::isDisplayedChild(const CoreComponent& child) const { auto& mutableThis = const_cast<CoreComponent&>(*this); mutableThis.ensureDisplayedChildren(); return std::count(mDisplayedChildren.begin(), mDisplayedChildren.end(), child.shared_from_corecomponent()); } void CoreComponent::ensureDisplayedChildren() { if (!mDisplayedChildrenStale) return; // clear previous calculations mDisplayedChildren.clear(); // Identify this components local viewport using bounds and scroll position // top left of viewport is the most significant offset found when comparing // bounds offset and scroll offset Rect bounds = getCalculated(kPropertyBounds).getRect(); // Get viewport offset by scroll Position Rect viewportRect = Rect(0,0,bounds.getWidth(),bounds.getHeight()); viewportRect.offset(scrollPosition()); std::vector<CoreComponentPtr> sticky; // Process the children, identify those displayed within local viewport for (auto& child : mChildren) { // only visible children if (child->isDisplayable()) { // compare child rect, transformed as needed, against the viewport auto childBounds = child->getCalculated(kPropertyBounds).getRect(); auto transform = child->getCalculated(kPropertyTransform).getTransform2D(); // The axis aligned bounding box is an approximation for checking bounds intersection. // The AABB test eliminates children that are guaranteed NOT to intersect. It does not // prove the parent and child do intersect. // TODO a complete solution applies the "separating axis theorem". The parent AABB is // TODO transformed into the child space and tested for intersection. If a separating axis cannot be // TODO identified using both tests, the parent and child intersect. // Note that the transform is applied assuming the top-left corner of the child is at (0,0) Point childBoundsTopLeft = childBounds.getTopLeft(); childBounds = transform.calculateAxisAlignedBoundingBox(Rect{0, 0, childBounds.getWidth(), childBounds.getHeight()}); childBounds.offset(childBoundsTopLeft); if (!viewportRect.intersect(childBounds).isEmpty()) { if (child->getCalculated(kPropertyPosition) == kPositionSticky) { sticky.emplace_back(child); } else { mDisplayedChildren.emplace_back(child); } } } } // Insert the sticky elements at the end mDisplayedChildren.insert(mDisplayedChildren.end(), sticky.begin(), sticky.end()); mDisplayedChildrenStale = false; } bool CoreComponent::insertChild(const ComponentPtr& child, size_t index) { return canInsertChild() && insertChild(std::dynamic_pointer_cast<CoreComponent>(child), index, true); } bool CoreComponent::appendChild(const ComponentPtr& child) { return insertChild(child, mChildren.size()); } bool CoreComponent::insertChild(const CoreComponentPtr& child, size_t index, bool useDirtyFlag) { if (!child || child->getParent()) return false; auto coreChild = std::static_pointer_cast<CoreComponent>(child); if (index > mChildren.size()) index = mChildren.size(); attachYogaNodeIfRequired(coreChild, index); mChildren.insert(mChildren.begin() + index, coreChild); if (useDirtyFlag) { notifyChildChanged(index, child->getUniqueId(), "insert"); // If we add a view hierarchy with dirty flags, we need to update the context coreChild->markAdded(); } coreChild->attachedToParent(shared_from_corecomponent()); coreChild->markGlobalToLocalTransformStale(); markDisplayedChildrenStale(useDirtyFlag); setVisualContextDirty(); // Update the position: sticky components tree auto p = stickyfunctions::getAncestorHorizontalAndVerticalScrollable(coreChild); auto horizontalScrollable = std::get<0>(p); auto verticalScrollable = std::get<1>(p); if (horizontalScrollable && horizontalScrollable->getStickyTree()) horizontalScrollable->getStickyTree()->handleChildInsert(coreChild); if (verticalScrollable && verticalScrollable->getStickyTree()) verticalScrollable->getStickyTree()->handleChildInsert(coreChild); return true; } bool CoreComponent::remove() { if (!mParent || !mParent->canRemoveChild()) return false; // When we've been removed, we need to clear Yoga properties that were set based on our parent type. // If we don't clear these, certain properties like "alignSelf" that apply only in Containers will mess // up the layout when we switch to a Sequence. auto propDefSet = mParent->layoutPropDefSet(); if (propDefSet) { for (const auto& pd : *propDefSet) { if ((pd.second.flags & kPropResetOnRemove) != 0 && pd.second.layoutFunc) { auto value = pd.second.defaultFunc ? pd.second.defaultFunc(*this, mContext->getRootConfig()) : pd.second.defvalue; pd.second.layoutFunc(mYGNodeRef, value, *mContext); } } } mParent->removeChild(shared_from_corecomponent(), true); mParent = nullptr; return true; } void CoreComponent::removeChild(const CoreComponentPtr& child, size_t index, bool useDirtyFlag) { // Release focus for this child and descendants. Also remove them from the dirty set child->markRemoved(); YGNodeRemoveChild(mYGNodeRef, child->getNode()); mChildren.erase(mChildren.begin() + index); // The parent component has changed the number of children if (useDirtyFlag) notifyChildChanged(index, child->getUniqueId(), "remove"); markDisplayedChildrenStale(useDirtyFlag); mDisplayedChildren.clear(); setVisualContextDirty(); // Update the position: sticky components tree auto p = stickyfunctions::getAncestorHorizontalAndVerticalScrollable(child); auto horizontalScrollable = std::get<0>(p); auto verticalScrollable = std::get<1>(p); if (horizontalScrollable && horizontalScrollable->getStickyTree()) horizontalScrollable->getStickyTree()->handleChildRemove(); if (verticalScrollable && verticalScrollable->getStickyTree()) verticalScrollable->getStickyTree()->handleChildRemove(); } void CoreComponent::removeChild(const CoreComponentPtr& child, bool useDirtyFlag) { auto it = std::find(mChildren.begin(), mChildren.end(), child); assert(it != mChildren.end()); size_t index = std::distance(mChildren.begin(), it); removeChild(child, index, useDirtyFlag); } void CoreComponent::removeChildAt(size_t index, bool useDirtyFlag) { if (index >= mChildren.size()) return; auto child = mChildren.at(index); removeChild(child, index, useDirtyFlag); child->release(); } /** * This component has been removed from the DOM. Walk the hierarchy and make sure that * it and its children are not focused and not dirty. Note that we don't clear dirty * flags from the component hierarchy. */ void CoreComponent::markRemoved() { auto self = shared_from_corecomponent(); mContext->clearDirty(self); auto& fm = mContext->focusManager(); if (fm.getFocus() == self) { auto next = fm.find(kFocusDirectionForward); if (next) fm.setFocus(next, true); else // If nothing suitable is found - clear focus forcefully as we don't have another choice. fm.clearFocus(true, kFocusDirectionNone, true); } for (auto& child : mChildren) std::static_pointer_cast<CoreComponent>(child)->markRemoved(); } /** * This component has been attached to the DOM. Walk the hierarchy and make sure that * any dirty components are reflected in the RootContext */ void CoreComponent::markAdded() { auto self = shared_from_this(); if (!mDirty.empty()) mContext->setDirty(self); for (auto& child : mChildren) std::static_pointer_cast<CoreComponent>(child)->markAdded(); } void CoreComponent::ensureLayoutInternal(bool useDirtyFlag) { LOG_IF(DEBUG_ENSURE) << toDebugSimpleString() << " useDirtyFlag=" << useDirtyFlag; APL_TRACE_BLOCK("CoreComponent:ensureLayout"); auto& lm = mContext->layoutManager(); if (lm.ensure(shared_from_corecomponent())) lm.layout(useDirtyFlag); } void CoreComponent::ensureChildLayout(const CoreComponentPtr& child, bool useDirtyFlag) { child->ensureLayoutInternal(useDirtyFlag); } void CoreComponent::reportLoaded(size_t index) { if (mRebuilder) { if (mRebuilder->hasFirstItem() && index == 0) { index++; } if (mRebuilder->hasLastItem() && index == mChildren.size() - 1) { index--; } mRebuilder->notifyItemOnScreen(index); } } bool CoreComponent::isAttached() const { return mYGNodeRef->getOwner() != nullptr; } bool CoreComponent::isLaidOut() const { auto component = shared_from_corecomponent(); while (true) { const auto& node = component->getNode(); if (YGNodeIsDirty(node)) return false; auto parent = std::static_pointer_cast<CoreComponent>(component->getParent()); if (!parent) return true; if (node->getOwner() == nullptr) return false; component = parent; } } void CoreComponent::updateNodeProperties() { const auto pds = getLayoutPropDefSet(); if (pds) { for (const auto& it : pds->needsNode()) { const ComponentPropDef& pd = it.second; pd.layoutFunc(mYGNodeRef, mCalculated.get(pd.key), *mContext); } } } /** * Initial assignment of properties. Don't set any dirty flags here; this * all should be running in the constructor. * @param propDefSet The current property definition set to use. */ void CoreComponent::assignProperties(const ComponentPropDefSet& propDefSet) { auto stylePtr = getStyle(); for (const auto& cpd : propDefSet) { const auto& pd = cpd.second; auto value = pd.defaultFunc ? pd.defaultFunc(*this, mContext->getRootConfig()) : pd.defvalue; if ((pd.flags & kPropIn) != 0) { // Check for user-defined property auto p = mProperties.find(pd.names); if (p != mProperties.end()) { // If the user assigned a string, we need to check for data binding if (p->second.isString()) { auto tmp = parseDataBinding(*mContext, p->second.getString()); // Expand data-binding if (tmp.isEvaluable()) { auto self = std::static_pointer_cast<CoreComponent>(shared_from_this()); ComponentDependant::create(self, pd.key, tmp, mContext, pd.getBindingFunction()); } value = pd.calculate(*mContext, evaluate(*mContext, tmp)); // Calculate the final value } else if ((pd.flags & kPropEvaluated) != 0) { // Explicitly marked for evaluation, so do it. // Will not attach dependant if no valid symbols. auto tmp = parseDataBindingRecursive(*mContext, p->second); auto self = std::static_pointer_cast<CoreComponent>(shared_from_this()); ComponentDependant::create(self, pd.key, tmp, mContext, pd.getBindingFunction()); value = pd.calculate(*mContext, p->second); } else { value = pd.calculate(*mContext, p->second); } mAssigned.emplace(pd.key); } else { // Make sure this wasn't a required property if ((pd.flags & kPropRequired) != 0) { mFlags |= kComponentFlagInvalid; CONSOLE_CTP(mContext) << "Missing required property: " << pd.names; } // Check for a styled property if ((pd.flags & kPropStyled) != 0 && stylePtr) { auto s = stylePtr->find(pd.names); if (s != stylePtr->end()) value = pd.calculate(*mContext, s->second); } } } mCalculated.set(pd.key, value); if (pd.key == kPropertyPosition && value == kPositionSticky) { zeroComponentInsets(shared_from_corecomponent()); auto p = stickyfunctions::getAncestorHorizontalAndVerticalScrollable(shared_from_corecomponent()); auto horizontalScrollable = std::get<0>(p); auto verticalScrollable = std::get<1>(p); if (horizontalScrollable && horizontalScrollable->getStickyTree()) horizontalScrollable->getStickyTree()->handleChildStickySet(); if (verticalScrollable && verticalScrollable->getStickyTree()) verticalScrollable->getStickyTree()->handleChildStickySet(); } //Apply this property to the yn if we care about it if (pd.layoutFunc != nullptr) pd.layoutFunc(mYGNodeRef, value, *mContext); } // Yoga padding values are calculated from a combination of two properties (e.g. "padding" and "paddingLeft"). // Since they can't be set directly during normal property assignment with a layout function, we update them here. fixPadding(); } void CoreComponent::handlePropertyChange(const ComponentPropDef& def, const Object& value) { // If the mixed state inherits from the parent, we block the change. if ((def.flags & kPropMixedState) != 0 && mInheritParentState) return; auto previous = getCalculated(def.key); if (value != previous) { mCalculated.set(def.key, value); // Update the position: sticky components tree if needed if (def.key == kPropertyPosition && value == kPositionSticky) { zeroComponentInsets(shared_from_corecomponent()); auto p = stickyfunctions::getAncestorHorizontalAndVerticalScrollable(shared_from_corecomponent()); auto horizontalScrollable = std::get<0>(p); auto verticalScrollable = std::get<1>(p); if (horizontalScrollable && horizontalScrollable->getStickyTree()) horizontalScrollable->getStickyTree()->handleChildStickySet(); if (verticalScrollable && verticalScrollable->getStickyTree()) verticalScrollable->getStickyTree()->handleChildStickySet(); } else if (def.key == kPropertyPosition && previous == kPositionSticky) { restoreComponentInsets(shared_from_corecomponent()); auto p = stickyfunctions::getAncestorHorizontalAndVerticalScrollable(shared_from_corecomponent()); auto horizontalScrollable = std::get<0>(p); auto verticalScrollable = std::get<1>(p); if (horizontalScrollable && horizontalScrollable->getStickyTree()) horizontalScrollable->getStickyTree()->handleChildStickyUnset(); if (verticalScrollable && verticalScrollable->getStickyTree()) verticalScrollable->getStickyTree()->handleChildStickyUnset(); } // display change, or opacity change to/from 0, makes parent display stale if (mParent && (def.key == kPropertyDisplay ||(def.key == kPropertyOpacity && ((value.asNumber() == 0) != (previous.asNumber() == 0))))) { mParent->markDisplayedChildrenStale(true); } // Properties with the kPropVisualContext flag the visual context as dirty if ((def.flags & kPropVisualContext) != 0) setVisualContextDirty(); // Properties with the kPropTextHash flag the text measurement hash as dirty if ((def.flags & kPropTextHash) != 0) mTextMeasurementHashStale = true; // Properties with kPropVisualHash flag the visual hash is dirty if ((def.flags & kPropVisualHash) != 0) mVisualHashStale = true; // Properties with the kPropOut flag mark the property as dirty if ((def.flags & kPropOut) != 0) setDirty(def.key); // Properties with a layout function will update the Yoga node if (def.layoutFunc != nullptr) def.layoutFunc(mYGNodeRef, value, *mContext); // Properties with a trigger function need to recompute other properties if (def.trigger != nullptr) def.trigger(*this); // If this property affects the layout, we'll need a new layout pass if ((def.flags & kPropLayout) != 0 && YGNodeHasMeasureFunc(mYGNodeRef)) YGNodeMarkDirty(mYGNodeRef); // If this property affects the state, we'll do a SetState change if ((def.flags & kPropMixedState) != 0) { // Propagate the property change to the children for (auto& child : mChildren) child->updateMixedStateProperty(def.key, value.asBoolean()); switch (def.key) { case kPropertyChecked: setState(kStateChecked, value.asBoolean()); break; case kPropertyDisabled: setState(kStateDisabled, value.asBoolean()); break; default: break; } } } } CoreComponentPtr CoreComponent::getLayoutRoot() { auto c = shared_from_corecomponent(); while (c->mParent && c->getNode()->getOwner()) c = c->mParent; return c; } /** * Walk down the hierarchy setting this mixed state/property to the new value. * Update dirty flags as necessary. * @param key The property to change * @param value The value to set */ void CoreComponent::updateMixedStateProperty(apl::PropertyKey key, bool value) { if (!mInheritParentState || value == mCalculated.get(key).asBoolean()) return; mCalculated.set(key, value); setDirty(key); for (auto& child : mChildren) child->updateMixedStateProperty(key, value); } /** * Find a component property in the current component. This could be a built-in component * property or it could be a layout property. * @param key The property to retrieve. * @return A pair of true if the property was found and the iterator pointing to the property definition. */ std::pair<bool, ConstComponentPropIterator> CoreComponent::find(PropertyKey key) const { // Check the main set of properties first const auto& pds = propDefSet(); auto it = pds.find(key); if (it != pds.end()) return {true, it}; // Check layout properties second if (mParent) { const auto& layoutPDS = getLayoutPropDefSet(); if (layoutPDS) { it = layoutPDS->find(key); if (it != layoutPDS->end()) return {true, it}; } } return {false, it}; } /** * A property has been set on the component. * @param id The property iterator. Contains the key of the property being changed and the definition. * @param value The new value of the property. * @return True if the property could be set (it must be dynamic). */ bool CoreComponent::setPropertyInternal(ConstComponentPropIterator it, const Object& value) { // Verify that this property is a valid dynamic property if ((it->second.flags & kPropDynamic) == 0) return false; // Some properties can only be set correctly if the component has been laid out if ((it->second.flags & kPropSetAfterLayout) != 0 && !isLaidOut()) { mContext->layoutManager().addPostProcess(shared_from_corecomponent(), it->first, value); return true; } // Properties with setters are called directly if (it->second.setterFunc) { it->second.setterFunc(*this, value); return true; } // If this property was previously assigned we need to clear any dependants auto assigned = mAssigned.find(it->first); if (assigned != mAssigned.end()) // Erase all upstream dependants that drive this key removeUpstream(it->first); // Mark this property in the "assigned" set of properties. mAssigned.emplace(it->first); // Check to see if the actual value of the property changed and update appropriately const ComponentPropDef& def = it->second; handlePropertyChange(def, def.calculate(*mContext, value)); return true; } std::pair<Object, bool> CoreComponent::getPropertyInternal(ConstComponentPropIterator it) const { auto dynamic = (it->second.flags & kPropDynamic) != 0; if (it->second.getterFunc) return { it->second.getterFunc(*this), dynamic }; auto v = mCalculated.get(it->first); // If it is a map we need to convert it back into a string if (it->second.map) return { it->second.map->get(v.asInt(), "<ERROR>"), dynamic }; return { v, dynamic }; } bool CoreComponent::setProperty(PropertyKey key, const Object& value) { auto findRef = find(key); if (findRef.first && setPropertyInternal(findRef.second, value)) return true; CONSOLE_CTP(mContext) << "Invalid property key '" << sComponentPropertyBimap.at(key) << "' for this component"; return false; } void CoreComponent::setProperty( const std::string& key, const Object& value ) { if (sComponentPropertyBimap.has(key) && setProperty(static_cast<PropertyKey>(sComponentPropertyBimap.at(key)), value)) return; // If we got here, there was no matching property. Assume it is a binding if (mContext->userUpdateAndRecalculate(key, value, true)) return; // Certain component may provide their own special processing if (setPropertyInternal(key, value)) return; CONSOLE_CTP(mContext) << "Unknown property name " << key; } std::pair<Object, bool> CoreComponent::getPropertyAndWriteableState(const std::string& key) const { // Check for a standard component property if (sComponentPropertyBimap.has(key)) { auto findRef = find(static_cast<PropertyKey>(sComponentPropertyBimap.at(key))); if (findRef.first) return getPropertyInternal(findRef.second); } // Check for a data binding auto ref = mContext->find(key); if (!ref.empty()) return { ref.object().value(), ref.object().isUserWriteable() }; // It may be an internal component property auto internal = getPropertyInternal(key); if (internal.second) return internal; CONSOLE_CTP(mContext) << "Unknown property name " << key; return { Object::NULL_OBJECT(), false }; } bool CoreComponent::markPropertyInternal(const ComponentPropDefSet& pds, PropertyKey key) { // Verify that we have a valid dynamic property auto it = pds.dynamic().find(key); if (it == pds.dynamic().end()) return false; const ComponentPropDef& def = it->second; // Properties with the kPropOut flag mark the property as dirty if ((def.flags & kPropOut) != 0) setDirty(def.key); // Properties with a layout function will update the Yoga node if (def.layoutFunc != nullptr) def.layoutFunc(mYGNodeRef, mCalculated.get(key), *mContext); // Properties with a trigger function need to recompute other properties if (def.trigger != nullptr) def.trigger(*this); // If this property affects the layout, we'll need a new layout pass if ((def.flags & kPropLayout) != 0) YGNodeMarkDirty(mYGNodeRef); return true; } void CoreComponent::markProperty(PropertyKey key) { if (!markPropertyInternal(propDefSet(), key) && mParent) { auto layoutPDS = getLayoutPropDefSet(); if (layoutPDS) markPropertyInternal(*layoutPDS, key); } } void CoreComponent::updateProperty(PropertyKey key, const Object& value) { auto it = mAssigned.find(key); if (it == mAssigned.end()) return; // Check the standard properties first auto& corePDS = propDefSet().dynamic(); auto pd = corePDS.find(key); if (pd != corePDS.end()) { handlePropertyChange(pd->second, value); return; } // Look for a layout property. Not all components have a layout auto layoutPDS = getLayoutPropDefSet(); if (!layoutPDS) return; // Check for a matching layout property auto& layoutDynamicPDS = layoutPDS->dynamic(); pd = layoutDynamicPDS.find(key); if (pd != layoutDynamicPDS.end()) { handlePropertyChange(pd->second, value); return; } // We should not reach this point. Only an assigned equation calls updateProperty CONSOLE_CTP(mContext) << "Property " << sComponentPropertyBimap.at(key) << " is not dynamic and can't be updated."; } /** * The style of the component may (or may not) have changed. If it has changed, * update each styled property in turn. Then update any children that share their * parent state. * * Calling this method sets dirty flags. */ void CoreComponent::updateStyleInternal(const StyleInstancePtr& stylePtr, const ComponentPropDefSet& pds) { // Check every property that has the "styled" flag. for (const auto& it : pds.styled()) { const ComponentPropDef& pd = it.second; // If the property was explicitly assigned by the user, the style won't change it. if (mAssigned.count(pd.key)) continue; // Check to see if the value has changed. auto value = (pd.defaultFunc ? pd.defaultFunc(*this, mContext->getRootConfig()) : pd.defvalue); auto s = stylePtr->find(pd.names); if (s != stylePtr->end()) value = pd.calculate(*mContext, s->second); handlePropertyChange(pd, value); } } /** * The style of the component may (or may not) have changed. If it has changed, * update each styled property in turn. Then update any children that share their * parent state. * * Calling this method sets dirty flags. * * Note that changing the style may force a new layout pass. */ void CoreComponent::updateStyle() { auto stylePtr = getStyle(); if (stylePtr) { updateStyleInternal(stylePtr, propDefSet()); const ComponentPropDefSet *layoutPDS = getLayoutPropDefSet(); if (layoutPDS) updateStyleInternal(stylePtr, *layoutPDS); } for (const auto& child : mChildren) { if (child->mInheritParentState) child->updateStyle(); } } /** * Update state of the component. This may trigger style changes locally and in children * Do NOT call this method directly to set the CHECKED or DISABLED states. Those calls should * go through setProperty. * @param stateProperty The enumerated state property * @param value The value to set. */ void CoreComponent::setState( StateProperty stateProperty, bool value ) { if (mInheritParentState) { CONSOLE_CTP(mContext) << "Cannot assign state properties to a child that inherits parent state"; return; } if (mState.set(stateProperty, value)) { auto self = shared_from_corecomponent(); if (stateProperty == kStateChecked || stateProperty == kStateFocused || stateProperty == kStateDisabled) { setVisualContextDirty(); } if (stateProperty == kStateDisabled) { if (value) { mState.set(kStatePressed, false); mState.set(kStateHover, false); auto& fm = mContext->focusManager(); if (fm.getFocus() == self) { auto next = fm.find(kFocusDirectionForward); if (next) fm.setFocus(next, true); else // If nothing suitable is found - clear focus forcefully as we don't have another choice. fm.clearFocus(true, kFocusDirectionNone, true); } } } for (auto& child: mChildren) child->updateInheritedState(); if (stateProperty == kStateDisabled) { // notify the hover manager that the disable state has changed mContext->hoverManager().componentToggledDisabled(self); } updateStyle(); } } void CoreComponent::setDirty( PropertyKey key ) { if (mDirty.emplace(key).second) { mContext->setDirty(shared_from_this()); if (!isVisualContextDirty() || !mTextMeasurementHashStale || !mVisualHashStale) { auto def = propDefSet().find(key); if (def == propDefSet().end()) return; // set the visual context dirty if this property causes change // called here because we handlePropertyChange may be bypassed in some circumstances // (for example scrolling) if (!isVisualContextDirty() && (def->second.flags & kPropVisualContext)) { setVisualContextDirty(); } // Set text measurement hash as stale if (!mTextMeasurementHashStale && (def->second.flags & kPropTextHash)) { mTextMeasurementHashStale = true; } // Set visual hash as stale if (!mVisualHashStale && (def->second.flags & kPropVisualHash)) { mVisualHashStale = true; } } } } const std::set<PropertyKey>& CoreComponent::getDirty() { // Do visual hash update if needed. fixVisualHash(true); return mDirty; } void CoreComponent::clearDirty() { Component::clearDirty(); // Update hash without causing dirty flag, otherwise they may be marked dirty when they are not supposed to. // Only case when it may happen - initial inflation (immediate onMount for example). fixVisualHash(false); } void CoreComponent::updateInheritedState() { if (!mInheritParentState || !mParent) return; mState = mParent->getState(); for (auto& child : mChildren) child->updateInheritedState(); } bool CoreComponent::inheritsStateFrom(const CoreComponentPtr& component) { auto stateOwner = shared_from_corecomponent(); // the component is this component if (component == stateOwner) { return true; } // compare to ancestor components while (stateOwner && stateOwner->getInheritParentState()) { stateOwner = std::static_pointer_cast<CoreComponent>(stateOwner->getParent()); if (stateOwner == component) { return true; } } return false; } CoreComponentPtr CoreComponent::findStateOwner() { auto ptr = shared_from_corecomponent(); while (ptr && ptr->getInheritParentState()) { ptr = std::static_pointer_cast<CoreComponent>(ptr->getParent()); } return ptr; } StyleInstancePtr CoreComponent::getStyle() const { return mContext->getStyle(mStyle, mState); } const ComponentPropDefSet * CoreComponent::getLayoutPropDefSet() const { if (mParent) return mParent->layoutPropDefSet(); return nullptr; } bool CoreComponent::needsLayout() const { return YGNodeIsDirty(mYGNodeRef); } bool CoreComponent::shouldNotPropagateLayoutChanges() const { return mChildren.empty() || static_cast<Display>(getCalculated(kPropertyDisplay).getInteger()) == kDisplayNone; } std::string CoreComponent::textMeasurementHash() const { return mTextMeasurementHash; } void CoreComponent::fixTextMeasurementHash() { auto& pds = propDefSet(); if (!mTextMeasurementHashStale) return; mTextMeasurementHashStale = false; size_t hash = 0; for (const auto& cpd : pds) { const auto &pd = cpd.second; if ((pd.flags & kPropTextHash) != 0) { hashCombine(hash, getCalculated(pd.key)); } } // Need to keep as string, as double or int will lead to loss of precision. mTextMeasurementHash = std::to_string(hash); } void CoreComponent::fixVisualHash(bool useDirtyFlag) { if (!mVisualHashStale) return; mVisualHashStale = false; size_t hash = 0; for (const auto& cpd : propDefSet()) { const auto &pd = cpd.second; if ((pd.flags & kPropVisualHash) != 0) { hashCombine(hash, getCalculated(pd.key)); } } // Need to keep as string, as double or int will lead to loss of precision. mCalculated.set(kPropertyVisualHash, std::to_string(hash)); if (useDirtyFlag) setDirty(kPropertyVisualHash); } void CoreComponent::preLayoutProcessing(bool useDirtyFlag) { for (auto& child : mChildren) if (child->isAttached()) child->preLayoutProcessing(useDirtyFlag); // Prior to layout, the visual hash may already be stale due to, for // example, pending commands and/or dynamic data changes. But view host // expects to be able to refer to a correct visual hash during layout, so // let's make it correct now. It's OK that the visual hash may change again // during layout, in which case the view host will use the new value. fixVisualHash(useDirtyFlag); } void CoreComponent::processLayoutChanges(bool useDirtyFlag, bool first) { if (DEBUG_BOUNDS) YGNodePrint(mYGNodeRef, YGPrintOptions::YGPrintOptionsLayout); APL_TRACE_BLOCK("CoreComponent:processLayoutChanges"); float left = YGNodeLayoutGetLeft(mYGNodeRef); float top = YGNodeLayoutGetTop(mYGNodeRef); float width = YGNodeLayoutGetWidth(mYGNodeRef); float height = YGNodeLayoutGetHeight(mYGNodeRef); bool changed = false; // If no bounds set - set some now to get sticky stuff a chance to calculate on the very first pass if (first && mCalculated.get(kPropertyBounds).empty()) { changed = true; mCalculated.set(kPropertyBounds, Rect(left, top, width, height)); } if (getCalculated(kPropertyPosition) == kPositionSticky) { mStickyOffset = stickyfunctions::calculateStickyOffset(shared_from_corecomponent()); left += mStickyOffset.getX(); top += mStickyOffset.getY(); } // Update the transformation matrix fixTransform(useDirtyFlag); // Update the layoutDirection. fixLayoutDirection(useDirtyFlag); Rect rect(left, top, width, height); changed |= rect != mCalculated.get(kPropertyBounds).getRect(); if (changed) { mCalculated.set(kPropertyBounds, std::move(rect)); markGlobalToLocalTransformStale(); markDisplayedChildrenStale(useDirtyFlag); if (mParent) mParent->markDisplayedChildrenStale(useDirtyFlag); setVisualContextDirty(); if (useDirtyFlag) setDirty(kPropertyBounds); } // Update the inner drawing area (this takes into account both padding and borders float borderLeft = YGNodeLayoutGetBorder(mYGNodeRef, YGEdgeLeft); float borderTop = YGNodeLayoutGetBorder(mYGNodeRef, YGEdgeTop); float borderRight = YGNodeLayoutGetBorder(mYGNodeRef, YGEdgeRight); float borderBottom = YGNodeLayoutGetBorder(mYGNodeRef, YGEdgeBottom); float paddingLeft = YGNodeLayoutGetPadding(mYGNodeRef, YGEdgeLeft); float paddingTop = YGNodeLayoutGetPadding(mYGNodeRef, YGEdgeTop); float paddingRight = YGNodeLayoutGetPadding(mYGNodeRef, YGEdgeRight); float paddingBottom = YGNodeLayoutGetPadding(mYGNodeRef, YGEdgeBottom); Rect inner(borderLeft + paddingLeft, borderTop + paddingTop, width - (borderLeft + paddingLeft + borderRight + paddingRight), height - (borderTop + paddingTop + borderBottom + paddingBottom)); changed = inner != mCalculated.get(kPropertyInnerBounds).getRect(); if (changed) { mCalculated.set(kPropertyInnerBounds, std::move(inner)); markDisplayedChildrenStale(useDirtyFlag); if (useDirtyFlag) setDirty(kPropertyInnerBounds); } if (!mCalculated.get(kPropertyLaidOut).asBoolean() && !mCalculated.get(kPropertyBounds).getRect().isEmpty()) { mCalculated.set(kPropertyLaidOut, true); if (useDirtyFlag) setDirty(kPropertyLaidOut); } // Break out early if possible - there are no need to propagate to children if (shouldNotPropagateLayoutChanges()) return; // Inform all children that they should re-check their bounds. No need to do that for not attached ones. // Note that children of a Pager are not attached, and hence they will not be processed. for (auto& child : mChildren) if (child->isAttached()) child->processLayoutChanges(useDirtyFlag, first); } void CoreComponent::postProcessLayoutChanges() { // Mark this component as having been laid out at least once mFlags |= kComponentFlagAllowEventHandlers; for (auto& child : mChildren) if (child->isAttached()) child->postProcessLayoutChanges(); // update the displayed children ensureDisplayedChildren(); } std::shared_ptr<ObjectMap> CoreComponent::createEventProperties(const std::string& handler, const Object& value) const { auto event = std::make_shared<ObjectMap>(); event->emplace("source", Object(ComponentEventSourceWrapper::create(shared_from_corecomponent(), handler, value))); addEventProperties(*event); return event; } ContextPtr CoreComponent::createEventContext(const std::string& handler, const ObjectMapPtr& optional, const Object& value) const { ContextPtr ctx = Context::createFromParent(mContext); auto compValue = getValue(); if (!value.isNull()) { compValue = value; } auto event = createEventProperties(handler, compValue); if (optional) event->insert(optional->begin(), optional->end()); ctx->putConstant("event", event); return ctx; } ContextPtr CoreComponent::createKeyboardEventContext(const std::string& handler, const ObjectMapPtr& keyboard) const { ContextPtr ctx = Context::createFromParent(mContext); auto event = createEventProperties(handler, getValue()); event->emplace("keyboard", keyboard); ctx->putConstant("event", event); return ctx; } const EventPropertyMap & CoreComponent::eventPropertyMap() const { static EventPropertyMap sCoreEventProperties( { {"bind", [](const CoreComponent *c) { return ContextWrapper::create(c->getContext()); }}, {"checked", [](const CoreComponent *c) { return c->getState().get(kStateChecked); }}, {"disabled", [](const CoreComponent *c) { return c->getState().get(kStateDisabled); }}, {"focused", [](const CoreComponent *c) { return c->getState().get(kStateFocused); }}, {"id", [](const CoreComponent *c) { return c->getId(); }}, {"uid", [](const CoreComponent *c) { return c->getUniqueId(); }}, {"width", [](const CoreComponent *c) { return YGNodeLayoutGetWidth(c->mYGNodeRef); }}, {"height", [](const CoreComponent *c) { return YGNodeLayoutGetHeight(c->mYGNodeRef); }}, {"opacity", [](const CoreComponent *c) { return c->getCalculated(kPropertyOpacity); }}, {"pressed", [](const CoreComponent *c) { return c->getState().get(kStatePressed); }}, {"type", [](const CoreComponent *c) { return sComponentTypeBimap.at(c->getType()); }}, {"layoutDirection", [](const CoreComponent *c) { return sLayoutDirectionMap.at(c->getCalculated(kPropertyLayoutDirection).asInt()); }} }); return sCoreEventProperties; } std::pair<bool, Object> CoreComponent::getEventProperty(const std::string &key) const { const auto& map = eventPropertyMap(); auto it = map.find(key); if (it != map.end()) return {true, it->second(this)}; return {false, Object::NULL_OBJECT()}; } size_t CoreComponent::getEventPropertySize() const { return eventPropertyMap().size(); } void CoreComponent::serializeEvent(rapidjson::Value& out, rapidjson::Document::AllocatorType& allocator) const { const auto& map = eventPropertyMap(); for (const auto& m : map) out.AddMember(rapidjson::Value(m.first.c_str(), allocator), m.second(this).serialize(allocator).Move(), allocator); } static const char sHierarchySig[] = "CEXFMIPSQTWGV"; // Must match ComponentType std::string CoreComponent::getHierarchySignature() const { std::string result(1, sHierarchySig[getType()]); if (!mChildren.empty()) { result += "["; for (const auto& child : mChildren) result += child->getHierarchySignature(); result += "]"; } return result; } void CoreComponent::fixTransform(bool useDirtyFlag) { LOG_IF(DEBUG_TRANSFORM) << mCalculated.get(kPropertyTransform).getTransform2D(); Transform2D updated; auto transform = mCalculated.get(kPropertyTransformAssigned); if (transform.isArray()) { transform = Transformation::create(*getContext(), transform.getArray()); mCalculated.set(kPropertyTransformAssigned, transform); } if (transform.isTransform()) { float width = YGNodeLayoutGetWidth(mYGNodeRef); float height = YGNodeLayoutGetHeight(mYGNodeRef); updated = transform.getTransformation()->get(width, height); } auto value = getCalculated(kPropertyTransform).getTransform2D(); if (updated != value) { mCalculated.set(kPropertyTransform, Object(std::move(updated))); markGlobalToLocalTransformStale(); // transform change make parent display stale if (mParent) { mParent->markDisplayedChildrenStale(useDirtyFlag); } setVisualContextDirty(); if (useDirtyFlag) setDirty(kPropertyTransform); LOG_IF(DEBUG_TRANSFORM) << "updated to " << mCalculated.get(kPropertyTransform).getTransform2D(); } } static bool setPaddingIfKeyFound(PropertyKey key, YGEdge edge, CalculatedPropertyMap& map, YGNodeRef nodeRef, const ContextPtr& context) { auto v = map.find(key); bool found = v != map.end() && !v->second.isNull(); if (found) yn::setPadding(nodeRef, edge, v->second, *context); return found; } void CoreComponent::fixPadding() { LOG_IF(DEBUG_PADDING) << mCalculated.get(kPropertyPadding); static std::vector<std::pair<PropertyKey, YGEdge>> EDGES = { {kPropertyPaddingLeft, YGEdgeLeft}, {kPropertyPaddingTop, YGEdgeTop}, {kPropertyPaddingRight, YGEdgeRight}, {kPropertyPaddingBottom, YGEdgeBottom}, }; auto commonPadding = mCalculated.get(kPropertyPadding); for (size_t i = 0 ; i < EDGES.size() ; i++) { const auto& edge = EDGES.at(i); // That value may be overridden by the specific paddingLeft/Top/Right/Bottom values if (!setPaddingIfKeyFound(edge.first, edge.second, mCalculated, mYGNodeRef, mContext)) { // If edge isn't set directly use padding value assigned by the "padding" property auto assigned = commonPadding.size() >= i ? commonPadding.at(i) : Dimension(0); yn::setPadding(mYGNodeRef, edge.second, assigned, *mContext); } } // paddingStart overrides left padding if layout is "ltf" or right padding if "rtl" setPaddingIfKeyFound(kPropertyPaddingStart, YGEdgeStart, mCalculated, mYGNodeRef, mContext); // paddingEnd overrides left padding if layout is "ltf" or right padding if "rtl" setPaddingIfKeyFound(kPropertyPaddingEnd, YGEdgeEnd, mCalculated, mYGNodeRef, mContext); } void CoreComponent::fixLayoutDirection(bool useDirtyFlag) { LOG_IF(DEBUG_LAYOUTDIRECTION) << mCalculated.get(kPropertyLayoutDirection); auto reportedLayoutDirection = static_cast<LayoutDirection>(mCalculated.get(kPropertyLayoutDirection).asInt()); auto currentLayoutDirection = getLayoutDirection() == YGDirectionLTR ? kLayoutDirectionLTR : kLayoutDirectionRTL; if (reportedLayoutDirection != currentLayoutDirection) { mCalculated.set(kPropertyLayoutDirection, currentLayoutDirection); if (useDirtyFlag) { setDirty(kPropertyLayoutDirection); } handleLayoutDirectionChange(useDirtyFlag); LOG_IF(DEBUG_LAYOUTDIRECTION) << "updated to " << mCalculated.get(kPropertyLayoutDirection); } } void CoreComponent::setHeight(const Dimension& height) { if (mYGNodeRef) yn::setHeight(mYGNodeRef, height, *mContext); else LOG(LogLevel::kError) << "setHeight: Missing yoga node for component id '" << getId() << "'"; mCalculated.set(kPropertyHeight, height); } void CoreComponent::setWidth(const Dimension& width) { if (mYGNodeRef) yn::setWidth(mYGNodeRef, width, *mContext); else LOG(LogLevel::kError) << "setWidth: Missing yoga node for component id '" << getId() << "'"; mCalculated.set(kPropertyWidth, width); } std::map<int,int> CoreComponent::calculateChildrenVisualLayer(const std::map<int, float>& visibleIndexes, const Rect& visibleRect, int visualLayer) { std::map<int,int> result; // For general case child has it's parent's layer. for(const auto &vi : visibleIndexes) { result.emplace(vi.first, visualLayer); } return result; } rapidjson::Value CoreComponent::serialize(rapidjson::Document::AllocatorType& allocator) const { rapidjson::Value component(rapidjson::kObjectType); component.AddMember("id", rapidjson::Value(mUniqueId.c_str(), allocator).Move(), allocator); component.AddMember("type", getType(), allocator); for (const auto& pds : propDefSet()) { if ((pds.second.flags & kPropOut) != 0 || (pds.second.flags & kPropRuntimeState) != 0) component.AddMember( rapidjson::StringRef(pds.second.names[0].c_str()), // We assume long-lived strings here mCalculated.get(pds.first).serialize(allocator), allocator); } if (!mChildren.empty()) { rapidjson::Value children(rapidjson::kArrayType); for (const auto& child : mChildren) children.PushBack(child->serialize(allocator), allocator); component.AddMember("children", children, allocator); } return component; } rapidjson::Value CoreComponent::serializeAll(rapidjson::Document::AllocatorType& allocator) const { rapidjson::Value component(rapidjson::kObjectType); component.AddMember("id", rapidjson::Value(mUniqueId.c_str(), allocator).Move(), allocator); component.AddMember("type", rapidjson::StringRef(sComponentTypeBimap.at(getType()).c_str()), allocator); component.AddMember("__id", rapidjson::Value(mId.c_str(), allocator), allocator); component.AddMember("__inheritParentState", mInheritParentState, allocator); component.AddMember("__style", rapidjson::Value(mStyle.c_str(), allocator), allocator); component.AddMember("__path", rapidjson::Value(mPath.toString().c_str(), allocator), allocator); for (const auto& pds : propDefSet()) { if (pds.second.map) { component.AddMember( rapidjson::StringRef(pds.second.names[0].c_str()), // We assume long-lived strings here rapidjson::StringRef(pds.second.map->at(mCalculated.get(pds.first).asInt()).c_str()), allocator); } else { component.AddMember( rapidjson::StringRef(pds.second.names[0].c_str()), // We assume long-lived strings here mCalculated.get(pds.first).serialize(allocator), allocator); } } if (!mChildren.empty()) { rapidjson::Value children(rapidjson::kArrayType); for (const auto& child : mChildren) children.PushBack(child->serializeAll(allocator), allocator); component.AddMember("children", children, allocator); } return component; } rapidjson::Value CoreComponent::serializeDirty(rapidjson::Document::AllocatorType& allocator) { rapidjson::Value component(rapidjson::kObjectType); component.AddMember("id", rapidjson::Value(mUniqueId.c_str(), allocator).Move(), allocator); for (auto& key : mDirty) { component.AddMember( rapidjson::Value(sComponentPropertyBimap.at(key).c_str(), allocator), mCalculated.get(key).serializeDirty(allocator), allocator); } mDirty.clear(); return component; } rapidjson::Value CoreComponent:: serializeVisualContext(rapidjson::Document::AllocatorType& allocator) { float viewportWidth = mContext->width(); float viewportHeight = mContext->height(); Rect viewportRect(0, 0, viewportWidth, viewportHeight); auto topComponentVisibleRect = calculateVisibleRect(viewportRect); auto topComponentOpacity = calculateRealOpacity(); auto topComponentVisibility = calculateVisibility(1.0, viewportRect); rapidjson::Value children(rapidjson::kArrayType); serializeVisualContextInternal(children, allocator, topComponentOpacity, topComponentVisibility, topComponentVisibleRect, 0); // We always have viewport component return children[0].GetObject(); } void CoreComponent::serializeVisualContextInternal(rapidjson::Value &outArray, rapidjson::Document::AllocatorType& allocator, float realOpacity, float visibility, const Rect& visibleRect, int visualLayer) { if(visibility == 0.0 && mParent) { // Not visible and not viewport component. return; } // Decide if actionable bool actionable = !getCalculated(kPropertyEntities).empty(); rapidjson::Value tags(rapidjson::kObjectType); actionable |= getTags(tags, allocator); bool includeInContext = !mParent || (visibility > 0.0 && actionable); rapidjson::Value children(rapidjson::kArrayType); // Process children if (!mChildren.empty() && visibility > 0.0) { auto visibleIndexes = getChildrenVisibility(realOpacity, visibleRect); auto visualLayers = calculateChildrenVisualLayer(visibleIndexes, visibleRect, visualLayer); for (auto childIdx : visibleIndexes) { const auto& child = mChildren.at(childIdx.first); auto childVisibleRect = child->calculateVisibleRect(visibleRect); auto childRealOpacity = child->calculateRealOpacity(realOpacity); auto childVisibility = childIdx.second; auto childVisualLayer = visualLayers.at(childIdx.first); child->serializeVisualContextInternal( includeInContext? children : outArray, allocator, childRealOpacity, childVisibility, childVisibleRect, childVisualLayer); } } // we already should have included visible children on this point so break out if parent is not "actionable". if(!includeInContext) { return; } rapidjson::Value visualContext(rapidjson::kObjectType); if(!children.Empty()) { visualContext.AddMember("children", children.Move(), allocator); } // Get entities (if any) if(!getCalculated(kPropertyEntities).empty()) { visualContext.AddMember("entities", getCalculated(kPropertyEntities).serialize(allocator).Move(), allocator); } // Transform auto transform = getCalculated(kPropertyTransform).getTransform2D(); if(!transform.isIdentity()) { visualContext.AddMember("transform", transform.serialize(allocator).Move(), allocator); } // Now calculate other related tags as component to be included. if(tags.MemberCount() > 0) { visualContext.AddMember("tags", tags, allocator); } if(!mId.empty()) { visualContext.AddMember("id", rapidjson::Value(mId.c_str(), allocator).Move(), allocator); } visualContext.AddMember("uid", rapidjson::Value(mUniqueId.c_str(), allocator).Move(), allocator); visualContext.AddMember("position", rapidjson::Value((getGlobalBounds().toString() + ":" + std::to_string(visualLayer)).c_str(), allocator).Move(), allocator); visualContext.AddMember("type", rapidjson::Value(getVisualContextType().c_str(), allocator), allocator); if(visibility > 0.0 && visibility < 1.0) { visualContext.AddMember("visibility", visibility, allocator); } outArray.PushBack(visualContext.Move(), allocator); } std::string CoreComponent::getVisualContextType() const { std::string type; for(const auto& child : mChildren) { auto childType = child->getVisualContextType(); if(type.empty()) { type = childType; } if(type != childType) { return VISUAL_CONTEXT_TYPE_MIXED; } } return !type.empty() ? type : VISUAL_CONTEXT_TYPE_EMPTY; } void CoreComponent::setVisualContextDirty() { // set this component as dirty visual context mContext->setDirtyVisualContext(shared_from_this()); } bool CoreComponent::isVisualContextDirty() { return mContext->isVisualContextDirty(shared_from_this()); } std::map<int, float> CoreComponent::getChildrenVisibility(float realOpacity, const Rect &visibleRect) const { std::map<int, float> visibleIndexes; for(int index = 0; index < mChildren.size(); index++) { const auto& child = getCoreChildAt(index); float visibility = child->calculateVisibility(realOpacity, visibleRect); if(visibility > 0.0) { visibleIndexes.emplace(index, visibility); } } return visibleIndexes; } float CoreComponent::calculateVisibility(float parentRealOpacity, const Rect& parentVisibleRect) const { auto realOpacity = calculateRealOpacity(parentRealOpacity); if(realOpacity <= 0 || (getCalculated(kPropertyDisplay).asInt() != kDisplayNormal)) { return 0.0; } auto boundingRect = getGlobalBounds(); if(boundingRect.area() <= 0) { return 0.0; } auto visibleRect = calculateVisibleRect(parentVisibleRect); auto visibility = visibleRect.area()/boundingRect.area() * realOpacity; // May be positive only, do simple math instead of including math.h return ((int)(visibility * 100 + .5f) / 100.0f); } bool CoreComponent::getTags(rapidjson::Value &outMap, rapidjson::Document::AllocatorType &allocator) { bool actionable = false; bool checked = mState.get(kStateChecked); bool disabled = mState.get(kStateDisabled); if(checked && !mInheritParentState) { outMap.AddMember("checked", checked, allocator); } if(disabled) { outMap.AddMember("disabled", disabled, allocator); } if(isFocusable()) { bool focused = mState.get(kStateFocused) && !disabled; outMap.AddMember("focused", focused, allocator); } if(mParent && mParent->scrollable() && mParent->multiChild()) { rapidjson::Value listItem(rapidjson::kObjectType); listItem.AddMember("index", mContext->opt("index").asInt(), allocator); outMap.AddMember("listItem", listItem, allocator); } if(mParent && mParent->getCalculated(kPropertyNumbered).truthy() && mContext->has("ordinal")) { outMap.AddMember("ordinal", mContext->opt("ordinal").asInt(), allocator); } if(!getCalculated(kPropertySpeech).empty()) { outMap.AddMember("spoken", true, allocator); actionable |= true; } if(!mParent) { outMap.AddMember("viewport", rapidjson::Value(rapidjson::kObjectType), allocator); actionable |= true; } return actionable; } Rect CoreComponent::calculateVisibleRect(const Rect& parentVisibleRect) const { return getGlobalBounds().intersect(parentVisibleRect); } Rect CoreComponent::calculateVisibleRect() const { auto rect = getGlobalBounds(); if(!mParent) { float viewportWidth = mContext->width(); float viewportHeight = mContext->height(); return rect.intersect({0, 0, viewportWidth, viewportHeight}); } return rect.intersect(mParent->calculateVisibleRect()); } float CoreComponent::calculateRealOpacity(float parentRealOpacity) const { auto assignedOpacity = getCalculated(kPropertyOpacity).asNumber(); return assignedOpacity * parentRealOpacity; } float CoreComponent::calculateRealOpacity() const { auto assignedOpacity = getCalculated(kPropertyOpacity).asNumber(); if(!mParent) { return assignedOpacity; } return assignedOpacity * mParent->calculateRealOpacity(); } bool CoreComponent::isDisplayable() const { return (getCalculated(kPropertyDisplay).asInt() == kDisplayNormal) && (getCalculated(kPropertyOpacity).asNumber() > 0); } void CoreComponent::executeOnCursorEnter() { auto eventContext = createDefaultEventContext("CursorEnter"); auto command = getCalculated(kPropertyOnCursorEnter); mContext->sequencer().executeCommands(command, eventContext, shared_from_corecomponent(), true); } void CoreComponent::executeOnCursorExit() { auto eventContext = createDefaultEventContext("CursorExit"); auto command = getCalculated(kPropertyOnCursorExit); mContext->sequencer().executeCommands(command, eventContext, shared_from_corecomponent(), true); } bool CoreComponent::processKeyPress(KeyHandlerType type, const Keyboard& keyboard) { auto consumed = executeKeyHandlers(type, keyboard); // If no handler executed - go for Core specific (intrinsic) processing. if (!consumed) { consumed = executeIntrinsicKeyHandlers(type, keyboard); } return consumed; } /*****************************************************************/ static inline void inlineFixTransform(Component& component) { auto& core = dynamic_cast<CoreComponent&>(component); core.fixTransform(true); } static inline void inlineFixPadding(Component& component) { auto& core = dynamic_cast<CoreComponent&>(component); core.fixPadding(); } static inline Object defaultWidth(Component& component, const RootConfig& rootConfig) { return rootConfig.getDefaultComponentWidth(component.getType()); } static inline Object defaultHeight(Component& component, const RootConfig& rootConfig) { return rootConfig.getDefaultComponentHeight(component.getType()); } void CoreComponent::fixSpacing(bool reset) { auto spacing = getCalculated(kPropertySpacing).asDimension(*mContext); if (reset) spacing = 0; if (spacing.isAbsolute()) { YGNodeRef parent = YGNodeGetParent(mYGNodeRef); if (!parent) return; auto parentLayoutDirection = getParent()->getCalculated(kPropertyLayoutDirection); auto dir = YGNodeStyleGetFlexDirection(parent); YGEdge edge = YGEdgeLeft; switch (dir) { case YGFlexDirectionColumn: edge = YGEdgeTop; break; case YGFlexDirectionColumnReverse: edge = YGEdgeBottom; break; case YGFlexDirectionRow: edge = (parentLayoutDirection == kLayoutDirectionLTR) ? YGEdgeLeft : YGEdgeRight; break; case YGFlexDirectionRowReverse: edge = (parentLayoutDirection == kLayoutDirectionLTR) ? YGEdgeRight : YGEdgeLeft; break; } float currentValue = YGNodeStyleGetMargin(mYGNodeRef, edge).value; if ((std::isnan(currentValue) && spacing.getValue() != 0) || std::abs(currentValue - spacing.getValue()) > 0.1) { YGNodeStyleSetMargin(mYGNodeRef, YGEdgeTop, 0); YGNodeStyleSetMargin(mYGNodeRef, YGEdgeBottom, 0); YGNodeStyleSetMargin(mYGNodeRef, YGEdgeLeft, 0); YGNodeStyleSetMargin(mYGNodeRef, YGEdgeRight, 0); YGNodeStyleSetMargin(mYGNodeRef, edge, spacing.getValue()); } } } /** * Used by components with a displayed border. */ void CoreComponent::resolveDrawnBorder(Component& component) { auto& comp = static_cast<CoreComponent&>(component); comp.calculateDrawnBorder(true); } /** * Used by components with a displayed border. * Derive the width of the drawn border. If borderStrokeWith is set, the drawn border is the min of borderWidth * and borderStrokeWidth. If borderStrokeWidth is unset, the drawn border defaults to borderWidth. * @param useDirtyFlag true if the drawn border changed as a result of other property changes */ void CoreComponent::calculateDrawnBorder(bool useDirtyFlag ) { auto strokeWidthProp = getCalculated(kPropertyBorderStrokeWidth); float borderWidth = getCalculated(kPropertyBorderWidth).asAbsoluteDimension(*mContext).getValue(); float drawnWidth = borderWidth; // default the drawn width to the border width if (strokeWidthProp == Object::NULL_OBJECT()) { // no stroke width - default draw border width to border width // initialize stroke width to border width mCalculated.set(kPropertyBorderStrokeWidth, Object(Dimension(borderWidth))); } else { // stroke width - clamp the drawn border to the border width float strokeWidth = strokeWidthProp.getAbsoluteDimension(); if (strokeWidth < borderWidth) drawnWidth = strokeWidth; } Dimension dimension(drawnWidth); auto drawnWidthProp = getCalculated(kPropertyDrawnBorderWidth); if (drawnWidthProp == Object::NULL_OBJECT() || dimension != mCalculated.get(kPropertyDrawnBorderWidth).asAbsoluteDimension(*mContext)) { mCalculated.set(kPropertyDrawnBorderWidth, Object(std::move(dimension))); if (useDirtyFlag) setDirty(kPropertyDrawnBorderWidth); } } void CoreComponent::executeEventHandler(const std::string& event, const Object& commands, bool fastMode, const ObjectMapPtr& optional) { if (!mState.get(kStateDisabled)) { if (!fastMode) mContext->sequencer().reset(); ContextPtr eventContext = createEventContext(event, optional); mContext->sequencer().executeCommands( commands, eventContext, shared_from_corecomponent(), fastMode); } } YGSize CoreComponent::textMeasureInternal(float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { APL_TRACE_BLOCK("CoreComponent:textMeasureInternal"); auto componentHash = textMeasurementHash(); LOG_IF(DEBUG_MEASUREMENT) << "Measuring: " << getUniqueId() << " hash: " << componentHash << " width: " << width << " widthMode: " << widthMode << " height: " << height << " heightMode: " << heightMode; TextMeasureRequest tmr = {width, widthMode, height, heightMode, componentHash}; auto& measuresCache = getContext()->cachedMeasures(); if (measuresCache.has(tmr)) { return measuresCache.get(tmr); } APL_TRACE_BEGIN("CoreComponent:textMeasureInternal:runtimeMeasure"); LayoutSize layoutSize = getContext()->measure()->measure( this, width, toMeasureMode(widthMode), height, toMeasureMode(heightMode)); auto size = YGSize({layoutSize.width, layoutSize.height}); measuresCache.put(tmr, size); LOG_IF(DEBUG_MEASUREMENT) << "Size: " << size.width << "x" << size.height; APL_TRACE_END("CoreComponent:textMeasureInternal:runtimeMeasure"); return size; } float CoreComponent::textBaselineInternal(float width, float height) { APL_TRACE_BEGIN("CoreComponent:textBaselineInternal"); TextMeasureRequest tmr = { width, YGMeasureMode::YGMeasureModeUndefined, height, YGMeasureMode::YGMeasureModeUndefined, textMeasurementHash() }; auto& baselineCache = getContext()->cachedBaselines(); if (baselineCache.has(tmr)) { return baselineCache.get(tmr); } APL_TRACE_BEGIN("CoreComponent:textBaselineInternal:runtimeMeasure"); auto size = getContext()->measure()->baseline(this, width, height); baselineCache.put(tmr, size); APL_TRACE_END("CoreComponent:textBaselineInternal:runtimeMeasure"); return size; } YGSize CoreComponent::textMeasureFunc( YGNodeRef node, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode ) { auto *component = static_cast<CoreComponent*>(node->getContext()); assert(component); return component->textMeasureInternal(width, widthMode, height, heightMode); } float CoreComponent::textBaselineFunc( YGNodeRef node, float width, float height ) { auto *component = static_cast<CoreComponent*>(node->getContext()); assert(component); return component->textBaselineInternal(width, height); } const ComponentPropDefSet& CoreComponent::propDefSet() const { static ComponentPropDefSet sCommonComponentProperties = ComponentPropDefSet().add({ {kPropertyAccessibilityLabel, "", asString, kPropInOut | kPropDynamic}, {kPropertyAccessibilityActions, Object::EMPTY_ARRAY(), asArray, kPropInOut}, {kPropertyBounds, Object::EMPTY_RECT(), nullptr, kPropOut | kPropVisualContext | kPropVisualHash}, {kPropertyChecked, false, asBoolean, kPropInOut | kPropDynamic | kPropMixedState | kPropVisualContext}, {kPropertyDescription, "", asString, kPropIn}, {kPropertyDisplay, kDisplayNormal, sDisplayMap, kPropInOut | kPropStyled | kPropDynamic | kPropVisualContext, yn::setDisplay}, {kPropertyDisabled, false, asBoolean, kPropInOut | kPropDynamic | kPropMixedState | kPropVisualContext}, {kPropertyEntities, Object::EMPTY_ARRAY(), asDeepArray, kPropIn | kPropVisualContext}, {kPropertyFocusable, false, nullptr, kPropOut}, {kPropertyHandleTick, Object::EMPTY_ARRAY(), asArray, kPropIn}, {kPropertyHeight, Dimension(), asDimension, kPropIn | kPropDynamic | kPropStyled, yn::setHeight, defaultHeight}, {kPropertyInnerBounds, Object::EMPTY_RECT(), nullptr, kPropOut | kPropVisualContext | kPropVisualHash}, {kPropertyLayoutDirectionAssigned, kLayoutDirectionInherit, sLayoutDirectionMap, kPropIn | kPropDynamic | kPropStyled, yn::setLayoutDirection}, {kPropertyLayoutDirection, kLayoutDirectionLTR, sLayoutDirectionMap, kPropOut | kPropTextHash | kPropVisualHash}, {kPropertyMaxHeight, Object::NULL_OBJECT(), asNonAutoDimension, kPropIn | kPropDynamic | kPropStyled, yn::setMaxHeight}, {kPropertyMaxWidth, Object::NULL_OBJECT(), asNonAutoDimension, kPropIn | kPropDynamic | kPropStyled, yn::setMaxWidth}, {kPropertyMinHeight, Dimension(0), asNonAutoDimension, kPropIn | kPropDynamic | kPropStyled, yn::setMinHeight}, {kPropertyMinWidth, Dimension(0), asNonAutoDimension, kPropIn | kPropDynamic | kPropStyled, yn::setMinWidth}, {kPropertyOnMount, Object::EMPTY_ARRAY(), asCommand, kPropIn}, {kPropertyOpacity, 1.0, asOpacity, kPropInOut | kPropStyled | kPropDynamic | kPropVisualContext | kPropVisualHash}, {kPropertyPadding, Object::EMPTY_ARRAY(), asPaddingArray, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingBottom, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingLeft, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingRight, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingTop, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingStart, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPaddingEnd, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropDynamic | kPropStyled, inlineFixPadding}, {kPropertyPreserve, Object::EMPTY_ARRAY(), asArray, kPropIn}, {kPropertyRole, kRoleNone, sRoleMap, kPropInOut | kPropStyled}, {kPropertyShadowColor, Color(), asColor, kPropInOut | kPropDynamic | kPropStyled | kPropVisualHash}, {kPropertyShadowHorizontalOffset, Dimension(0), asAbsoluteDimension, kPropInOut | kPropDynamic | kPropStyled | kPropVisualHash}, {kPropertyShadowRadius, Dimension(0), asAbsoluteDimension, kPropInOut | kPropDynamic | kPropStyled | kPropVisualHash}, {kPropertyShadowVerticalOffset, Dimension(0), asAbsoluteDimension, kPropInOut | kPropDynamic | kPropStyled | kPropVisualHash}, {kPropertySpeech, "", asString, kPropIn | kPropVisualContext}, {kPropertyTransformAssigned, Object::NULL_OBJECT(), asTransformOrArray, kPropIn | kPropDynamic | kPropEvaluated | kPropVisualContext, inlineFixTransform}, {kPropertyTransform, Object::IDENTITY_2D(), nullptr, kPropOut | kPropVisualContext}, {kPropertyUser, Object::NULL_OBJECT(), nullptr, kPropOut}, {kPropertyWidth, Dimension(), asDimension, kPropIn | kPropDynamic | kPropStyled, yn::setWidth, defaultWidth}, {kPropertyOnCursorEnter, Object::EMPTY_ARRAY(), asCommand, kPropIn}, {kPropertyOnCursorExit, Object::EMPTY_ARRAY(), asCommand, kPropIn}, {kPropertyLaidOut, false, asBoolean, kPropOut | kPropVisualContext}, {kPropertyVisualHash, "", asString, kPropOut | kPropRuntimeState}, }); return sCommonComponentProperties; } bool CoreComponent::containsLocalPosition(const Point &position) const { auto bounds = getCalculated(kPropertyBounds).getRect(); Rect localBounds(0, 0, bounds.getWidth(), bounds.getHeight()); return localBounds.contains(position); } Point CoreComponent::toLocalPoint(const Point& globalPoint) const { auto toLocal = getGlobalToLocalTransform(); if (toLocal.singular()) { static float NaN = std::numeric_limits<float>::quiet_NaN(); return {NaN, NaN}; } else { return toLocal * globalPoint; } } bool CoreComponent::inParentViewport() const { if (!mParent) { return false; } Rect bounds = getCalculated(kPropertyBounds).getRect(); auto parentBounds = mParent->getCalculated(kPropertyBounds).getRect(); // Reset to "viewport" parentBounds = Rect(0, 0, parentBounds.getWidth(), parentBounds.getHeight()); // Shift by scroll position if any parentBounds.offset(mParent->scrollPosition()); return !parentBounds.intersect(bounds).isEmpty(); } PointerCaptureStatus CoreComponent::processPointerEvent(const PointerEvent& event, apl_time_t timestamp) { if (mState.get(kStateDisabled)) return kPointerStatusNotCaptured; if (processGestures(event, timestamp)) return kPointerStatusCaptured; auto pointInCurrent = toLocalPoint(event.pointerEventPosition); auto it = sEventHandlers.find(event.pointerEventType); if (it != sEventHandlers.end()) executePointerEventHandler(it->second, pointInCurrent); return kPointerStatusNotCaptured; } const RootConfig& CoreComponent::getRootConfig() const { return mContext->getRootConfig(); } void CoreComponent::ensureGlobalToLocalTransform() { // Check for a stale parent, since marking a cache transform as stale does not // mark children (see markGlobalToLocalTransformStale()). If any parent is stale, // the mark will bubble up to this component during this phase. if (mParent) { mParent->ensureGlobalToLocalTransform(); } if (!mGlobalToLocalIsStale) { return; } Transform2D newLocalTransform; auto componentTransform = getCalculated(kPropertyTransform).getTransform2D(); // To transform from the coordinate space of the parent component to the // coordinate space of the child component, first offset by the position of // the child in the parent, then undo the child transformation: auto boundsInParent = getCalculated(kPropertyBounds).getRect(); auto offsetInParent = boundsInParent.getTopLeft(); newLocalTransform = componentTransform.inverse() * Transform2D::translate(-offsetInParent); if (mParent) { // Account for the parent's scroll position. The scroll position only affects the // coordinate space of children, so we account for it in the child component // transformation. auto scrollPosition = mParent->scrollPosition(); newLocalTransform = newLocalTransform * Transform2D::translate(scrollPosition) * mParent->getGlobalToLocalTransform(); } if (newLocalTransform != mGlobalToLocal) { mGlobalToLocal = newLocalTransform; for (auto i = 0; i < getChildCount(); i++) { auto child = getCoreChildAt(i); if (child->getCalculated(kPropertyLaidOut).truthy()) { child->markGlobalToLocalTransformStale(); } } } mGlobalToLocalIsStale = false; } const Transform2D& CoreComponent::getGlobalToLocalTransform() const { auto &mutableThis = const_cast<CoreComponent&>(*this); mutableThis.ensureGlobalToLocalTransform(); return mGlobalToLocal; } YGDirection CoreComponent::getLayoutDirection() const { auto direction = YGNodeStyleGetDirection(mYGNodeRef); if (direction == YGDirectionInherit) { if (!mParent) // Fallback to document level layoutDirection return mContext->getLayoutDirection() == kLayoutDirectionRTL ? YGDirectionRTL : YGDirectionLTR; return mParent->getLayoutDirection(); } return direction; } } // namespace apl
pxviet1997/hyreyou-frontend
src/utils/index.js
<reponame>pxviet1997/hyreyou-frontend import getInitials from './getInitials'; import Roles from './Roles'; import * as validationSchema from './validationSchema'; export { getInitials, Roles, validationSchema };
mk-prg-net/PlaygroundJS
HTML5/Scripts/lodash-amd/internal/Reflect.js
define(['./root'], function(root) { /** Built-in value references. */ var Reflect = root.Reflect; return Reflect; });
BW-AnyWhereFitness1/Backend
data/migrations/20201019113852_user.js
<reponame>BW-AnyWhereFitness1/Backend exports.up = function(knex) { return knex.schema.createTable('user', tbl => { tbl.increments(); tbl.string('name').notNullable(); tbl .string('email') .notNullable() .unique(); tbl .string('username') .notNullable() .unique() .index(); tbl.string('password').notNullable(); tbl.string('role').notNullable(); }); }; exports.down = function(knex) { return knex.schema.dropTableIfExists('user'); };
log-Z/iblog
src/main/java/com/log/blog/mapper/AdminMapper.java
package com.log.blog.mapper; import com.log.blog.dto.AdminParam; import com.log.blog.entity.Admin; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface AdminMapper { Admin getAdminById(@Param("id") String id); Admin getAdminByEmail(@Param("email") String email); List<Admin> listAdmins(@Param("admin") AdminParam adminParam); List<Admin> findAdmins(@Param("admin") AdminParam adminParam); boolean insertAdmin(@Param("admin") AdminParam adminParam); boolean updateAdmin(@Param("admin") AdminParam adminParam); boolean deleteAdmin(@Param("adminId") String adminId); }
zayloxd/OtakuBot
events/ready.js
<reponame>zayloxd/OtakuBot const Discord = require('discord.js'); const settings = require('../settings.json'); const client = new Discord.Client(); const fs = require('fs'); module.exports = client => { console.log(`yourbots Online and ready to serve ${client.guilds.cache.size} servers.`); };
Roopesh2/C.js
src/color/color_converters.js
export function hue2RGB(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes values of red, green, and blue are between 0 & 1 and * returns hue, saturation and lightness in range 0 to 1 * @global * @param {number} r The red color value * @param {number} g The green color value * @param {number} b The blue color value * @return {Array<number>} The HSL representation */ export function RGBToHSL(r, g, b) { let max = Math.max(r, g, b), min = Math.min(r, g, b), hue, saturation, lightness = (max + min) / 2; if (max === min) { hue = saturation = 0; // achromatic } else { let d = max - min; saturation = lightness > 0.5 ? d / (2 - max - min) : d / (max + min); if (max == r) hue = (g - b) / d + (g < b ? 6 : 0); else if (max == g) hue = (b - r) / d + 2; else if (max == b) hue = (r - g) / d + 4; hue /= 6; } return [hue, saturation, lightness]; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes values of hue is between 0 and 360, saturation and lightness are between 0 & 1 and * returns red, green, and blue values between 0 & 1 * * @param {number} hue The hue * @param {number} saturation The saturation * @param {number} lightness The lightness * @return {Array<number>} The RGB representation */ export function HSLToRGB(hue, saturation, lightness) { let r, g, b; hue /= 360; if (saturation === 0) { r = g = b = lightness; // achromatic } else { let q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; let p = 2 * lightness - q; r = hue2RGB(p, q, hue + 1 / 3); g = hue2RGB(p, q, hue); b = hue2RGB(p, q, hue - 1 / 3); } return [r, g, b]; } /** * Converts an RGB color value to HSV. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes values of red, green, and blue are between 0 & 1 and * returns hue, saturation and value in range 0 to 1 * * @global * @param {number} r The red color value * @param {number} g The green color value * @param {number} b The blue color value * @return {Array<number>} The HSV representation */ export function RGBToHSV(r, g, b) { let max = Math.max(r, g, b), // val min = Math.min(r, g, b), // chroma hue, value = max, d = max - min, saturation = max === 0 ? 0 : d / max; if (max === min) { hue = 0; // achromatic } else { if (max == r) hue = (g - b) / d + (g < b ? 6 : 0); else if (max == g) hue = (b - r) / d + 2; else if (max == b) hue = (r - g) / d + 4; hue /= 6; } return [hue, saturation, value]; } /** * Converts an HSV color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes values of hue is between 0 to 360, saturation, and value are between 0 & 1 and * returns red, green, and blue in range 0 to 1 * * @param {number} hue The hue * @param {number} saturation The saturation * @param {number} value The value * @return {Array<number>} The RGB representation */ export function HSVToRGB(hue, saturation, value) { let r, g, b, i = Math.floor(hue / 60), f = hue / 60 - i, p = value * (1 - saturation), q = value * (1 - f * saturation), t = value * (1 - (1 - f) * saturation); i %= 6; if (i == 0) (r = value), (g = t), (b = p); else if (i == 1) (r = q), (g = value), (b = p); else if (i == 2) (r = p), (g = value), (b = t); else if (i == 3) (r = p), (g = q), (b = value); else if (i == 4) (r = t), (g = p), (b = value); else if (i == 5) (r = value), (g = p), (b = q); return [r, g, b]; }
MAKENTNU/web
docs/migrations/0001_initial.py
<gh_stars>1-10 # Generated by Django 2.2.8 on 2019-12-14 22:00 import ckeditor_uploader.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=64, unique=True, verbose_name='Title')), ], ), migrations.CreateModel( name='Content', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('changed', models.DateTimeField(verbose_name='Time changed')), ('content', ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Content')), ('page', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_history', to='docs.Page', verbose_name='Page')), ], ), ]
cjmcv/cuda
opencl/ocl_util.h
<reponame>cjmcv/cuda #ifndef CJMCV_OCL_UTIL_HPP_ #define CJMCV_OCL_UTIL_HPP_ #include <iostream> #include <CL/cl.h> namespace cjmcv_ocl_util { //////////////// // Macro. //////////////// #define OCL_CHECK(condition) \ do { \ cl_int error = condition; \ if (error != CL_SUCCESS) { \ fprintf(stderr, "OCL_CHECK error in line %d of file %s : %s \n", \ __LINE__, __FILE__, cjmcv_ocl_util::GetErrorString(error)); \ exit(EXIT_FAILURE); \ } \ } while(0); //////////////// // Functions. //////////////// // Get the error string by error code. const char* GetErrorString(cl_int error); // Print the name and version of the platform. void PrintPlatBasicInfo(cl_platform_id &platform); // Get a multiple that's rounded up. size_t GetRoundUpMultiple(size_t dividend, size_t divisor); void PrintCommandElapsedTime(cl_event ev); //////////////// // Structure. //////////////// //////////////// // Class. //////////////// // KernelLoader: It is used to get the kernel functions from the program file. class KernelLoader { public: KernelLoader(); // Load bool Load(const char *source_file); void UnLoad(); bool CreateProgram(const cl_context &context); bool GetKernel(const char *kernel_name, cl_kernel *kernel); private: char* LoadProgSource(const char* file_name, const char* preamble, size_t* final_length); private: cl_int err_code_; // Byte size of kernel code // Buffer to hold source for compilation size_t program_length_; char* program_source_; cl_program program_; }; class PlatformSelector { public: PlatformSelector(); ~PlatformSelector(); void QueryPlatforms(); inline cl_platform_id *platforms() { return platforms_; } // platform_name: "NVIDIA CUDA" / "Intel(R) OpenCL" // device_order: Serial number of the same platform. bool GetDeviceId(std::string platform_name, cl_device_id* device_id, int device_order = 0); private: cl_platform_id *platforms_; cl_uint num_; char **names_; char **versions_; }; } //namespace cjmcv_ocl_util #endif //CJMCV_OCL_UTIL_HPP_
RajeshKumarC6/Learn-Scala-Programming
Chapter11/src/main/scala/ch11/Store.scala
<filename>Chapter11/src/main/scala/ch11/Store.scala package ch11 import akka.actor._ import com.typesafe.config.ConfigFactory import Manager.ShoppingList import Mixer.Groceries abstract class Store { val store = ActorSystem("Store", ConfigFactory.load("grocery.conf")) val seller: ActorRef = store.actorOf(Props(new Actor { override def receive: Receive = { case s: ShoppingList => ShoppingList.unapply(s).map(Groceries.tupled).foreach(sender() ! _) } }), "Seller") } object Store extends Store with App
leongold/ovirt-engine
frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/PatternflyIconType.java
package org.ovirt.engine.ui.common.widget; import com.google.gwt.dom.client.Style.HasCssName; public enum PatternflyIconType implements HasCssName { PF_CLOSE("pficon-close"); //$NON-NLS-1$ private final String cssName; private PatternflyIconType(String cssName) { this.cssName = cssName; } @Override public String getCssName() { return cssName; } }
web-health-portal/portal-capstone
frontend/src/store/articleCategory.js
import {createSlice} from "@reduxjs/toolkit" import {httpConfig} from "../ui/shared/utils/http-config"; const articleCategorySlice = createSlice({ name: "articleCategory", initialState: [], reducers: { getAllArticleCategories: (articleCategory, action) => { return action.payload }, setArticleCategory: (articleCategory, action) => { articleCategory.push(...action.payload) } }, }) export const {getAllArticleCategories, setArticleCategory} = articleCategorySlice.actions export const fetchArticleCategoryByArticleIds = () => async (dispatch, getState) => { const articleIds = getState().article.articleId for (const articleId of articleIds) { const {data} = await httpConfig.get(`/apis/article-category/articleId/${articleId}`) dispatch(setArticleCategory(data)) } // console.log("data", data) // dispatch(getAllArticleCategories(data)) } export default articleCategorySlice.reducer
Matthijsy/amber-api
spec/requests/v1/groups_controller/create_spec.rb
require 'rails_helper' describe V1::GroupsController do describe 'POST /groups', version: 1 do it_behaves_like 'a creatable and permissible model' do let(:record) { FactoryBot.build(:group) } let(:record_url) { '/v1/groups' } let(:record_permission) { 'group.create' } let(:invalid_attributes) { { name: '' } } end end end
JakubVojvoda/design-patterns-java
visitor/Main.java
/* * Java Design Patterns: Visitor * Author: <NAME> [github.com/JakubVojvoda] * 2016 * * Source code is licensed under MIT License * (for more details see LICENSE) * */ package app; public class Main { public static void main(String[] args) { Element elementA = new ConcreteElementA(); Element elementB = new ConcreteElementB(); Visitor visitor1 = new ConcreteVisitor1(); Visitor visitor2 = new ConcreteVisitor2(); elementA.accept(visitor1); elementA.accept(visitor2); elementB.accept(visitor1); elementB.accept(visitor2); } }
pintoXD/stm32wb55LoRaFuota
Middlewares/ST/STM32_Cryptographic/Fw_Crypto/STM32H7A3/Inc/DES/Common/des_common.h
/** ****************************************************************************** * @file des_common.h * @author MCD Application Team * @brief DES common functions and definitions ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2015 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Image license SLA0044, * 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.st.com/SLA0044 * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __DES_COMMON_H__ #define __DES_COMMON_H__ #ifdef __cplusplus extern "C" { #endif /** @addtogroup DES * @{ */ /* Exported constants --------------------------------------------------------*/ #define CRL_DES_BLOCK 8 /*!< Number of bytes (uint8_t) necessary to store a DES block. */ #define CRL_DES_KEY 8 /*!< Number of bytes (uint8_t) necessary to store a DES key. */ /* Exported types ------------------------------------------------------------*/ typedef struct { uint32_t mContextId; /*!< Unique ID of this context. \b Not \b used in current implementation. */ SKflags_et mFlags; /*!< 32 bit mFlags, used to perform keyschedule */ const uint8_t *pmKey; /*!< Pointer to original Key buffer */ const uint8_t *pmIv; /*!< Pointer to original Initialization Vector buffer */ int32_t mIvSize; /*!< Size of the Initialization Vector in bytes */ uint32_t amIv[2]; /*!< Temporary result/IV */ uint32_t amExpKey[32]; /*!< Expanded DES key */ } DESCBCctx_stt; /*!< Structure for the context of a DES operation */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__DES_COMMON_H__*/ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
wiidz/goutil
structs/networkStruct/networkStruct.go
package networkStruct type ContentType int8 const ( Query ContentType = 1 BodyJson ContentType = 2 BodyForm ContentType = 3 ) // ReadCommonStruct 读取列表公用的参数 type ReadCommonStruct struct { PageNow int `json:"page_now" belong:"etc" default:"1"` PageSize int `json:"page_size" belong:"etc" default:"10"` Order string `json:"order" belong:"etc" default:"id asc"` } type Method int8 const ( Get Method = 1 Post Method = 2 Put Method = 3 Delete Method = 4 Options Method = 5 ) func (p Method) String() string { switch p { case Get: return "GET" case Post: return "POST" case Put: return "PUT" case Delete: return "DELETE" case Options: return "OPTIONS" default: return "UNKNOWN" } } // ParamsInterface 参数接口 type ParamsInterface interface { // order 顺序 GetOrder() string SetOrder(string) // page 页码 GetPageSize() int SetPageSize(int) GetPageNow() int SetPageNow(int) GetLimit() int GetOffset() int // [read] - prelaoad 附加 GetPreloads() []string SetPreloads([]string) // [read、update、post、delete] - 原始数据 GetRawMap() map[string]interface{} SetRawMap(map[string]interface{}) // [read、update、delete] - condition 条件 GetCondition() map[string]interface{} SetCondition(map[string]interface{}) // [read] - rows 查询记录 GetRows() interface{} SetRows(interface{}) // [read、insert、update、delete] - row GetRow() interface{} SetRow(interface{}) // [read] - count 查询数目 GetCount() int64 SetCount(int64) // error 错误 GetError() error SetError(error) // [update、delete] - rows affected 影响行数 GetRowsAffected() int64 SetRowsAffected(int64) // [update、insert] - value 数据 GetValue() map[string]interface{} SetValue(map[string]interface{}) // [update、delete] - 表名 GetTableName() string SetTableName(string) // [insert] - 新的主键 GetNewID() uint64 SetNewID(newID uint64) // 其他 GetEtc() map[string]interface{} SetEtc(data map[string]interface{}) } // Params 参数结构体 type Params struct { // 前端参数 PageNow int `json:"page_now" belong:"etc" default:"1"` // [read] PageSize int `json:"page_size" belong:"etc" default:"10"` // [read] Order string `json:"order" belong:"etc" default:"ids asc"` // [read] // 根据前端参数处理后的数据 Condition map[string]interface{} // [read、update、delete] 条件 Value map[string]interface{} // [update、insert] - 数据 Etc map[string]interface{} // 其他 RawMap map[string]interface{} // 内部补充参数 Single bool // [read] - 附加条件 Preloads []string // [read] - 附加 TableName string // [update、delete] - 指定表名 // 操作结果 NewID uint64 // [insert] - 新主键 Rows interface{} // [read] - 结构切片 Row interface{} // [read、update、delete、insert] - 结构 Count int64 // [read] - 统计行数 RowsAffected int64 // [update、delete] - 影响行数 Error error // 错误 } // TableName 表名 func (params *Params) GetTableName() string { return params.TableName } func (params *Params) SetTableName(tableName string) { params.TableName = tableName } // Condition 条件 func (params *Params) GetCondition() map[string]interface{} { return params.Condition } func (params *Params) SetCondition(condition map[string]interface{}) { params.Condition = condition } // Value 操作值 func (params *Params) GetValue() map[string]interface{} { return params.Value } func (params *Params) SetValue(value map[string]interface{}) { params.Value = value } // Page 页码 func (params *Params) GetPageNow() int { return params.PageNow } func (params *Params) SetPageNow(pageNow int) { params.PageNow = pageNow } func (params *Params) GetPageSize() int { return params.PageSize } func (params *Params) SetPageSize(pageSize int) { params.PageSize = pageSize } func (params *Params) GetOffset() int { var offset int if params.PageNow > 1 { offset = (params.PageNow - 1) * params.PageSize } else { offset = 0 } return offset } func (params *Params) GetLimit() int { return params.PageSize } // RawMap 原始数据 func (params *Params) GetRawMap() map[string]interface{} { return params.RawMap } func (params *Params) SetRawMap(RawMap map[string]interface{}) { params.RawMap = RawMap } // Count 结果数目 func (params *Params) SetCount(count int64) { params.Count = count } func (params *Params) GetCount() int64 { return params.Count } // RowsAffected 影响行数 func (params *Params) GetRowsAffected() int64 { return params.RowsAffected } func (params *Params) SetRowsAffected(rowsAffected int64) { params.RowsAffected = rowsAffected } // Error 错误 func (params *Params) GetError() error { return params.Error } func (params *Params) SetError(err error) { params.Error = err } // Rows 查询结果 func (params *Params) SetRows(rows interface{}) { params.Rows = rows } func (params *Params) GetRows() interface{} { return params.Rows } // Row 查询结果 func (params *Params) SetRow(rows interface{}) { params.Row = rows } func (params *Params) GetRow() interface{} { return params.Row } // Order 顺序 func (params *Params) GetOrder() string { return params.Order } func (params *Params) SetOrder(order string) { params.Order = order } // Preloads 预加载 func (params *Params) GetPreloads() []string { return params.Preloads } func (params *Params) SetPreloads(preloads []string) { params.Preloads = preloads } // NewID 新主键 func (params *Params) GetNewID() uint64 { return params.NewID } func (params *Params) SetNewID(newID uint64) { params.NewID = newID } // Etc 其他 func (params *Params) GetEtc() map[string]interface{} { return params.Etc } func (params *Params) SetEtc(data map[string]interface{}) { params.Etc = data }
tizzen33/core
homeassistant/components/knx/weather.py
"""Support for KNX/IP weather station.""" from __future__ import annotations from xknx import XKNX from xknx.devices import Weather as XknxWeather from homeassistant.components.weather import WeatherEntity from homeassistant.const import CONF_ENTITY_CATEGORY, CONF_NAME, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import DOMAIN from .knx_entity import KnxEntity from .schema import WeatherSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up weather entities for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXWeather(xknx, entity_config) for entity_config in platform_config ) def _create_weather(xknx: XKNX, config: ConfigType) -> XknxWeather: """Return a KNX weather device to be used within XKNX.""" return XknxWeather( xknx, name=config[CONF_NAME], sync_state=config[WeatherSchema.CONF_SYNC_STATE], group_address_temperature=config[WeatherSchema.CONF_KNX_TEMPERATURE_ADDRESS], group_address_brightness_south=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_SOUTH_ADDRESS ), group_address_brightness_east=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_EAST_ADDRESS ), group_address_brightness_west=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_WEST_ADDRESS ), group_address_brightness_north=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_NORTH_ADDRESS ), group_address_wind_speed=config.get(WeatherSchema.CONF_KNX_WIND_SPEED_ADDRESS), group_address_wind_bearing=config.get( WeatherSchema.CONF_KNX_WIND_BEARING_ADDRESS ), group_address_rain_alarm=config.get(WeatherSchema.CONF_KNX_RAIN_ALARM_ADDRESS), group_address_frost_alarm=config.get( WeatherSchema.CONF_KNX_FROST_ALARM_ADDRESS ), group_address_wind_alarm=config.get(WeatherSchema.CONF_KNX_WIND_ALARM_ADDRESS), group_address_day_night=config.get(WeatherSchema.CONF_KNX_DAY_NIGHT_ADDRESS), group_address_air_pressure=config.get( WeatherSchema.CONF_KNX_AIR_PRESSURE_ADDRESS ), group_address_humidity=config.get(WeatherSchema.CONF_KNX_HUMIDITY_ADDRESS), ) class KNXWeather(KnxEntity, WeatherEntity): """Representation of a KNX weather device.""" _device: XknxWeather _attr_temperature_unit = TEMP_CELSIUS def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize of a KNX sensor.""" super().__init__(_create_weather(xknx, config)) self._attr_unique_id = str(self._device._temperature.group_address_state) self._attr_entity_category = config.get(CONF_ENTITY_CATEGORY) @property def temperature(self) -> float | None: """Return current temperature.""" return self._device.temperature @property def pressure(self) -> float | None: """Return current air pressure.""" # KNX returns pA - HA requires hPa return ( self._device.air_pressure / 100 if self._device.air_pressure is not None else None ) @property def condition(self) -> str: """Return current weather condition.""" return self._device.ha_current_state().value @property def humidity(self) -> float | None: """Return current humidity.""" return self._device.humidity @property def wind_bearing(self) -> int | None: """Return current wind bearing in degrees.""" return self._device.wind_bearing @property def wind_speed(self) -> float | None: """Return current wind speed in km/h.""" # KNX only supports wind speed in m/s return ( self._device.wind_speed * 3.6 if self._device.wind_speed is not None else None )
labs14-lambda-app-store/FE
src/components/student/share/Share.js
<reponame>labs14-lambda-app-store/FE import React, { useState } from 'react'; import { LinkedinShareButton, TwitterShareButton, LinkedinIcon, TwitterIcon, } from 'react-share'; import Fade from 'react-reveal/Fade'; import { Link } from 'react-router-dom'; const Share = ({ studentId, name, about }) => { const [hide, toggleHide] = useState(true); const url = `https://hirelambdastudents.com/student/profile/${studentId}`; about = 'about string'; return ( <div className='share-wrapper'> <Link className='share-btn' onClick={() => { toggleHide(!hide); }} to='#' > Share </Link> <div className='share-links'> <Fade when={!hide}> <div className='share-button'> <LinkedinShareButton url={url} title={`Hire Lambda Students: ${name}`} > <LinkedinIcon size={32} round /> </LinkedinShareButton> </div> <div className='share-button'> <TwitterShareButton url={url} title={`Hire Lambda Students: ${name}`} hashtags={['lambda', 'developers', 'hirelambda']} > <TwitterIcon size={32} round /> </TwitterShareButton> </div> </Fade> </div> </div> ); }; export default Share;
AeneasPlatform/Aeneas
node/src/main/scala/com/aeneas/transaction/validation/impl/TransferTxValidator.scala
package com.aeneas.transaction.validation.impl import cats.data.ValidatedNel import com.aeneas.lang.ValidationError import com.aeneas.transaction.transfer.TransferTransaction import com.aeneas.transaction.validation.TxValidator object TransferTxValidator extends TxValidator[TransferTransaction] { override def validate(transaction: TransferTransaction): ValidatedNel[ValidationError, TransferTransaction] = { import transaction._ V.seq(transaction)( V.fee(fee), V.positiveAmount(amount, assetId.maybeBase58Repr.getOrElse("waves")), V.transferAttachment(attachment), V.addressChainId(recipient, chainId) ) } }
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/domain/AlipayTradeOrderSettleModel.java
package cn.felord.wepay.ali.sdk.api.domain; import java.util.List; import cn.felord.wepay.ali.sdk.api.AlipayObject; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiListField; /** * 统一收单交易结算接口 * * @author auto create * @version $Id: $Id */ public class AlipayTradeOrderSettleModel extends AlipayObject { private static final long serialVersionUID = 6496958111839716367L; /** * 操作员id */ @ApiField("operator_id") private String operatorId; /** * 结算请求流水号 开发者自行生成并保证唯一性 */ @ApiField("out_request_no") private String outRequestNo; /** * 分账明细信息 */ @ApiListField("royalty_parameters") @ApiField("open_api_royalty_detail_info_pojo") private List<OpenApiRoyaltyDetailInfoPojo> royaltyParameters; /** * 支付宝订单号 */ @ApiField("trade_no") private String tradeNo; /** * <p>Getter for the field <code>operatorId</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorId() { return this.operatorId; } /** * <p>Setter for the field <code>operatorId</code>.</p> * * @param operatorId a {@link java.lang.String} object. */ public void setOperatorId(String operatorId) { this.operatorId = operatorId; } /** * <p>Getter for the field <code>outRequestNo</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOutRequestNo() { return this.outRequestNo; } /** * <p>Setter for the field <code>outRequestNo</code>.</p> * * @param outRequestNo a {@link java.lang.String} object. */ public void setOutRequestNo(String outRequestNo) { this.outRequestNo = outRequestNo; } /** * <p>Getter for the field <code>royaltyParameters</code>.</p> * * @return a {@link java.util.List} object. */ public List<OpenApiRoyaltyDetailInfoPojo> getRoyaltyParameters() { return this.royaltyParameters; } /** * <p>Setter for the field <code>royaltyParameters</code>.</p> * * @param royaltyParameters a {@link java.util.List} object. */ public void setRoyaltyParameters(List<OpenApiRoyaltyDetailInfoPojo> royaltyParameters) { this.royaltyParameters = royaltyParameters; } /** * <p>Getter for the field <code>tradeNo</code>.</p> * * @return a {@link java.lang.String} object. */ public String getTradeNo() { return this.tradeNo; } /** * <p>Setter for the field <code>tradeNo</code>.</p> * * @param tradeNo a {@link java.lang.String} object. */ public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } }
utilitywarehouse/poc-pg-mirror
billmodel/mobprepa.xo.go
// Package billmodel contains the types for schema 'equinox'. package billmodel // GENERATED BY XO. DO NOT EDIT. import ( "database/sql" "github.com/lib/pq" ) // Mobprepa represents a row from 'equinox.mobprepa'. type Mobprepa struct { Mppcliuniquesys sql.NullFloat64 `json:"mppcliuniquesys"` // mppcliuniquesys Mppcli sql.NullString `json:"mppcli"` // mppcli Mppsim sql.NullString `json:"mppsim"` // mppsim Mppaccountno sql.NullString `json:"mppaccountno"` // mppaccountno Mppminbalance sql.NullInt64 `json:"mppminbalance"` // mppminbalance Mppmaxbalance sql.NullInt64 `json:"mppmaxbalance"` // mppmaxbalance Mppdebitno sql.NullString `json:"mppdebitno"` // mppdebitno Mppdebitstart sql.NullString `json:"mppdebitstart"` // mppdebitstart Mppdebitexpiry sql.NullString `json:"mppdebitexpiry"` // mppdebitexpiry Mppdebitissue sql.NullString `json:"mppdebitissue"` // mppdebitissue Mppdebitcv2 sql.NullString `json:"mppdebitcv2"` // mppdebitcv2 Mpptopuppin sql.NullString `json:"mpptopuppin"` // mpptopuppin Mpplivedate pq.NullTime `json:"mpplivedate"` // mpplivedate Mppenddate pq.NullTime `json:"mppenddate"` // mppenddate Mpptexttopup sql.NullInt64 `json:"mpptexttopup"` // mpptexttopup Mppccunique sql.NullFloat64 `json:"mppccunique"` // mppccunique Mppshopperref sql.NullString `json:"mppshopperref"` // mppshopperref EquinoxLrn int64 `json:"equinox_lrn"` // equinox_lrn EquinoxSec sql.NullInt64 `json:"equinox_sec"` // equinox_sec } func AllMobprepa(db XODB, callback func(x Mobprepa) bool) error { // sql query const sqlstr = `SELECT ` + `mppcliuniquesys, mppcli, mppsim, mppaccountno, mppminbalance, mppmaxbalance, mppdebitno, mppdebitstart, mppdebitexpiry, mppdebitissue, mppdebitcv2, mpptopuppin, mpplivedate, mppenddate, mpptexttopup, mppccunique, mppshopperref, equinox_lrn, equinox_sec ` + `FROM equinox.mobprepa ` q, err := db.Query(sqlstr) if err != nil { return err } defer q.Close() // load results for q.Next() { m := Mobprepa{} // scan err = q.Scan(&m.Mppcliuniquesys, &m.Mppcli, &m.Mppsim, &m.Mppaccountno, &m.Mppminbalance, &m.Mppmaxbalance, &m.Mppdebitno, &m.Mppdebitstart, &m.Mppdebitexpiry, &m.Mppdebitissue, &m.Mppdebitcv2, &m.Mpptopuppin, &m.Mpplivedate, &m.Mppenddate, &m.Mpptexttopup, &m.Mppccunique, &m.Mppshopperref, &m.EquinoxLrn, &m.EquinoxSec) if err != nil { return err } if !callback(m) { return nil } } return nil } // MobprepaByEquinoxLrn retrieves a row from 'equinox.mobprepa' as a Mobprepa. // // Generated from index 'mobprepa_pkey'. func MobprepaByEquinoxLrn(db XODB, equinoxLrn int64) (*Mobprepa, error) { var err error // sql query const sqlstr = `SELECT ` + `mppcliuniquesys, mppcli, mppsim, mppaccountno, mppminbalance, mppmaxbalance, mppdebitno, mppdebitstart, mppdebitexpiry, mppdebitissue, mppdebitcv2, mpptopuppin, mpplivedate, mppenddate, mpptexttopup, mppccunique, mppshopperref, equinox_lrn, equinox_sec ` + `FROM equinox.mobprepa ` + `WHERE equinox_lrn = $1` // run query XOLog(sqlstr, equinoxLrn) m := Mobprepa{} err = db.QueryRow(sqlstr, equinoxLrn).Scan(&m.Mppcliuniquesys, &m.Mppcli, &m.Mppsim, &m.Mppaccountno, &m.Mppminbalance, &m.Mppmaxbalance, &m.Mppdebitno, &m.Mppdebitstart, &m.Mppdebitexpiry, &m.Mppdebitissue, &m.Mppdebitcv2, &m.Mpptopuppin, &m.Mpplivedate, &m.Mppenddate, &m.Mpptexttopup, &m.Mppccunique, &m.Mppshopperref, &m.EquinoxLrn, &m.EquinoxSec) if err != nil { return nil, err } return &m, nil }
shahedex/tfjson
vendor/github.com/hashicorp/terraform/builtin/providers/azurerm/resource_arm_virtual_machine_extension_test.go
<reponame>shahedex/tfjson<filename>vendor/github.com/hashicorp/terraform/builtin/providers/azurerm/resource_arm_virtual_machine_extension_test.go package azurerm import ( "fmt" "net/http" "testing" "regexp" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAzureRMVirtualMachineExtension_basic(t *testing.T) { ri := acctest.RandInt() preConfig := fmt.Sprintf(testAccAzureRMVirtualMachineExtension_basic, ri, ri, ri, ri, ri, ri, ri, ri) postConfig := fmt.Sprintf(testAccAzureRMVirtualMachineExtension_basicUpdate, ri, ri, ri, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineExtensionDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExtensionExists("azurerm_virtual_machine_extension.test"), resource.TestMatchResourceAttr("azurerm_virtual_machine_extension.test", "settings", regexp.MustCompile("hostname")), ), }, resource.TestStep{ Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExtensionExists("azurerm_virtual_machine_extension.test"), resource.TestMatchResourceAttr("azurerm_virtual_machine_extension.test", "settings", regexp.MustCompile("whoami")), ), }, }, }) } func TestAccAzureRMVirtualMachineExtension_concurrent(t *testing.T) { ri := acctest.RandInt() config := fmt.Sprintf(testAccAzureRMVirtualMachineExtension_concurrent, ri, ri, ri, ri, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineExtensionDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExtensionExists("azurerm_virtual_machine_extension.test"), testCheckAzureRMVirtualMachineExtensionExists("azurerm_virtual_machine_extension.test2"), resource.TestMatchResourceAttr("azurerm_virtual_machine_extension.test", "settings", regexp.MustCompile("hostname")), resource.TestMatchResourceAttr("azurerm_virtual_machine_extension.test2", "settings", regexp.MustCompile("whoami")), ), }, }, }) } func TestAccAzureRMVirtualMachineExtension_linuxDiagnostics(t *testing.T) { ri := acctest.RandInt() config := fmt.Sprintf(testAccAzureRMVirtualMachineExtension_linuxDiagnostics, ri, ri, ri, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineExtensionDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExtensionExists("azurerm_virtual_machine_extension.test"), ), }, }, }) } func testCheckAzureRMVirtualMachineExtensionExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { // Ensure we have enough information in state to look up in API rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } name := rs.Primary.Attributes["name"] vmName := rs.Primary.Attributes["virtual_machine_name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] conn := testAccProvider.Meta().(*ArmClient).vmExtensionClient resp, err := conn.Get(resourceGroup, vmName, name, "") if err != nil { return fmt.Errorf("Bad: Get on vmExtensionClient: %s", err) } if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("Bad: VirtualMachine Extension %q (resource group: %q) does not exist", name, resourceGroup) } return nil } } func testCheckAzureRMVirtualMachineExtensionDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*ArmClient).vmExtensionClient for _, rs := range s.RootModule().Resources { if rs.Type != "azurerm_virtual_machine_extension" { continue } name := rs.Primary.Attributes["name"] vmName := rs.Primary.Attributes["virtual_machine_name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] resp, err := conn.Get(resourceGroup, vmName, name, "") if err != nil { return nil } if resp.StatusCode != http.StatusNotFound { return fmt.Errorf("Virtual Machine Extension still exists:\n%#v", resp.VirtualMachineExtensionProperties) } } return nil } var testAccAzureRMVirtualMachineExtension_basic = ` resource "azurerm_resource_group" "test" { name = "acctestrg-%d" location = "West US" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_subnet" "test" { name = "acctsub-%d" resource_group_name = "${azurerm_resource_group.test.name}" virtual_network_name = "${azurerm_virtual_network.test.name}" address_prefix = "10.0.2.0/24" } resource "azurerm_network_interface" "test" { name = "acctni-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { name = "testconfiguration1" subnet_id = "${azurerm_subnet.test.id}" private_ip_address_allocation = "dynamic" } } resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" location = "westus" account_type = "Standard_LRS" tags { environment = "staging" } } resource "azurerm_storage_container" "test" { name = "vhds" resource_group_name = "${azurerm_resource_group.test.name}" storage_account_name = "${azurerm_storage_account.test.name}" container_access_type = "private" } resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] vm_size = "Standard_A0" storage_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "14.04.2-LTS" version = "latest" } storage_os_disk { name = "myosdisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" caching = "ReadWrite" create_option = "FromImage" } os_profile { computer_name = "hostname%d" admin_username = "testadmin" admin_password = "<PASSWORD>!" } os_profile_linux_config { disable_password_authentication = false } } resource "azurerm_virtual_machine_extension" "test" { name = "acctvme-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.Azure.Extensions" type = "CustomScript" type_handler_version = "2.0" settings = <<SETTINGS { "commandToExecute": "hostname" } SETTINGS tags { environment = "Production" } } ` var testAccAzureRMVirtualMachineExtension_basicUpdate = ` resource "azurerm_resource_group" "test" { name = "acctestrg-%d" location = "West US" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_subnet" "test" { name = "acctsub-%d" resource_group_name = "${azurerm_resource_group.test.name}" virtual_network_name = "${azurerm_virtual_network.test.name}" address_prefix = "10.0.2.0/24" } resource "azurerm_network_interface" "test" { name = "acctni-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { name = "testconfiguration1" subnet_id = "${azurerm_subnet.test.id}" private_ip_address_allocation = "dynamic" } } resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" location = "westus" account_type = "Standard_LRS" tags { environment = "staging" } } resource "azurerm_storage_container" "test" { name = "vhds" resource_group_name = "${azurerm_resource_group.test.name}" storage_account_name = "${azurerm_storage_account.test.name}" container_access_type = "private" } resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] vm_size = "Standard_A0" storage_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "14.04.2-LTS" version = "latest" } storage_os_disk { name = "myosdisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" caching = "ReadWrite" create_option = "FromImage" } os_profile { computer_name = "hostname%d" admin_username = "testadmin" admin_password = "<PASSWORD>!" } os_profile_linux_config { disable_password_authentication = false } } resource "azurerm_virtual_machine_extension" "test" { name = "acctvme-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.Azure.Extensions" type = "CustomScript" type_handler_version = "2.0" settings = <<SETTINGS { "commandToExecute": "whoami" } SETTINGS tags { environment = "Production" cost_center = "MSFT" } } ` var testAccAzureRMVirtualMachineExtension_concurrent = ` resource "azurerm_resource_group" "test" { name = "acctestrg-%d" location = "West US" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_subnet" "test" { name = "acctsub-%d" resource_group_name = "${azurerm_resource_group.test.name}" virtual_network_name = "${azurerm_virtual_network.test.name}" address_prefix = "10.0.2.0/24" } resource "azurerm_network_interface" "test" { name = "acctni-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { name = "testconfiguration1" subnet_id = "${azurerm_subnet.test.id}" private_ip_address_allocation = "dynamic" } } resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" location = "westus" account_type = "Standard_LRS" tags { environment = "staging" } } resource "azurerm_storage_container" "test" { name = "vhds" resource_group_name = "${azurerm_resource_group.test.name}" storage_account_name = "${azurerm_storage_account.test.name}" container_access_type = "private" } resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] vm_size = "Standard_A0" storage_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "14.04.2-LTS" version = "latest" } storage_os_disk { name = "myosdisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" caching = "ReadWrite" create_option = "FromImage" } os_profile { computer_name = "hostname%d" admin_username = "testadmin" admin_password = "<PASSWORD>!" } os_profile_linux_config { disable_password_authentication = false } } resource "azurerm_virtual_machine_extension" "test" { name = "acctvme-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.Azure.Extensions" type = "CustomScript" type_handler_version = "2.0" settings = <<SETTINGS { "commandToExecute": "hostname" } SETTINGS } resource "azurerm_virtual_machine_extension" "test2" { name = "acctvme-%d-2" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.OSTCExtensions" type = "CustomScriptForLinux" type_handler_version = "1.5" settings = <<SETTINGS { "commandToExecute": "whoami" } SETTINGS } ` var testAccAzureRMVirtualMachineExtension_linuxDiagnostics = ` resource "azurerm_resource_group" "test" { name = "acctestrg-%d" location = "West US" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_subnet" "test" { name = "acctsub-%d" resource_group_name = "${azurerm_resource_group.test.name}" virtual_network_name = "${azurerm_virtual_network.test.name}" address_prefix = "10.0.2.0/24" } resource "azurerm_network_interface" "test" { name = "acctni-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { name = "testconfiguration1" subnet_id = "${azurerm_subnet.test.id}" private_ip_address_allocation = "dynamic" } } resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" location = "westus" account_type = "Standard_LRS" tags { environment = "staging" } } resource "azurerm_storage_container" "test" { name = "vhds" resource_group_name = "${azurerm_resource_group.test.name}" storage_account_name = "${azurerm_storage_account.test.name}" container_access_type = "private" } resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] vm_size = "Standard_A0" storage_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "14.04.2-LTS" version = "latest" } storage_os_disk { name = "myosdisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" caching = "ReadWrite" create_option = "FromImage" } os_profile { computer_name = "hostname%d" admin_username = "testadmin" admin_password = "<PASSWORD>!" } os_profile_linux_config { disable_password_authentication = false } } resource "azurerm_virtual_machine_extension" "test" { name = "acctvme-%d" location = "West US" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.OSTCExtensions" type = "LinuxDiagnostic" type_handler_version = "2.3" protected_settings = <<SETTINGS { "storageAccountName": "${azurerm_storage_account.test.name}", "storageAccountKey": "${azurerm_storage_account.test.primary_access_key}" } SETTINGS tags { environment = "Production" } } `
goderbauer/ftl
strings/trim.cc
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "lib/ftl/strings/trim.h" namespace ftl { ftl::StringView TrimString(ftl::StringView str, ftl::StringView chars_to_trim) { size_t start_index = str.find_first_not_of(chars_to_trim); if (start_index == ftl::StringView::npos) { return ftl::StringView(); } size_t end_index = str.find_last_not_of(chars_to_trim); return str.substr(start_index, end_index - start_index + 1); } } // namespace ftl
TeamNuclear/external_chromium_org_third_party_webrtc
modules/audio_coding/main/acm2/acm_common_defs.h
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_MODULES_AUDIO_CODING_MAIN_ACM2_ACM_COMMON_DEFS_H_ #define WEBRTC_MODULES_AUDIO_CODING_MAIN_ACM2_ACM_COMMON_DEFS_H_ #include <string.h> #include "webrtc/common_types.h" #include "webrtc/engine_configurations.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module_typedefs.h" #include "webrtc/typedefs.h" // Checks for enabled codecs, we prevent enabling codecs which are not // compatible. #if ((defined WEBRTC_CODEC_ISAC) && (defined WEBRTC_CODEC_ISACFX)) #error iSAC and iSACFX codecs cannot be enabled at the same time #endif namespace webrtc { // 60 ms is the maximum block size we support. An extra 20 ms is considered // for safety if process() method is not called when it should be, i.e. we // accept 20 ms of jitter. 80 ms @ 48 kHz (full-band) stereo is 7680 samples. #define AUDIO_BUFFER_SIZE_W16 7680 // There is one timestamp per each 10 ms of audio // the audio buffer, at max, may contain 32 blocks of 10ms // audio if the sampling frequency is 8000 Hz (80 samples per block). // Therefore, The size of the buffer where we keep timestamps // is defined as follows #define TIMESTAMP_BUFFER_SIZE_W32 (AUDIO_BUFFER_SIZE_W16/80) // The maximum size of a payload, that is 60 ms of PCM-16 @ 32 kHz stereo #define MAX_PAYLOAD_SIZE_BYTE 7680 // General codec specific defines const int kIsacWbDefaultRate = 32000; const int kIsacSwbDefaultRate = 56000; const int kIsacPacSize480 = 480; const int kIsacPacSize960 = 960; const int kIsacPacSize1440 = 1440; // An encoded bit-stream is labeled by one of the following enumerators. // // kNoEncoding : There has been no encoding. // kActiveNormalEncoded : Active audio frame coded by the codec. // kPassiveNormalEncoded : Passive audio frame coded by the codec. // kPassiveDTXNB : Passive audio frame coded by narrow-band CN. // kPassiveDTXWB : Passive audio frame coded by wide-band CN. // kPassiveDTXSWB : Passive audio frame coded by super-wide-band CN. // kPassiveDTXFB : Passive audio frame coded by full-band CN. enum WebRtcACMEncodingType { kNoEncoding, kActiveNormalEncoded, kPassiveNormalEncoded, kPassiveDTXNB, kPassiveDTXWB, kPassiveDTXSWB, kPassiveDTXFB }; // A structure which contains codec parameters. For instance, used when // initializing encoder and decoder. // // codec_inst: c.f. common_types.h // enable_dtx: set true to enable DTX. If codec does not have // internal DTX, this will enable VAD. // enable_vad: set true to enable VAD. // vad_mode: VAD mode, c.f. audio_coding_module_typedefs.h // for possible values. struct WebRtcACMCodecParams { CodecInst codec_inst; bool enable_dtx; bool enable_vad; ACMVADMode vad_mode; }; // TODO(turajs): Remove when ACM1 is removed. struct WebRtcACMAudioBuff { int16_t in_audio[AUDIO_BUFFER_SIZE_W16]; int16_t in_audio_ix_read; int16_t in_audio_ix_write; uint32_t in_timestamp[TIMESTAMP_BUFFER_SIZE_W32]; int16_t in_timestamp_ix_write; uint32_t last_timestamp; uint32_t last_in_timestamp; }; } // namespace webrtc #endif // WEBRTC_MODULES_AUDIO_CODING_MAIN_ACM2_ACM_COMMON_DEFS_H_
ceekay1991/CallTraceForWeChat
CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/ScanBookMgr.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "MMService.h" #import "MMServiceProtocol-Protocol.h" #import "PBMessageObserverDelegate-Protocol.h" @class MMTimer, NSData, NSString; @interface ScanBookMgr : MMService <MMServiceProtocol, PBMessageObserverDelegate> { unsigned int _scanBookId; unsigned int _sessionId; unsigned int _opCode; NSData *_dataToSend; unsigned int _totalLen; unsigned int _offset; unsigned int _lastPackLen; int _imageType; int _uploadAction; _Bool _isUploading; MMTimer *_uploadTimer; } - (void).cxx_destruct; - (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2; - (void)saveProductItem:(id)arg1; - (id)getLocalProductItemById:(id)arg1; - (void)checkUpload; - (void)stop; - (void)start; - (id)getProductItemById:(id)arg1 Scence:(unsigned int)arg2 QRCodeUrl:(id)arg3; - (int)sendSBImage:(id)arg1 BufLen:(unsigned int)arg2 ImageType:(int)arg3 OPCode:(unsigned int)arg4 SessionId:(unsigned int)arg5; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
jasha64/jasha64
Spring 2018/ACM/2018.4.14/J.cpp
<gh_stars>0 #include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <climits> using namespace std; const int N = 100001; bool f[N]; //is_prime vector<int> a; void Get_Prime() { fill(f, f+N, 1); f[0] = f[1] = 0; for (int i = 2; i < N; i++) if (f[i]) for (int j = 2; j*i < N; j++) f[j*i] = 0; } bool Test(const int x) { int cc = 0; for (int i = 0; i < a.size(); i++) { if (cc + a[i] > x) return false; cc += a[i]; if (cc == x) cc = 0; } return true; } int main() { ios::sync_with_stdio(false); Get_Prime(); int kase; cin >> kase; cin.ignore(INT_MAX, '\n'); istringstream ss; while (kase--) { string s; getline(cin, s); int tot_len = 0; a.clear(); ss.clear(); ss.str(s); while (ss >> s) {tot_len += s.size()+1; a.push_back(s.size()+1);} bool sol = 0; for (int i = 2; i < N; i++) if (f[i] && tot_len % i == 0 && Test(tot_len / i)) {cout << "YES" << endl; sol = 1; break;} if (!sol) cout << "NO" << endl; } return 0; }
sarismet/basic-CRM-module
src/main/java/com/layermark/layermark_sarismet/exception/GlobalExceptionHandler.java
package com.layermark.layermark_sarismet.exception; import com.layermark.layermark_sarismet.exception.bad_request.*; import com.layermark.layermark_sarismet.exception.not_found.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.layermark.layermark_sarismet.model.Error; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) private ResponseEntity<Error> notFoundExceptionHandler( Exception e) { return exceptionHandler(HttpStatus.NOT_FOUND, e); } @ExceptionHandler({BadRequestException.class}) private ResponseEntity<Error> badRequestExceptionHandler( Exception e) { return exceptionHandler(HttpStatus.BAD_REQUEST, e); } private ResponseEntity<Error> exceptionHandler(HttpStatus status, Exception e){ Error error = new Error(); error.setCode(status.toString()); error.setError(e.getMessage().toString()); return ResponseEntity.status(status).body(error); } }
wangsenyuan/learn-go
src/leetcode/set0000/set800/set800/p831/solution_test.go
<reponame>wangsenyuan/learn-go package p831 import "testing" func TestMaskEmail(t *testing.T) { S := "<EMAIL>" expect := "<EMAIL>" res := maskPII(S) if res != expect { t.Errorf("error got %s", res) } } func TestMaskPhone(t *testing.T) { S := "+111 111 111 1111" expect := "+***-***-***-1111" res := maskPII(S) if res != expect { t.Errorf("error got %s", res) } } func TestMaskPhone2(t *testing.T) { S := "1(234)567-890" expect := "***-***-7890" res := maskPII(S) if res != expect { t.Errorf("error got %s", res) } }
bborisov11/Java-Frameworks-Hibernate-Spring
05. Spring data intro/src/main/java/org/bookshop/system/bookshopsystem/enums/AgeRestriction.java
<filename>05. Spring data intro/src/main/java/org/bookshop/system/bookshopsystem/enums/AgeRestriction.java package org.bookshop.system.bookshopsystem.enums; public enum AgeRestriction { MINOR,TEEN,ADULT }
rande/pkgmirror
mirror/npm/npm_pat_test.go
// Copyright © 2016-present <NAME> <<EMAIL>>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package npm import ( "testing" "net/http" "github.com/stretchr/testify/assert" "goji.io/pattern" "golang.org/x/net/context" ) type TestVersion struct { Url string Package string Version string } func mustReq(method, path string) (context.Context, *http.Request) { req, err := http.NewRequest(method, path, nil) if err != nil { panic(err) } ctx := pattern.SetPath(context.Background(), req.URL.EscapedPath()) return ctx, req } func Test_Npm_Pat(t *testing.T) { cases := []struct{ Url, Package, Version string }{ {"/npm/npm/aspace/-/aspace-0.0.1.tgz", "aspace", "0.0.1"}, {"/npm/npm/@type%2fnode/-/node-6.0.90.tgz", "@type%2fnode", "6.0.90"}, {"/npm/npm/dateformat/-/dateformat-1.0.2-1.2.3.tgz", "dateformat", "1.0.2-1.2.3"}, {"/npm/npm/@storybook%2freact/-/react-3.0.0.tgz", "@storybook%2freact", "3.0.0"}, } matcher := NewArchivePat("npm") for _, p := range cases { c, r := mustReq("GET", p.Url) result := matcher.Match(c, r) assert.NotNil(t, result) assert.Equal(t, p.Package, result.Value(pattern.Variable("package"))) assert.Equal(t, p.Version, result.Value(pattern.Variable("version"))) assert.Equal(t, "tgz", result.Value(pattern.Variable("format"))) } } func Test_Npm_Pat_AllVariables(t *testing.T) { p := NewArchivePat("npm") c, r := mustReq("GET", "/npm/npm/aspace/-/aspace-0.0.1.tgz") result := p.Match(c, r) assert.NotNil(t, result) vars := result.Value(pattern.AllVariables).(map[pattern.Variable]string) assert.Equal(t, "aspace", vars["package"]) assert.Equal(t, "0.0.1", vars["version"]) assert.Equal(t, "tgz", vars["format"]) } func Test_Npm_Pat_OtherVariable(t *testing.T) { p := NewArchivePat("npm") c, r := mustReq("GET", "/npm/npm/aspace/-/aspace-0.0.1.tgz") result := p.Match(c, r) assert.NotNil(t, result) assert.Nil(t, result.Value(pattern.Variable("foo"))) }
WeDoSoftware/trino
core/trino-main/src/test/java/io/trino/sql/planner/iterative/rule/TestPushLimitThroughSemiJoin.java
<reponame>WeDoSoftware/trino /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.iterative.rule; import com.google.common.collect.ImmutableList; import io.trino.sql.planner.Symbol; import io.trino.sql.planner.iterative.rule.test.BaseRuleTest; import io.trino.sql.planner.iterative.rule.test.PlanBuilder; import io.trino.sql.planner.plan.PlanNode; import org.testng.annotations.Test; import java.util.Optional; import static io.trino.sql.planner.assertions.PlanMatchPattern.limit; import static io.trino.sql.planner.assertions.PlanMatchPattern.semiJoin; import static io.trino.sql.planner.assertions.PlanMatchPattern.sort; import static io.trino.sql.planner.assertions.PlanMatchPattern.values; import static io.trino.sql.tree.SortItem.NullOrdering.FIRST; import static io.trino.sql.tree.SortItem.Ordering.ASCENDING; public class TestPushLimitThroughSemiJoin extends BaseRuleTest { @Test public void test() { tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.limit(1, buildSemiJoin(p))) .matches( semiJoin( "leftKey", "rightKey", "match", limit(1, values("leftKey")), values("rightKey"))); } @Test public void testPushLimitWithTies() { tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.limit( 1, ImmutableList.of(p.symbol("leftKey")), buildSemiJoin(p))) .matches( semiJoin( "leftKey", "rightKey", "match", limit(1, ImmutableList.of(sort("leftKey", ASCENDING, FIRST)), values("leftKey")), values("rightKey"))); } @Test public void testPushLimitWithPreSortedInputs() { tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.limit( 1, false, ImmutableList.of(p.symbol("leftKey")), buildSemiJoin(p))) .matches( semiJoin( "leftKey", "rightKey", "match", limit( 1, ImmutableList.of(), false, ImmutableList.of("leftKey"), values("leftKey")), values("rightKey"))); } @Test public void testDoesNotFire() { tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.semiJoin( p.symbol("leftKey"), p.symbol("rightKey"), p.symbol("output"), Optional.empty(), Optional.empty(), p.values(p.symbol("leftKey")), p.limit(1, p.values(p.symbol("rightKey"))))) .doesNotFire(); tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.limit( 1, ImmutableList.of(p.symbol("match")), buildSemiJoin(p))) .doesNotFire(); // Do not push down Limit with pre-sorted inputs if input ordering depends on symbol produced by SemiJoin tester().assertThat(new PushLimitThroughSemiJoin()) .on(p -> p.limit( 1, false, ImmutableList.of(p.symbol("match")), buildSemiJoin(p))) .doesNotFire(); } private static PlanNode buildSemiJoin(PlanBuilder p) { Symbol leftKey = p.symbol("leftKey"); Symbol rightKey = p.symbol("rightKey"); return p.semiJoin( leftKey, rightKey, p.symbol("match"), Optional.empty(), Optional.empty(), p.values(leftKey), p.values(rightKey)); } }
rsjtaylor/libadm
tests/position_interaction_range_tests.cpp
#include <catch2/catch.hpp> #include "adm/elements/position_interaction_range.hpp" TEST_CASE("positionRange_interaction_range") { using namespace adm; // Default contructor { PositionInteractionRange positionRange; REQUIRE(positionRange.has<AzimuthInteractionMin>() == false); REQUIRE(positionRange.has<ElevationInteractionMin>() == false); REQUIRE(positionRange.has<DistanceInteractionMin>() == false); REQUIRE(positionRange.has<AzimuthInteractionMax>() == false); REQUIRE(positionRange.has<ElevationInteractionMax>() == false); REQUIRE(positionRange.has<DistanceInteractionMax>() == false); REQUIRE(positionRange.has<XInteractionMin>() == false); REQUIRE(positionRange.has<YInteractionMin>() == false); REQUIRE(positionRange.has<ZInteractionMin>() == false); REQUIRE(positionRange.has<XInteractionMax>() == false); REQUIRE(positionRange.has<YInteractionMax>() == false); REQUIRE(positionRange.has<ZInteractionMax>() == false); } // Full specification { PositionInteractionRange positionRange( AzimuthInteractionMin{-30.f}, ElevationInteractionMin{-45.f}, DistanceInteractionMin{0.5f}, AzimuthInteractionMax{30.f}, ElevationInteractionMax{45.f}, DistanceInteractionMax{1.5f}); REQUIRE(positionRange.has<AzimuthInteractionMin>() == true); REQUIRE(positionRange.has<ElevationInteractionMin>() == true); REQUIRE(positionRange.has<DistanceInteractionMin>() == true); REQUIRE(positionRange.has<AzimuthInteractionMax>() == true); REQUIRE(positionRange.has<ElevationInteractionMax>() == true); REQUIRE(positionRange.has<DistanceInteractionMax>() == true); REQUIRE(positionRange.isDefault<AzimuthInteractionMin>() == false); REQUIRE(positionRange.isDefault<ElevationInteractionMin>() == false); REQUIRE(positionRange.isDefault<DistanceInteractionMin>() == false); REQUIRE(positionRange.isDefault<AzimuthInteractionMax>() == false); REQUIRE(positionRange.isDefault<ElevationInteractionMax>() == false); REQUIRE(positionRange.isDefault<DistanceInteractionMax>() == false); REQUIRE(positionRange.get<AzimuthInteractionMin>() == Approx(-30.f)); REQUIRE(positionRange.get<ElevationInteractionMin>() == Approx(-45.f)); REQUIRE(positionRange.get<DistanceInteractionMin>() == Approx(0.5f)); REQUIRE(positionRange.get<AzimuthInteractionMax>() == Approx(30.f)); REQUIRE(positionRange.get<ElevationInteractionMax>() == Approx(45.f)); REQUIRE(positionRange.get<DistanceInteractionMax>() == Approx(1.5f)); } { PositionInteractionRange positionRange( XInteractionMin{-1.f}, YInteractionMin{-1.f}, ZInteractionMin{-1.f}, XInteractionMax{1.f}, YInteractionMax{1.f}, ZInteractionMax{1.f}); REQUIRE(positionRange.has<XInteractionMin>() == true); REQUIRE(positionRange.has<YInteractionMin>() == true); REQUIRE(positionRange.has<ZInteractionMin>() == true); REQUIRE(positionRange.has<XInteractionMax>() == true); REQUIRE(positionRange.has<YInteractionMax>() == true); REQUIRE(positionRange.has<ZInteractionMax>() == true); REQUIRE(positionRange.isDefault<XInteractionMin>() == false); REQUIRE(positionRange.isDefault<YInteractionMin>() == false); REQUIRE(positionRange.isDefault<ZInteractionMin>() == false); REQUIRE(positionRange.isDefault<XInteractionMax>() == false); REQUIRE(positionRange.isDefault<YInteractionMax>() == false); REQUIRE(positionRange.isDefault<ZInteractionMax>() == false); REQUIRE(positionRange.get<XInteractionMin>() == Approx(-1.f)); REQUIRE(positionRange.get<YInteractionMin>() == Approx(-1.f)); REQUIRE(positionRange.get<ZInteractionMin>() == Approx(-1.f)); REQUIRE(positionRange.get<XInteractionMax>() == Approx(1.f)); REQUIRE(positionRange.get<YInteractionMax>() == Approx(1.f)); REQUIRE(positionRange.get<ZInteractionMax>() == Approx(1.f)); } }
laides/mbed-cloud-client
factory-configurator-client/utils/utils/mbed_stats_helper.c
<reponame>laides/mbed-cloud-client // ---------------------------------------------------------------------------- // Copyright 2016-2017 ARM Ltd. // // 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. // ---------------------------------------------------------------------------- #if defined(MBED_HEAP_STATS_ENABLED) || defined(MBED_STACK_STATS_ENABLED) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "mbed_stats.h" #include "mbed_stats_helper.h" #include "pal.h" #include <string.h> #if MBED_CONF_RTOS_PRESENT #include "cmsis_os2.h" #endif #define MBED_STATS_FILE_NAME "/mbedos_stats.txt" /** Print mbed-os stack and heap usage to stdout and to text file named mbedos_stats.txt. Note: Make sure MBED_HEAP_STATS_ENABLED or MBED_STACK_STATS_ENABLED flags are defined */ void print_mbed_stats(void) { palStatus_t pal_result = PAL_SUCCESS; // Max size of directory acquired by pal_fsGetMountPoint + file name (including '/') + '\0' char file_name[PAL_MAX_FOLDER_DEPTH_CHAR + sizeof(MBED_STATS_FILE_NAME)] = { 0 }; pal_result = pal_fsGetMountPoint(PAL_FS_PARTITION_PRIMARY, PAL_MAX_FOLDER_DEPTH_CHAR + 1, file_name); if (pal_result != PAL_SUCCESS) { return; } strcat(file_name, MBED_STATS_FILE_NAME); FILE *f = fopen(file_name, "wt"); if (f) { // Heap #if defined(MBED_HEAP_STATS_ENABLED) mbed_stats_heap_t heap_stats; mbed_stats_heap_get(&heap_stats); fprintf(f, "Current heap usage size: %" PRIu32 "\n", heap_stats.current_size); printf("Current heap usage size: %" PRIu32 "\n", heap_stats.current_size); fprintf(f, "Max heap usage size: %" PRIu32 "\n", heap_stats.max_size); printf("Max heap usage size: %" PRIu32 "\n", heap_stats.max_size); #endif // Stacks #if defined(MBED_STACK_STATS_ENABLED) && defined(MBED_CONF_RTOS_PRESENT) int cnt = osThreadGetCount(); mbed_stats_stack_t *stack_stats = (mbed_stats_stack_t*)malloc(cnt * sizeof(mbed_stats_stack_t)); if (stack_stats) { fprintf(f, "Thread's stack usage:\n"); printf("Thread's stack usage:\n"); cnt = mbed_stats_stack_get_each(stack_stats, cnt); for (int i = 0; i < cnt; i++) { fprintf(f, "Thread: 0x%" PRIx32 ", Stack size: %" PRIu32 ", Max stack: %" PRIu32 "\r\n", stack_stats[i].thread_id, stack_stats[i].reserved_size, stack_stats[i].max_size); printf("Thread: 0x%" PRIx32 ", Stack size: %" PRIu32 ", Max stack: %" PRIu32 "\r\n", stack_stats[i].thread_id, stack_stats[i].reserved_size, stack_stats[i].max_size); } free(stack_stats); } #endif fclose(f); printf("*****************************\n\n"); } } #endif
iamlmn/PyDS
queues/dequeue_linkedLists.py
class Node: def __init__(self, element, next): self.element = element self.next = next class DQ: def __init__(self): self.front = None self.rear = None self.size = 0 def __len__(self): return self.size def isEmpty(self): return self.size == 0 def display(self): p = self.front while p: print(p.element, end= '-->') p = p.next print() def addFirst(self, element): newest = Node(element, None) if self.isEmpty(): self.front = newest self.rear = newest else: newest.next = self.front self.front = newest self.size += 1 def addLast(self, element): newest = Node(element, None) if self.isEmpty(): self.front = newest else: self.rear.next = newest self.rear = newest self.size += 1 def removeFirst(self): if self.isEmpty(): print("Queue is empty") return else: e = self.front.element self.front = self.front.next self.size -= 1 return e def removeLast(self): if self.isEmpty(): print("Queue is empty!") return # else: p = self.front i = 1 while i < len(self) - 1: p = p.next i = i + 1 self.rear = p p = p.next e = p.element # p.next = None self.rear.next = None self.size -= 1 return e def first(self): if self.isEmpty(): print("DeQueue is empty") return return self.front.element def last(self): if self.isEmpty(): print("DeQueue is empty") return return self.rear.element if __name__ == '__main__': Q = DQ() Q.addFirst(5) Q.addFirst(3) Q.addLast(7) Q.addLast(12) Q.display() print(f"Length : {len(Q)}") print("Remove First", Q.removeFirst()) print("Remove Last", Q.removeLast()) Q.display() print(f"First element : {Q.first()}") print(f"Last element : {Q.last()}")
gridgentoo/titus-control-plane
titus-supplementary-component/task-relocation/src/main/java/com/netflix/titus/supplementary/relocation/workflow/DefaultNodeConditionController.java
<gh_stars>100-1000 package com.netflix.titus.supplementary.relocation.workflow; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.api.model.callmetadata.Caller; import com.netflix.titus.api.model.callmetadata.CallerType; import com.netflix.titus.common.framework.scheduler.ExecutionContext; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.retry.Retryers; import com.netflix.titus.runtime.connector.jobmanager.JobDataReplicator; import com.netflix.titus.runtime.connector.jobmanager.JobManagementClient; import com.netflix.titus.supplementary.relocation.RelocationConfiguration; import com.netflix.titus.supplementary.relocation.connector.Node; import com.netflix.titus.supplementary.relocation.connector.NodeDataResolver; import com.netflix.titus.supplementary.relocation.util.RelocationUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; public class DefaultNodeConditionController implements NodeConditionController { private static final Logger logger = LoggerFactory.getLogger(DefaultNodeConditionController.class); private final RelocationConfiguration configuration; private final NodeDataResolver nodeDataResolver; private final JobDataReplicator jobDataReplicator; private final ReadOnlyJobOperations jobOperations; private final JobManagementClient jobManagementClient; private final NodeConditionCtrlMetrics metrics; private final TitusRuntime titusRuntime; private static final CallMetadata CALL_METADATA = buildCallMetadata(); private static final String CALLER_APP_ID = "titusrelocation"; private static final String CALL_REASON = "This task was automatically terminated because the underlying host had issues."; private ScheduleReference scheduleReference; public DefaultNodeConditionController(RelocationConfiguration relocationConfiguration, NodeDataResolver nodeDataResolver, JobDataReplicator jobDataReplicator, ReadOnlyJobOperations jobOperations, JobManagementClient jobManagementClient, TitusRuntime titusRuntime) { this.configuration = relocationConfiguration; this.nodeDataResolver = nodeDataResolver; this.jobDataReplicator = jobDataReplicator; this.jobOperations = jobOperations; this.jobManagementClient = jobManagementClient; this.metrics = new NodeConditionCtrlMetrics(titusRuntime.getRegistry()); this.titusRuntime = titusRuntime; } @Override public void activate() { logger.info("Activating DefaultNodeConditionController"); ScheduleDescriptor nodeConditionControlLoopSchedulerDescriptor = ScheduleDescriptor.newBuilder() .withName("nodeConditionCtrl") .withDescription("Node Condition control loop") .withInitialDelay(Duration.ZERO) .withInterval(Duration.ofMillis(configuration.getNodeConditionControlLoopIntervalMs())) .withTimeout(Duration.ofMillis(configuration.getNodeConditionControlLoopTimeoutMs())) .withRetryerSupplier(() -> Retryers.exponentialBackoff(1, 5, TimeUnit.MINUTES)) .build(); this.scheduleReference = titusRuntime.getLocalScheduler().scheduleMono(nodeConditionControlLoopSchedulerDescriptor, this::handleNodesWithBadCondition, Schedulers.parallel()); } @Override public void deactivate() { if (scheduleReference != null) { scheduleReference.cancel(); } } @VisibleForTesting Mono<Void> handleNodesWithBadCondition(ExecutionContext executionContext) { int iterationCount = executionContext.getExecutionId().getTotal(); logger.debug("Starting node condition controller iteration {} ...", iterationCount); if (hasStaleData()) { logger.info("Stale data. Skipping the node condition control loop iteration- {} ", iterationCount); return Mono.empty(); } return handleNodesWithBadCondition(); } private boolean hasStaleData() { long dataStaleness = getDataStalenessMs(); boolean stale = dataStaleness > configuration.getDataStalenessThresholdMs(); metrics.setStaleness(stale, dataStaleness); return stale; } private long getDataStalenessMs() { return Math.max(nodeDataResolver.getStalenessMs(), jobDataReplicator.getStalenessMs()); } public Mono<Void> handleNodesWithBadCondition() { // Identify bad nodes from node resolver Map<String, Node> badConditionNodesById = nodeDataResolver.resolve().entrySet().stream().filter(nodeEntry -> nodeEntry.getValue().isInBadCondition()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // Find jobs that are eligible for bad node condition treatment Set<String> eligibleJobIds = jobOperations.getJobs().stream() .filter(job -> { JobDescriptor<?> jobDescriptor = job.getJobDescriptor(); Map<String, String> jobAttributes = jobDescriptor.getAttributes(); if (jobAttributes.containsKey(JobAttributes.JOB_PARAMETER_TERMINATE_ON_BAD_AGENT)) { String value = jobAttributes.get(JobAttributes.JOB_PARAMETER_TERMINATE_ON_BAD_AGENT); return Boolean.parseBoolean(value); } return false; }) .map(Job::getId) .collect(Collectors.toSet()); if (eligibleJobIds.isEmpty()) { logger.info("No jobs configured for task terminations on bad node conditions"); metrics.setTasksTerminated(0); return Mono.empty(); } // Find eligible tasks that are running on the bad condition nodes List<String> eligibleTaskIds = RelocationUtil.buildTasksFromNodesAndJobsFilter(badConditionNodesById, eligibleJobIds, jobOperations); if (configuration.isTaskTerminationOnBadNodeConditionEnabled()) { // Terminate tasks directly using JobManagementClient return Flux.fromIterable(eligibleTaskIds) .delayElements(Duration.ofSeconds(1)) .flatMap(taskId -> { return jobManagementClient.killTask(taskId, false, CALL_METADATA) .doOnSuccess(v -> logger.info("Task {} terminated", taskId)); }) .doOnComplete(() -> metrics.setTasksTerminated(eligibleTaskIds.size())) .doOnError(e -> logger.error("Exception terminating task ", e)) .then(); } else { logger.info("Skipping {} task terminations on bad node conditions", eligibleTaskIds.size()); metrics.setTasksTerminated(0); } return Mono.empty(); } private static CallMetadata buildCallMetadata() { Caller caller = Caller.newBuilder().withCallerType(CallerType.Application).withId(CALLER_APP_ID).build(); return CallMetadata.newBuilder().withCallers(Collections.singletonList(caller)).withCallReason(CALL_REASON).build(); } }
qyangge/wechat
node_modules/_wechaty-puppet-padplus@0.6.3@wechaty-puppet-padplus/dist/src/pure-function-helpers/room-event-join-message-parser.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const xml_to_json_1 = require("./xml-to-json"); const schemas_1 = require("../schemas"); const is_type_1 = require("./is-type"); const split_name_1 = require("./split-name"); const wechaty_puppet_1 = require("wechaty-puppet"); /** * * 1. Room Join Event * * * try to find 'join' event for Room * * 1. * 李卓桓 invited Huan to the group chat * 李卓桓 invited 李佳芮, Huan to the group chat * 李卓桓 invited you to a group chat with * 李卓桓 invited you and Huan to the group chat * 2. * "李卓桓"邀请"Huan LI++"加入了群聊 * "李佳芮"邀请你加入了群聊,群聊参与人还有:小桔、桔小秘、小小桔、wuli舞哩客服、舒米 * "李卓桓"邀请你和"Huan LI++"加入了群聊 */ const ROOM_JOIN_BOT_INVITE_OTHER_REGEX_LIST_ZH = [ /^你邀请"(.+)"加入了群聊/, /^" ?(.+)"通过扫描你分享的二维码加入群聊/, ]; const ROOM_JOIN_BOT_INVITE_OTHER_REGEX_LIST_EN = [ /^You invited (.+) to the group chat/, /^" ?(.+)" joined group chat via the QR code you shared/, ]; /* ----------------------------------------------- */ const ROOM_JOIN_OTHER_INVITE_BOT_REGEX_LIST_ZH = [ /^"([^"]+?)"邀请你加入了群聊/, /^"([^"]+?)"邀请你和"(.+)"加入了群聊/, ]; const ROOM_JOIN_OTHER_INVITE_BOT_REGEX_LIST_EN = [ /^(.+) invited you to a group chat/, /^(.+) invited you and (.+) to the group chat/, ]; /* ----------------------------------------------- */ const ROOM_JOIN_OTHER_INVITE_OTHER_REGEX_LIST_ZH = [ /^"(.+)"邀请"(.+)"加入了群聊/, ]; const ROOM_JOIN_OTHER_INVITE_OTHER_REGEX_LIST_EN = [ /^(.+?) invited (.+?) to (the|a) group chat/, ]; /* ----------------------------------------------- */ const ROOM_JOIN_OTHER_INVITE_OTHER_QRCODE_REGEX_LIST_ZH = [ /^" (.+)"通过扫描"(.+)"分享的二维码加入群聊/, ]; const ROOM_JOIN_OTHER_INVITE_OTHER_QRCODE_REGEX_LIST_EN = [ /^"(.+)" joined the group chat via the QR Code shared by "(.+)"/, ]; function roomJoinEventMessageParser(rawPayload) { return __awaiter(this, void 0, void 0, function* () { if (!is_type_1.isPayload(rawPayload)) { return null; } const roomId = rawPayload.fromUserName; if (!roomId) { return null; } if (!is_type_1.isRoomId(roomId)) { return null; } const timestamp = rawPayload.createTime; let content = rawPayload.content; /** * when the message is a Recalled type, bot can undo the invitation */ if (rawPayload.msgType === schemas_1.PadplusMessageType.Recalled) { /** * content: * ``` * 3453262102@chatroom: * <sysmsg type="delchatroommember"> * ... * </sysmsg> * ``` */ const tryXmlText = content.replace(/^[^\n]+\n/, ''); const jsonPayload = yield xml_to_json_1.xmlToJson(tryXmlText); // toJson(tryXmlText, { object: true }) as XmlSchema try { const type = jsonPayload.sysmsg.$.type; switch (type) { case 'delchatroommember': content = jsonPayload.sysmsg.delchatroommember.plain; break; case 'revokemsg': content = jsonPayload.sysmsg.revokemsg.replacemsg; break; case 'banner': case 'multivoip': case 'roomtoolstips': case 'NewXmlDisableChatRoomAccessVerifyApplication': case 'sysmsgtemplate': return null; default: wechaty_puppet_1.log.warn('XmlSchema', `unkonw type: ${type} jsonPayload: ${JSON.stringify(jsonPayload)}`); break; } } catch (e) { console.error(e); throw e; } } let matchesForBotInviteOtherEn = null; let matchesForOtherInviteBotEn = null; let matchesForOtherInviteOtherEn = null; let matchesForOtherInviteOtherQrcodeEn = null; let matchesForBotInviteOtherZh = null; let matchesForOtherInviteBotZh = null; let matchesForOtherInviteOtherZh = null; let matchesForOtherInviteOtherQrcodeZh = null; ROOM_JOIN_BOT_INVITE_OTHER_REGEX_LIST_EN.some(regex => !!(matchesForBotInviteOtherEn = content.match(regex))); ROOM_JOIN_OTHER_INVITE_BOT_REGEX_LIST_EN.some(regex => !!(matchesForOtherInviteBotEn = content.match(regex))); ROOM_JOIN_OTHER_INVITE_OTHER_REGEX_LIST_EN.some(regex => !!(matchesForOtherInviteOtherEn = content.match(regex))); ROOM_JOIN_OTHER_INVITE_OTHER_QRCODE_REGEX_LIST_EN.some(regex => !!(matchesForOtherInviteOtherQrcodeEn = content.match(regex))); ROOM_JOIN_BOT_INVITE_OTHER_REGEX_LIST_ZH.some(regex => !!(matchesForBotInviteOtherZh = content.match(regex))); ROOM_JOIN_OTHER_INVITE_BOT_REGEX_LIST_ZH.some(regex => !!(matchesForOtherInviteBotZh = content.match(regex))); ROOM_JOIN_OTHER_INVITE_OTHER_REGEX_LIST_ZH.some(regex => !!(matchesForOtherInviteOtherZh = content.match(regex))); ROOM_JOIN_OTHER_INVITE_OTHER_QRCODE_REGEX_LIST_ZH.some(regex => !!(matchesForOtherInviteOtherQrcodeZh = content.match(regex))); const matchesForBotInviteOther = matchesForBotInviteOtherEn || matchesForBotInviteOtherZh; const matchesForOtherInviteBot = matchesForOtherInviteBotEn || matchesForOtherInviteBotZh; const matchesForOtherInviteOther = matchesForOtherInviteOtherEn || matchesForOtherInviteOtherZh; const matchesForOtherInviteOtherQrcode = matchesForOtherInviteOtherQrcodeEn || matchesForOtherInviteOtherQrcodeZh; const languageEn = matchesForBotInviteOtherEn || matchesForOtherInviteBotEn || matchesForOtherInviteOtherEn || matchesForOtherInviteOtherQrcodeEn; const languageZh = matchesForBotInviteOtherZh || matchesForOtherInviteBotZh || matchesForOtherInviteOtherZh || matchesForOtherInviteOtherQrcodeZh; const matches = matchesForBotInviteOther || matchesForOtherInviteBot || matchesForOtherInviteOther || matchesForOtherInviteOtherQrcode; if (!matches) { return null; } /** * * Parse all Names From the Event Text * */ if (matchesForBotInviteOther) { /** * 1. Bot Invite Other to join the Room * (include invite via QrCode) */ const other = matches[1]; let inviteeNameList; if (languageEn) { inviteeNameList = split_name_1.splitEnglishNameList(other); } else if (languageZh) { inviteeNameList = split_name_1.splitChineseNameList(other); } else { throw new Error('make typescript happy'); } const inviterName = wechaty_puppet_1.YOU; const joinEvent = { inviteeNameList, inviterName, roomId, timestamp, }; return joinEvent; } else if (matchesForOtherInviteBot) { /** * 2. Other Invite Bot to join the Room */ // /^"([^"]+?)"邀请你加入了群聊/, // /^"([^"]+?)"邀请你和"(.+?)"加入了群聊/, const inviterName = matches[1]; let inviteeNameList = [wechaty_puppet_1.YOU]; if (matches[2]) { let nameList; if (languageEn) { nameList = split_name_1.splitEnglishNameList(matches[2]); } else if (languageZh) { nameList = split_name_1.splitChineseNameList(matches[2]); } else { throw new Error('neither English nor Chinese'); } inviteeNameList = inviteeNameList.concat(nameList); } const joinEvent = { inviteeNameList, inviterName, roomId, timestamp, }; return joinEvent; } else if (matchesForOtherInviteOther) { /** * 3. Other Invite Other to a Room * (NOT include invite via Qrcode) */ // /^"([^"]+?)"邀请"([^"]+)"加入了群聊$/, // /^([^"]+?) invited ([^"]+?) to (the|a) group chat/, const inviterName = matches[1]; let inviteeNameList; const other = matches[2]; if (languageEn) { inviteeNameList = split_name_1.splitEnglishNameList(other); } else if (languageZh) { inviteeNameList = split_name_1.splitChineseNameList(other); } else { throw new Error('neither English nor Chinese'); } const joinEvent = { inviteeNameList, inviterName, roomId, timestamp, }; return joinEvent; } else if (matchesForOtherInviteOtherQrcode) { /** * 4. Other Invite Other via Qrcode to join a Room * /^" (.+)"通过扫描"(.+)"分享的二维码加入群聊/, */ const inviterName = matches[2]; let inviteeNameList; const other = matches[1]; if (languageEn) { inviteeNameList = split_name_1.splitEnglishNameList(other); } else if (languageZh) { inviteeNameList = split_name_1.splitChineseNameList(other); } else { throw new Error('neither English nor Chinese'); } const joinEvent = { inviteeNameList, inviterName, roomId, timestamp, }; return joinEvent; } else { throw new Error('who invite who?'); } }); } exports.roomJoinEventMessageParser = roomJoinEventMessageParser; //# sourceMappingURL=room-event-join-message-parser.js.map
velasqueziturrate/multiplataforma
node_modules/.staging/@nativescript/core-b2cc363a/ui/activity-indicator/activity-indicator-common.js
import { View, CSSType } from '../core/view'; import { booleanConverter } from '../core/view-base'; import { Property } from '../core/properties'; let ActivityIndicatorBase = class ActivityIndicatorBase extends View { }; ActivityIndicatorBase = __decorate([ CSSType('ActivityIndicator') ], ActivityIndicatorBase); export { ActivityIndicatorBase }; ActivityIndicatorBase.prototype.recycleNativeView = 'auto'; export const busyProperty = new Property({ name: 'busy', defaultValue: false, valueConverter: booleanConverter, }); busyProperty.register(ActivityIndicatorBase); //# sourceMappingURL=activity-indicator-common.js.map
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java
package com.latenighters.runicarcana.common.symbols.categories; import com.latenighters.runicarcana.common.symbols.Symbols; import com.latenighters.runicarcana.common.symbols.backend.Symbol; import static com.latenighters.runicarcana.RunicArcana.MODID; public class SymbolCategory { public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); private Symbol displaySymbol; private final String unlocalizedName; public static void generateCategories() { //TODO figure out why static initialization isn't working DEFAULT.setDisplaySymbol(Symbols.EXPULSION); } public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { this.displaySymbol = displaySymbol; this.unlocalizedName = unlocalizedName; } public Symbol getDisplaySymbol() { return displaySymbol; } public void setDisplaySymbol(Symbol displaySymbol) { this.displaySymbol = displaySymbol; } public String getUnlocalizedName() { return unlocalizedName; } }
enwords/enwords
spec/services/yandex/kassa/check_payment_spec.rb
require 'rails_helper' describe Yandex::Kassa::CheckPayment do subject { described_class.run!(options) } let(:options) do { payment: payment } end let(:payment) { create(:payment, status: :pending, data: [{ 'id' => 123 }]) } let(:response_body) do { id: '23d93cac-000f-5000-8000-126628f15141', status: 'succeeded', paid: false, amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', confirmation_url: 'https://money.yandex.ru' }, created_at: '2019-01-22T14:30:45.129Z', description: 'Заказ №1', metadata: {}, recipient: { account_id: '100001', gateway_id: '1000001' }, refundable: false, test: false } end before do stub_request(:get, "https://payment.yandex.net/api/v3/payments/123") .to_return(status: 200, body: response_body.to_json, headers: {}) end it 'changes payment status' do expect { subject }.to change { payment.reload.status }.to('succeeded') end end
kx-Huang/VE482
lab/lab_6/ex3/core/plugin_utility.c
<filename>lab/lab_6/ex3/core/plugin_utility.c #include "plugin_utility.h" #include <dirent.h> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static char *get_plugin_name(char *filename) { char *extension = strrchr(filename, '.'); if (!extension || strcmp(extension, ".so") != 0) return NULL; return filename; } static void *load_plugin(char *plugin_name, char *path, manager_t *m) { // add "./" to plugin path char slashed_path[MAX_PATH_LEN]; strcpy(slashed_path, "./"); strcat(slashed_path, path); // open plugin void *fd = dlopen(slashed_path, RTLD_NOW); // error open plugin if (!fd) { fprintf(stderr, "[Error] cannot open dynamic library: %s\n", dlerror()); return NULL; } // call initialize funtion "init_plugin_name" char init_fn_name[MAX_PATH_LEN]; strcpy(init_fn_name, "init_"); plugin_name[strlen(plugin_name) - 3] = 0; strcat(init_fn_name, plugin_name); reg_fn_t init_func = (reg_fn_t)dlsym(fd, init_fn_name); // error load initialize function if (!init_func) { fprintf(stderr, "[Error] cannot load initialize function: %s\n", dlerror()); dlclose(fd); return NULL; } // error return value from initialize funciton int ret = init_func(m); if (ret < 0) { fprintf(stderr, "[Error] plugin initialize function returned: %d\n", ret); dlclose(fd); return NULL; } // success and return file descriptor fprintf(stderr, "[Success] load plugin from: '%s'\n", path); return fd; } void *discover_plugins(manager_t *m, char *dir_name) { // open directory DIR *dir = opendir(dir_name); // error open directory if (!dir) { fprintf(stderr, "[Error] cannot open directory: %s\n", dir_name); return NULL; } // initialize file desciptor list fd_list_t *fd_list = malloc(sizeof(fd_node_t)); fd_list->head = NULL; // scan all files to load dynamic library struct dirent *dp; while ((dp = readdir(dir)) != NULL) { // get plugin name char *plugin_name = get_plugin_name(dp->d_name); if (!plugin_name) continue; // concatenate plugin name to directory name char full_path[MAX_PATH_LEN]; strcpy(full_path, dir_name); strcat(full_path, "/"); strcat(full_path, dp->d_name); // load plugin void *plugin_dl = load_plugin(plugin_name, full_path, m); if (plugin_dl) { // create node and connect to front fd_node_t *fd_node = malloc(sizeof(fd_node_t)); fd_node->fd = plugin_dl; fd_node->next = fd_list->head; fd_list->head = fd_node; } } // close directory closedir(dir); // return fd_list if any plugin exists and loaded if (fd_list->head) { return (void *)fd_list; } else { free(fd_list); return NULL; } } void close_all_plugins(void *list) { fd_list_t *fd_list = (fd_list_t *)list; if (fd_list == NULL) return; fd_node_t *node_it = fd_list->head; while (node_it != NULL) { fd_node_t *node_tmp = node_it; dlclose(node_it->fd); node_it = node_it->next; free(node_tmp); } free(fd_list); }
RdecKa/bark
docs/tutorials/config_notebook.py
import os cwd = os.getcwd() runfiles_dir = cwd.split("run.runfiles")[0] bark_root = os.path.join(runfiles_dir, "run.runfiles/bark_project") try: os.chdir(bark_root) print("Changing to bark root {}".format(bark_root)) except: pass
perfectsense/gyro-aws-provider
src/main/java/gyro/aws/dynamodb/DynamoDbTableBackupFinder.java
<filename>src/main/java/gyro/aws/dynamodb/DynamoDbTableBackupFinder.java /* * Copyright 2020, Perfect Sense, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gyro.aws.dynamodb; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import gyro.aws.AwsFinder; import gyro.core.Type; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.BackupDescription; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; /** * Query dynamodb-table-backup. * * Example * ------- * * .. code-block:: gyro * * dynamodb-table-backup: $(external-query aws::dynamodb-table-backup { backup-arn: ""}) */ @Type("dynamodb-table-backup") public class DynamoDbTableBackupFinder extends AwsFinder<DynamoDbClient, BackupDescription, DynamoDbTableBackupResource> { private String tableName; private String backupArn; /** * The DynamoDb table name. */ public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } /** * The table backup ARN. */ public String getBackupArn() { return backupArn; } public void setBackupArn(String backupArn) { this.backupArn = backupArn; } @Override protected List<BackupDescription> findAllAws(DynamoDbClient client) { return client.listBackups().backupSummaries().stream() .map(t -> client.describeBackup(r -> r.backupArn(t.backupArn())).backupDescription()) .collect(Collectors.toList()); } @Override protected List<BackupDescription> findAws(DynamoDbClient client, Map<String, String> filters) { if (!filters.containsKey("backup-arn") && !filters.containsKey("table-name")) { throw new IllegalArgumentException("'table-name' or 'backup-arn' is required."); } try { if (filters.containsKey("backup-arn")) { return Collections.singletonList( client.describeBackup(r -> r.backupArn(filters.get("backup-arn"))).backupDescription()); } else { return client.listBackups(r -> r.tableName(filters.get("table-name"))) .backupSummaries() .stream() .map(t -> client.describeBackup(r -> r.backupArn(t.backupArn())).backupDescription()) .collect(Collectors.toList()); } } catch (ResourceNotFoundException ex) { return Collections.emptyList(); } } }
jsoref/atlassian-bitbucket-server-integration-plugin
src/main/java/com/atlassian/bitbucket/jenkins/internal/model/BitbucketWebhook.java
package com.atlassian.bitbucket.jenkins.internal.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.Objects; import java.util.Set; import static org.apache.commons.lang3.builder.ToStringStyle.JSON_STYLE; @JsonIgnoreProperties(ignoreUnknown = true) public class BitbucketWebhook extends BitbucketWebhookRequest { private static final String ID = "id"; private static final String NAME = "name"; private static final String EVENTS = "events"; private static final String URL = "url"; private static final String ACTIVE = "active"; private final int id; @JsonCreator public BitbucketWebhook(@JsonProperty(value = ID) int id, @JsonProperty(value = NAME) String name, @JsonProperty(value = EVENTS) Set<String> events, @JsonProperty(value = URL) String url, @JsonProperty(value = ACTIVE) boolean isActive) { super(name, events, url, isActive); this.id = id; } public int getId() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BitbucketWebhook that = (BitbucketWebhook) o; return id == that.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return new ToStringBuilder(this, JSON_STYLE) .append(ID, id) .append(NAME, getName()) .append(URL, getUrl()) .append(EVENTS, getEvents()) .append(ACTIVE, isActive()) .toString(); } }
fabricebouye/gw2-web-api-mapping
test/api/web/gw2/mapping/v2/mounts/skins/MountsSkinsUtilsTest.java
/* * Copyright (C) 2015-2019 <NAME> * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ package api.web.gw2.mapping.v2.mounts.skins; import api.web.gw2.mapping.core.EnumValueFactory; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit test. * * @author <NAME> */ public class MountsSkinsUtilsTest { public MountsSkinsUtilsTest() { } @BeforeAll public static void setUpClass() { } @AfterAll public static void tearDownClass() { } @BeforeEach public void setUp() { } @AfterEach public void tearDown() { } /** * Test of {@code MountDyeSlotMaterial}. */ @Test public void testFindMountDyeSlotMaterial() { System.out.println("findMountDyeSlotMaterial"); final String[] values = { "cloth", // NOI18N. "fur", // NOI18N. "leather", // NOI18N. "metal", // NOI18N. null, "" // NOI18N. }; final MountDyeSlotMaterial[] expResults = { MountDyeSlotMaterial.CLOTH, MountDyeSlotMaterial.FUR, MountDyeSlotMaterial.LEATHER, MountDyeSlotMaterial.METAL, MountDyeSlotMaterial.UNKNOWN, MountDyeSlotMaterial.UNKNOWN }; assertEquals(values.length, expResults.length); IntStream.range(0, values.length). forEach(index -> { final String value = values[index]; final MountDyeSlotMaterial expResult = expResults[index]; final MountDyeSlotMaterial result = EnumValueFactory.INSTANCE.mapEnumValue(MountDyeSlotMaterial.class, value); assertEquals(expResult, result); }); } }
RNAcentral/rnacentral-import-pipeline
tests/rnacentral/precompute/qa/missing_rfam_match_test.py
<filename>tests/rnacentral/precompute/qa/missing_rfam_match_test.py # -*- coding: utf-8 -*- """ Copyright [2009-2018] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import pytest from rnacentral_pipeline.rnacentral.precompute.data import context as ctx import rnacentral_pipeline.rnacentral.precompute.qa.missing_rfam_match as miss from .. import helpers @pytest.mark.parametrize( "rna_id,rna_type,flag", [ # pylint: disable=no-member ("URS0000400378_30527", "tRNA", False), ("URS000058E89C_39432", "rRNA", False), ("URS000061A10B_9606", "tRNA", False), ("URS0000866382_1000416", "tRNA", True), ("URS00009ED984_77133", "rRNA", False), ("URS0000A80D0E_60711", "rRNA", True), ("URS0000BB3C76_486071", "rRNA", True), ], ) def test_can_detect_missing_rfam_match(rna_id, rna_type, flag): context, sequence = helpers.load_data(rna_id) assert miss.validate(context, rna_type, sequence).has_issue == flag @pytest.mark.parametrize( "rna_id,rna_type,message", [ # pylint: disable=no-member ( "URS00007D23E5_6239", "tRNA", ( u"No match to a tRNA Rfam model " u'(<a href="http://rfam.org/family/RF00005">RF00005</a>,' u' <a href="http://rfam.org/family/RF01852">RF01852</a>)' ), ), ], ) def test_can_produce_correct_contamination_warnings(rna_id, rna_type, message): context, sequence = helpers.load_data(rna_id) assert miss.validate(ctx, rna_type, sequence).message == message
kbingman/bkr
vendor/disabled_extensions/multi_site/vendor/plugins/haml/lib/haml/filters.rb
<reponame>kbingman/bkr<filename>vendor/disabled_extensions/multi_site/vendor/plugins/haml/lib/haml/filters.rb # This file contains redefinitions of and wrappers around various text # filters so they can be used as Haml filters. # :stopdoc: require 'erb' require 'sass/engine' require 'stringio' begin require 'rubygems' rescue LoadError; end class ERB; alias_method :render, :result; end module Haml module Filters class Plain def initialize(text) @text = text end def render @text end end class Ruby def initialize(text) @text = text end def render old_stdout = $stdout $stdout = StringIO.new Object.new.instance_eval(@text) old_stdout, $stdout = $stdout, old_stdout old_stdout.pos = 0 old_stdout.read end end class Preserve def initialize(text) @text = text end def render Haml::Helpers.preserve(@text) end end class LazyLoaded def initialize(*reqs) reqs[0...-1].each do |req| begin @required = req require @required return rescue LoadError; end # RCov doesn't see this, but it is run end begin @required = reqs[-1] require @required rescue LoadError => e classname = self.class.to_s.gsub(/\w+::/, '') if reqs.size == 1 raise HamlError.new("Can't run #{classname} filter; required file '#{reqs.first}' not found") else raise HamlError.new("Can't run #{classname} filter; required #{reqs.map { |r| "'#{r}'" }.join(' or ')}, but none were found") end end end end class RedCloth < LazyLoaded def initialize(text) super('redcloth') @engine = ::RedCloth.new(text) end def render @engine.to_html end end # Uses RedCloth to provide only Textile (not Markdown) parsing class Textile < RedCloth def render @engine.to_html(:textile) end end # Uses BlueCloth or RedCloth to provide only Markdown (not Textile) parsing class Markdown < LazyLoaded def initialize(text) super('bluecloth', 'redcloth') if @required == 'bluecloth' @engine = ::BlueCloth.new(text) else @engine = ::RedCloth.new(text) end end def render if @engine.is_a?(::BlueCloth) @engine.to_html else @engine.to_html(:markdown) end end end end end # :startdoc:
projekt86/goartik-cloud
model/subscription_array..go
package model // SubscriptionArray model type SubscriptionArray struct { Subscriptions []Subscription `json:"subscriptions,omitempty"` }
bingo1118/SST_AS
p2PCoresst0405/src/main/java/com/p2p/shake/ShakeManager.java
<reponame>bingo1118/SST_AS package com.p2p.shake; import java.net.InetAddress; import android.os.Handler; public class ShakeManager { public static final int HANDLE_ID_SEARCH_END = 0x11; public static final int HANDLE_ID_RECEIVE_DEVICE_INFO = 0x12; public static final int HANDLE_ID_APDEVICE_END = 0x13; private static ShakeManager manager = null; private ShakeThread shakeThread; private ShakeManager(){}; private long searchTime = 10000; private InetAddress host; public synchronized static ShakeManager getInstance(){ if(null==manager){ synchronized(ShakeManager.class){ manager = new ShakeManager(); } } return manager; } public Handler handler; public void setHandler(Handler handler){ this.handler = handler; } public void setSearchTime(long time){ this.searchTime = time; } public void setInetAddress(InetAddress host){ this.host = host; } public boolean shaking(){ if(null==shakeThread){ shakeThread = new ShakeThread(handler); shakeThread.setHandler(handler); shakeThread.setSearchTime(searchTime); shakeThread.setInetAddress(host); shakeThread.start(); return true; }else{ return false; } } public void stopShaking(){ if(null!=shakeThread){ shakeThread.killThread(); shakeThread = null; } } public boolean isShaking(){ if(null!=shakeThread){ return true; }else{ return false; } } }
Grosskopf/openoffice
main/toolkit/qa/complex/toolkit/awtgrid/DummyColumn.java
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package complex.toolkit.awtgrid; import com.sun.star.awt.grid.XGridColumn; import com.sun.star.awt.grid.XGridColumnListener; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.XEventListener; import com.sun.star.style.HorizontalAlignment; import com.sun.star.util.XCloneable; /** * a dummy implementation of css.awt.grid.XGridColumn * @author <EMAIL> */ public class DummyColumn implements XGridColumn { public DummyColumn() { } public Object getIdentifier() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setIdentifier( Object o ) { throw new UnsupportedOperationException( "Not supported yet." ); } public int getColumnWidth() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setColumnWidth( int i ) { throw new UnsupportedOperationException( "Not supported yet." ); } public int getMinWidth() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setMinWidth( int i ) { throw new UnsupportedOperationException( "Not supported yet." ); } public int getMaxWidth() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setMaxWidth( int i ) { throw new UnsupportedOperationException( "Not supported yet." ); } public boolean getResizeable() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setResizeable( boolean bln ) { throw new UnsupportedOperationException( "Not supported yet." ); } public int getFlexibility() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setFlexibility( int i ) throws IllegalArgumentException { throw new UnsupportedOperationException( "Not supported yet." ); } public HorizontalAlignment getHorizontalAlign() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setHorizontalAlign( HorizontalAlignment ha ) { throw new UnsupportedOperationException( "Not supported yet." ); } public String getTitle() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setTitle( String string ) { throw new UnsupportedOperationException( "Not supported yet." ); } public String getHelpText() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setHelpText( String string ) { throw new UnsupportedOperationException( "Not supported yet." ); } public int getIndex() { throw new UnsupportedOperationException( "Not supported yet." ); } public int getDataColumnIndex() { throw new UnsupportedOperationException( "Not supported yet." ); } public void setDataColumnIndex( int i ) { throw new UnsupportedOperationException( "Not supported yet." ); } public void addGridColumnListener( XGridColumnListener xl ) { throw new UnsupportedOperationException( "Not supported yet." ); } public void removeGridColumnListener( XGridColumnListener xl ) { throw new UnsupportedOperationException( "Not supported yet." ); } public void dispose() { throw new UnsupportedOperationException( "Not supported yet." ); } public void addEventListener( XEventListener xl ) { throw new UnsupportedOperationException( "Not supported yet." ); } public void removeEventListener( XEventListener xl ) { throw new UnsupportedOperationException( "Not supported yet." ); } public XCloneable createClone() { throw new UnsupportedOperationException( "Not supported yet." ); } }
whitemike889/afdko
c/spot/source/pathbuild.c
/* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ #include <math.h> #include <stdio.h> #include "global.h" #include "pathbuild.h" double currx, curry; static boolean Pathaddmoveto(PPath O[], int subpth, Curve C); static boolean Pathaddlineto(PPath O[], int subpth, Curve Cv); static boolean Pathaddcurveto(PPath O[], int subpth, Curve Cv); static boolean Pathaddclosepath(PPath O[], int subpth, Curve C, boolean isLCP); void bisectbez(Curve oldc, Curve lft, Curve rgt); static Pelt FreeEltHead = (Pelt)NULL; static Pelt _tmpelt; #define ALLOCELT(e) \ do { \ if (FreeEltHead == (Pelt)NULL) { \ (e) = (Pelt)calloc(1, sizeof(Elt)); \ if ((e) == (Pelt)NULL) fatal(SPOT_MSG_pathNOPELT); \ } else { \ (e) = FreeEltHead; \ FreeEltHead = FreeEltHead->nextelt; \ } \ (e)->elttype = 0; \ (e)->prevelt = (e)->nextelt = (Pelt)NULL; \ } while (0) #define FREEELT(e) \ do { \ _tmpelt = FreeEltHead; \ FreeEltHead = (e); \ (e)->nextelt = _tmpelt; \ } while (0) static PPath FreePathHead = (PPath)NULL; static PPath _tmppath; #define ALLOCPATH(p) \ do { \ if (FreePathHead == (PPath)NULL) { \ if (((p) = (PPath)calloc(1, sizeof(Path))) == (PPath)NULL) fatal(SPOT_MSG_pathNOSUBP); \ } else { \ (p) = FreePathHead; \ FreePathHead = FreePathHead->matches; \ } \ (p)->numelts = 0; \ (p)->elements = (p)->lastelement = (Pelt)NULL; \ (p)->matches = (PPath)NULL; \ } while (0) #define FREEPATH(p) \ do { \ _tmppath = FreePathHead; \ FreePathHead = (p); \ (p)->matches = _tmppath; \ } while (0) #define ASSIGNBBX(dest, src) \ do { \ (dest).lx = (src).lx; \ (dest).ly = (src).ly; \ (dest).hx = (src).hx; \ (dest).hy = (src).hy; \ } while (0) static boolean pathisopen = false; static void Initload(void) { currx = curry = 0.0; pathisopen = false; } #define MTCPCOORDS(Cv, xval, yval) \ (Cv)[XP0] = (Cv)[XP1] = (Cv)[XP2] = (Cv)[XP3] = (xval); \ (Cv)[YP0] = (Cv)[YP1] = (Cv)[YP2] = (Cv)[YP3] = (yval) boolean addmoveto(double movx, double movy, POutline Outlin) { Curve C; if (pathisopen) { addclosepath(currx, curry, Outlin, 1); } MTCPCOORDS(C, movx, movy); currx = movx; curry = movy; if (Pathaddmoveto(Outlin->subpath, Outlin->numsubpaths, C)) { pathisopen = true; return true; } else return false; } boolean addlineto(double sx, double sy, double ex, double ey, boolean isreallyaclosepath, POutline Outlin) { Curve C; C[XP0] = C[XP1] = sx; C[YP0] = C[YP1] = sy; C[XP2] = C[XP3] = ex; C[YP2] = C[YP3] = ey; currx = ex; curry = ey; if (isreallyaclosepath && (Outlin->subpath[Outlin->numsubpaths] != (PPath)NULL) && (Outlin->subpath[Outlin->numsubpaths]->numelts < 2)) return (false); return (Pathaddlineto(Outlin->subpath, Outlin->numsubpaths, C)); } boolean addcurveto(double c0x, double c0y, double c1x, double c1y, double c2x, double c2y, double c3x, double c3y, POutline Outlin) { Curve C; C[XP0] = c0x; C[YP0] = c0y; C[XP1] = c1x; C[YP1] = c1y; C[XP2] = c2x; C[YP2] = c2y; C[XP3] = c3x; C[YP3] = c3y; currx = c3x; curry = c3y; return (Pathaddcurveto(Outlin->subpath, Outlin->numsubpaths, C)); } boolean addclosepath(double closx, double closy, POutline Outlin, boolean isLCP) { Curve C; MTCPCOORDS(C, closx, closy); currx = closx; curry = closy; return (Pathaddclosepath(Outlin->subpath, Outlin->numsubpaths, C, isLCP)); /* NOTE: caller must take care of incrementing Outlin->numsubpaths because it is presumably the caretaker of that array-size, and should be the one to test for overflow */ } boolean isaspacechar(POutline OTL) { PPath P; P = OTL->subpath[OTL->numsubpaths]; if ((P == (PPath)NULL) && (OTL->numsubpaths == 0)) return (true); return ((OTL->numsubpaths == 0) && (P->numelts == 0) && (P->lastelement == (Pelt)NULL)); } static boolean startpath(PPath pth, Pelt ele) { if (pth == (PPath)NULL) return false; if ((pth->numelts != 0) || (pth->lastelement != (Pelt)NULL)) { fatal(SPOT_MSG_pathMTMT); } if (ele == (Pelt)NULL) return false; ele->prevelt = (Pelt)NULL; ele->nextelt = (Pelt)NULL; pth->elements = ele; pth->lastelement = ele; pth->numelts += 1; pth->bbx.lx = pth->bbx.hx = ele->coord[XP0]; pth->bbx.ly = pth->bbx.hy = ele->coord[YP0]; return (true); } static boolean finishpath(PPath pth, Pelt ele) { if (pth == (PPath)NULL) return false; if ((pth->numelts == 0) || (pth->lastelement == (Pelt)NULL)) return false; if (ele == (Pelt)NULL) return false; if (pth->numelts < 3) return false; ele->prevelt = pth->lastelement; ele->nextelt = pth->elements; /* CIRCULAR LIST */ pth->elements->prevelt = ele; (pth->lastelement)->nextelt = ele; pth->lastelement = ele; pth->numelts += 1; /* ensure that the closepath is at the same place as the initial moveto*/ MTCPCOORDS(ele->coord, pth->elements->coord[XP0], pth->elements->coord[YP0]); ele->prevelt->coord[XP3] = ele->coord[XP0]; ele->prevelt->coord[YP3] = ele->coord[YP0]; pathisopen = false; return (true); } static void BBoxClosure(BBox *dest, BBox *suitor) { if (suitor->lx < dest->lx) dest->lx = suitor->lx; if (suitor->ly < dest->ly) dest->ly = suitor->ly; if (suitor->hx > dest->hx) dest->hx = suitor->hx; if (suitor->hy > dest->hy) dest->hy = suitor->hy; } void CtrlPointBBox(Curve crv, BBox *bbox) { int ip; bbox->lx = bbox->hx = crv[XP0]; for (ip = XP1; ip <= XP3; ip++) { if (crv[ip] < bbox->lx) bbox->lx = crv[ip]; if (crv[ip] > bbox->hx) bbox->hx = crv[ip]; } bbox->ly = bbox->hy = crv[YP0]; for (ip = YP1; ip <= YP3; ip++) { if (crv[ip] < bbox->ly) bbox->ly = crv[ip]; if (crv[ip] > bbox->hy) bbox->hy = crv[ip]; } } static void CurveBBox(Pelt e, BBox *ebx) { Curve tmp, c1, c2; BBox b1, b2; COPYCOORDS(tmp, e->coord); bisectbez(tmp, c1, c2); CtrlPointBBox(c1, &b1); CtrlPointBBox(c2, &b2); BBoxClosure(&b1, &b2); ASSIGNBBX((*ebx), b1); } #define BIGGESTdouble (1.0e+10) #define SMALLESTdouble (-1.0e+10) boolean addtopath(PPath pth, Pelt ele) { if (pth == (PPath)NULL) return false; if ((pth->numelts == 0) || (pth->lastelement == (Pelt)NULL)) return false; if (ele == (Pelt)NULL) return false; ele->prevelt = pth->lastelement; ele->nextelt = (Pelt)NULL; ele->ebbx.lx = BIGGESTdouble; /* infinity */ ele->ebbx.ly = BIGGESTdouble; /* infinity */ ele->ebbx.hx = SMALLESTdouble; /* -infinity */ ele->ebbx.hy = SMALLESTdouble; /* -infinity */ (pth->lastelement)->nextelt = ele; pth->lastelement = ele; pth->numelts += 1; if (ele->elttype == CTtype) { CurveBBox(ele, &(ele->ebbx)); } else { CtrlPointBBox(ele->coord, &(ele->ebbx)); } if ISDTorCTTYPE(ele) { BBoxClosure(&(pth->bbx), &(ele->ebbx)); } return (true); } #define DEG(x) ((x)*57.29577951308232088) static boolean Pathaddlineto(PPath O[], int subpth, Curve Cv) { Pelt pel; ALLOCELT(pel); pel->elttype = DTtype; COPYCOORDS(pel->coord, Cv); pel->coord[XP1] = pel->coord[XP0]; pel->coord[YP1] = pel->coord[YP0]; pel->coord[XP2] = pel->coord[XP3]; pel->coord[YP2] = pel->coord[YP3]; return (addtopath(O[subpth], pel)); } static boolean Pathaddcurveto(PPath O[], int subpth, Curve Cv) { Pelt pel; ALLOCELT(pel); pel->elttype = CTtype; COPYCOORDS(pel->coord, Cv); return (addtopath(O[subpth], pel)); } static boolean Pathaddmoveto(PPath O[], int subpth, Curve C) { Pelt pel; ALLOCELT(pel); if (O[subpth] == (Path *)NULL) ALLOCPATH(O[subpth]); pel->elttype = MTtype; MTCPCOORDS(pel->coord, C[XP0], C[YP0]); return (startpath(O[subpth], pel)); } static boolean Pathaddclosepath(PPath O[], int subpth, Curve C, boolean isLCP) { Pelt pel; ALLOCELT(pel); pel->elttype = (isLCP) ? LCPtype : PCPtype; MTCPCOORDS(pel->coord, C[XP0], C[YP0]); return (finishpath(O[subpth], pel)); } Pelt SUCC(Pelt e) { Pelt Pnx; Pnx = e->nextelt; if ISMTorCPTYPE(Pnx) { /* might be the closepath */ Pnx = Pnx->nextelt; } else { return (Pnx); } if ISMTorCPTYPE(Pnx) { /* might be the successive moveto */ Pnx = Pnx->nextelt; } return (Pnx); } Pelt PRED(Pelt e) { Pelt Pnx; Pnx = e->prevelt; if ISMTorCPTYPE(Pnx) { /* might be the closepath */ Pnx = Pnx->prevelt; } else { return (Pnx); } if ISMTorCPTYPE(Pnx) { /* might be the successive moveto */ Pnx = Pnx->prevelt; } return (Pnx); } void curve2line(Pelt pel) { pel->coord[XP1] = pel->coord[XP0]; pel->coord[YP1] = pel->coord[YP0]; pel->coord[XP2] = pel->coord[XP3]; pel->coord[YP2] = pel->coord[YP3]; pel->elttype = DTtype; /* check successor */ if (pel->nextelt->elttype == PCPtype) pel->nextelt->elttype = LCPtype; } #define onethird 0.33333333333333 void line2curve(Pelt pel) { double cbase, sbase; cbase = pel->coord[XP3] - pel->coord[XP0]; sbase = pel->coord[YP3] - pel->coord[YP0]; pel->coord[XP1] = pel->coord[XP0] + onethird * cbase; pel->coord[YP1] = pel->coord[YP0] + onethird * sbase; pel->coord[XP2] = pel->coord[XP3] - onethird * cbase; pel->coord[YP2] = pel->coord[YP3] - onethird * sbase; pel->elttype = CTtype; /* check successor */ if (pel->nextelt->elttype == LCPtype) pel->nextelt->elttype = PCPtype; } void free_path(PPath *pp) { register int ecount; int emax; register Pelt e, enxt; /* nuke the elements list */ enxt = (Pelt)NULL; /* break the circular list */ if ((*pp)->lastelement != (Pelt)NULL) (*pp)->lastelement->nextelt = (Pelt)NULL; emax = (*pp)->numelts; for (ecount = 0, e = (*pp)->elements; (e != (Pelt)NULL) && (ecount < emax); ecount++, e = enxt) { enxt = e->nextelt; /* free the elt*/ FREEELT(e); } FREEPATH(*pp); } void free_Outlines(POutline O) { register int i; for (i = 0; i < MAXNUMPATHS; i++) { if (O->subpath[i] != (PPath)NULL) { free_path(&(O->subpath[i])); O->subpath[i] = (PPath)NULL; } } memFree(O->subpath); O->subpath = NULL; } void init_Outlines(POutline O) { int j; if ((O)->subpath == (PPath *)NULL) { if (((O)->subpath = (PPath *)calloc(MAXNUMPATHS, sizeof(PPath))) == (PPath *)NULL) { fatal(SPOT_MSG_pathNOOSA); } } for (j = 0; j < MAXNUMPATHS; j++) (O)->subpath[j] = (PPath)NULL; (O)->numsubpaths = 0; Initload(); } void compute_outline_bbx(POutline OTL) { PPath pth; register int i; OTL->Obbx.lx = BIGGESTdouble; OTL->Obbx.ly = BIGGESTdouble; OTL->Obbx.hx = SMALLESTdouble; OTL->Obbx.hy = SMALLESTdouble; for (i = 0; i < OTL->numsubpaths; i++) { pth = OTL->subpath[i]; BBoxClosure(&(OTL->Obbx), &(pth->bbx)); } } #define CHOP_EPS .002 #define GENAVG(a, b, t) ((a) + (t) * ((b) - (a))) #define GENAVG2(a, b) (((a) + (b)) * 0.5) static boolean practicallyequal(double a, double b) { double d; d = fabs((a - b)); return (d < CHOP_EPS); } void init_vector(Pelt e, Vector *v) { double vx, vy, d; Pelt s; switch ((int)(e->elttype)) { case CTtype: vx = e->coord[XP1] - e->coord[XP0]; vy = e->coord[YP1] - e->coord[YP0]; break; case DTtype: vx = e->coord[XP3] - e->coord[XP0]; vy = e->coord[YP3] - e->coord[YP0]; break; case LCPtype: s = SUCC(e); if (s->elttype == DTtype) { vx = s->coord[XP3] - s->coord[XP0]; vy = s->coord[YP3] - s->coord[YP0]; } else { vx = s->coord[XP1] - s->coord[XP0]; vy = s->coord[YP1] - s->coord[YP0]; } break; default: vx = vy = 0.0; break; } /* normalize */ d = sqrt(vx * vx + vy * vy); if (practicallyequal(d, 0.0)) { v->x = v->y = 1.0; } else { v->x = vx / d; v->y = vy / d; } } void end_vector(Pelt e, Vector *v) { double vx, vy, d; Pelt s; switch ((int)(e->elttype)) { case CTtype: vx = e->coord[XP3] - e->coord[XP2]; vy = e->coord[YP3] - e->coord[YP2]; break; case DTtype: vx = e->coord[XP3] - e->coord[XP0]; vy = e->coord[YP3] - e->coord[YP0]; break; case LCPtype: s = PRED(e); vx = s->coord[XP3] - s->coord[XP0]; vy = s->coord[YP3] - s->coord[YP0]; break; default: vx = vy = 0.0; break; } /* normalize */ d = sqrt(vx * vx + vy * vy); if (practicallyequal(d, 0.0)) { v->x = v->y = 1.0; } else { v->x = vx / d; v->y = vy / d; } } void bisectbez(Curve oldc, Curve lft, Curve rgt) /* on exit, lft on [0..1] follows path of input oldc on [0..0.5] */ /* rgt on [0..1] follows path of oldc on [0.5..1] */ { double tmpx, tmpy; lft[XP0] = oldc[XP0]; lft[YP0] = oldc[YP0]; rgt[XP3] = oldc[XP3]; rgt[YP3] = oldc[YP3]; if (practicallyequal(oldc[XP0], oldc[XP1]) && practicallyequal(oldc[YP0], oldc[YP1]) && practicallyequal(oldc[XP2], oldc[XP3]) && practicallyequal(oldc[YP2], oldc[YP3])) { /* a line */ lft[XP1] = oldc[XP0]; lft[YP1] = oldc[YP0]; rgt[XP2] = oldc[XP3]; rgt[YP2] = oldc[YP3]; lft[XP3] = lft[XP2] = rgt[XP0] = rgt[XP1] = GENAVG2(oldc[XP1], oldc[XP2]); lft[YP3] = lft[YP2] = rgt[YP0] = rgt[YP1] = GENAVG2(oldc[YP1], oldc[YP2]); } else { lft[XP1] = GENAVG2(oldc[XP0], oldc[XP1]); lft[YP1] = GENAVG2(oldc[YP0], oldc[YP1]); tmpx = GENAVG2(oldc[XP1], oldc[XP2]); tmpy = GENAVG2(oldc[YP1], oldc[YP2]); rgt[XP2] = GENAVG2(oldc[XP2], oldc[XP3]); rgt[YP2] = GENAVG2(oldc[YP2], oldc[YP3]); lft[XP2] = GENAVG2(lft[XP1], tmpx); lft[YP2] = GENAVG2(lft[YP1], tmpy); rgt[XP1] = GENAVG2(tmpx, rgt[XP2]); rgt[YP1] = GENAVG2(tmpy, rgt[YP2]); lft[XP3] = rgt[XP0] = GENAVG2(lft[XP2], rgt[XP1]); lft[YP3] = rgt[YP0] = GENAVG2(lft[YP2], rgt[YP1]); } }
raindigi/Merchello
src/Merchello.Web.UI.Client/src/views/common/dialogs/edit.address.controller.js
 /** * @ngdoc controller * @name Merchello.Common.Dialogs.EditAddressController * @function * * @description * The controller for adding a country */ angular.module('merchello') .controller('Merchello.Common.Dialogs.EditAddressController', function ($scope) { // public methods $scope.save = save; function init() { $scope.address = $scope.dialogData.address; }; function save() { $scope.dialogData.address.countryCode = $scope.dialogData.selectedCountry.countryCode; if($scope.dialogData.selectedCountry.provinces.length > 0) { $scope.dialogData.address.region = $scope.dialogData.selectedProvince.code; } $scope.submit($scope.dialogData); }; init(); });
falcon11/ASFoundation
ASFoundation/Classes/Base/ViewController/ASBaseViewController.h
// // BaseViewController.h // ASFoundation // // Created by Ashoka on 2020/6/23. // #import <UIKit/UIKit.h> #import <QMUIKit/QMUIKit.h> #import "BaseViewModel.h" NS_ASSUME_NONNULL_BEGIN @interface ASBaseViewController : QMUICommonViewController // MVVM 时使用 @property (strong, nonatomic) BaseViewModel *viewModel; - (instancetype)initWithViewModel:(BaseViewModel *)viewModel; // 需要在适当时调 bindViewModel,做下绑定 - (void)bindViewModel; @end NS_ASSUME_NONNULL_END
THEONLYDarkShadow/alive_reversing
Source/AliveLibAE/ShadowZone.cpp
#include "stdafx.h" #include "ShadowZone.hpp" #include "Function.hpp" #include "Game.hpp" #include "Map.hpp" #include "stdlib.hpp" #include "Events.hpp" BaseGameObject* ShadowZone::VDestructor(signed int flags) { return vdtor_463A70(flags); } void ShadowZone::VUpdate() { vUpdate_463C40(); } void ShadowZone::VScreenChanged() { vScreenChanged_463CC0(); } ShadowZone* ShadowZone::ctor_463900(Path_ShadowZone* pTlv, Path* /*pPath*/, DWORD tlvInfo) { BaseGameObject_ctor_4DBFA0(TRUE, 0); SetVTable(this, 0x545E10); // vTbl_ShadowZone_545E10 sShadowZone_dArray_5C1B80->Push_Back(this); field_26_path = gMap_5C3030.field_2_current_path; field_24_level = gMap_5C3030.field_0_current_level; field_20_tlvInfo = tlvInfo; field_30_mid_x = (pTlv->field_C_bottom_right.field_0_x - pTlv->field_8_top_left.field_0_x) / 2; field_32_mid_y = (pTlv->field_C_bottom_right.field_2_y - pTlv->field_8_top_left.field_2_y) / 2; field_28_centre_x = field_30_mid_x + pTlv->field_8_top_left.field_0_x; field_2C_centre_mid_x = field_30_mid_x - 75; if (field_2C_centre_mid_x < 0) { field_2C_centre_mid_x = 0; } field_2A_center_y = field_32_mid_y + pTlv->field_8_top_left.field_2_y; field_2E_centre_mid_y = field_32_mid_y - 75; if (field_2E_centre_mid_y < 0) { field_2E_centre_mid_y = 0; } field_38_r = FP_FromInteger(pTlv->field_14_r); field_3C_g = FP_FromInteger(pTlv->field_16_g); field_40_b = FP_FromInteger(pTlv->field_18_b); field_34_id = pTlv->field_1A_id; field_36_scale = pTlv->field_1C_scale; return this; } EXPORT void CC ShadowZone::ShadowZones_Calculate_Colour_463CE0(int xpos, int ypos, __int16 scale, short* r, short* g, short* b) { for (int idx = 0; idx < sShadowZone_dArray_5C1B80->Size(); idx++) { ShadowZone* pShadow = sShadowZone_dArray_5C1B80->ItemAt(idx); if (!pShadow) { break; } if (pShadow->ApplysToScale_463C70(scale)) { FP amount = {}; // TODO: This was probably a reference, refactor later pShadow->GetColourAmount_463AA0(&amount, static_cast<short>(xpos), static_cast<short>(ypos)); *r = FP_GetExponent(FP_FromInteger(*r) + (pShadow->field_38_r * amount)); *b = FP_GetExponent(FP_FromInteger(*b) + (pShadow->field_40_b * amount)); // NOTE: Never seems to be enabled, a debugging feature so instead of being hidden // in the shadow zones you appear green. //if (!word_5C1BE2) { *g = FP_GetExponent(FP_FromInteger(*g) + (pShadow->field_3C_g * amount)); } } } // Clamp min/max if (*r > 255) { *r = 255; } if (*r < 0) { *r = 0; } if (*g > 255) { *g = 255; } if (*g < 0) { *g = 0; } if (*b > 255) { *b = 255; } if (*b < 0) { *b = 0; } } void ShadowZone::dtor_463BB0() { SetVTable(this, 0x545E10); // vTbl_ShadowZone_545E10 Path::TLV_Reset_4DB8E0(field_20_tlvInfo, -1, 0, 0); sShadowZone_dArray_5C1B80->Remove_Item(this); BaseGameObject_dtor_4DBEC0(); } ShadowZone* ShadowZone::vdtor_463A70(signed int flags) { dtor_463BB0(); if (flags & 1) { ae_delete_free_495540(this); } return this; } void ShadowZone::vScreenChanged_463CC0() { field_6_flags.Set(BaseGameObject::eDead_Bit3); } __int16 ShadowZone::ApplysToScale_463C70(__int16 scale) { if (field_36_scale == ShadowZoneScale::eBoth_0) { return 1; } else if (field_36_scale == ShadowZoneScale::eFull_2 && scale == 1) { return 1; } else if (field_36_scale == ShadowZoneScale::eHalf_1 && scale == 0) { return 1; } return 0; } void ShadowZone::vUpdate_463C40() { if (Event_Get_422C00(kEventDeathReset)) { field_6_flags.Set(BaseGameObject::eDead_Bit3); } } FP* ShadowZone::GetColourAmount_463AA0(FP* pOut, __int16 xpos, __int16 ypos) { const int deltaX = abs(xpos - field_28_centre_x); const int deltaY = abs(ypos - field_2A_center_y); if (deltaX > field_30_mid_x || deltaY > field_32_mid_y) { // Not in range *pOut = FP_FromInteger(0); } else { if (deltaX > field_2C_centre_mid_x) { // Partly in range const FP midXDistance = FP_FromInteger(field_30_mid_x - field_2C_centre_mid_x); const FP value = midXDistance - FP_FromInteger(deltaX - field_2C_centre_mid_x); *pOut = value / midXDistance; } else { // Fully in range *pOut = FP_FromInteger(1); } } return pOut; }
legsem/legstar-core2
legstar-maven-plugin/src/test/java/com/legstar/maven/plugin/BaseGeneratorMojoTest.java
package com.legstar.maven.plugin; import java.io.File; public class BaseGeneratorMojoTest extends LegStarAbstractMojoTestCase { public void testMojoBasic() throws Exception { File testPom = new File(getBasedir(), "src/test/resources/poms/basic-test-plugin-config.xml"); BaseGeneratorMojo mojo = (BaseGeneratorMojo) lookupAndPrepareMojo( "generate-base", testPom ); mojo.execute(); assertTrue(new File( "target/generated-sources/java/flat01/CobolFlat01Record.java") .exists()); } public void testMojoComplete() throws Exception { File testPom = new File(getBasedir(), "src/test/resources/poms/complete-test-java-plugin-config.xml"); BaseGeneratorMojo mojo = (BaseGeneratorMojo) lookupAndPrepareMojo( "generate-base", testPom ); mojo.execute(); assertTrue(new File( "target/generated-test-sources/java/com/example/flat01/CobolFlat01Record.java") .exists()); } }
coheigea/tcommon-studio-se
main/plugins/org.talend.metadata.managment.ui/src/main/java/org/talend/metadata/managment/ui/wizard/CheckLastVersionRepositoryWizard.java
<reponame>coheigea/tcommon-studio-se // ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.metadata.managment.ui.wizard; import java.util.List; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.ui.IWorkbench; import org.talend.commons.exception.PersistenceException; import org.talend.commons.ui.runtime.exception.ExceptionHandler; import org.talend.commons.utils.VersionUtils; import org.talend.core.GlobalServiceRegister; import org.talend.core.model.metadata.builder.connection.MetadataTable; import org.talend.core.model.properties.ConnectionItem; import org.talend.core.model.properties.Item; import org.talend.core.model.repository.IRepositoryViewObject; import org.talend.core.repository.model.ProxyRepositoryFactory; import org.talend.core.ui.ILastVersionChecker; import org.talend.designer.core.IDesignerCoreService; import org.talend.metadata.managment.ui.wizard.context.ContextWizard; import org.talend.metadata.managment.ui.wizard.documentation.DocumentationCreateWizard; import org.talend.metadata.managment.ui.wizard.documentation.DocumentationUpdateWizard; import org.talend.repository.model.IProxyRepositoryFactory; /** * DOC hywang class global comment. Detailled comment */ public abstract class CheckLastVersionRepositoryWizard extends RepositoryWizard implements ILastVersionChecker { protected ConnectionItem connectionItem; protected MetadataTable metadataTable; // protected MetadataTable metadataTableCopy; // // protected Connection connectionCopy; public CheckLastVersionRepositoryWizard(IWorkbench workbench, boolean creation) { super(workbench, creation, false); } public CheckLastVersionRepositoryWizard(IWorkbench workbench, boolean creation, boolean forceReadOnly) { super(workbench, creation, forceReadOnly); } @Override public boolean performFinish() { // TODO Auto-generated method stub return false; } /** * Initializes the copies including connection and metadata table. The input parameter is not <code>null</code>. */ // protected void initConnectionCopy(Connection connection) { // this.connectionCopy = cloneConnectionCopy(connection); // if (connectionCopy != null) // this.metadataTableCopy = ConnectionHelper.getTableById(connectionCopy, metadataTable.getId()); // } /** * Clones a copy of connection. * * @param connection */ // protected Connection cloneConnectionCopy(Connection connection) { // Connection connectionCopy = EcoreUtil.copy(connection); // EList<Package> dataPackage = connection.getDataPackage(); // Collection<Package> newDataPackage = EcoreUtil.copyAll(dataPackage); // ConnectionHelper.addPackages(newDataPackage, connectionCopy); // return connectionCopy; // } /** * Applys the copies to the actural object, inclues connection and metadata table. */ // protected void applyConnectionCopy() { // connectionItem.setConnection(connectionCopy); // this.metadataTable = metadataTableCopy; // } @Override public boolean isRepositoryObjectEditable() { if (getVersionItem() != null && !creation) { if (this instanceof ContextWizard || this instanceof DocumentationCreateWizard || this instanceof DocumentationUpdateWizard) { return super.isRepositoryObjectEditable() && isLastVersion(getVersionItem()); } } if (getConnectionItem() != null && !creation) { return super.isRepositoryObjectEditable() && isLastVersion(getConnectionItem()); } return super.isRepositoryObjectEditable(); } public Item getVersionItem() { return null; } /* * (non-Javadoc) * * @see org.talend.core.ui.ILastVersionChecker#isLastVersion(org.talend.core.model.properties.Item) */ public boolean isLastVersion(Item item) { if (item.getProperty() != null) { if (item.getProperty().getId() == null) { return true; } try { List<IRepositoryViewObject> allVersion = ProxyRepositoryFactory.getInstance().getAllVersion( item.getProperty().getId()); if (allVersion != null && !allVersion.isEmpty()) { String lastVersion = VersionUtils.DEFAULT_VERSION; for (IRepositoryViewObject object : allVersion) { if (VersionUtils.compareTo(object.getVersion(), lastVersion) > 0) { lastVersion = object.getVersion(); } } if (VersionUtils.compareTo(item.getProperty().getVersion(), lastVersion) == 0) { return true; } } } catch (PersistenceException e) { ExceptionHandler.process(e); } } return false; } /* * (non-Javadoc) * * @see org.talend.core.ui.ILastVersionChecker#setLastVersion(java.lang.Boolean) */ public void setLastVersion(Boolean lastVersion) { // TODO Auto-generated method stub } protected void updateConnectionItem() throws CoreException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IProxyRepositoryFactory factory = ProxyRepositoryFactory.getInstance(); IWorkspaceRunnable operation = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { try { factory.save(connectionItem); closeLockStrategy(); } catch (PersistenceException e) { throw new CoreException(new Status(IStatus.ERROR, "org.talend.metadata.management.ui", "Error when save the connection", e)); } } }; ISchedulingRule schedulingRule = workspace.getRoot(); // the update the project files need to be done in the workspace runnable to avoid all // notification of changes before the end of the modifications. workspace.run(operation, schedulingRule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } @Override public boolean performCancel() { // connectionCopy = null; // metadataTableCopy = null; return super.performCancel(); } protected void refreshInFinish(boolean isModified) { if (isModified) { if (GlobalServiceRegister.getDefault().isServiceRegistered(IDesignerCoreService.class)) { IDesignerCoreService service = (IDesignerCoreService) GlobalServiceRegister.getDefault().getService( IDesignerCoreService.class); if (service != null) { service.refreshComponentView(connectionItem); } } } } }
Connway/Shibboleth
src/Frameworks/Gleam/Gleam_Frustum.cpp
/************************************************************************************ Copyright (C) 2021 by <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************************/ #include "Gleam_Frustum.h" #include "Gleam_Transform.h" #include "Gleam_AABB.h" #include "Gleam_OBB.h" #include <cmath> NS_GLEAM Frustum::Frustum(float fov, float aspect_ratio, float z_near, float z_far) { construct(fov, aspect_ratio, z_near, z_far); } void Frustum::construct(float fov, float aspect_ratio, float z_near, float z_far) { fov *= 0.5f; float tan_fov = tanf(fov); float near_height = tan_fov * z_near; float far_height = tan_fov * z_far; float near_width = near_height * aspect_ratio; float far_width = far_height * aspect_ratio; Vec3 nlt(-near_width, near_height, z_near); Vec3 nlb(-near_width, -near_height, z_near); Vec3 nrt(near_width, near_height, z_near); Vec3 nrb(near_width, -near_height, z_near); //Vec3 flt(-far_width, far_height, z_far); Vec3 flb(-far_width, -far_height, z_far); Vec3 frt(far_width, far_height, z_far); Vec3 frb(far_width, -far_height, z_far); _planes[0] = Plane(nlb, flb, nlt); _planes[1] = Plane(nrb, nrt, frb); _planes[2] = Plane(nrb, frb, nlb); _planes[3] = Plane(nrt, nlt, frt); _planes[4] = Plane(Vec3(0.0f, 0.0f, -1.0f), -z_near); _planes[5] = Plane(Vec3(0.0f, 0.0f, 1.0f), z_far); } bool Frustum::contains(const AABB& aabb) const { const int32_t size = static_cast<int32_t>(ARRAY_SIZE(_planes)); for (int32_t i = 0; i < size; ++i) { // Plane normals are pointing outside. Therefore, if we are in front of a plane, we are outside the frustum. if (_planes[i].contains(aabb) == Plane::FRONT) { return false; } } return true; } bool Frustum::contains(const OBB& obb) const { // Assuming compiler will unroll this loop for (int32_t i = 0; i < 6; ++i) { // Plane normals are pointing outside. Therefore, if we are in front of a plane, we are outside the frustum. if (_planes[i].contains(obb) == Plane::FRONT) { return false; } } return true; } void Frustum::transform(const Transform& transform) { _planes[0].transform(transform); _planes[1].transform(transform); _planes[2].transform(transform); _planes[3].transform(transform); _planes[4].transform(transform); _planes[5].transform(transform); } NS_END
hpehl/domino-ui
domino-ui/src/main/java/org/dominokit/domino/ui/datatable/plugins/SortPlugin.java
<gh_stars>0 package org.dominokit.domino.ui.datatable.plugins; import elemental2.dom.HTMLElement; import org.dominokit.domino.ui.datatable.ColumnConfig; import org.dominokit.domino.ui.datatable.DataTable; import org.dominokit.domino.ui.datatable.events.SortEvent; import org.dominokit.domino.ui.icons.Icons; import org.dominokit.domino.ui.style.Style; import org.dominokit.domino.ui.style.Styles; import org.dominokit.domino.ui.utils.ElementUtil; import org.jboss.elemento.EventType; import java.util.HashMap; import java.util.Map; import static java.util.Objects.isNull; import static org.jboss.elemento.Elements.span; public class SortPlugin<T> implements DataTablePlugin<T> { private SortContainer currentContainer; private Map<String, SortContainer> sortContainers=new HashMap<>(); private DataTable<T> dataTable; @Override public void init(DataTable<T> dataTable) { this.dataTable = dataTable; } @Override public void onHeaderAdded(DataTable<T> dataTable, ColumnConfig<T> column) { if (column.isSortable()) { SortContainer sortContainer = new SortContainer(column.getName()); sortContainers.put(column.getName(), sortContainer); column.getHeadElement().style().add(Styles.cursor_pointer, Styles.disable_selection); column.contextMenu.appendChild(sortContainer.sortElement); Style.of(column.contextMenu).setDisplay("block"); column.getHeadElement().addEventListener(EventType.click.getName(), evt -> { updateStyles(sortContainer); fireSortEvent(currentContainer.sortDirection, column); }); } } private void updateStyles(SortContainer sortContainer) { Style.of(sortContainer.sortElement) .setProperty("right", "15px") .setProperty("list-style", "none"); sortContainer.clear(); if (isNull(currentContainer)) { sortContainer.update(false); } else { currentContainer.clear(); sortContainer.update(currentContainer.columnName.equals(sortContainer.columnName)); } currentContainer = sortContainer; } public void sort(SortDirection direction, ColumnConfig<T> column){ SortContainer sortContainer = sortContainers.get(column.getName()); updateStyles(sortContainer); fireSortEvent(direction, column); } private void fireSortEvent(SortDirection direction, ColumnConfig<T> column) { dataTable.fireTableEvent(new SortEvent<>(direction, column)); } private class SortContainer { private final String columnName; private SortDirection sortDirection = SortDirection.DESC; private HTMLElement directionElement = Style.of(ElementUtil.contentBuilder(Icons.ALL.arrow_upward().element()).textContent("import_export")).add(Styles.font_15).element(); private HTMLElement sortElement = span().css(Styles.pull_right).add(directionElement) .style("min-width: 15px;") .element(); public SortContainer(String columnName) { this.columnName = columnName; } public void clear() { directionElement.textContent = "import_export"; } public void update(boolean flip) { if (flip) { if (SortDirection.ASC.equals(sortDirection)) { sortDirection = SortDirection.DESC; } else { sortDirection = SortDirection.ASC; } } clear(); directionElement.textContent = getSortArrow(); } public String getSortArrow() { if (SortDirection.ASC.equals(sortDirection)) { return Icons.ALL.arrow_upward().getName(); } else { return Icons.ALL.arrow_downward().getName(); } } } }
SLB-Pizza/radio-pizza
src/components/helpers/HeroRightArrow.js
<gh_stars>0 import React from 'react' /** * Renders the right arrow for the Hero. * @category Layout Helper * @function HeroRightArrow * @param {Function} onClick * @returns {jsx} */ export default function HeroRightArrow({ onClick }) { return ( <svg className="hero-arrow__right" baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" width={40} height={40} viewBox="-11.321 -11.321 315 315" onClick={onClick} > <path d="M82.228 297.36c-6.302 0-11.814-2.317-16.384-6.889-4.571-4.572-6.889-10.084-6.891-16.382V18.275c0-6.302 2.319-11.815 6.893-16.385C70.417-2.681 75.929-5 82.228-5c6.3 0 11.813 2.319 16.384 6.893l127.905 127.906c4.571 4.571 6.889 10.083 6.889 16.383 0 6.296-2.317 11.808-6.887 16.381L98.612 290.471c-4.57 4.572-10.082 6.889-16.384 6.889z" /> <path fill="#FFF" d="M82.228 0c4.949 0 9.233 1.812 12.848 5.428l127.906 127.907c3.614 3.614 5.424 7.898 5.424 12.848 0 4.948-1.81 9.229-5.424 12.847L95.076 286.936c-3.615 3.616-7.899 5.424-12.848 5.424s-9.232-1.808-12.848-5.424c-3.617-3.618-5.426-7.898-5.427-12.848V18.275c0-4.949 1.81-9.233 5.427-12.848C72.996 1.811 77.28 0 82.228 0m0-10c-7.565 0-14.454 2.89-19.919 8.357-5.465 5.46-8.355 12.349-8.355 19.918v255.813c.001 7.565 2.891 14.452 8.354 19.918 5.464 5.465 12.352 8.354 19.92 8.354s14.456-2.889 19.919-8.354L230.053 166.1c5.465-5.47 8.353-12.356 8.353-19.918 0-7.566-2.889-14.454-8.353-19.919L102.147-1.644C96.684-7.11 89.795-10 82.228-10z" /> </svg> ) }