repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
tomorrow-rain/pjsip
|
pjsip/pjsip/src/pjsua-lib/pjsua_im.c
|
<gh_stars>0
/* $Id$ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjsua-lib/pjsua.h>
#include <pjsua-lib/pjsua_internal.h>
#define THIS_FILE "pjsua_im.h"
/* Declare MESSAGE method */
/* We put PJSIP_MESSAGE_METHOD as the enum here, so that when
* somebody add that method into pjsip_method_e in sip_msg.h we
* will get an error here.
*/
enum
{
PJSIP_MESSAGE_METHOD = PJSIP_OTHER_METHOD
};
const pjsip_method pjsip_message_method =
{
(pjsip_method_e) PJSIP_MESSAGE_METHOD,
{ "MESSAGE", 7 }
};
/* Proto */
static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata);
/* The module instance. */
static pjsip_module mod_pjsua_im =
{
NULL, NULL, /* prev, next. */
{ "mod-pjsua-im", 12 }, /* Name. */
-1, /* Id */
PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */
NULL, /* load() */
NULL, /* start() */
NULL, /* stop() */
NULL, /* unload() */
&im_on_rx_request, /* on_rx_request() */
NULL, /* on_rx_response() */
NULL, /* on_tx_request. */
NULL, /* on_tx_response() */
NULL, /* on_tsx_state() */
};
/* MIME constants. */
static const pj_str_t STR_MIME_APP = { "application", 11 };
static const pj_str_t STR_MIME_ISCOMPOSING = { "im-iscomposing+xml", 18 };
/* Check if content type is acceptable */
#if 0
static pj_bool_t acceptable_message(const pjsip_media_type *mime)
{
const pj_str_t STR_MIME_TEXT = { "text", 4 };
const pj_str_t STR_MIME_PLAIN = { "plain", 5 };
return (pj_stricmp(&mime->type, &STR_MIME_TEXT)==0 &&
pj_stricmp(&mime->subtype, &STR_MIME_PLAIN)==0)
||
(pj_stricmp(&mime->type, &STR_MIME_APP)==0 &&
pj_stricmp(&mime->subtype, &STR_MIME_ISCOMPOSING)==0);
}
#endif
/**
* Create Accept header for MESSAGE.
*/
pjsip_accept_hdr* pjsua_im_create_accept(pj_pool_t *pool)
{
/* Create Accept header. */
pjsip_accept_hdr *accept;
accept = pjsip_accept_hdr_create(pool);
accept->values[0] = pj_str("text/plain");
accept->values[1] = pj_str("application/im-iscomposing+xml");
accept->count = 2;
return accept;
}
/**
* Private: check if we can accept the message.
*/
pj_bool_t pjsua_im_accept_pager(pjsip_rx_data *rdata,
pjsip_accept_hdr **p_accept_hdr)
{
/* Some UA sends text/html, so this check will break */
#if 0
pjsip_ctype_hdr *ctype;
pjsip_msg *msg;
msg = rdata->msg_info.msg;
/* Request MUST have message body, with Content-Type equal to
* "text/plain".
*/
ctype = (pjsip_ctype_hdr*)
pjsip_msg_find_hdr(msg, PJSIP_H_CONTENT_TYPE, NULL);
if (msg->body == NULL || ctype == NULL ||
!acceptable_message(&ctype->media))
{
/* Create Accept header. */
if (p_accept_hdr)
*p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool);
return PJ_FALSE;
}
#elif 0
pjsip_msg *msg;
msg = rdata->msg_info.msg;
if (msg->body == NULL) {
/* Create Accept header. */
if (p_accept_hdr)
*p_accept_hdr = pjsua_im_create_accept(rdata->tp_info.pool);
return PJ_FALSE;
}
#else
/* Ticket #693: allow incoming MESSAGE without message body */
PJ_UNUSED_ARG(rdata);
PJ_UNUSED_ARG(p_accept_hdr);
#endif
return PJ_TRUE;
}
/**
* Private: process pager message.
* This may trigger pjsua_ui_on_pager() or pjsua_ui_on_typing().
*/
void pjsua_im_process_pager(int call_id, const pj_str_t *from,
const pj_str_t *to, pjsip_rx_data *rdata)
{
pjsip_contact_hdr *contact_hdr;
pj_str_t contact;
pjsip_msg_body *body = rdata->msg_info.msg->body;
#if 0
/* Ticket #693: allow incoming MESSAGE without message body */
/* Body MUST have been checked before */
pj_assert(body != NULL);
#endif
/* Build remote contact */
contact_hdr = (pjsip_contact_hdr*)
pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT,
NULL);
if (contact_hdr && contact_hdr->uri) {
contact.ptr = (char*) pj_pool_alloc(rdata->tp_info.pool,
PJSIP_MAX_URL_SIZE);
contact.slen = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR,
contact_hdr->uri, contact.ptr,
PJSIP_MAX_URL_SIZE);
} else {
contact.slen = 0;
}
if (body && pj_stricmp(&body->content_type.type, &STR_MIME_APP)==0 &&
pj_stricmp(&body->content_type.subtype, &STR_MIME_ISCOMPOSING)==0)
{
/* Expecting typing indication */
pj_status_t status;
pj_bool_t is_typing;
status = pjsip_iscomposing_parse(rdata->tp_info.pool, (char*)body->data,
body->len, &is_typing, NULL, NULL,
NULL );
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Invalid MESSAGE body", status);
return;
}
if (pjsua_var.ua_cfg.cb.on_typing) {
(*pjsua_var.ua_cfg.cb.on_typing)(call_id, from, to, &contact,
is_typing);
}
if (pjsua_var.ua_cfg.cb.on_typing2) {
pjsua_acc_id acc_id;
if (call_id == PJSUA_INVALID_ID) {
acc_id = pjsua_acc_find_for_incoming(rdata);
} else {
pjsua_call *call = &pjsua_var.calls[call_id];
acc_id = call->acc_id;
}
if (acc_id != PJSUA_INVALID_ID) {
(*pjsua_var.ua_cfg.cb.on_typing2)(call_id, from, to, &contact,
is_typing, rdata, acc_id);
}
}
} else {
pj_str_t mime_type;
char buf[256];
pjsip_media_type *m;
pj_str_t text_body;
/* Save text body */
if (body) {
text_body.ptr = (char*)rdata->msg_info.msg->body->data;
text_body.slen = rdata->msg_info.msg->body->len;
/* Get mime type */
m = &rdata->msg_info.msg->body->content_type;
mime_type.ptr = buf;
mime_type.slen = pj_ansi_snprintf(buf, sizeof(buf),
"%.*s/%.*s",
(int)m->type.slen,
m->type.ptr,
(int)m->subtype.slen,
m->subtype.ptr);
if (mime_type.slen < 1)
mime_type.slen = 0;
} else {
text_body.ptr = mime_type.ptr = "";
text_body.slen = mime_type.slen = 0;
}
if (pjsua_var.ua_cfg.cb.on_pager) {
(*pjsua_var.ua_cfg.cb.on_pager)(call_id, from, to, &contact,
&mime_type, &text_body);
}
if (pjsua_var.ua_cfg.cb.on_pager2) {
pjsua_acc_id acc_id;
if (call_id == PJSUA_INVALID_ID) {
acc_id = pjsua_acc_find_for_incoming(rdata);
} else {
pjsua_call *call = &pjsua_var.calls[call_id];
acc_id = call->acc_id;
}
if (acc_id != PJSUA_INVALID_ID) {
(*pjsua_var.ua_cfg.cb.on_pager2)(call_id, from, to, &contact,
&mime_type, &text_body, rdata,
acc_id);
}
}
}
}
/*
* Handler to receive incoming MESSAGE
*/
static pj_bool_t im_on_rx_request(pjsip_rx_data *rdata)
{
pj_str_t from, to;
pjsip_accept_hdr *accept_hdr;
pjsip_msg *msg;
msg = rdata->msg_info.msg;
/* Only want to handle MESSAGE requests. */
if (pjsip_method_cmp(&msg->line.req.method, &pjsip_message_method) != 0) {
return PJ_FALSE;
}
/* Should not have any transaction attached to rdata. */
PJ_ASSERT_RETURN(pjsip_rdata_get_tsx(rdata)==NULL, PJ_FALSE);
/* Should not have any dialog attached to rdata. */
PJ_ASSERT_RETURN(pjsip_rdata_get_dlg(rdata)==NULL, PJ_FALSE);
/* Check if we can accept the message. */
if (!pjsua_im_accept_pager(rdata, &accept_hdr)) {
pjsip_hdr hdr_list;
pj_list_init(&hdr_list);
pj_list_push_back(&hdr_list, accept_hdr);
pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata,
PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL,
&hdr_list, NULL);
return PJ_TRUE;
}
/* Respond with 200 first, so that remote doesn't retransmit in case
* the UI takes too long to process the message.
*/
pjsip_endpt_respond( pjsua_var.endpt, NULL, rdata, 200, NULL,
NULL, NULL, NULL);
/* For the source URI, we use Contact header if present, since
* Contact header contains the port number information. If this is
* not available, then use From header.
*/
from.ptr = (char*)pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE);
from.slen = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR,
rdata->msg_info.from->uri,
from.ptr, PJSIP_MAX_URL_SIZE);
if (from.slen < 1)
from = pj_str("<--URI is too long-->");
/* Build the To text. */
to.ptr = (char*) pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE);
to.slen = pjsip_uri_print( PJSIP_URI_IN_FROMTO_HDR,
rdata->msg_info.to->uri,
to.ptr, PJSIP_MAX_URL_SIZE);
if (to.slen < 1)
to = pj_str("<--URI is too long-->");
/* Process pager. */
pjsua_im_process_pager(-1, &from, &to, rdata);
/* Done. */
return PJ_TRUE;
}
/* Outgoing IM callback. */
static void im_callback(void *token, pjsip_event *e)
{
pjsua_im_data *im_data = (pjsua_im_data*) token;
if (e->type == PJSIP_EVENT_TSX_STATE) {
pjsip_transaction *tsx = e->body.tsx_state.tsx;
/* Ignore provisional response, if any */
if (tsx->status_code < 200)
return;
/* Handle authentication challenges */
if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG &&
(tsx->status_code == 401 || tsx->status_code == 407))
{
pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
pjsip_tx_data *tdata;
pjsip_auth_clt_sess auth;
pj_status_t status;
PJ_LOG(4,(THIS_FILE, "Resending IM with authentication"));
/* Create temporary authentication session */
pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0);
pjsip_auth_clt_set_credentials(&auth,
pjsua_var.acc[im_data->acc_id].cred_cnt,
pjsua_var.acc[im_data->acc_id].cred);
pjsip_auth_clt_set_prefs(&auth,
&pjsua_var.acc[im_data->acc_id].cfg.auth_pref);
status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx,
&tdata);
if (status == PJ_SUCCESS) {
pjsua_im_data *im_data2;
/* Must duplicate im_data */
im_data2 = pjsua_im_data_dup(tdata->pool, im_data);
/* Increment CSeq */
PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++;
/* Re-send request */
status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1,
im_data2, &im_callback);
if (status == PJ_SUCCESS) {
/* Done */
pjsip_auth_clt_deinit(&auth);
return;
}
pjsip_auth_clt_deinit(&auth);
}
}
if (tsx->status_code/100 == 2) {
PJ_LOG(4,(THIS_FILE,
"Message \'%s\' delivered successfully",
im_data->body.ptr));
} else {
PJ_LOG(3,(THIS_FILE,
"Failed to deliver message \'%s\': %d/%.*s",
im_data->body.ptr,
tsx->status_code,
(int)tsx->status_text.slen,
tsx->status_text.ptr));
}
if (pjsua_var.ua_cfg.cb.on_pager_status) {
pjsua_var.ua_cfg.cb.on_pager_status(im_data->call_id,
&im_data->to,
&im_data->body,
im_data->user_data,
(pjsip_status_code)
tsx->status_code,
&tsx->status_text);
}
if (pjsua_var.ua_cfg.cb.on_pager_status2) {
pjsip_rx_data *rdata;
if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
rdata = e->body.tsx_state.src.rdata;
else
rdata = NULL;
pjsua_var.ua_cfg.cb.on_pager_status2(im_data->call_id,
&im_data->to,
&im_data->body,
im_data->user_data,
(pjsip_status_code)
tsx->status_code,
&tsx->status_text,
tsx->last_tx,
rdata, im_data->acc_id);
}
}
}
/* Outgoing typing indication callback.
* (used to reauthenticate request)
*/
static void typing_callback(void *token, pjsip_event *e)
{
pjsua_im_data *im_data = (pjsua_im_data*) token;
if (e->type == PJSIP_EVENT_TSX_STATE) {
pjsip_transaction *tsx = e->body.tsx_state.tsx;
/* Ignore provisional response, if any */
if (tsx->status_code < 200)
return;
/* Handle authentication challenges */
if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG &&
(tsx->status_code == 401 || tsx->status_code == 407))
{
pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
pjsip_tx_data *tdata;
pjsip_auth_clt_sess auth;
pj_status_t status;
PJ_LOG(4,(THIS_FILE, "Resending IM with authentication"));
/* Create temporary authentication session */
pjsip_auth_clt_init(&auth,pjsua_var.endpt,rdata->tp_info.pool, 0);
pjsip_auth_clt_set_credentials(&auth,
pjsua_var.acc[im_data->acc_id].cred_cnt,
pjsua_var.acc[im_data->acc_id].cred);
pjsip_auth_clt_set_prefs(&auth,
&pjsua_var.acc[im_data->acc_id].cfg.auth_pref);
status = pjsip_auth_clt_reinit_req(&auth, rdata, tsx->last_tx,
&tdata);
if (status == PJ_SUCCESS) {
pjsua_im_data *im_data2;
/* Must duplicate im_data */
im_data2 = pjsua_im_data_dup(tdata->pool, im_data);
/* Increment CSeq */
PJSIP_MSG_CSEQ_HDR(tdata->msg)->cseq++;
/* Re-send request */
status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1,
im_data2, &typing_callback);
if (status == PJ_SUCCESS) {
/* Done */
pjsip_auth_clt_deinit(&auth);
return;
}
pjsip_auth_clt_deinit(&auth);
}
}
}
}
/*
* Send instant messaging outside dialog, using the specified account for
* route set and authentication.
*/
PJ_DEF(pj_status_t) pjsua_im_send( pjsua_acc_id acc_id,
const pj_str_t *to,
const pj_str_t *mime_type,
const pj_str_t *content,
const pjsua_msg_data *msg_data,
void *user_data)
{
pjsip_tx_data *tdata;
const pj_str_t mime_text_plain = pj_str("text/plain");
pjsip_media_type media_type;
pjsua_im_data *im_data;
pjsua_acc *acc;
pj_status_t status;
/* To and message body must be specified. */
PJ_ASSERT_RETURN(to && content, PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* Create request. */
status = pjsip_endpt_create_request(pjsua_var.endpt,
&pjsip_message_method,
(msg_data && msg_data->target_uri.slen?
&msg_data->target_uri: to),
&acc->cfg.id,
to, NULL, NULL, -1, NULL, &tdata);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create request", status);
return status;
}
/* If account is locked to specific transport, then set transport to
* the request.
*/
if (acc->cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
pjsip_tx_data_set_transport(tdata, &tp_sel);
}
/* Add accept header. */
pjsip_msg_add_hdr( tdata->msg,
(pjsip_hdr*)pjsua_im_create_accept(tdata->pool));
/* Create suitable Contact header unless a Contact header has been
* set in the account.
*/
/* Ticket #1632: According to RFC 3428:
* MESSAGE requests do not initiate dialogs.
* User Agents MUST NOT insert Contact header fields into MESSAGE requests
*/
/*
if (acc->contact.slen) {
contact = acc->contact;
} else {
status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to generate Contact header", status);
pjsip_tx_data_dec_ref(tdata);
return status;
}
}
pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*)
pjsip_generic_string_hdr_create(tdata->pool,
&STR_CONTACT, &contact));
*/
/* Create IM data to keep message details and give it back to
* application on the callback
*/
im_data = PJ_POOL_ZALLOC_T(tdata->pool, pjsua_im_data);
im_data->acc_id = acc_id;
im_data->call_id = PJSUA_INVALID_ID;
pj_strdup_with_null(tdata->pool, &im_data->to, to);
pj_strdup_with_null(tdata->pool, &im_data->body, content);
im_data->user_data = user_data;
/* Set default media type if none is specified */
if (mime_type == NULL) {
mime_type = &mime_text_plain;
}
/* Parse MIME type */
pjsua_parse_media_type(tdata->pool, mime_type, &media_type);
/* Add message body */
tdata->msg->body = pjsip_msg_body_create( tdata->pool, &media_type.type,
&media_type.subtype,
&im_data->body);
if (tdata->msg->body == NULL) {
pjsua_perror(THIS_FILE, "Unable to create msg body", PJ_ENOMEM);
pjsip_tx_data_dec_ref(tdata);
return PJ_ENOMEM;
}
/* Add additional headers etc. */
pjsua_process_msg_data(tdata, msg_data);
/* Add route set */
pjsua_set_msg_route_set(tdata, &acc->route_set);
/* If via_addr is set, use this address for the Via header. */
if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) {
tdata->via_addr = acc->via_addr;
tdata->via_tp = acc->via_tp;
}
/* Send request (statefully) */
status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1,
im_data, &im_callback);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to send request", status);
return status;
}
return PJ_SUCCESS;
}
/*
* Send typing indication outside dialog.
*/
PJ_DEF(pj_status_t) pjsua_im_typing( pjsua_acc_id acc_id,
const pj_str_t *to,
pj_bool_t is_typing,
const pjsua_msg_data *msg_data)
{
pjsua_im_data *im_data;
pjsip_tx_data *tdata;
pjsua_acc *acc;
pj_status_t status;
acc = &pjsua_var.acc[acc_id];
/* Create request. */
status = pjsip_endpt_create_request( pjsua_var.endpt, &pjsip_message_method,
to, &acc->cfg.id,
to, NULL, NULL, -1, NULL, &tdata);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create request", status);
return status;
}
/* If account is locked to specific transport, then set transport to
* the request.
*/
if (acc->cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
pjsip_tx_data_set_transport(tdata, &tp_sel);
}
/* Add accept header. */
pjsip_msg_add_hdr( tdata->msg,
(pjsip_hdr*)pjsua_im_create_accept(tdata->pool));
/* Create suitable Contact header unless a Contact header has been
* set in the account.
*/
/* Ticket #1632: According to RFC 3428:
* MESSAGE requests do not initiate dialogs.
* User Agents MUST NOT insert Contact header fields into MESSAGE requests
*/
/*
if (acc->contact.slen) {
contact = acc->contact;
} else {
status = pjsua_acc_create_uac_contact(tdata->pool, &contact, acc_id, to);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to generate Contact header", status);
pjsip_tx_data_dec_ref(tdata);
return status;
}
}
pjsip_msg_add_hdr( tdata->msg, (pjsip_hdr*)
pjsip_generic_string_hdr_create(tdata->pool,
&STR_CONTACT, &contact));
*/
/* Create "application/im-iscomposing+xml" msg body. */
tdata->msg->body = pjsip_iscomposing_create_body( tdata->pool, is_typing,
NULL, NULL, -1);
/* Add additional headers etc. */
pjsua_process_msg_data(tdata, msg_data);
/* Add route set */
pjsua_set_msg_route_set(tdata, &acc->route_set);
/* If via_addr is set, use this address for the Via header. */
if (acc->cfg.allow_via_rewrite && acc->via_addr.host.slen > 0) {
tdata->via_addr = acc->via_addr;
tdata->via_tp = acc->via_tp;
}
/* Create data to reauthenticate */
im_data = PJ_POOL_ZALLOC_T(tdata->pool, pjsua_im_data);
im_data->acc_id = acc_id;
/* Send request (statefully) */
status = pjsip_endpt_send_request( pjsua_var.endpt, tdata, -1,
im_data, &typing_callback);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to send request", status);
return status;
}
return PJ_SUCCESS;
}
/*
* Init pjsua IM module.
*/
pj_status_t pjsua_im_init(void)
{
const pj_str_t msg_tag = { "MESSAGE", 7 };
const pj_str_t STR_MIME_TEXT_PLAIN = { "text/plain", 10 };
const pj_str_t STR_MIME_APP_ISCOMPOSING =
{ "application/im-iscomposing+xml", 30 };
pj_status_t status;
/* Register module */
status = pjsip_endpt_register_module(pjsua_var.endpt, &mod_pjsua_im);
if (status != PJ_SUCCESS)
return status;
/* Register support for MESSAGE method. */
pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ALLOW,
NULL, 1, &msg_tag);
/* Register support for "application/im-iscomposing+xml" content */
pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ACCEPT,
NULL, 1, &STR_MIME_APP_ISCOMPOSING);
/* Register support for "text/plain" content */
pjsip_endpt_add_capability( pjsua_var.endpt, &mod_pjsua_im, PJSIP_H_ACCEPT,
NULL, 1, &STR_MIME_TEXT_PLAIN);
return PJ_SUCCESS;
}
|
danielfireman-ifal/coletores
|
mpsp/src/active_members_parser.py
|
import pandas as pd
import math
import parser
# Due to the different format of the spreadsheets, a specific parser is required for a few months
# Contains the parsers for monthly remuneration worksheets for active members:
# parse_jan_19: January 2019
# parse_feb_to_may_19: February to May 2019
# parse_jun_19: June 2019
# Adjust existing spreadsheet variations
def format_value(element):
if element == None:
return 0.0
if type(element) == str and "-" in element:
return 0.0
if element == "#N/DISP":
return 0.0
return element
# Parser for Active Members - January 2019
def parse_jan_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[14])
contribuicao_previdenciaria = format_value(row[11])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + moradia
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Parser for Active Members - February to May 2019
def parse_feb_to_may_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[16]) # Auxilio alimentação
ferias_pc = format_value(row[17]) # Férias em pecunia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[14])
contribuicao_previdenciaria = format_value(row[11])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + ferias_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_gratificacoes + total_indenizacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"ferias em pecunia": ferias_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Parser for Active Members - June 2019
def parse_jun_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[15]) # Auxilio alimentação
ferias_pc = format_value(row[16]) # Férias em pecunia
licensa_pc = format_value(row[17]) # Licença Prêmio em Pecúnia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[13])
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + ferias_pc + licensa_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"ferias em pecunia": ferias_pc,
"LP em pecunia": licensa_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporarias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# January to May - 2018
def parse_jan_to_may_18(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
total_descontos = format_value(row[14])
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
ferias_pc = format_value(row[18])
licensa_pc = format_value(row[19])
outras_remuneracoes_temporarias = format_value(
row[20]
) # Gratificação Cumulativa, Gratific. Serv. Nat. Especial Art. 2 Ato 40, Gratific. Atuação Especial Ato 709/2011
total_indenizacoes = alimentacao + moradia + ferias_pc + licensa_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + outras_remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
"vacation_pecuniary": ferias_pc,
"premium_license_pecuniary": licensa_pc
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ outras_remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": outras_remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Juny to December - 2018
def parse_june_to_dec_18(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
total_descontos = format_value(row[14])
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
ferias_pc = format_value(row[18])
outras_remuneracoes_temporarias = format_value(
row[19]
) # Gratificação Cumulativa, Gratific. Serv. Nat. Especial Art. 2 Ato 40, Gratific. Atuação Especial Ato 709/2011
total_indenizacoes = alimentacao + moradia + ferias_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + outras_remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
"vacation_pecuniary": ferias_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ outras_remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": outras_remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
|
Manu343726/boost-cmake
|
libs/asio/include/boost/asio/local/connect_pair.hpp
|
//
// local/connect_pair.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
#define BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include <boost/asio/basic_socket.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/local/basic_endpoint.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace local {
/// Create a pair of connected sockets.
template <typename Protocol, typename SocketService1, typename SocketService2>
void connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2);
/// Create a pair of connected sockets.
template <typename Protocol, typename SocketService1, typename SocketService2>
boost::system::error_code connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2,
boost::system::error_code& ec);
template <typename Protocol, typename SocketService1, typename SocketService2>
inline void connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2)
{
boost::system::error_code ec;
connect_pair(socket1, socket2, ec);
boost::asio::detail::throw_error(ec, "connect_pair");
}
template <typename Protocol, typename SocketService1, typename SocketService2>
inline boost::system::error_code connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2,
boost::system::error_code& ec)
{
// Check that this function is only being used with a UNIX domain socket.
boost::asio::local::basic_endpoint<Protocol>* tmp
= static_cast<typename Protocol::endpoint*>(0);
(void)tmp;
Protocol protocol;
boost::asio::detail::socket_type sv[2];
if (boost::asio::detail::socket_ops::socketpair(protocol.family(),
protocol.type(), protocol.protocol(), sv, ec)
== boost::asio::detail::socket_error_retval)
return ec;
if (socket1.assign(protocol, sv[0], ec))
{
boost::system::error_code temp_ec;
boost::asio::detail::socket_ops::state_type state[2] = { 0, 0 };
boost::asio::detail::socket_ops::close(sv[0], state[0], true, temp_ec);
boost::asio::detail::socket_ops::close(sv[1], state[1], true, temp_ec);
return ec;
}
if (socket2.assign(protocol, sv[1], ec))
{
boost::system::error_code temp_ec;
socket1.close(temp_ec);
boost::asio::detail::socket_ops::state_type state = 0;
boost::asio::detail::socket_ops::close(sv[1], state, true, temp_ec);
return ec;
}
return ec;
}
} // namespace local
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
|
hmrc/individual-income-des-stub
|
app/uk/gov/hmrc/individualincomedesstub/controller/SelfAssessmentIncomeController.scala
|
<filename>app/uk/gov/hmrc/individualincomedesstub/controller/SelfAssessmentIncomeController.scala<gh_stars>0
/*
* Copyright 2020 HM Revenue & Customs
*
* 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 uk.gov.hmrc.individualincomedesstub.controller
import javax.inject.{Inject, Singleton}
import play.api.libs.json.Json
import play.api.mvc.{Action, ControllerComponents}
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.individualincomedesstub.domain.JsonFormatters._
import uk.gov.hmrc.individualincomedesstub.domain.RecordNotFoundException
import uk.gov.hmrc.individualincomedesstub.service.SelfAssessmentIncomeService
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class SelfAssessmentIncomeController @Inject() (selfAssessmentIncomeService: SelfAssessmentIncomeService,controllerComponents : ControllerComponents ) extends CommonController(controllerComponents) {
def income(nino: Nino, startYear: Int, endYear: Int) = Action.async { implicit request =>
selfAssessmentIncomeService.income(nino, startYear, endYear) map { saReturns => Ok(Json.toJson(saReturns))
} recover {
case _: RecordNotFoundException => NotFound
}
}
}
|
TecArt/servicecatalog-development
|
j2ep/javasrc/net/sf/j2ep/UrlRewritingResponseWrapper.java
|
/*
* Copyright 2000,2004 The Apache Software Foundation.
*
* 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 net.sf.j2ep;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import net.sf.j2ep.model.Server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A wrapper for the normal HttpServletResponse, based on the content-type
* either the normal output stream of a wrapped stream will be returned. The
* wrapped stream can handle rewrite of links found in the source.
*
* This class also handles rewriting of the headers Location and Set-Cookie.
*
* @author <NAME>
*/
public final class UrlRewritingResponseWrapper extends
HttpServletResponseWrapper {
/**
* Stream we are using for the response.
*/
private UrlRewritingOutputStream outStream;
/**
* Writer we are using for the response.
*/
private PrintWriter outWriter;
/**
* Writer that writes to the underlying stream.
*/
private PrintWriter originalWriter;
/**
* Server used for this page
*/
private Server server;
/**
* The location for this server, used when we rewrite absolute URIs
*/
private String ownHostName;
/**
* The contextPath, needed when we rewrite links.
*/
private String contextPath;
/**
* The servers.
*/
private ServerChain serverChain;
/**
* Regex to find absolute links.
*/
// pock: '-' added to the pattern as it is a valid character for a domain
// name
private static Pattern linkPattern = Pattern.compile(
"\\b([^/]+://)([^/]+)([\\w/-]*)", Pattern.CASE_INSENSITIVE
| Pattern.CANON_EQ);
/**
* Regex to find the path in Set-Cookie headers.
*/
private static Pattern pathAndDomainPattern = Pattern.compile(
"\\b(path=|domain=)([^;\\s]+);?", Pattern.CASE_INSENSITIVE
| Pattern.CANON_EQ);
/**
* Logging element supplied by commons-logging.
*/
private static Log log;
/**
* Basic constructor.
*
* pock: For BES we use a new server for every request. We can't determine
* this server from the serverChain --> use the server of the request as
* parameter (Bug 5487)
*
* @param response
* The response we are wrapping
* @param server
* The server that was matched
* @param ownHostName
* String we are rewriting servers to
* @throws IOException
* When there is a problem with the streams
*/
public UrlRewritingResponseWrapper(HttpServletResponse response,
Server server, String ownHostName, String contextPath,
ServerChain serverChain) throws IOException {
super(response);
this.server = server;
this.ownHostName = ownHostName;
this.contextPath = contextPath;
this.serverChain = serverChain;
log = LogFactory.getLog(UrlRewritingResponseWrapper.class);
outStream = new UrlRewritingOutputStream(response.getOutputStream(),
contextPath, response
.getCharacterEncoding());
outWriter = new PrintWriter(outStream);
originalWriter = new PrintWriter(response.getOutputStream());
}
/**
* Checks if we have to rewrite the header and if so will rewrite it.
*
* @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String,
* java.lang.String)
*/
public void addHeader(String name, String originalValue) {
String value;
if (name.equalsIgnoreCase("location")) {
value = rewriteLocation(originalValue);
} else if (name.equalsIgnoreCase("set-cookie")) {
value = rewriteSetCookie(originalValue);
} else {
value = originalValue;
}
super.addHeader(name, value);
}
/**
* Checks if we have to rewrite the header and if so will rewrite it.
*
* @see javax.servlet.http.HttpServletResponse#setHeader(java.lang.String,
* java.lang.String)
*/
public void setHeader(String name, String originalValue) {
String value;
if (name.equalsIgnoreCase("location")) {
value = rewriteLocation(originalValue);
} else if (name.equalsIgnoreCase("set-cookie")) {
value = rewriteSetCookie(originalValue);
} else {
value = originalValue;
}
super.setHeader(name, value);
}
/**
* Rewrites the location header. Will first locate any links in the header
* and then rewrite them.
*
* @param value
* The header value we are to rewrite
* @return A rewritten header
*/
private String rewriteLocation(String value) {
StringBuffer header = new StringBuffer();
Matcher matcher = linkPattern.matcher(value);
while (matcher.find()) {
String link = matcher.group(3).replaceAll("\\$", "\\\\$");
if (link.length() == 0) {
link = "/";
}
String location = matcher.group(2) + link;
// pock: we first consider the current server (this helps to
// identify the right server even if multiple server would match the
// location
Server matchingServer = null;
String fullPath = server.getDomainName() + server.getPath() + "/";
if (location.startsWith(fullPath)) {
matchingServer = server;
}
if (matchingServer == null) {
matchingServer = serverChain.getServerMapped(location);
}
// pock: don't rewrite the link if it already starts with the
// current context path
if (matchingServer != null && !link.startsWith(contextPath)) {
link = link.substring(matchingServer.getPath().length());
link = matchingServer.getRule().revert(link);
matcher.appendReplacement(header, "$1" + ownHostName
+ contextPath + link);
}
}
matcher.appendTail(header);
log.debug("Location header rewritten " + value + " >> "
+ header.toString());
return header.toString();
}
/**
* Rewrites the header Set-Cookie so that path and domain is correct.
*
* @param value
* The original header
* @return The rewritten header
*/
private String rewriteSetCookie(String value) {
StringBuffer header = new StringBuffer();
Matcher matcher = pathAndDomainPattern.matcher(value);
while (matcher.find()) {
if (matcher.group(1).equalsIgnoreCase("path=")) {
String path = server.getRule().revert(matcher.group(2));
matcher.appendReplacement(header, "$1" + contextPath + path
+ ";");
} else {
matcher.appendReplacement(header, "");
}
}
matcher.appendTail(header);
log.debug("Set-Cookie header rewritten \"" + value + "\" >> "
+ header.toString());
return header.toString();
}
/**
* Based on the value in the content-type header we either return the
* default stream or our own stream that can rewrite links.
*
* @see javax.servlet.ServletResponse#getOutputStream()
*/
public ServletOutputStream getOutputStream() throws IOException {
if (getContentType() != null && shouldRewrite(getContentType())) {
return outStream;
} else {
return super.getOutputStream();
}
}
/**
* Based on the value in the content-type header we either return the
* default writer or our own writer. Our own writer will write to the stream
* that can rewrite links.
*
* @see javax.servlet.ServletResponse#getWriter()
*/
public PrintWriter getWriter() throws IOException {
if (getContentType() != null && shouldRewrite(getContentType())) {
return outWriter;
} else {
return originalWriter;
}
}
/**
* Rewrites the output stream to change any links. Also closes all the
* streams and writers. We need the user to flush and close the streams
* himself as usual but we can't be sure that the writers created are used
* by the client and therefor we close them here.
*
* @throws IOException
* Is thrown when there is a problem with the streams
*/
public void processStream() throws IOException {
if (getContentType() != null && shouldRewrite(getContentType())) {
outStream.rewrite(server);
}
super.getOutputStream().flush();
super.getOutputStream().close();
outStream.close();
originalWriter.close();
outWriter.close();
}
/**
* Checks the contentType to evaluate if we should do link rewriting for
* this content.
*
* @param contentType
* The Content-Type header
* @return true if we need to rewrite links, false otherwise
*/
private boolean shouldRewrite(String contentType) {
String lowerCased = contentType.toLowerCase();
return (lowerCased.indexOf("html") > -1
|| lowerCased.indexOf("css") > -1 || lowerCased
.indexOf("javascript") > -1);
}
}
|
leonchen83/redis-replicator
|
src/test/java/com/moilioncircle/redis/replicator/rdb/RdbV8ParserTest.java
|
/*
* Copyright 2016-2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.moilioncircle.redis.replicator.rdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Test;
import com.moilioncircle.redis.replicator.Configuration;
import com.moilioncircle.redis.replicator.FileType;
import com.moilioncircle.redis.replicator.RedisReplicator;
import com.moilioncircle.redis.replicator.Replicator;
import com.moilioncircle.redis.replicator.event.Event;
import com.moilioncircle.redis.replicator.event.EventListener;
import com.moilioncircle.redis.replicator.rdb.datatype.KeyValuePair;
import com.moilioncircle.redis.replicator.rdb.datatype.ZSetEntry;
import com.moilioncircle.redis.replicator.util.Strings;
/**
* @author <NAME>
* @since 2.1.0
*/
@SuppressWarnings("unchecked")
public class RdbV8ParserTest {
@Test
public void testParse() {
ConcurrentHashMap<String, KeyValuePair<byte[], ?>> map = new ConcurrentHashMap<>();
String[] resources = new String[]{"rdb_version_8_with_64b_length_and_scores.rdb", "non_ascii_values.rdb"};
for (String resource : resources) {
template(resource, map);
}
assertEquals("bar", Strings.toString(map.get("foo").getValue()));
List<ZSetEntry> zset = new ArrayList<>(((Set<ZSetEntry>) map.get("bigset").getValue()));
assertEquals(1000, zset.size());
for (ZSetEntry entry : zset) {
if (Strings.toString(entry.getElement()).equals("finalfield")) {
assertEquals(2.718d, entry.getScore(), 0.0001);
}
}
}
@SuppressWarnings("resource")
public void template(String filename, final ConcurrentHashMap<String, KeyValuePair<byte[], ?>> map) {
try {
Replicator replicator = new RedisReplicator(RdbV8ParserTest.class.
getClassLoader().getResourceAsStream(filename)
, FileType.RDB, Configuration.defaultSetting());
replicator.addEventListener(new EventListener() {
@Override
public void onEvent(Replicator replicator, Event event) {
if (event instanceof KeyValuePair<?, ?>) {
KeyValuePair<byte[], ?> kv = (KeyValuePair<byte[], ?>) event;
map.put(Strings.toString(kv.getKey()), kv);
}
}
});
replicator.open();
} catch (Exception e) {
fail();
}
}
}
|
afentev/Algorithms-and-Data-structures
|
Algorithms on graphs/LCA and LA/LD + BL.cpp
|
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
class TreeAncestor {
public:
TreeAncestor(int n, vector<int>& p) {
this->n = n;
parents = p;
children.resize(n, vector<int>());
for (int i = 1; i < n; ++i) {
children[p[i]].push_back(i);
}
matching.resize(n, {0, 0});
createPaths(0, 0);
createLadders();
createBinLiftings();
}
int getKthAncestor(int node, int k) {
if (k > d[node]) {
return -1;
}
if (k == 0) {
return node;
}
int power = 31 - __builtin_clz(k);
k &= ~(1u << power);
node = liftings[node][power];
auto index = matching[node];
return longestPaths[index.first][index.second + k];
}
void createBinLiftings() {
d.resize(n, 0);
d[0] = 0;
queue<int> q;
q.push(0);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int child: children[u]) {
q.push(child);
d[child] = d[u] + 1;
}
}
int lg = ceil(log2(n));
liftings.resize(n, vector<int> (lg, 0));
for (int i = 0; i < n; ++i) {
liftings[i][0] = parents[i];
}
for (int j = 1; j < lg; ++j) {
for (int i = 0; i < n; ++i) {
if (liftings[i][j - 1] != -1) {
liftings[i][j] = liftings[liftings[i][j - 1]][j - 1];
} else {
liftings[i][j] = -1;
}
}
}
}
int createPaths(int vertex, int depth) {
int maxima = depth;
int continuation;
for (int child: children[vertex]) {
int curDepth = createPaths(child, depth + 1);
if (curDepth > maxima) {
maxima = curDepth;
continuation = child;
}
}
if (maxima != depth) {
int index = matching[continuation].first;
longestPaths[index].push_back(vertex);
matching[vertex] = {index, longestPaths[index].size() - 1};
} else {
longestPaths.push_back(vector<int>{vertex});
matching[vertex] = {longestPaths.size() - 1, 0};
}
return maxima;
}
void createLadders() {
for (auto& path : longestPaths) {
int size = longestPaths.size();
for (int j = 0; j < size && parents[path.back()] != -1; ++j) {
path.push_back(parents[path.back()]);
}
}
}
int n;
vector<int> d;
vector<vector<int>> liftings;
vector<int> parents;
vector<vector<int>> children;
vector<vector<int>> longestPaths;
vector<pair<int, int>> matching;
};
// solution for https://leetcode.com/problems/kth-ancestor-of-a-tree-node/
int main() {
auto x = vector<int>{-1, 0, 0, 1, 1, 2, 2};
TreeAncestor* treeAncestor = new TreeAncestor(7, x);
cout << treeAncestor->getKthAncestor(3, 1) << '\n';
cout << treeAncestor->getKthAncestor(5, 2) << '\n';
cout << treeAncestor->getKthAncestor(6, 3) << '\n';
delete treeAncestor;
}
|
ncats/gsrs-play
|
modules/ginas/test/protractor/ParameterFormTest.js
|
<reponame>ncats/gsrs-play
var WizardParameterPage = function () {
this.getPage = function () {
browser.get('/ginas/app/wizard?kind=structurallyDiverse');
};
this.clickById = function (name) {
element(by.id(name)).click();
};
this.clickByModel = function (name) {
element(by.model(name)).click();
};
this.formElements = {
formName: 'parameterForm',
buttonID: 'parameters',
formObj: 'parameter',
fields: [{
model: 'parameter.name',
type: 'text-input'
}, {
model: 'parameter.type',
type: 'text-input'
}, {
model: 'parameter.amount',
type: 'form-selector'
}]
}
};
module.exports = WizardParameterPage;
|
eid101/InjazErp
|
modules/org.openbravo.client.application/web/org.openbravo.userinterface.smartclient/openbravo/skins/Default/org.openbravo.client.application/ob-grid-styles.js
|
<reponame>eid101/InjazErp
/*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2010-2013 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
// Styling properties for a generic grid (ob-grid.js)
isc.OBGrid.addProperties({
editFailedBaseStyle: null,
// is done through the additional csstext
editFailedCSSText: 'background-color: red; border-right-color: red; border-bottom-color: red;',
bodyStyleName: 'OBGridBody',
baseStyle: 'OBGridCell',
baseStyleEdit: 'OBGridCellEdit',
// for use in ob-view-grid.js while editing a cell
recordStyleError: 'OBGridCellError',
recordStyleSelectedViewInActive: 'OBGridCellSelectedViewInactive',
headerBaseStyle: 'OBGridHeaderCell',
headerBarStyle: 'OBGridHeaderBar',
headerTitleStyle: 'OBGridHeaderCellTitle',
emptyMessageStyle: 'OBGridNotificationText',
emptyMessageLinkStyle: 'OBGridNotificationTextLink',
cellPadding: 0,
/* Set in the CSS */
cellAlign: 'center',
leaveHeaderMenuButtonSpace: false,
sorterConstructor: 'ImgButton',
sortAscendingImage: {
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeader_sortAscending.png',
width: 7,
height: 11
},
sortDescendingImage: {
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeader_sortDescending.png',
width: 7,
height: 11
},
headerMenuButtonConstructor: 'OBGridHeaderImgButton',
headerButtonConstructor: 'ImgButton',
headerMenuButtonWidth: 17,
headerMenuButtonSrc: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeaderMenuButton.png',
hoverWidth: 200,
editLinkColumnWidth: 56,
summaryRowConstructor: 'OBGridSummary',
summaryRowDefaults: {
showRollOver: false
},
summaryRowHeight: 22,
groupSummaryStyle: 'OBGridSummaryCell',
summaryRowStyle: 'OBGridSummaryCell',
summaryRowStyle_min: 'OBGridSummaryCell_min',
summaryRowStyle_max: 'OBGridSummaryCell_max',
summaryRowStyle_sum: 'OBGridSummaryCell_sum',
summaryRowStyle_avg: 'OBGridSummaryCell_avg',
summaryRowStyle_count: 'OBGridSummaryCell_count',
groupNodeStyle: 'OBGridSummaryCell',
progressIconDefaults: {
width: 16,
height: 16,
visibility: 'hidden',
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridButton-progress.gif' /* Generated @ http://www.ajaxload.info/ */
/* Indicator type: 'Snake' - Background color: #FFE1C0 - Transparent background - Foreground color: #333333 */
}
});
isc.OBGrid.addClassProperties({
defaultColumnWidths: [50, 100, 200],
getDefaultColumnWidth: function (length) {
if (length <= 1) {
return isc.OBGrid.defaultColumnWidths[0];
} else if (length <= 30) {
return isc.OBGrid.defaultColumnWidths[1];
} else if (length <= 60) {
return isc.OBGrid.defaultColumnWidths[2];
}
return 200;
}
});
isc.OBGrid.changeDefaults('filterEditorDefaults', {
height: 22,
styleName: 'OBGridFilterBase',
baseStyle: 'OBGridFilterCell'
});
isc.OBGrid.changeDefaults('filterEditorProperties', {
filterImg: {
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/funnel-icon.png'
}
});
isc.OBGrid.changeDefaults('sorterDefaults', {
// baseStyle / titleStyle is auto-assigned from headerBaseStyle
showFocused: false,
// src: '[SKIN]ListGrid/header.png',
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeader_bg.png',
baseStyle: 'OBGridSorterButton'
});
isc.OBGrid.changeDefaults('headerButtonDefaults', {
showTitle: true,
showDown: true,
showFocused: false,
// baseStyle / titleStyle is auto-assigned from headerBaseStyle
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeader_bg.png'
});
isc.OBGrid.changeDefaults('headerMenuButtonDefaults', {
showDown: false,
showTitle: true
//src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridHeader_bg.png'
});
// Styling properties for the header button of a generic grid (ob-grid.js)
isc.OBGridHeaderImgButton.addProperties({
showFocused: false,
showRollOver: false,
showFocusedAsOver: false,
showDown: false
});
// Styling properties for the buttons of the grid in 'grid mode' (ob-view-grid.js)
isc.OBGridToolStripIcon.addProperties({
width: 21,
height: 19,
showRollOver: true,
showDown: true,
showDisabled: false,
showFocused: false,
showFocusedAsOver: true,
baseStyle: 'OBGridToolStripIcon',
genericIconSrc: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridButton.png',
/* Can be: edit - form - cancel - save */
initWidgetStyle: function () {
var fileExt = this.genericIconSrc.substring(this.genericIconSrc.lastIndexOf('.'), this.genericIconSrc.length);
var filePath = this.genericIconSrc.substring(0, this.genericIconSrc.length - fileExt.length) + '-';
this.setSrc(filePath + this.buttonType + fileExt);
},
setErrorState: function (error) {
var fileExt = this.genericIconSrc.substring(this.genericIconSrc.lastIndexOf('.'), this.genericIconSrc.length);
var filePath = this.genericIconSrc.substring(0, this.genericIconSrc.length - fileExt.length) + '-';
if (error) {
this.setSrc(filePath + this.buttonType + '-error' + fileExt);
} else {
this.setSrc(filePath + this.buttonType + fileExt);
}
}
});
isc.OBGridToolStripSeparator.addProperties({
width: 1,
height: 11,
baseStyle: 'OBGridToolStripSeparator',
imageType: 'normal',
src: OB.Styles.skinsPath + 'Default/org.openbravo.client.application/images/grid/gridButton-separator.png'
});
isc.OBGridButtonsComponent.addProperties({
// note this height should be the same as the recordComponentHeight defined above
height: 21,
width: '100%',
overflow: 'hidden',
align: 'center',
defaultLayoutAlign: 'center',
styleName: 'OBGridToolStrip',
layoutLeftMargin: -2,
layoutRightMargin: 0,
membersMargin: 4
});
isc.OBGridLinkButton.addProperties({
baseStyle: 'OBGridLinkButton',
showDown: true,
showFocused: true,
showFocusedAsOver: true,
showRollOver: true,
autoFit: true,
height: 1,
overflow: 'visible'
});
/******************************/
isc.OBViewGrid.addProperties({
// note should be the same as the height of the OBGridButtonsComponent
recordComponentHeight: 21,
cellHeight: 25,
bodyStyleName: 'OBViewGridBody'
});
isc.OBViewGrid.changeDefaults('editLinkFieldProperties', {
filterEditorProperties: {
textBoxStyle: 'OBGridFilterStaticText',
textAlign: 'center'
}
});
isc.OBViewGrid.changeDefaults('checkboxFieldDefaults', {
filterEditorProperties: {
textBoxStyle: 'OBGridFilterStaticText',
nonClickableTextBoxStyle: 'OBGridFilterStaticText',
clickableTextBoxStyle: 'OBGridFilterStaticTextLink',
textAlign: 'center'
}
});
/******************************/
isc.OBAlertGrid.addProperties({
bodyStyleName: 'OBAlertGridBody'
});
/******************************/
isc.OBGridFormButton.addProperties({
baseStyle: 'OBGridFormButton',
titleStyle: 'OBFormButtonTitle',
width: 1,
height: 21,
overflow: 'visible'
});
isc.OBGridFormLabel.addProperties({
wrap: false,
baseStyle: 'OBGridFormLabel'
});
|
xunyss/commons
|
commons-base/src/main/java/io/xunyss/commons/lang/ArrayUtils.java
|
<reponame>xunyss/commons
package io.xunyss.commons.lang;
import java.lang.reflect.Array;
/**
* Array utilities.
*
* @author XUNYSS
*/
public final class ArrayUtils {
/**
* An empty immutable {@code Object} array.
*/
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/**
* An empty immutable {@code String} array.
*/
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* Constructor.
*/
private ArrayUtils() {
// cannot create instance
}
/**
* Determine whether the given object is an array.
*
* @param object object
* @return {@code true} if object is array, {@code false} otherwise
*/
public static boolean isArray(final Object object) {
return object != null && object.getClass().isArray();
}
/**
* Create a type-safe generic array.
*
* @param array the varargs array items, null allowed
* @param <T> the array's element type
* @return the array, not null unless a null array is passed in
*/
@SafeVarargs
public static <T> T[] toArray(final T... array) {
return array;
}
/**
*
* @param array
* @return
*/
public static Object[] nullToEmpty(final Object[] array) {
if (getLength(array) == 0) {
return EMPTY_OBJECT_ARRAY;
}
return array;
}
/**
*
* @param array
* @return
*/
public static String[] nullToEmpty(final String[] array) {
if (getLength(array) == 0) {
return EMPTY_STRING_ARRAY;
}
return array;
}
/**
* Add the given element at the end of the new array.
*
* @param array array
* @param element the object to add
* @param <T> the component type of the array
* @return a new array
*/
public static <T> T[] add(final T[] array, final T element) {
int arrayLength = array.length;
@SuppressWarnings("unchecked")
final T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
System.arraycopy(array, 0, newArray, 0, arrayLength);
newArray[arrayLength] = element;
return newArray;
}
/**
* Add the elements of the given arrays into a new array.
*
* @param array1 array1
* @param array2 array2
* @param <T> the component type of the array
* @return a new array
*/
@SafeVarargs
public static <T> T[] add(final T[] array1, final T... array2) {
int newArrayLength = array1.length + array2.length;
@SuppressWarnings("unchecked")
final T[] newArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), newArrayLength);
System.arraycopy(array1, 0, newArray, 0, array1.length);
System.arraycopy(array2, 0, newArray, array1.length, array2.length);
return newArray;
}
/**
* Add the elements of the given arrays into a new array.
*
* @param element the object to add
* @param array array
* @param <T> the component type of the array
* @return a new array
*/
@SafeVarargs
public static <T> T[] add(final T element, final T... array) {
int arrayLength = array.length;
@SuppressWarnings("unchecked")
final T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
newArray[0] = element;
System.arraycopy(array, 0, newArray, 1, arrayLength);
return newArray;
}
/**
* Return the length of the specified array.
*
* @param array the array to retrieve the length from
* @return the length of the array, or {@code 0} if the array is {@code null}
*/
public static int getLength(final Object array) {
if (array == null) {
return 0;
}
return Array.getLength(array);
}
// /**
// * Output an array as a String.
// *
// * @param array array
// * @param <T> the component type of the array
// * @return a string representation of the array
// */
// public static <T> String toString(final T[] array) {
// if (array != null) {
// int arrayLength = array.length;
// StringBuilder arrayString = new StringBuilder();
//
// arrayString.append('[');
// for (int index = 0; index < arrayLength; index++) {
// if (index > 0) {
// arrayString.append(',').append(' ');
// }
// arrayString.append(array[index]);
// }
// return arrayString.append(']')
// .toString();
// }
// return null;
// }
/**
* Output an array as a String.
*
* @param array object array
* @param <T> the component type of the array
* @return a string representation of the array
*/
public static <T> String toString(final T[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array byte array
* @return a string representation of the array
*/
public static String toString(final byte[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array short array
* @return a string representation of the array
*/
public static String toString(final short[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array int array
* @return a string representation of the array
*/
public static String toString(final int[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array long array
* @return a string representation of the array
*/
public static String toString(final long[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array float array
* @return a string representation of the array
*/
public static String toString(final float[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array double array
* @return a string representation of the array
*/
public static String toString(final double[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array char array
* @return a string representation of the array
*/
public static String toString(final char[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String.
*
* @param array boolean array
* @return a string representation of the array
*/
public static String toString(final boolean[] array) {
return toStringInternal(array);
}
/**
* Output an array as a String using reflection.
*
* @param object array object
* @return a string representation of the array
*/
private static String toStringInternal(final Object object) {
// if (isArray(object)) {
int arrayLength = Array.getLength(object);
StringBuilder arrayString = new StringBuilder();
arrayString.append('[');
for (int index = 0; index < arrayLength; index++) {
if (index > 0) {
arrayString.append(',').append(' ');
}
arrayString.append(Array.get(object, index));
}
return arrayString.append(']')
.toString();
// }
// return null;
}
}
|
ScalablyTyped/SlinkyTyped
|
g/grumbler-scripts/src/main/scala/typingsSlinky/grumblerScripts/configMod.scala
|
package typingsSlinky.grumblerScripts
import typingsSlinky.grumblerScripts.anon.Version
import typingsSlinky.grumblerScripts.typesMod.WebpackConfigOptions
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object configMod {
@JSImport("grumbler-scripts/config", "ENV")
@js.native
object ENV extends StObject {
@JSBracketAccess
def apply(value: String): js.UndefOr[typingsSlinky.grumblerScripts.constantsMod.ENV with String] = js.native
/* "demo" */ val DEMO: typingsSlinky.grumblerScripts.constantsMod.ENV.DEMO with String = js.native
/* "local" */ val LOCAL: typingsSlinky.grumblerScripts.constantsMod.ENV.LOCAL with String = js.native
/* "production" */ val PRODUCTION: typingsSlinky.grumblerScripts.constantsMod.ENV.PRODUCTION with String = js.native
/* "sandbox" */ val SANDBOX: typingsSlinky.grumblerScripts.constantsMod.ENV.SANDBOX with String = js.native
/* "stage" */ val STAGE: typingsSlinky.grumblerScripts.constantsMod.ENV.STAGE with String = js.native
/* "test" */ val TEST: typingsSlinky.grumblerScripts.constantsMod.ENV.TEST with String = js.native
}
@JSImport("grumbler-scripts/config", "getCurrentVersion")
@js.native
def getCurrentVersion(pkg: Version): String = js.native
@JSImport("grumbler-scripts/config", "getKarmaConfig")
@js.native
def getKarmaConfig(karma: js.Object): js.Object = js.native
@JSImport("grumbler-scripts/config", "getKarmaConfig")
@js.native
def getKarmaConfig(karma: js.Object, cfg: js.Object): js.Object = js.native
@JSImport("grumbler-scripts/config", "getNextVersion")
@js.native
def getNextVersion(pkg: Version): String = js.native
@JSImport("grumbler-scripts/config", "getNextVersion")
@js.native
def getNextVersion(pkg: Version, level: String): String = js.native
@JSImport("grumbler-scripts/config", "getWebpackConfig")
@js.native
def getWebpackConfig(): js.Object = js.native
@JSImport("grumbler-scripts/config", "getWebpackConfig")
@js.native
def getWebpackConfig(options: WebpackConfigOptions): js.Object = js.native
}
|
martinogden/24hdujeu
|
client/tests/reducers/selectors.js
|
<reponame>martinogden/24hdujeu
import assert from 'assert';
import deepFreeze from 'deep-freeze';
import { getOwnedGameIDs, getKnownGameIDs } from 'reducers';
import { getGames } from 'reducers/games';
describe('selectors::getGames', () => {
it('should compose array of games using keys from gameList and gamesByID reducers', () => {
const state = {
list: [1, 2],
byID: {
1: {id: 1},
2: {id: 2},
3: {id: 3},
},
page: 1,
};
const expectedGames = [
{ id: 1, knowers: [], owners: [] },
{ id: 2, knowers: [], owners: [] },
];
deepFreeze(state);
const games = getGames(state);
assert.deepEqual(games, expectedGames);
})
})
describe('selectors::getOwnedGameIDs', () => {
it('should return list of games owned by user', () => {
const USER_ID = 1;
const state = {
games: {
list: [1, 2],
byID: {
1: { id: 1, owners: [], knowers: [] },
2: { id: 2, owners: [USER_ID], knowers: [] },
3: { id: 3, owners: [USER_ID], knowers: [] },
},
usersByID: {
[USER_ID]: { id: USER_ID },
},
page: 1,
},
auth: { userID: USER_ID },
};
const expectedGameIDs = [2];
const gameIDs = getOwnedGameIDs(state);
assert.deepEqual(gameIDs, expectedGameIDs);
})
})
describe('selectors::getKnownGameIDs', () => {
it('should return list of games known by user', () => {
const USER_ID = 1;
const state = {
games: {
list: [1, 2],
byID: {
1: { id: 1, owners: [], knowers: [] },
2: { id: 2, owners: [], knowers: [USER_ID] },
3: { id: 3, owners: [], knowers: [USER_ID] },
},
usersByID: {
[USER_ID]: { id: USER_ID },
},
page: 1,
},
auth: { userID: USER_ID },
};
const expectedGameIDs = [2];
const gameIDs = getKnownGameIDs(state);
assert.deepEqual(gameIDs, expectedGameIDs);
})
})
|
SKatiyar/cri
|
tethering/commands.go
|
/*
* CODE GENERATED AUTOMATICALLY WITH github.com/SKatiyar/cri/cmd/cri-gen
* THIS FILE SHOULD NOT BE EDITED BY HAND
*/
// Package tethering provides commands and events for Tethering domain.
package tethering
import (
"github.com/SKatiyar/cri"
)
// List of commands in Tethering domain
const (
Bind = "Tethering.bind"
Unbind = "Tethering.unbind"
)
// List of events in Tethering domain
const (
Accepted = "Tethering.accepted"
)
// The Tethering domain defines methods and events for browser port binding.
type Tethering struct {
conn cri.Connector
}
// New creates a Tethering instance
func New(conn cri.Connector) *Tethering {
return &Tethering{conn}
}
type BindRequest struct {
// Port number to bind.
Port int `json:"port"`
}
// Request browser port binding.
func (obj *Tethering) Bind(request *BindRequest) (err error) {
err = obj.conn.Send(Bind, request, nil)
return
}
type UnbindRequest struct {
// Port number to unbind.
Port int `json:"port"`
}
// Request browser port unbinding.
func (obj *Tethering) Unbind(request *UnbindRequest) (err error) {
err = obj.conn.Send(Unbind, request, nil)
return
}
type AcceptedParams struct {
// Port number that was successfully bound.
Port int `json:"port"`
// Connection id to be used.
ConnectionId string `json:"connectionId"`
}
// Informs that port was successfully bound and got a specified connection id.
func (obj *Tethering) Accepted(fn func(params *AcceptedParams, err error) bool) {
closeChn := make(chan struct{})
decoder := obj.conn.On(Accepted, closeChn)
go func() {
for {
params := AcceptedParams{}
readErr := decoder(¶ms)
if !fn(¶ms, readErr) {
close(closeChn)
break
}
}
}()
}
|
pdpdds/SDLGameProgramming
|
sdl2/3Guys/src/entities/firePitTrap.c
|
<reponame>pdpdds/SDLGameProgramming<gh_stars>0
/*
Copyright (C) 2018 Parallel Realities
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "firePitTrap.h"
static void touch(Entity *other);
static int blocking(void);
static void tick(void);
static void describe(void);
static void die(void);
void initFirePitTrap(Entity *e)
{
e->type = ET_FIRE_PIT;
e->sprite = getSprite("FirePitTrap");
e->touch = touch;
e->die = die;
e->tick = tick;
e->isBlocking = blocking;
e->describe = describe;
}
static void tick(void)
{
Entity *candidates[MAX_CANDIDATES];
int i, n, guyStanding;
guyStanding = 0;
getEntitiesAt(self->x, self->y, &n, self, candidates);
for (i = 0 ; i < n ; i++)
{
if (isGuy(candidates[i]))
{
guyStanding = 1;
}
}
if (guyStanding)
{
self->weight = 1;
}
else
{
if (self->weight > 0)
{
self->visible = 1;
}
}
}
static void touch(Entity *other)
{
if (self->visible)
{
if (isGuy(other))
{
other->alive = 0;
}
else if (other->type == ET_PUSH_BLOCK)
{
addFloor(self->x, self->y);
other->alive = 0;
self->alive = 0;
}
}
}
static int blocking(void)
{
return 0;
}
static void describe(void)
{
level.message = app.strings[ST_FIRE_PIT_DESC];
}
static void die(void)
{
playSound(SND_DIE, -1);
addExplosionEffect(self->x, self->y, 255, 255, 255);
}
|
TheCodeLabsDevs/jlibs
|
libJfx/src/main/java/de/thecodelabs/utils/ui/cell/TemplateListCellFactory.java
|
<filename>libJfx/src/main/java/de/thecodelabs/utils/ui/cell/TemplateListCellFactory.java
package de.thecodelabs.utils.ui.cell;
import de.thecodelabs.utils.ui.DetailItem;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import java.lang.reflect.InvocationTargetException;
public class TemplateListCellFactory<T> implements Callback<ListView<T>, ListCell<T>> {
private Class<? extends DetailItem<T>> viewController;
public TemplateListCellFactory(Class<? extends DetailItem<T>> viewController) {
this.viewController = viewController;
}
@Override
public ListCell<T> call(ListView<T> param) {
try {
return new TemplateListCell<>(viewController.getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
|
JingMeng/Mart-Android
|
app/src/main/java/net/coding/mart/json/v2/phase/Phases.java
|
<filename>app/src/main/java/net/coding/mart/json/v2/phase/Phases.java
package net.coding.mart.json.v2.phase;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.coding.mart.json.BaseHttpResult;
import java.io.Serializable;
import java.util.List;
public class Phases extends BaseHttpResult implements Serializable {
private static final long serialVersionUID = -6872110986964757282L;
@SerializedName("phases")
@Expose
public List<Phase> phases = null;
}
|
mikiec84/bml
|
docs/API/search/enumvalues_5.js
|
<filename>docs/API/search/enumvalues_5.js
var searchData=
[
['precision_5funinitialized',['precision_uninitialized',['../bml__types_8h.html#a8d762ed64876f48d5eb687cb62f20d5caf4da658d031a1d1fb8303df656517607',1,'bml_types.h']]]
];
|
rialang/ria
|
src/main/java/ria/lang/compiler/RiaParser.java
|
package ria.lang.compiler;
import ria.lang.Core;
import ria.lang.compiler.nodes.BinOp;
import ria.lang.compiler.nodes.Bind;
import ria.lang.compiler.nodes.Eof;
import ria.lang.compiler.nodes.InstanceOf;
import ria.lang.compiler.nodes.IsOp;
import ria.lang.compiler.nodes.Node;
import ria.lang.compiler.nodes.NumLit;
import ria.lang.compiler.nodes.ObjectRefOp;
import ria.lang.compiler.nodes.ParseExpr;
import ria.lang.compiler.nodes.Seq;
import ria.lang.compiler.nodes.Str;
import ria.lang.compiler.nodes.Sym;
import ria.lang.compiler.nodes.TypeDef;
import ria.lang.compiler.nodes.TypeNode;
import ria.lang.compiler.nodes.TypeOp;
import ria.lang.compiler.nodes.XNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class RiaParser {
public static final ThreadLocal<char[]> currentSrc = new ThreadLocal<>();
public static final String FIELD_OP = ".fieldop.";
private static final char[] CHS = (
" " + // 0x
// !"#$%&'()*+,-./0123456789:;<=>?
" .'.x..x .. ../xxxxxxxxxx. ...x" + // 2x
//`abcdefghijklmnopqrstuvwxyz{|}~
".xxxxxxxxxxxxxxxxxxxxxxxxxx[ ].x" + // 4x
"`xxxxxxxxxxxxxxxxxxxxxxxxxx . . ").toCharArray();
private static final String[][] OPS = {
{"*", "/", "%"},
{"+", "-"},
{null}, // non-standard operators
{"."},
{"<", ">", "<=", ">=", "==", "!=", "=~", "!~"},
{null}, // not
{null}, // and or
{"^"},
{":+", ":.", "++"},
{"|>"},
{"is"},
{":="},
{null}, // loop
};
private static final int FIRST_OP_LEVEL = 3;
public static final int IS_OP_LEVEL = opLevel("is");
public static final int COMP_OP_LEVEL = opLevel("<");
public static final int NOT_OP_LEVEL = COMP_OP_LEVEL + 1;
private static final int LIST_OP_LEVEL = NOT_OP_LEVEL + 3;
private static final Eof EOF = new Eof("EOF");
private static final String EXPECT_DEF = "Expected field or method definition, found";
// ugly all-in-one type expression parser
private static final int TYPE_NORMAL = 0;
private static final int TYPE_FUNRET = 1;
private static final int TYPE_VARIANT = 2;
private static final int TYPE_VARIANT_ARG = 3;
XNode loads;
String sourceName;
String moduleName;
int moduleNameLine;
String topDoc;
boolean isModule;
boolean deprecated;
private char[] src;
private int p;
private Node eofWas;
private int flags;
private int line = 1;
private int lineStart;
private String riaDocStr;
private boolean riaDocReset;
RiaParser(String sourceName, char[] src, int flags) {
this.sourceName = sourceName;
this.src = src;
this.flags = flags;
}
private static int opLevel(String op) {
int i = 0;
while(!Objects.equals(OPS[i][0], op)) {
++i;
}
return i + FIRST_OP_LEVEL;
}
int currentLine() {
return line;
}
private int directive(int from, int to) {
boolean doc = src[from] != '%';
if(doc && (flags & Compiler.GF_DOC) == 0) {
return to;
}
++from;
String str = new String(src, from, to - from);
if(doc) {
riaDocStr = riaDocStr == null || riaDocReset
? str : riaDocStr + '\n' + str;
riaDocReset = false;
} else if(str.length() >= 2) {
// Reserved for future use "%directive params"
throw new CompileException(line, from - lineStart, "Directives are not yet supported");
}
return to;
}
private int skipSpace() {
char[] src = this.src;
int i = p, sp;
char c;
riaDocReset = true;
for(; ; ) {
while(i < src.length &&
((c = src[i]) >= '\000' && c <= ' ' || c == 0xa0)) {
++i;
if(c == '\n') {
++line;
lineStart = i;
}
}
if(i + 1 < src.length && src[i] == '/') {
if(src[i + 1] == '/') {
sp = i += 2;
while(i < src.length && src[i] != '\n' && src[i] != '\r') {
++i;
}
if(i > sp && (src[sp] == '/' || src[sp] == '%')) {
i = directive(sp, i);
}
continue;
}
if(src[i + 1] == '*') {
int l = line, col = i - lineStart + 1;
sp = i += 2;
for(int level = 1; level > 0; ) {
if(++i >= src.length) {
throw new CompileException(l, col, "Unclosed /* comment");
}
if((c = src[i - 1]) == '\n') {
++line;
lineStart = i - 1;
} else if(c == '*' && src[i] == '/') {
++i;
--level;
} else if(c == '/' && src[i] == '*') {
++i;
++level;
}
}
if(i - 3 > sp && src[sp] == '*') {
directive(sp, i - 2);
}
continue;
}
}
return i;
}
}
private Node fetch() {
int i = skipSpace();
if(i >= src.length) {
return EOF;
}
char[] src = this.src;
char c;
p = i + 1;
int line = this.line, col = p - lineStart;
// Easy cases first... well apart from the dots,
// which is needed to differentiate between compose operator and struct field access
switch(src[i]) {
case '.':
// Check for "." operator being used to compose functions
if((i <= 0 || (c = src[i - 1]) < '~' && CHS[c] == ' ' &&
(i + 1 >= src.length || (c = src[i + 1]) < '~' && CHS[c] == ' '))) {
return new BinOp(".", COMP_OP_LEVEL - 1, true).pos(line, col);
}
break;
case ';':
return new XNode(";").pos(line, col);
case ',':
return new XNode(",").pos(line, col);
case '(':
return readSeq(')', null);
case '[':
return readList().pos(line, col);
case '{':
return XNode.struct(readMany(",", '}')).pos(line, col);
case ')':
p = i;
return new Eof(")").pos(line, col);
case ']':
p = i;
return new Eof("]").pos(line, col);
case '}':
p = i;
return new Eof("}").pos(line, col);
case '"':
return readStr().pos(line, col);
case '\'':
return readAStr().pos(line, col);
case '$':
return new BinOp("$", 1, false).pos(line, col);
}
// Try to parse operators
p = i;
while(i < src.length && (c = src[i]) <= '~' &&
(CHS[c] == '.' || c == '$' ||
c == '/' && (i + 1 >= src.length ||
(c = src[i + 1]) != '/' && c != '*'))) {
++i;
}
if(i != p) {
String s = new String(src, p, i - p);
p = i;
if(Objects.equals(s, "=") || Objects.equals(s, ":")) {
return new XNode(s).pos(line, col);
}
if(Objects.equals(s, ".")) // Check for field access
{
return new BinOp(FIELD_OP, 0, true).pos(line, col);
}
if(Objects.equals(s, "::")) {
return readObjectRef().pos(line, col);
}
for(i = OPS.length; --i >= 0; ) {
for(int j = OPS[i].length; --j >= 0; ) {
if(Objects.equals(OPS[i][j], s)) {
return new BinOp(s, i + FIRST_OP_LEVEL, i != LIST_OP_LEVEL - FIRST_OP_LEVEL)
.pos(line, col);
}
}
}
if(Objects.equals(s, "->")) {
return new BinOp("->", 0, true).pos(line, col);
}
// Special type operator
// TODO: Shall we keep this?
if(Objects.equals(s, "<:")) {
TypeNode t = readType(TYPE_NORMAL);
if(t == null) {
throw new CompileException(line, col, "Expecting type expression");
}
return (Objects.equals(s, "<:") ? new IsOp(t) : new TypeOp(s, t))
.pos(line, col);
}
return new BinOp(s, FIRST_OP_LEVEL + 2, true).pos(line, col);
}
// Now try parsing number literals
if((c = src[i]) >= '0' && c <= '9') {
while(++i < src.length && ((c = src[i]) <= 'z' &&
(CHS[c] == 'x' ||
c == '.' && (i + 1 >= src.length || src[i + 1] != '.')
|| ((c == '+' || c == '-') &&
(src[i - 1] == 'e' || src[i - 1] == 'E'))))) {
}
String s = new String(src, p, i - p);
p = i;
try {
return new NumLit(Core.parseNum(s)).pos(line, col);
} catch(Exception e) {
throw new CompileException(line, col, "Bad number literal '" + s + "'");
}
}
// We probably have a symbol of some kind, so find the end of it
while(++i < src.length && ((c = src[i]) > '~' || CHS[c] == 'x')) {
}
String s = new String(src, p, i - p);
p = i;
Node res;
// Check for keywords
switch(s) {
case "if":
res = readIf();
break;
case "do":
res = readDo();
break;
case "and":
case "or":
res = new BinOp(s, NOT_OP_LEVEL + 1, true);
break;
case "not":
res = new BinOp(s, NOT_OP_LEVEL, true);
break;
case "then":
case "elif":
case "else":
case "of":
case "done":
case "catch":
case "finally":
case "end":
res = new Eof(s);
break;
case "case":
res = readCase();
break;
case "in":
res = new BinOp(s, COMP_OP_LEVEL, true);
break;
case "div":
case "shr":
case "shl":
case "b_and":
case "with":
res = new BinOp(s, FIRST_OP_LEVEL, true);
break;
case "b_or":
case "xor":
res = new BinOp(s, FIRST_OP_LEVEL + 1, true);
break;
case "is":
case "cast":
case "as":
TypeNode t = readType(TYPE_NORMAL);
if(t == null) {
throw new CompileException(line, col, "Expecting type expression");
}
return (Objects.equals(s, "is") ? new IsOp(t) : new TypeOp(s, t))
.pos(line, col);
case "new":
res = readNew();
break;
case "var":
case "let":
case "unbind":
case "fall":
res = new XNode(s);
break;
case "loop":
res = new BinOp(s, IS_OP_LEVEL + 2, false);
break;
case "import":
res = readImport();
break;
case "load":
res = loads = new XNode(s, new Node[] {
readDotted("Expected module name after 'load', not a "),
loads
});
break;
case "classOf":
res = new XNode(s, readDottedType("Expected class name, not a "));
break;
case "typedef":
res = readTypeDef();
break;
case "try":
res = readTry();
break;
case "instanceof":
res = new InstanceOf(readDotted("Expected class name, not a ").sym);
break;
case "class":
res = readClassDef();
break;
default:
if(s.charAt(0) != '`') {
res = new Sym(s); // normal identifier
} else if(p >= src.length || src[p] != '`') {
throw new CompileException(line, col, "Syntax error"); // Invalid quoted symbol
} else if(s.length() == 1) {
// Check for double quoted identifier
do {
if(++p >= src.length || src[p] == '\n') {
throw new CompileException(line, col, "Unterminated ``identifier");
}
} while(src[p - 1] != '`' || src[p] != '`');
// Strip off the `` from the identifier
s = new String(src, i + 1, p - i - 2);
res = new XNode("``", new Sym(s));
++p;
} else {
++p; // swallow closing ` and return quoted identifier as an operator
res = new BinOp(s.substring(1), FIRST_OP_LEVEL + 2, true);
}
break;
}
return res.pos(line, col);
}
private Node readList() {
char c;
int i = p;
if(i + 1 < src.length && src[i] == ':' && src[i + 1] == ']') {
p = i + 2;
return new XNode("list");
}
Node[] elem = readMany(",", ']');
if(elem.length != 1 || i <= 1 ||
(c = src[i - 2]) < '~' && CHS[c] == ' ' && c != ')' ||
elem[0] instanceof BinOp && Objects.equals(((BinOp)elem[0]).op, "..")) {
return new XNode("list", elem);
}
Node res = new ObjectRefOp(null, elem);
res.kind = "listop";
return res;
}
private Node def(List<Node> args, List<Node> expr, boolean structDef, String doc) {
BinOp partial = null;
String s = null;
int i = 0, cnt = expr.size();
if(cnt > 0) {
Node o = expr.get(0);
// We exclude some operators from partial binding
// '-' is excluded so that we can parse -2 as a negative number
// '$' is used to denote a lambda, so has no partial
// '::' is field or method access, so cannot be partial either
// 'not' is unary, and hence has no partial either
if(o instanceof BinOp
&& (partial = (BinOp)o).parent == null
&& !Objects.equals(partial.op, "$") && !Objects.equals(partial.op, "-")
&& !Objects.equals(partial.op, "not") && !Objects.equals(partial.op, "::")) {
s = partial.op;
i = 1;
} else if((o = expr.get(cnt - 1)) instanceof BinOp &&
(partial = (BinOp)o).parent == null &&
!partial.postfix) {
if(Objects.equals(partial.op, "loop")) {
partial.postfix = true;
} else {
s = partial.op;
--cnt;
}
if(Objects.equals(s, FIELD_OP)) {
throw new CompileException(partial, "Unexpected '.' here. Add space before it, if you want a compose section.");
}
}
}
if(s != null && i >= cnt) {
if(Objects.equals(s, "loop") || Objects.equals(s, "with") || partial instanceof IsOp) {
throw new CompileException(partial, "Special operator `" + s + "` cannot be used as a function");
}
if(partial instanceof TypeOp) {
partial.right = new Sym(partial.hashCode() + partial.op);
partial.right.pos(partial.line, partial.col);
return XNode.lambda(partial.right, partial, null);
}
return new Sym(s).pos(partial.line, partial.col);
}
ParseExpr parseExpr = new ParseExpr();
while(i < cnt) {
parseExpr.add(expr.get(i++));
}
Node e = parseExpr.result();
if(s != null) {
if(cnt < expr.size()) {
BinOp r = new BinOp("", 2, true);
r.parent = r;
r.right = e;
r.left = e = new Sym(s);
e.line = partial.line;
e.col = partial.col;
e = r;
} else if(Objects.equals(s, "with")) { // handle using 'with' as right partial
// TODO: Still experimental, although it seems to work
// TODO: Need some more tests to confirm before we merge to master
partial.right = new Sym(partial.hashCode() + s);
partial.right.pos(partial.line, partial.col);
BinOp bp = new BinOp("with", FIRST_OP_LEVEL, true);
bp.left = partial.right;
bp.right = parseExpr.result();
e = XNode.lambda(partial.right, bp, null);
} else {
e = new XNode("rsection", new Node[] {new Sym(s), parseExpr.result()});
}
e.line = partial.line;
e.col = partial.col;
}
Bind bind;
return args == null ? e :
args.size() == 1 && Objects.equals(args.get(0).kind, "struct")
? new XNode("struct-bind",
new Node[] {args.get(0), e})
: !Objects.equals((bind = new Bind(args, e, structDef, doc)).name, "_") ? bind
: Objects.equals(bind.expr.kind, "lambda")
? bind.expr : new XNode("_", bind.expr);
}
private Node[] readArgs() {
if((p = skipSpace()) >= src.length || src[p] != '(') {
return null;
}
++p;
return readMany(",", ')');
}
// new ClassName(...)
private Node readNew() {
Node[] args = null;
StringBuilder name = new StringBuilder();
int dimensions = 0;
while(args == null) {
int nline = line, ncol = p - lineStart + 1;
Node sym = fetch();
if(!(sym instanceof Sym)) {
throw new CompileException(nline, ncol, "Expecting class name after new");
}
name.append(((Sym)sym).sym);
args = readArgs();
// If we didn't get an argument list in '()' then try see if it is an array
if(args == null) {
char c = p >= src.length ? '\000' : src[p];
if(c == '[') {
++p;
args = new Node[] {readSeq(']', null)};
while(p + 1 < src.length &&
src[p] == '[' && src[p + 1] == ']') {
p += 2;
++dimensions;
}
++dimensions;
break;
}
// Check for further components of the name and add to the current name
if(c == '.' || c == '$') {
++p;
name.append(c == '.' ? '/' : c);
} else {
throw new CompileException(line, p - lineStart + 1, "Expecting constructor argument list");
}
}
}
Node[] ex = new Node[args.length + 1];
for(int i = 0; i < dimensions; ++i) {
name.append("[]");
}
ex[0] = new Sym(name.toString());
System.arraycopy(args, 0, ex, 1, args.length);
return new XNode(dimensions == 0 ? "new" : "new-array", ex);
}
// ::something or ::something(...)
private Node readObjectRef() {
int nline = line, ncol = p - lineStart + 1;
int st = skipSpace(), i = st;
while(i < src.length && Character.isJavaIdentifierPart(src[i])) {
++i;
}
if(i == st) {
throw new CompileException(nline, ncol, "Expecting java identifier after ::");
}
p = i;
return new ObjectRefOp(new String(src, st, i - st),
i < src.length && src[i] == '(' ? readArgs() : null);
}
private Node readIf() {
Node cond = readSeqTo("then");
Node expr = readSeq(' ', null);
Node els;
if(Objects.equals(eofWas.kind, "elif")) {
els = readIf();
} else {
if(Objects.equals(eofWas.kind, "else")) {
if(src.length > p && src[p] == ':') {
++p;
List<Node> l = new ArrayList<>();
while(!((els = fetch()) instanceof Eof) && !Objects.equals(els.kind, ";")) {
l.add(els);
}
if(l.size() == 0) {
throw new CompileException(els, "Unexpected " + els);
}
if(Objects.equals(els.kind, ";") ||
!Objects.equals(els.kind, "EOF") && els.kind.length() > 1) {
p -= els.kind.length();
}
els = def(null, l, false, null);
eofWas = null;
} else {
els = readSeq(' ', null);
}
} else {
els = eofWas;
}
if(eofWas != null && !Objects.equals(eofWas.kind, "end")) {
throw new CompileException(eofWas, "Expected end, found " + eofWas);
}
}
return new XNode("if", new Node[] {cond, expr, els});
}
private void addCase(List<Node> cases, XNode choice, List<Node> expr) {
if(expr.size() == 0) {
throw new CompileException(choice, "Missing expression");
}
Node code;
if(expr.size() == 1) {
code = expr.get(0);
} else {
code = new Seq(expr.toArray(new Node[0]), null).pos(choice.line, choice.col);
}
choice.expr = new Node[] {choice.expr[0], code};
cases.add(choice);
}
private Node readCase() {
Node val = readSeqTo("of");
Node[] statements = readMany(";", ' ');
if(!Objects.equals(eofWas.kind, "end")) {
throw new CompileException(eofWas, "Expected end, found " + eofWas);
}
List<Node> cases = new ArrayList<>(statements.length + 1);
cases.add(val);
XNode pattern = null;
List<Node> expr = new ArrayList<>();
for(int i = 0; i < statements.length; ++i) {
if(Objects.equals(statements[i].kind, ":")) {
if(pattern != null) {
addCase(cases, pattern, expr);
expr.clear();
}
pattern = (XNode)statements[i];
} else if(statements[i] instanceof Sym && Objects.equals(statements[i].sym(), "...")) {
if(i == 0 || i != statements.length - 1) {
throw new CompileException(statements[i], "Unexpected ...");
}
addCase(cases, pattern, expr);
pattern = null;
cases.add(new XNode("...", statements[i]));
} else if(pattern != null) {
expr.add(statements[i]);
} else {
throw new CompileException(statements[i], "Expecting option, not a " + statements[i]);
}
}
if(pattern != null) {
addCase(cases, pattern, expr);
}
return new XNode("case-of",
cases.toArray(new Node[0]));
}
private Node readTry() {
List<Node> catches = new ArrayList<>();
catches.add(readSeq(' ', null));
while(!Objects.equals(eofWas.kind, "finally") && !Objects.equals(eofWas.kind, "end")) {
if(!Objects.equals(eofWas.kind, "catch")) {
throw new CompileException(eofWas, "Expected finally or end, found " + eofWas);
}
XNode c = (XNode)eofWas;
catches.add(c);
c.expr = new Node[3];
c.expr[0] = readDotted("Expected exception name, not ");
Node n = fetch();
if(n instanceof Sym) {
c.expr[1] = n;
n = fetch();
}
if(!Objects.equals(n.kind, ":")) {
throw new CompileException(n, "Expected ':'" +
(c.expr[1] == null ? " or identifier" : "") +
", but found " + n);
}
if(c.expr[1] == null) {
c.expr[1] = new Sym("_").pos(n.line, n.col);
}
c.expr[2] = readSeq(' ', null);
}
if(!Objects.equals(eofWas.kind, "end")) {
catches.add(readSeqTo("end"));
}
Node[] expr = catches.toArray(new Node[0]);
if(expr.length <= 1) {
throw new CompileException(eofWas, "try block must contain at least one catch or finally");
}
return new XNode("try", expr);
}
private Sym readDottedType(String what) {
Sym t = readDotted(what);
int s = p;
while(src.length > p + 1 && src[p] == '[' && src[p + 1] == ']') {
p += 2;
}
if(s != p) {
t.sym = t.sym.concat(new String(src, s, p - s));
}
return t;
}
private Node readArgDefs() {
int line_ = line, col_ = p++ - lineStart + 1;
List<Node> args = new ArrayList<>();
while((p = skipSpace()) < src.length && src[p] != ')') {
if(args.size() != 0 && src[p++] != ',') {
throw new CompileException(line, p - lineStart, "Expecting , or )");
}
args.add(readDottedType("Expected argument type, found "));
Node name = fetch();
if(!(name instanceof Sym)) {
throw new CompileException(name, "Expected an argument name, found " + name);
}
args.add(name);
}
++p;
return new XNode("argument-list", args.toArray(new Node[0])).pos(line_, col_);
}
// Read the definition of a class
private Node readClassDef() {
List<Node> defs = new ArrayList<>();
Node node = fetch();
if(!(node instanceof Sym)) {
throw new CompileException(node, "Expected a class name, found " + node);
}
p = skipSpace();
defs.add(node);
defs.add(p < src.length && src[p] == '(' ? readArgDefs()
: new XNode("argument-list", new Node[0]));
riaDocStr = null;
List<Node> l = new ArrayList<>();
node = readDottedType("Expected extends, field or method definition, found ");
Node epos = node;
if(Objects.equals(node.sym(), "extends")) {
do {
l.add(readDotted("Expected a class name, found "));
int line_ = line, col_ = p - lineStart + 1;
l.add(new XNode("arguments", readArgs()).pos(line_, col_));
} while((p = skipSpace()) < src.length && src[p++] == ',');
--p;
node = readDottedType(EXPECT_DEF);
}
defs.add(new XNode("extends", l.toArray(new Node[0])).pos(epos.line, epos.col));
l.clear();
eofWas = node;
collect:
while(!(Objects.equals(eofWas.kind, "end") || eofWas instanceof Sym && Objects.equals(((Sym)eofWas).sym, "end"))) {
if(node == null) {
node = readDottedType(EXPECT_DEF);
}
String vsym = node.sym();
if(Objects.equals(vsym, "var") || Objects.equals(vsym, "unbind") || Objects.equals(vsym, "let")) {
l.add(new XNode(vsym).pos(node.line, node.col));
node = fetch();
}
String doc = riaDocStr;
String meth = "method";
Node args = null;
while(node instanceof Sym && !(Objects.equals(((Sym)node).sym, "end"))) {
p = skipSpace();
if(p < src.length && src[p] == '(') {
if(Objects.equals(meth, "error")) {
throw new CompileException(line, p - lineStart + 1, "Static method cannot be abstract");
}
if(!Objects.equals(meth, "method")) {
l.remove(0);
}
if(l.size() == 0) {
throw new CompileException(line, p - lineStart + 1, "Expected method name, found (");
}
if(l.size() == 1) {
args = readArgDefs();
}
break;
}
if(Objects.equals(((Sym)node).sym, "end") && l.size() == 0) {
break collect;
}
l.add(node);
String s;
// Check for static and abstract method
if(Objects.equals(s = node.sym(), "static") || Objects.equals(s, "abstract")) {
meth = !Objects.equals(meth, "method") ? "error" :
Objects.equals(s, "static") ? "static-method" : "abstract-method";
node = readDottedType(EXPECT_DEF);
} else {
node = fetch();
}
}
if(args == null) {
if(node instanceof IsOp) {
l.add(node);
node = fetch();
}
if(!Objects.equals(node.kind, "=")) {
throw new CompileException(node, "Expected '=' or argument list, found " + node);
}
}
Node expr;
if(Objects.equals(meth, "abstract-method")) {
expr = null;
eofWas = fetch();
} else {
expr = readSeq('e', null);
}
if(!Objects.equals(eofWas.kind, ",") && !Objects.equals(eofWas.kind, "end") && (!(eofWas instanceof Sym) ||
!Objects.equals(((Sym)eofWas).sym, "end"))) {
throw new CompileException(eofWas, "Unexpected " + eofWas);
}
if(args == null) {
defs.add(new Bind(l, expr, false, doc));
} else {
Node[] m = expr != null
? new Node[] {l.get(0), node, args, expr}
: new Node[] {l.get(0), node, args};
defs.add(new XNode(meth, m).pos(node.line, node.col));
}
l.clear();
node = null;
riaDocStr = null;
}
return new XNode("class",
defs.toArray(new Node[0]));
}
private Node readDo() {
for(List<Node> args = new ArrayList<>(); ; ) {
Node arg = fetch();
if(arg instanceof Eof) {
throw new CompileException(arg, "Unexpected " + arg);
}
if(Objects.equals(arg.kind, ":")) {
Node expr = readSeqTo("done");
if(args.isEmpty()) {
return XNode.lambda(new Sym("_").pos(arg.line, arg.col),
expr, null);
}
for(int i = args.size(); --i >= 0; ) {
expr = XNode.lambda(args.get(i), expr, null);
}
return expr;
}
args.add(arg);
}
}
private Sym readDotted(String err) {
Node first = fetch();
StringBuilder result = new StringBuilder();
for(Node n = first; ; n = fetch()) {
if(!(n instanceof Sym)) {
if(!Objects.equals(n.kind, "var") && !Objects.equals(n.kind, "let") && !Objects.equals(n.kind, "end")) {
throw new CompileException(n, err + n);
}
result.append(n.kind);
} else {
result.append(((Sym)n).sym);
}
p = skipSpace();
if(p >= src.length || src[p] != '.') {
break;
}
++p;
result.append("/");
}
Sym sym = new Sym(result.toString());
sym.pos(first.line, first.col);
return sym;
}
private XNode readImport() {
Sym s = readDotted("Expected class path after 'import', not a ");
ArrayList<Sym> imports = null;
for(char c = ':'; ((p = skipSpace()) < src.length &&
src[p] == c); c = ',') {
++p;
if(imports == null) {
imports = new ArrayList<>();
}
imports.add(new Sym(s.sym + '/' + fetch().sym()));
}
return imports == null ? new XNode("import", s) :
new XNode("import", imports.toArray(new Node[0]));
}
private Node[] readMany(String sep, char end) {
List<Node> res = new ArrayList<>();
List<Node> args = null;
List<Node> l = new ArrayList<>();
String doc = null;
// TODO: check for (something=) error
Node sym;
riaDocStr = null;
while(!((sym = fetch()) instanceof Eof)) {
if(doc == null) {
doc = riaDocStr;
}
if(Objects.equals(sym.kind, ":") && args == null) {
if(l.size() == 0) {
throw new CompileException(sym, "Unexpected `:'");
}
XNode colon = (XNode)sym;
colon.expr = new Node[] {def(null, l, false, null)};
colon.doc = doc;
doc = null;
riaDocStr = null;
l = new ArrayList<>();
res.add(sym);
continue;
}
if(Objects.equals(sym.kind, "=")) {
args = l;
if(end == '}') {
l = new ArrayList<>();
l.add(readSeq(' ', "{}"));
if((sym = eofWas) instanceof Eof) {
break;
}
} else {
l = new ArrayList<>();
continue;
}
}
if(Objects.equals(sym.kind, ";") || Objects.equals(sym.kind, ",")) {
if(!Objects.equals(sym.kind, sep)) {
break;
}
if(args == null && Objects.equals(sep, ";") && l.size() == 0) {
continue;
}
} else {
l.add(sym);
if(!Objects.equals(sep, ";") || !(sym instanceof TypeDef)) {
continue; // look for next in line
}
}
if(l.size() == 0) {
throw new CompileException(sym, "Unexpected " + sym);
}
res.add(def(args, l, end == '}', doc));
if(args != null) {
doc = null;
}
args = null;
l = new ArrayList<>();
riaDocStr = null;
}
eofWas = sym;
if(end != ' ' && end != 'e' &&
(p >= src.length || src[p++] != end)) {
throw new CompileException(line, p - lineStart + 1, "Expecting " + end);
}
if(l.size() != 0) {
res.add(def(args, l, end == '}', doc));
} else if(args != null) {
throw new CompileException(line, p - lineStart, "Expression missing after `='");
}
return res.toArray(new Node[0]);
}
private Node readSeq(char end, Object kind) {
String doc = riaDocStr;
Node[] list = readMany(";", end);
if(list.length == 1 && kind != Seq.EVAL) {
if(doc != null && list[0] instanceof Sym) {
riaDocStr = doc;
}
return list[0];
}
if(list.length == 0) {
return new XNode("()", end == ')' ? null : new Node[0])
.pos(line, p - lineStart);
}
// find last element for line/col position
Node w = list[list.length - 1];
for(BinOp bo; w instanceof BinOp &&
(bo = (BinOp)w).left != null; ) {
w = bo.left;
}
Seq rs = new Seq(list, kind);
rs.checkBind();
rs.pos(w.line, w.col);
return rs;
}
private Node readSeqTo(String endKind) {
Node node = readSeq(' ', null);
if(!Objects.equals(eofWas.kind, endKind)) {
throw new CompileException(eofWas, "Expected " + endKind + ", found " + eofWas);
}
return node;
}
private Node readStr() {
int st = p;
List<Node> parts = null;
StringBuilder res = new StringBuilder();
int sline = line, scol = p - lineStart;
for(; p < src.length && src[p] != '"'; ++p) {
if(src[p] == '\n') {
lineStart = p + 1;
++line;
}
// Parse embedded lambdas
if(src[p] == '$' && p + 1 < src.length && src[p + 1] == '{') {
res.append(src, st, p - st);
p += 2;
if(parts == null) {
parts = new ArrayList<>();
}
if(res.length() != 0) {
parts.add(new Str(res.toString()));
}
parts.add(readSeq('}', null));
res.setLength(0);
st = p;
--p;
} else if(src[p] == '\\') {
res.append(src, st, p - st);
st = ++p;
if(p >= src.length) {
break;
}
switch(src[p]) {
case '\\':
case '"':
continue;
case 'a':
res.append('\u0007');
break;
case 'b':
res.append('\b');
break;
case 'f':
res.append('\f');
break;
case 'n':
res.append('\n');
break;
case 'r':
res.append('\r');
break;
case 't':
res.append('\t');
break;
case 'e':
res.append('\u001b');
break;
case '0':
res.append('\000');
break;
case 'u': {
st += 4;
if(st > src.length) {
st = src.length;
}
int n = st - p;
String s = new String(src, p + 1, n);
if(n == 4) {
try {
res.append((char)Integer.parseInt(s, 16));
break;
} catch(NumberFormatException ignored) {
}
}
throw new CompileException(line, p - lineStart, "Invalid unicode escape code \\u" + s);
}
default:
if(src[p] > ' ') {
throw new CompileException(line, p - lineStart, "Unexpected escape: \\" + src[p]);
}
p = skipSpace();
if(p >= src.length || src[p] != '"') {
throw new CompileException(line, p - lineStart, "Expecting continuation of string");
}
st = p;
}
++st;
}
}
if(p >= src.length) {
throw new CompileException(sline, scol, "Unclosed \"");
}
res.append(src, st, p++ - st);
if(parts == null) {
return new Str(res.toString());
}
if(res.length() != 0) {
parts.add(new Str(res.toString()));
}
return new XNode("concat", parts.toArray(new Node[0]));
}
private Str readAStr() {
int i = p, sline = line, scol = i - lineStart;
String s = "";
do {
for(; i < src.length && src[i] != '\''; ++i) {
if(src[i] == '\n') {
lineStart = i + 1;
++line;
}
}
if(i >= src.length) {
throw new CompileException(sline, scol, "Unclosed '");
}
s = s.concat(new String(src, p, i - p));
p = ++i;
} while(i < src.length && src[i++] == '\'');
return new Str(s);
}
String getTypename(Node node) {
if(!(node instanceof Sym)) {
throw new CompileException(node, "Expected typename, not a " + node);
}
String s = ((Sym)node).sym;
if(!Character.isLowerCase(s.charAt(0)) && s.charAt(0) != '_') {
throw new CompileException(node, "Typename must start with lowercase character");
}
return s;
}
TypeDef readTypeDef() {
TypeDef def = new TypeDef();
def.doc = riaDocStr;
riaDocStr = null;
def.name = getTypename(fetch());
List<String> param = new ArrayList<>();
Node node = fetch();
if(Objects.equals(def.name, "opaque")) {
def.kind = TypeDef.OPAQUE;
} else if(!(node instanceof Sym)) {
} else if(Objects.equals(def.name, "shared")) {
def.kind = TypeDef.SHARED;
} else if(Objects.equals(def.name, "unshare")) {
def.kind = TypeDef.UNSHARE;
}
if(def.kind != 0) {
def.name = getTypename(node);
if(def.kind == TypeDef.UNSHARE) {
def.param = new String[0];
(def.type = new TypeNode(def.name, new TypeNode[0]))
.pos(node.line, node.col);
return def;
}
node = fetch();
}
if(node instanceof BinOp && Objects.equals(((BinOp)node).op, "<") &&
def.kind != TypeDef.SHARED) {
do {
param.add(getTypename(fetch()));
} while(Objects.equals((node = fetch()).kind, ","));
if(!(node instanceof BinOp) || !Objects.equals(((BinOp)node).op, ">")) {
throw new CompileException(node, "Expected '>', not a " + node);
}
node = fetch();
}
if(!Objects.equals(node.kind, "=")) {
throw new CompileException(node, "Expected '=', not a " + node);
}
def.param = param.toArray(new String[0]);
if((def.type = readType(TYPE_NORMAL)) == null) {
throw new CompileException(node, "Missing type in typedef declaration");
}
return def;
}
TypeNode readType(int checkVariant) {
riaDocStr = null;
int i = skipSpace();
if(p >= src.length || src[i] == ')' || src[i] == '>') {
p = i;
return null;
}
int sline = line, scol = i - lineStart;
TypeNode res;
if(src[i] == '(') {
p = i + 1;
res = readType(TYPE_NORMAL);
if(p >= src.length || src[p] != ')') {
if(res == null) {
throw new CompileException(sline, scol, "Unclosed (");
}
throw new CompileException(line, p - lineStart, "Expecting ) here");
}
++p;
if(res == null) {
res = new TypeNode("()", null);
res.pos(sline, scol);
}
} else if(src[i] == '{') {
p = i + 1;
Node t, field;
ArrayList<TypeNode> param = new ArrayList<>();
String expect = "Expecting field name or '}' here, not ";
for(; ; ) {
riaDocStr = null;
boolean isVar = Objects.equals((field = fetch()).kind, "var");
if(Objects.equals(field.kind, "let")) {
field = fetch();
}
if(isVar) {
field = fetch();
}
String fieldName;
if(field instanceof BinOp &&
Objects.equals(((BinOp)field).op, FIELD_OP) &&
(field = fetch()) instanceof Sym) {
fieldName = ".".concat(field.sym());
} else if(!(field instanceof Sym)) {
if(isVar) {
throw new CompileException(field, "Expecting field name after var");
}
break;
} else {
fieldName = field.sym();
}
TypeNode f = new TypeNode(fieldName, new TypeNode[1]);
f.var = isVar;
f.doc = riaDocStr;
if(!((t = fetch()) instanceof IsOp) || ((BinOp)t).right != null) {
throw new CompileException(t, "Expecting '<:' or 'is' after field name");
}
f.param[0] = ((IsOp)t).type;
param.add(f);
if(!Objects.equals((field = fetch()).kind, ",")) {
expect = "Expecting ',' or '}' here, not ";
break;
}
}
if(!Objects.equals(field.kind, "}")) {
throw new CompileException(field, expect + field);
}
++p;
res = new TypeNode("",
param.toArray(new TypeNode[0]));
res.pos(sline, scol);
} else {
do {
int start = i;
char c = ' ', dot = '.';
if(i < src.length && ((c = src[i]) == '~' || c == '^')) {
++i;
}
boolean maybeArr = c == '~' || c == '`';
if(c != '.') {
if(Character.isUpperCase(c)) {
dot = '_';
}
while(i < src.length && ((c = src[i]) > '~' ||
CHS[c] == 'x' || c == dot || c == '$' || c == '`')) {
++i;
}
while(src[i - 1] == '.') {
--i;
}
}
if(maybeArr) {
c = ' ';
while(i + 1 < src.length && // java arrays
src[i] == '[' && src[i + 1] == ']') {
i += 2;
}
}
if(i == start) {
throw new CompileException(sline, scol,
"Expected type identifier, not '" +
src[i] + "' in the type expression");
}
p = i;
String sym = new String(src, start, i - start);
ArrayList<TypeNode> param = new ArrayList<>();
if(dot == '_') { // Tag variant
String doc = riaDocStr;
if(i < src.length && src[i] == '.') {
++p;
} else {
sym = ".".concat(sym);
}
TypeNode node = readType(TYPE_VARIANT_ARG);
if(node == null) {
throw new CompileException(line, p - lineStart, "Expecting variant argument");
}
node = new TypeNode(sym, new TypeNode[] {node});
node.doc = doc;
node.pos(sline, scol);
if(checkVariant == TYPE_VARIANT) {
return node;
}
param.add(node);
if(checkVariant != TYPE_VARIANT_ARG) {
while((p = skipSpace() + 1) < src.length &&
src[p - 1] == '|' &&
(node = readType(TYPE_VARIANT)) != null) {
param.add(node);
}
--p;
}
res = (TypeNode)
new TypeNode("|", param.toArray(new TypeNode[0])).pos(sline, scol);
break; // break do...while, go check for ->
}
if(c == '!') {
++p;
}
if((p = skipSpace()) < src.length && src[p] == '<') {
++p;
for(TypeNode node; (node = readType(TYPE_NORMAL)) != null;
++p) {
param.add(node);
if((p = skipSpace()) >= src.length || src[p] != ',') {
break;
}
}
if(p >= src.length || src[p] != '>') {
throw new CompileException(line, p - lineStart, "Expecting > here");
}
++p;
}
res = new TypeNode(sym,
param.toArray(new TypeNode[0]));
res.exact = c == '!';
res.pos(sline, scol);
} while(false);
}
if(checkVariant == TYPE_VARIANT) {
throw new CompileException(res, "Invalid `| " + res.str() +
"' in variant type (expecting Tag after `|')");
}
p = i = skipSpace();
if(checkVariant == TYPE_VARIANT_ARG || i + 1 >= src.length ||
src[i] != '\u2192' && (src[i] != '-' || src[++i] != '>')) {
return res;
}
sline = line;
scol = p - lineStart;
p = i + 1;
TypeNode arg = readType(TYPE_FUNRET);
if(arg == null) {
throw new CompileException(sline, scol, "Expecting return type after ->");
}
return (TypeNode)new TypeNode("->", new TypeNode[] {res, arg})
.pos(sline, scol);
}
Node parse(Object topLevel) {
// Skip the first line if it starts with shebang
if(src.length > 2 && src[0] == '#' && src[1] == '!') {
for(p = 2; p < src.length && src[p] != '\n'; ++p) {
}
}
int i = p = skipSpace();
topDoc = riaDocStr;
while(i < src.length && src[i] < '~' && CHS[src[i]] == 'x') {
++i;
}
String s = new String(src, p, i - p);
// We expect the module or program definition first
// TODO: Should we accept "package" here for compatibility with Java instead of module?
if(s.equals("module") || s.equals("program")) {
// Read the name as a series of names separated by dots
p = i;
Sym name = readDotted("Expected " + s + " name, not a ");
moduleName = name.sym;
moduleNameLine = name.line;
isModule = s.equals("module");
if(isModule) {
// if we are a module then we can be deprecated
// by adding ":deprecated" to the end of the module name
if(p < src.length && src[p] == ':') {
++p;
Node node = fetch();
if(Objects.equals(node.sym(), "deprecated")) {
deprecated = true;
p = skipSpace();
} else if(Objects.equals(node.sym(), "strict")) {
// Strict mode is not implemented yet
} else {
throw new CompileException(node, "Unknown module attribute: " + node);
}
}
}
// Finally we expect to see ";" to finish off the module/program statement
if(p >= src.length || src[p++] != ';') {
throw new CompileException(line, p - lineStart, "Expected ';' here");
}
}
// TODO: Remove unused variable?
char first = p < src.length ? src[p] : ' ';
Node res;
if((flags & Compiler.CF_EVAL_STORE) != 0) {
res = readSeq(' ', Seq.EVAL);
if(res instanceof Seq) {
Seq seq = (Seq)res;
Node last = seq.st[seq.st.length - 1];
if(last instanceof Bind ||
Objects.equals(last.kind, "struct-bind") ||
Objects.equals(last.kind, "import") ||
last instanceof TypeDef) {
Node[] tmp = new Node[seq.st.length + 1];
System.arraycopy(seq.st, 0, tmp, 0, seq.st.length);
tmp[tmp.length - 1] = new XNode("()").pos(seq.line, seq.col);
seq.st = tmp;
seq.checkBind();
} else if(seq.st.length == 1) {
res = seq.st[0];
}
}
} else {
res = readSeq(' ', topLevel);
if(Objects.equals(res.kind, "class")) {
res = new Seq(new Node[] {res}, topLevel).pos(res.line, res.col);
}
}
if(eofWas != EOF) {
throw new CompileException(eofWas, "Unexpected " + eofWas);
}
return res;
}
}
|
ornicar/lichobile
|
project/src/js/ui/analyse/view/treeView.js
|
<gh_stars>1-10
import * as m from 'mithril';
import * as helper from '../../helper';
import treePath from '../path';
import { empty, defined, renderEval, isSynthetic } from '../util';
export function renderTree(ctrl, tree) {
const turns = [];
const initPly = ctrl.analyse.firstPly();
if (initPly % 2 === 0) {
for (var i = 1, nb = tree.length; i < nb; i += 2) turns.push({
turn: Math.floor((initPly + i) / 2) + 1,
white: tree[i],
black: tree[i + 1]
});
}
else {
turns.push({
turn: Math.floor(initPly / 2) + 1,
white: null,
black: tree[1]
});
for (var j = 2, jnb = tree.length; j < jnb; j += 2) turns.push({
turn: Math.floor((initPly + j) / 2) + 1,
white: tree[j],
black: tree[j + 1]
});
}
const path = treePath.default();
var tags = [];
for (var k = 0, len = turns.length; k < len; k++) {
tags = tags.concat(renderTurn(ctrl, turns[k], path));
}
return tags;
}
function renderEvalTag(e) {
return <eval>{e}</eval>;
}
function renderGlyph(glyph) {
return <glyph>{glyph.symbol}</glyph>;
}
const emptyMove = <move className="emptyMove">...</move>;
function renderMove(ctrl, move, path) {
if (!move) return emptyMove;
const pathStr = treePath.write(path);
const evaluation = path[1] ? {} : (move.rEval || move.ceval || {});
const judgment = move.rEval && move.rEval.judgment;
const className = [
pathStr === ctrl.vm.pathStr ? 'current' : ''
].join(' ');
return (
<move data-path={pathStr} className={className}>
{move.san[0] === 'P' ? move.san.slice(1) : move.san}
{defined(evaluation.cp) ? renderEvalTag(renderEval(evaluation.cp)) : (
defined(evaluation.mate) ? renderEvalTag('#' + evaluation.mate) : null
)}
{judgment && judgment.glyph ? renderGlyph(judgment.glyph) : null}
</move>
);
}
function plyToTurn(ply) {
return Math.floor((ply - 1) / 2) + 1;
}
function renderVariationMenu(ctrl, path) {
const showing = ctrl.vm.variationMenu && ctrl.vm.variationMenu === treePath.write(path.slice(0, 1));
if (!showing) return null;
const promotable = isSynthetic(ctrl.data) ||
!ctrl.analyse.getStepAtPly(path[0].ply).fixed;
const content = m('div.variationMenu', [
m('button', {
className: 'withIcon',
'data-icon': 'q',
oncreate: helper.ontap(ctrl.deleteVariation.bind(undefined, path))
}, 'Delete variation'),
promotable ? m('button', {
className: 'withIcon',
'data-icon': 'E',
oncreate: helper.ontap(ctrl.promoteVariation.bind(undefined, path))
}, 'Promote to main line') : null
]);
return (
<div className="overlay_popup_wrapper variationMenuPopup">
<div className="popup_overlay_close"
oncreate={helper.ontap(helper.fadesOut(ctrl.toggleVariationMenu, '.overlay_popup_wrapper'))} />
<div className="overlay_popup">
{content}
</div>
</div>
);
}
function renderVariation(ctrl, variation, path, klass) {
const visiting = treePath.contains(path, ctrl.vm.path);
return (
<div className="variationWrapper">
<span className="menuIcon fa fa-ellipsis-v" oncreate={helper.ontapY(ctrl.toggleVariationMenu.bind(undefined, path))}></span>
<div className={klass + ' variation' + (visiting ? ' visiting' : '')}>
{renderVariationContent(ctrl, variation, path)}
{renderVariationMenu(ctrl, path)}
</div>
</div>
);
}
function renderVariationNested(ctrl, variation, path) {
return (
<span className="variation nested">
(
{renderVariationContent(ctrl, variation, path)}
)
</span>
);
}
function renderVariationContent(ctrl, variation, path) {
const turns = [];
if (variation[0].ply % 2 === 0) {
variation = variation.slice(0);
const move = variation.shift();
turns.push({
turn: plyToTurn(move.ply),
black: move
});
}
const visiting = treePath.contains(path, ctrl.vm.path);
const maxPlies = Math.min(visiting ? 999 : (path[2] ? 2 : 4), variation.length);
for (var i = 0; i < maxPlies; i += 2) turns.push({
turn: plyToTurn(variation[i].ply),
white: variation[i],
black: variation[i + 1]
});
return turns.map(turn => renderVariationTurn(ctrl, turn, path));
}
function renderVariationMeta(ctrl, move, path) {
if (!move || empty(move.variations)) return null;
return move.variations.map(function(variation, i) {
return renderVariationNested(ctrl, variation, treePath.withVariation(path, i + 1));
});
}
function renderVariationTurn(ctrl, turn, path) {
const wPath = turn.white ? treePath.withPly(path, turn.white.ply) : null;
const wMove = wPath ? renderMove(ctrl, turn.white, wPath) : null;
const wMeta = renderVariationMeta(ctrl, turn.white, wPath);
const bPath = turn.black ? treePath.withPly(path, turn.black.ply) : null;
const bMove = bPath ? renderMove(ctrl, turn.black, bPath) : null;
const bMeta = renderVariationMeta(ctrl, turn.black, bPath);
if (wMove) {
if (wMeta) return [
renderIndex(turn.turn + '.'),
wMove,
wMeta,
bMove ? bMove : null,
bMove ? bMeta : null
];
return [
renderIndex(turn.turn + '.'),
wMove,
bMeta ? ' ' : null,
bMove ? bMove : null,
bMove ? bMeta : null
];
}
return [
renderIndex(turn.turn + '...'),
bMove,
bMeta
];
}
function renderCommentOpening(opening) {
return (
<div className="comment opening">
{truncateComment(opening.eco + ' ' + opening.name)}
</div>
);
}
function renderMeta(ctrl, step, path) {
const judgment = step && step.rEval && step.rEval.judgment;
const opening = ctrl.data.game.opening;
const moveOpening = (step && opening && opening.ply === step.ply) ? renderCommentOpening(opening) : null;
if (!step || (!moveOpening && empty(step.variations) && (empty(judgment) || !ctrl.vm.showComments))) return null;
const children = [];
if (moveOpening) {
children.push(moveOpening);
}
const colorClass = step.ply % 2 === 0 ? 'black ' : 'white ';
if (ctrl.vm.showComments && !empty(judgment)) {
children.push(renderComment(judgment.comment, colorClass, judgment.name));
}
if (!empty(step.variations)) {
for (var i = 0, len = step.variations.length; i < len; i++) {
const variation = step.variations[i];
if (empty(variation)) return null;
children.push(renderVariation(
ctrl,
variation,
treePath.withVariation(path, i + 1),
i === 0 ? colorClass : null
));
}
}
return (
<div key={step.ply + ':meta'} className="meta">{children}</div>
);
}
function truncateComment(text) {
if (text.length <= 140) return text;
return text.slice(0, 125) + ' [...]';
}
function renderComment(comment, colorClass, commentClass) {
return comment && (
<div className={'comment ' + colorClass + commentClass}>
{truncateComment(comment)}
</div>
);
}
function turnKey(turn, meta) {
const key = turn.turn.toString() + ':' + (meta ? meta : '');
return key;
}
function renderIndex(txt) {
return <index>{txt}</index>;
}
function renderTurnEl(children, key) {
return <turn key={key}>{children}</turn>;
}
function renderTurn(ctrl, turn, path) {
const index = renderIndex(turn.turn);
const wPath = turn.white ? treePath.withPly(path, turn.white.ply) : null;
const wMove = wPath ? renderMove(ctrl, turn.white, wPath) : null;
const wMeta = renderMeta(ctrl, turn.white, wPath);
const bPath = turn.black ? treePath.withPly(path, turn.black.ply) : null;
const bMove = bPath ? renderMove(ctrl, turn.black, bPath) : null;
const bMeta = renderMeta(ctrl, turn.black, bPath);
if (wMove) {
if (wMeta) {
let temp = [
renderTurnEl([index, wMove, emptyMove], turnKey(turn, 'emptyBlack')),
wMeta
];
if (bMove) {
if (bMeta) {
temp = temp.concat([
renderTurnEl([index, emptyMove, bMove], turnKey(turn, 'emptyWhiteAfterWhiteMetaAndBlackMeta')),
bMeta
]);
} else {
temp.push(
renderTurnEl([index, emptyMove, bMove], turnKey(turn, 'emptyWhiteAfterWhiteMeta'))
);
}
}
return temp;
} else if (bMeta) {
return [
renderTurnEl([index, wMove, bMove], turnKey(turn, 'andBlackMeta')),
bMeta
];
} else {
return renderTurnEl([index, wMove, bMove], turnKey(turn));
}
}
else if (bMeta) {
return [
renderTurnEl([index, emptyMove, bMove], turnKey(turn, 'emptyWhiteAndBlackMeta')),
bMeta
];
} else {
return renderTurnEl([index, emptyMove, bMove], turnKey(turn, 'emptyWhite'));
}
}
|
JailMango/learning-java
|
java-netty/src/main/java/com/jailmango/netty/lightman/netty/chat/counter/ClientCounter.java
|
package com.jailmango.netty.lightman.netty.chat.counter;
import java.util.concurrent.atomic.AtomicLong;
/**
* ClientCounter
*/
public enum ClientCounter {
/**
* INSTANCE
*/
INSTANCE;
/**
* list
*/
private AtomicLong count;
/**
* Constructor
*/
ClientCounter() {
init();
}
/**
* fillData
*/
private void init() {
this.count = new AtomicLong(0);
}
/**
* connect
*
* @return long
*/
public long connect() {
return this.count.incrementAndGet();
}
/**
* disconnect
*
* @return long
*/
public long disconnect() {
return this.count.decrementAndGet();
}
/**
* getClientCount
*
* @return long
*/
public long getClientCount() {
return this.count.get();
}
}
|
duguyifang/btcpool
|
test/TestMain.cc
|
/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 <signal.h>
#include <execinfo.h>
#include <string>
#include "gtest/gtest.h"
#include "config/bpool-version.h"
#include <glog/logging.h>
using std::string;
#if defined(CHAIN_TYPE_BSV)
bool fRequireStandard = true;
#endif
//
// run all: ./unittest
// run single: ./unittest --gtest_filter=StratumSession\*
//
extern "C" {
static void handler(int sig);
// just for debug, should be removed when release
void handler(int sig) {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, 2);
exit(1);
}
}
typedef char *CString;
int main(int argc, char **argv) {
signal(SIGSEGV, handler);
signal(SIGFPE, handler);
signal(SIGPIPE, handler);
// Initialize Google's logging library.
google::InitGoogleLogging(argv[0]);
FLAGS_logbuflevel = -1;
FLAGS_logtostderr = true;
FLAGS_colorlogtostderr = true;
LOG(INFO) << BIN_VERSION_STRING("unittest");
CString *newArgv = new CString[argc];
memcpy(newArgv, argv, argc * sizeof(CString));
string testname = "--gtest_filter=";
if (argc == 2 && newArgv[1][0] != '-') {
testname.append(newArgv[1]);
newArgv[1] = (char *)testname.c_str();
}
testing::InitGoogleTest(&argc, newArgv);
int ret = RUN_ALL_TESTS();
delete[] newArgv;
return ret;
}
|
bhrunno/fs-agent
|
test_input/ksa/ksa-web-root/ksa-logistics-web/src/main/java/com/ksa/web/struts2/action/logistics/bookingnote/BookingNoteSaveAction.java
|
package com.ksa.web.struts2.action.logistics.bookingnote;
import com.ksa.context.ServiceContextUtils;
import com.ksa.model.logistics.BookingNoteState;
import com.ksa.service.logistics.BookingNoteService;
import com.ksa.service.security.util.SecurityUtils;
import com.ksa.util.StringUtils;
public class BookingNoteSaveAction extends BookingNoteAction {
private static final long serialVersionUID = 1912217534839054639L;
protected boolean returned = false;
@Override
public String execute() throws Exception {
if( ! SecurityUtils.isPermitted( "bookingnote:edit" ) ) {
return NO_PERMISSION;
}
return super.execute();
}
@Override
public String doExecute() throws Exception {
BookingNoteService service = ServiceContextUtils.getService( BookingNoteService.class );
if( returned ) {
// 将托单的状态置为已完成退单
bookingNote.setState( BookingNoteState.RETURNED );
}
if( StringUtils.hasText( bookingNote.getId() ) ) {
// update
service.modifyBookingNote( bookingNote );
addActionMessage( String.format( "成功更新托单:'%s'。", bookingNote.getCode() ) );
} else {
// insert
int serialNumber = bookingNote.getSerialNumber();
service.createBookingNote( bookingNote );
if( serialNumber == bookingNote.getSerialNumber() ) {
addActionMessage( String.format( "成功创建托单:'%s'。", bookingNote.getCode() ) );
} else {
addActionMessage( String.format( "成功创建托单,但原托单编号已经被占用,更新托单编号为:'%s'。", bookingNote.getCode() ) );
}
}
return SUCCESS;
}
@Override
public void validate() {
super.validate();
if( !StringUtils.hasText( bookingNote.getCode() ) ) {
this.addActionError( "请输入托单编号。" );
}
if( !StringUtils.hasText( bookingNote.getCustomer().getId() ) ) {
this.addActionError( "请输入客户信息。" );
}
if( !StringUtils.hasText( bookingNote.getSaler().getId() ) ) {
this.addActionError( "请输入销售担当。" );
}
if( !StringUtils.hasText( bookingNote.getCargoName() ) ) {
this.addActionError( "请输入货物品名。" );
}
if( returned ) {
if( !StringUtils.hasText( bookingNote.getReturnCode() ) ) {
this.addActionError( "请输入退单号。" );
}
if( bookingNote.getReturnDate() == null ) {
this.addActionError( "请输入退单日期。" );
}
}
}
public boolean getReturned() {
return returned;
}
public boolean isReturned() {
return returned;
}
public void setReturned( boolean returned ) {
this.returned = returned;
}
}
|
ProKil/ShapeWorld
|
shapeworld/captioners/number_bound.py
|
from random import choice, random
from shapeworld import util
from shapeworld.captions import NumberBound
from shapeworld.captioners import WorldCaptioner
class NumberBoundCaptioner(WorldCaptioner):
# incorrect modes
# 0: incorrect quantifier
# 1: number off by one
# 2: number off by two
# 3: random incorrect number
def __init__(
self,
quantifier_captioner,
pragmatical_redundancy_rate=1.0,
pragmatical_tautology_rate=0.0,
logical_redundancy_rate=0.0,
logical_tautology_rate=0.0,
logical_contradiction_rate=0.0,
number_bounds=None,
incorrect_distribution=(3, 1, 1, 1)
):
super(NumberBoundCaptioner, self).__init__(
internal_captioners=(quantifier_captioner,),
pragmatical_redundancy_rate=pragmatical_redundancy_rate,
pragmatical_tautology_rate=pragmatical_tautology_rate,
logical_redundancy_rate=logical_redundancy_rate,
logical_tautology_rate=logical_tautology_rate,
logical_contradiction_rate=logical_contradiction_rate
)
self.quantifier_captioner = quantifier_captioner
self.number_bounds = number_bounds
self.incorrect_distribution = util.cumulative_distribution(incorrect_distribution)
def set_realizer(self, realizer):
if not super(NumberBoundCaptioner, self).set_realizer(realizer):
return False
if self.number_bounds is None:
self.number_bounds = list(realizer.number_bounds)
else:
self.number_bounds = [bound for bound in realizer.number_bounds if bound in self.number_bounds]
return True
def pn_length(self):
return self.quantifier_captioner.pn_length() + 1
def pn_symbols(self):
return super(NumberBoundCaptioner, self).pn_symbols() | {'{}-{}'.format(NumberBound.__name__, bound) for bound in self.number_bounds}
def pn_arity(self):
arity = super(NumberBoundCaptioner, self).pn_arity()
arity.update({'{}-{}'.format(NumberBound.__name__, bound): 1 for bound in self.number_bounds})
return arity
def sample_values(self, mode, predication):
assert predication.empty()
if not super(NumberBoundCaptioner, self).sample_values(mode=mode, predication=predication):
return False
if not self.quantifier_captioner.sample_values(mode=mode, predication=predication):
return False
for _ in range(self.__class__.MAX_SAMPLE_ATTEMPTS):
self.incorrect_mode = util.sample(self.incorrect_distribution)
if self.incorrect_mode == 0 and not self.quantifier_captioner.incorrect_possible():
continue
break
else:
return False
# potentially option to choose fixed number bound?
# self.bound = choice(self.number_bounds)
return True
def incorrect_possible(self):
return True
def model(self):
model = super(NumberBoundCaptioner, self).model()
model.update(
incorrect_mode=self.incorrect_mode,
quantifier_captioner=self.quantifier_captioner.model()
)
return model
def caption(self, predication, world):
assert predication.empty()
quant_predication = predication.copy()
quantifier = self.quantifier_captioner.caption(predication=quant_predication, world=world)
if quantifier is None:
return None
num_predication = predication.copy()
self.quantifier_captioner.restrictor_captioner.correct(caption=quantifier.restrictor, predication=num_predication)
# potentially option to choose fixed number bound?
number_bound = NumberBound(bound=num_predication.num_agreeing, quantifier=quantifier)
if not self.correct(caption=number_bound, predication=predication):
return None
return number_bound
def correct(self, caption, predication):
num_predication = caption.apply_to_predication(predication=predication)
return num_predication.num_agreeing in self.number_bounds
def incorrect(self, caption, predication, world):
assert predication.empty()
if self.incorrect_mode == 0: # 0: incorrect quantifier
quant_predication = predication.copy()
if not self.quantifier_captioner.incorrect(caption=caption.quantifier, predication=quant_predication, world=world):
return False
elif self.incorrect_mode == 1 or self.incorrect_mode == 2: # 1/2: number off by one/two
num_predication = caption.apply_to_predication(predication=predication)
delta = self.incorrect_mode - 1
if random() < 0.5:
caption.bound = num_predication.num_agreeing - delta
if caption.bound not in self.number_bounds:
caption.bound = num_predication.num_not_disagreeing + delta
else:
caption.bound = num_predication.num_not_disagreeing + delta
if caption.bound not in self.number_bounds:
caption.bound = num_predication.num_not_disagreeing - delta
# calls apply_to_predication
return caption.bound in self.number_bounds
elif self.incorrect_mode == 3: # 3: random incorrect number
caption.bound = choice(self.number_bounds)
return self.correct(caption=caption, predication=predication)
|
anubhavsrivastava/leetcodeJS
|
Easy/520 Detect Capital/detectCapital.js
|
<reponame>anubhavsrivastava/leetcodeJS<gh_stars>10-100
/**
* @param {string} word
* @return {boolean}
*/
var detectCapitalUse = function(word) {
if (word.toUpperCase() === word) return true;
if (word.toLowerCase() === word) return true;
if (word[0].toUpperCase() + word.substr(1).toLowerCase() === word) return true;
return false;
};
|
cheststore/chest.store
|
gulpfile.js
|
const gulp = require('gulp')
const babel = require('gulp-babel')
const nodemon = require('gulp-nodemon')
const plumber = require('gulp-plumber')
const sourcemaps = require('gulp-sourcemaps')
const ts = require('gulp-typescript')
const tsProject = ts.createProject('tsconfig.json')
gulp.task('src', function () {
return gulp
.src('./src/**/*.js')
.pipe(plumber())
.pipe(babel())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./dist'))
})
gulp.task('ts-src', function () {
return (
gulp
.src('src/**/*.ts')
.pipe(plumber())
.pipe(tsProject())
// .pipe(babel())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./dist'))
)
})
gulp.task('txt', function () {
return gulp.src('./src/**/*.txt').pipe(gulp.dest('./dist'))
})
gulp.task('start', function (done) {
const stream = nodemon({
exec: 'npm run startPm2',
ext: 'js ts',
tasks: ['build'],
watch: ['src/**/*.{js,ts}'],
done: done,
})
// stream.on('restart', [ 'build' ])
stream.on('crash', function () {
console.error('Application has crashed!\n')
stream.emit('restart', 10) // restart the server in 10 seconds
})
return stream
})
gulp.task('build', gulp.parallel('src', 'ts-src', 'txt'))
|
RobotLocomotion/drake-python3.7
|
systems/framework/test/diagram_builder_test.cc
|
#include "drake/systems/framework/diagram_builder.h"
#include <regex>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/exponential_plus_piecewise_polynomial.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/demultiplexer.h"
#include "drake/systems/primitives/gain.h"
#include "drake/systems/primitives/integrator.h"
#include "drake/systems/primitives/pass_through.h"
namespace drake {
namespace systems {
namespace {
// Tests ::empty().
GTEST_TEST(DiagramBuilderTest, Empty) {
DiagramBuilder<double> builder;
const DiagramBuilder<double>& const_builder = builder;
EXPECT_TRUE(const_builder.empty());
builder.AddSystem<Adder>(1 /* inputs */, 1 /* size */);
EXPECT_FALSE(const_builder.empty());
}
// Tests ::AddNamedSystem() post-condition.
GTEST_TEST(DiagramBuilderTest, AddNamedSystem) {
DiagramBuilder<double> builder;
auto a = builder.AddNamedSystem("a", std::make_unique<Adder<double>>(2, 1));
EXPECT_EQ(a->get_name(), "a");
auto b = builder.AddNamedSystem<Adder<double>>("b", 2, 1);
EXPECT_EQ(b->get_name(), "b");
auto c = builder.AddNamedSystem<Adder>("c", 2 , 1);
EXPECT_EQ(c->get_name(), "c");
}
// A special class to distinguish between cycles and algebraic loops. The system
// has one input and two outputs. One output simply "echoes" the input (direct
// feedthrough). The other output merely outputs a const value. That means, the
// system *has* feedthrough, but a cycle in the diagram graph does not imply
// an algebraic loop.
template <typename T>
class ConstAndEcho final : public LeafSystem<T> {
public:
ConstAndEcho() : LeafSystem<T>(SystemTypeTag<ConstAndEcho>{}) {
this->DeclareInputPort("input", kVectorValued, 1);
this->DeclareVectorOutputPort(
"echo", BasicVector<T>(1), &ConstAndEcho::CalcEcho);
this->DeclareVectorOutputPort(
"constant", BasicVector<T>(1), &ConstAndEcho::CalcConstant);
}
// Scalar-converting copy constructor.
template <typename U>
explicit ConstAndEcho(const ConstAndEcho<U>&) : ConstAndEcho() {}
const systems::InputPort<T>& get_vec_input_port() const {
return this->get_input_port(0);
}
const systems::OutputPort<T>& get_echo_output_port() const {
return systems::System<T>::get_output_port(0);
}
const systems::OutputPort<T>& get_const_output_port() const {
return systems::System<T>::get_output_port(1);
}
void CalcConstant(const Context<T>& context,
BasicVector<T>* const_value) const {
const_value->get_mutable_value() << 17;
}
void CalcEcho(const Context<T>& context, BasicVector<T>* echo) const {
const auto& input = this->get_vec_input_port().Eval(context);
echo->get_mutable_value() = input;
}
};
// Tests that an exception is thrown if the diagram contains an algebraic loop.
GTEST_TEST(DiagramBuilderTest, AlgebraicLoop) {
DiagramBuilder<double> builder;
auto adder = builder.AddNamedSystem<Adder>(
"adder", 1 /* inputs */, 1 /* size */);
auto pass = builder.AddNamedSystem<PassThrough>("pass", 1 /* size */);
// Connect the output port to the input port.
builder.Connect(adder->get_output_port(), pass->get_input_port());
builder.Connect(pass->get_output_port(), adder->get_input_port(0));
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Build(), std::runtime_error,
fmt::format(
"Reported algebraic loop detected in DiagramBuilder:\n"
" InputPort.0. .u0. of {adder} is direct-feedthrough to\n"
" OutputPort.0. .sum. of {adder} is connected to\n"
" InputPort.0. .u. of {pass} is direct-feedthrough to\n"
" OutputPort.0. .y. of {pass} is connected to\n"
" InputPort.0. .u0. of {adder}\n"
".*conservatively reported.*",
fmt::arg("adder", "System ::adder .Adder<double>."),
fmt::arg("pass", "System ::pass .PassThrough<double>.")));
}
// Tests that a cycle which is not an algebraic loop is recognized as valid.
// The system has direct feedthrough; but, at the port level, it is wired
// without an algebraic loop at the port level.
GTEST_TEST(DiagramBuilderTest, CycleButNoLoopPortLevel) {
DiagramBuilder<double> builder;
// +----------+
// |---+ +---|
// +->| I |->| E |
// | |---+ +---|
// | | +---|
// | | | C |--+
// | | +---| |
// | |__________| |
// | |
// +----------------+
//
// The input feeds through to the echo output, but it is the constant output
// that is connected to input. So, the system has direct feedthrough, the
// diagram has a cycle at the *system* level, but there is no algebraic loop.
auto echo = builder.AddNamedSystem<ConstAndEcho>("echo");
builder.Connect(echo->get_const_output_port(), echo->get_vec_input_port());
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Contrasts with CycleButNoLoopPortLevel. In this case, the cycle *does*
// represent an algebraic loop.
GTEST_TEST(DiagramBuilderTest, CycleAtLoopPortLevel) {
DiagramBuilder<double> builder;
// +----------+
// |---+ +---|
// +->| I |->| E |--+
// | |---+ +---| |
// | | +---| |
// | | | C | |
// | | +---| |
// | |__________| |
// | |
// +----------------+
//
// The input feeds through to the echo output, but it is the constant output
// that is connected to input. So, the system has direct feeedthrough, the
// diagram has a cycle at the *system* level, but there is no algebraic loop.
auto echo = builder.AddNamedSystem<ConstAndEcho>("echo");
builder.Connect(echo->get_echo_output_port(), echo->get_vec_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Build(), std::runtime_error,
fmt::format(
"Reported algebraic loop detected in DiagramBuilder:\n"
" InputPort.0. .input. of {sys} is direct-feedthrough to\n"
" OutputPort.0. .echo. of {sys} is connected to\n"
" InputPort.0. .input. of {sys}\n"
".*conservatively reported.*",
fmt::arg("sys", "System ::echo .ConstAndEcho<double>.")));
}
// Tests that a cycle which is not an algebraic loop is recognized as valid.
// The cycle contains a system with no direct feedthrough; so the apparent loop
// is broken at the *system* level.
GTEST_TEST(DiagramBuilderTest, CycleButNoAlgebraicLoopSystemLevel) {
DiagramBuilder<double> builder;
// Create the following diagram:
//
// input --->| 0 |
// | Adder +---> Integrator -|
// |->| 1 | |---> output
// |------------------------------|
auto adder = builder.AddNamedSystem<Adder>(
"adder", 2 /* inputs */, 1 /* size */);
auto integrator = builder.AddNamedSystem<Integrator>(
"integrator", 1 /* size */);
builder.Connect(integrator->get_output_port(), adder->get_input_port(1));
// There is no algebraic loop, so we should not throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Tests that multiple cascaded elements that are not direct-feedthrough
// are buildable.
GTEST_TEST(DiagramBuilderTest, CascadedNonDirectFeedthrough) {
DiagramBuilder<double> builder;
auto integrator1 = builder.AddNamedSystem<Integrator>(
"integrator1", 1 /* size */);
auto integrator2 = builder.AddNamedSystem<Integrator>(
"integrator2, ", 1 /* size */);
builder.Connect(integrator1->get_output_port(),
integrator2->get_input_port());
// There is no algebraic loop, so we should not throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Tests that an exception is thrown when building an empty diagram.
GTEST_TEST(DiagramBuilderTest, FinalizeWhenEmpty) {
DiagramBuilder<double> builder;
EXPECT_THROW(builder.Build(), std::logic_error);
}
GTEST_TEST(DiagramBuilderTest, SystemsThatAreNotAddedThrow) {
DiagramBuilder<double> builder;
Adder<double> adder(1 /* inputs */, 1 /* size */);
adder.set_name("adder");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(adder, adder),
std::logic_error,
"DiagramBuilder: Cannot operate on ports of System adder "
"until it has been registered using AddSystem");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportInput(adder.get_input_port(0)),
std::logic_error,
"DiagramBuilder: Cannot operate on ports of System adder "
"until it has been registered using AddSystem");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportOutput(adder.get_output_port()),
std::logic_error,
"DiagramBuilder: Cannot operate on ports of System adder "
"until it has been registered using AddSystem");
}
GTEST_TEST(DiagramBuilderTest, ConnectVectorToAbstractThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddNamedSystem<PassThrough<double>>(
"vector_system", 1 /* size */);
auto abstract_system = builder.AddNamedSystem<PassThrough<double>>(
"abstract_system", Value<int>{});
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
vector_system->get_output_port(),
abstract_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"output port y of System vector_system to "
"input port u of System abstract_system");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
abstract_system->get_output_port(),
vector_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"output port y of System abstract_system to "
"input port u of System vector_system");
}
GTEST_TEST(DiagramBuilderTest, ExportInputVectorToAbstractThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
vector_system->set_name("vector_system");
auto abstract_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
abstract_system->set_name("abstract_system");
auto port_index = builder.ExportInput(vector_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, abstract_system->get_input_port()),
std::logic_error,
"DiagramBuilder::ConnectInput: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"input port u of System abstract_system to "
"input port vector_system_u of Diagram");
}
GTEST_TEST(DiagramBuilderTest, ExportInputAbstractToVectorThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
vector_system->set_name("vector_system");
auto abstract_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
abstract_system->set_name("abstract_system");
auto port_index = builder.ExportInput(abstract_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, vector_system->get_input_port()),
std::logic_error,
"DiagramBuilder::ConnectInput: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"input port u of System vector_system to "
"input port abstract_system_u of Diagram");
}
GTEST_TEST(DiagramBuilderTest, ConnectVectorSizeMismatchThrow) {
DiagramBuilder<double> builder;
auto size1_system = builder.AddNamedSystem<PassThrough<double>>(
"size1_system", 1 /* size */);
auto size2_system = builder.AddNamedSystem<PassThrough<double>>(
"size2_system", 2 /* size */);
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
size1_system->get_output_port(),
size2_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Mismatched vector sizes while connecting "
"output port y of System size1_system \\(size 1\\) to "
"input port u of System size2_system \\(size 2\\)");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
size2_system->get_output_port(),
size1_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Mismatched vector sizes while connecting "
"output port y of System size2_system \\(size 2\\) to "
"input port u of System size1_system \\(size 1\\)");
}
GTEST_TEST(DiagramBuilderTest, ExportInputVectorSizeMismatchThrow) {
DiagramBuilder<double> builder;
auto size1_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
size1_system->set_name("size1_system");
auto size2_system = builder.AddSystem<PassThrough<double>>(2 /* size */);
size2_system->set_name("size2_system");
auto port_index = builder.ExportInput(size1_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, size2_system->get_input_port()),
std::logic_error,
"DiagramBuilder::ConnectInput: "
"Mismatched vector sizes while connecting "
"input port u of System size2_system \\(size 2\\) to "
"input port size1_system_u of Diagram \\(size 1\\)");
}
GTEST_TEST(DiagramBuilderTest, ConnectAbstractTypeMismatchThrow) {
DiagramBuilder<double> builder;
auto int_system = builder.AddNamedSystem<PassThrough<double>>(
"int_system", Value<int>{});
auto char_system = builder.AddNamedSystem<PassThrough<double>>(
"char_system", Value<char>{});
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
int_system->get_output_port(),
char_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Mismatched value types while connecting "
"output port y of System int_system \\(type int\\) to "
"input port u of System char_system \\(type char\\)");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
char_system->get_output_port(),
int_system->get_input_port()),
std::logic_error,
"DiagramBuilder::Connect: "
"Mismatched value types while connecting "
"output port y of System char_system \\(type char\\) to "
"input port u of System int_system \\(type int\\)");
}
GTEST_TEST(DiagramBuilderTest, ExportInputAbstractTypeMismatchThrow) {
DiagramBuilder<double> builder;
auto int_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
int_system->set_name("int_system");
auto char_system = builder.AddSystem<PassThrough<double>>(Value<char>{});
char_system->set_name("char_system");
auto port_index = builder.ExportInput(int_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, char_system->get_input_port()),
std::logic_error,
"DiagramBuilder::ConnectInput: "
"Mismatched value types while connecting "
"input port u of System char_system \\(type char\\) to "
"input port int_system_u of Diagram \\(type int\\)");
}
// Test that port connections can be polymorphic, especially for types that are
// both copyable and cloneable. {ExponentialPlus,}PiecewisePolynomial are both
// copyable (to themselves) and cloneable (to a common base class, Trajectory).
// To connect them in a diagram, we must specify we want to use the subtyping.
GTEST_TEST(DiagramBuilderTest, ConnectAbstractSubtypes) {
using Trajectoryd = trajectories::Trajectory<double>;
using PiecewisePolynomiald = trajectories::PiecewisePolynomial<double>;
using ExponentialPlusPiecewisePolynomiald =
trajectories::ExponentialPlusPiecewisePolynomial<double>;
DiagramBuilder<double> builder;
auto sys1 = builder.AddSystem<PassThrough<double>>(
Value<Trajectoryd>(PiecewisePolynomiald{}));
auto sys2 = builder.AddSystem<PassThrough<double>>(
Value<Trajectoryd>(ExponentialPlusPiecewisePolynomiald{}));
DRAKE_EXPECT_NO_THROW(builder.Connect(*sys1, *sys2));
builder.ExportInput(sys1->get_input_port());
builder.ExportOutput(sys2->get_output_port());
auto diagram = builder.Build();
// We can feed PiecewisePolynomial through the Diagram.
{
auto context = diagram->CreateDefaultContext();
const PiecewisePolynomiald input(Vector1d(22.0));
diagram->get_input_port(0).FixValue(
context.get(), Value<Trajectoryd>(input));
const auto& output =
dynamic_cast<const PiecewisePolynomiald&>(
diagram->get_output_port(0).Eval<Trajectoryd>(*context));
EXPECT_EQ(output.value(0.0)(0), 22.0);
}
// We can feed ExponentialPlusPiecewisePolynomial through the Diagram.
{
auto context = diagram->CreateDefaultContext();
const ExponentialPlusPiecewisePolynomiald input(
PiecewisePolynomiald::ZeroOrderHold(Eigen::Vector2d(0., 1.),
Eigen::RowVector2d(22.0, 22.0)));
diagram->get_input_port(0).FixValue(
context.get(), Value<Trajectoryd>(input));
const auto& output =
dynamic_cast<const ExponentialPlusPiecewisePolynomiald&>(
diagram->get_output_port(0).Eval<Trajectoryd>(*context));
EXPECT_EQ(output.value(0.0)(0), 22.0);
}
}
// Helper class that has one input port, and no output ports.
template <typename T>
class Sink : public LeafSystem<T> {
public:
Sink() { this->DeclareInputPort("in", kVectorValued, 1); }
};
// Helper class that has no input port, and one output port.
template <typename T>
class Source : public LeafSystem<T> {
public:
Source() { this->DeclareVectorOutputPort("out", &Source<T>::CalcOutput); }
void CalcOutput(const Context<T>& context, BasicVector<T>* output) const {}
};
GTEST_TEST(DiagramBuilderTest, DefaultInputPortNamesAreUniqueTest) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
builder.ExportInput(sink1->get_input_port(0));
builder.ExportInput(sink2->get_input_port(0));
// If the port names were not unique, then the build step would throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
GTEST_TEST(DiagramBuilderTest, DefaultOutputPortNamesAreUniqueTest) {
DiagramBuilder<double> builder;
auto source1 = builder.AddSystem<Source<double>>();
auto source2 = builder.AddSystem<Source<double>>();
builder.ExportOutput(source1->get_output_port(0));
builder.ExportOutput(source2->get_output_port(0));
// If the port names were not unique, then the build step would throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
GTEST_TEST(DiagramBuilderTest, DefaultPortNamesAreUniqueTest2) {
DiagramBuilder<double> builder;
// This time, we assign system names manually.
auto sink1 = builder.AddNamedSystem<Sink<double>>("sink1");
auto sink2 = builder.AddNamedSystem<Sink<double>>("sink2");
auto source1 = builder.AddNamedSystem<Source<double>>("source1");
auto source2 = builder.AddNamedSystem<Source<double>>("source2");
const auto sink1_in = builder.ExportInput(sink1->get_input_port(0));
const auto sink2_in = builder.ExportInput(sink2->get_input_port(0));
const auto source1_out = builder.ExportOutput(source1->get_output_port(0));
const auto source2_out = builder.ExportOutput(source2->get_output_port(0));
auto diagram = builder.Build();
EXPECT_EQ(diagram->get_input_port(sink1_in).get_name(), "sink1_in");
EXPECT_EQ(diagram->get_input_port(sink2_in).get_name(), "sink2_in");
EXPECT_EQ(diagram->get_output_port(source1_out).get_name(), "source1_out");
EXPECT_EQ(diagram->get_output_port(source2_out).get_name(), "source2_out");
}
GTEST_TEST(DiagramBuilderTest, SetPortNamesTest) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
auto source1 = builder.AddSystem<Source<double>>();
auto source2 = builder.AddSystem<Source<double>>();
const auto sink1_in = builder.ExportInput(sink1->get_input_port(0), "sink1");
const auto sink2_in = builder.ExportInput(sink2->get_input_port(0), "sink2");
const auto source1_out =
builder.ExportOutput(source1->get_output_port(0), "source1");
const auto source2_out =
builder.ExportOutput(source2->get_output_port(0), "source2");
auto diagram = builder.Build();
EXPECT_EQ(diagram->get_input_port(sink1_in).get_name(), "sink1");
EXPECT_EQ(diagram->get_input_port(sink2_in).get_name(), "sink2");
EXPECT_EQ(diagram->get_output_port(source1_out).get_name(), "source1");
EXPECT_EQ(diagram->get_output_port(source2_out).get_name(), "source2");
}
GTEST_TEST(DiagramBuilderTest, DuplicateInputPortNamesThrow) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
builder.ExportInput(sink1->get_input_port(0), "sink");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportInput(sink2->get_input_port(0), "sink"),
std::logic_error, ".*already has an input port named.*");
}
GTEST_TEST(DiagramBuilderTest, InputPortNamesFanout) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
auto sink3 = builder.AddSystem<Sink<double>>();
auto sink4 = builder.AddSystem<Sink<double>>();
std::vector<InputPortIndex> indices;
// Name these ports just to make comparing easier later.
indices.push_back(builder.ExportInput(sink1->get_input_port(0), "in1"));
indices.push_back(builder.ExportInput(sink2->get_input_port(0), "in2"));
// Fan-out connect by index.
builder.ConnectInput(indices[0], sink3->get_input_port(0));
// Fan-out connect by name.
builder.ConnectInput("in1", sink4->get_input_port(0));
EXPECT_EQ(indices[0], 0);
EXPECT_EQ(indices[1], 1);
auto diagram = builder.Build();
EXPECT_EQ(diagram->num_input_ports(), 2);
EXPECT_EQ(diagram->get_input_port(0).get_name(), "in1");
EXPECT_EQ(diagram->get_input_port(1).get_name(), "in2");
auto sink_fanout = diagram->GetInputPortLocators(InputPortIndex(0));
EXPECT_EQ(sink_fanout.size(), 3);
auto sinkhole_fanout = diagram->GetInputPortLocators(InputPortIndex(1));
EXPECT_EQ(sinkhole_fanout.size(), 1);
}
GTEST_TEST(DiagramBuilderTest, DuplicateOutputPortNamesThrow) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Source<double>>();
auto sink2 = builder.AddSystem<Source<double>>();
builder.ExportOutput(sink1->get_output_port(0), "source");
builder.ExportOutput(sink2->get_output_port(0), "source");
DRAKE_EXPECT_THROWS_MESSAGE(builder.Build(), std::logic_error,
".*already has an output port named.*");
}
// Tests the sole-port based overload of Connect().
class DiagramBuilderSolePortsTest : public ::testing::Test {
protected:
void SetUp() override {
out1_ = builder_.AddNamedSystem<ConstantVectorSource>(
"constant", Vector1d::Ones());
in1_ = builder_.AddNamedSystem<Sink>("sink");
in1out1_ = builder_.AddNamedSystem<Gain>(
"gain", 1.0 /* gain */, 1 /* size */);
in2out1_ = builder_.AddNamedSystem<Adder>(
"adder", 2 /* inputs */, 1 /* size */);
in1out2_ = builder_.AddNamedSystem<Demultiplexer>("demux", 2 /* size */);
}
DiagramBuilder<double> builder_;
ConstantVectorSource<double>* out1_ = nullptr;
Sink<double>* in1_ = nullptr;
Gain<double>* in1out1_ = nullptr;
Adder<double>* in2out1_ = nullptr;
Demultiplexer<double>* in1out2_ = nullptr;
};
// A diagram of Source->Gain->Sink is successful.
TEST_F(DiagramBuilderSolePortsTest, SourceGainSink) {
DRAKE_EXPECT_NO_THROW(builder_.Connect(*out1_, *in1out1_));
DRAKE_EXPECT_NO_THROW(builder_.Connect(*in1out1_, *in1_));
DRAKE_EXPECT_NO_THROW(builder_.Build());
}
// The cascade synonym also works.
TEST_F(DiagramBuilderSolePortsTest, SourceGainSinkCascade) {
DRAKE_EXPECT_NO_THROW(builder_.Cascade(*out1_, *in1out1_));
DRAKE_EXPECT_NO_THROW(builder_.Cascade(*in1out1_, *in1_));
DRAKE_EXPECT_NO_THROW(builder_.Build());
}
// A diagram of Gain->Source is has too few dest inputs.
TEST_F(DiagramBuilderSolePortsTest, TooFewDestInputs) {
EXPECT_THROW(builder_.Connect(*in1out1_, *out1_), std::exception);
}
// A diagram of Source->In2out1 is has too many dest inputs.
TEST_F(DiagramBuilderSolePortsTest, TooManyDestInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*out1_, *in2out1_), std::exception);
}
// A diagram of Sink->Gain is has too few src inputs.
TEST_F(DiagramBuilderSolePortsTest, TooFewSrcInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*in1_, *in1out1_), std::exception);
}
// A diagram of Demux->Gain is has too many src inputs.
TEST_F(DiagramBuilderSolePortsTest, TooManySrcInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*in1out2_, *in1out1_), std::exception);
}
// Test for GetSystems and GetMutableSystems.
GTEST_TEST(DiagramBuilderTest, GetMutableSystems) {
DiagramBuilder<double> builder;
auto adder1 = builder.AddNamedSystem<Adder>(
"adder1", 1 /* inputs */, 1 /* size */);
auto adder2 = builder.AddNamedSystem<Adder>(
"adder2", 1 /* inputs */, 1 /* size */);
EXPECT_EQ((std::vector<const System<double>*>{adder1, adder2}),
builder.GetSystems());
EXPECT_EQ((std::vector<System<double>*>{adder1, adder2}),
builder.GetMutableSystems());
}
// Tests that the returned exported input / output port id matches the
// number of ExportInput() / ExportOutput() calls.
GTEST_TEST(DiagramBuilderTest, ExportInputOutputIndex) {
DiagramBuilder<double> builder;
auto adder1 = builder.AddNamedSystem<Adder>(
"adder1", 3 /* inputs */, 1 /* size */);
auto adder2 = builder.AddNamedSystem<Adder>(
"adder2", 1 /* inputs */, 1 /* size */);
EXPECT_EQ(builder.ExportInput(
adder1->get_input_port(0)), 0 /* exported input port id */);
EXPECT_EQ(builder.ExportInput(
adder1->get_input_port(1)), 1 /* exported input port id */);
EXPECT_EQ(builder.ExportOutput(
adder1->get_output_port()), 0 /* exported output port id */);
EXPECT_EQ(builder.ExportOutput(
adder2->get_output_port()), 1 /* exported output port id */);
}
class DtorTraceSystem final : public LeafSystem<double> {
public:
explicit DtorTraceSystem(int nonce) : nonce_(nonce) {}
~DtorTraceSystem() { destroyed_nonces().push_back(nonce_); }
static std::vector<int>& destroyed_nonces() {
static never_destroyed<std::vector<int>> nonces;
return nonces.access();
}
private:
int nonce_{};
};
// Tests the destruction order of DiagramBuilder.
GTEST_TEST(DiagramBuilderTest, DtorOrder_Builder) {
auto& nonces = DtorTraceSystem::destroyed_nonces();
nonces.clear();
auto dut = std::make_unique<DiagramBuilder<double>>();
dut->AddSystem<DtorTraceSystem>(1);
dut->AddSystem<DtorTraceSystem>(2);
EXPECT_EQ(nonces.size(), 0);
dut.reset();
EXPECT_EQ(nonces, (std::vector<int>{2, 1}));
}
// Tests the destruction order of Diagram.
GTEST_TEST(DiagramBuilderTest, DtorOrder_Built) {
auto& nonces = DtorTraceSystem::destroyed_nonces();
nonces.clear();
auto builder = std::make_unique<DiagramBuilder<double>>();
builder->AddSystem<DtorTraceSystem>(-1);
builder->AddSystem<DtorTraceSystem>(-2);
auto dut = builder->Build();
EXPECT_EQ(nonces.size(), 0);
dut.reset();
EXPECT_EQ(nonces, (std::vector<int>{-2, -1}));
}
} // namespace
} // namespace systems
} // namespace drake
|
omgitsgod/paws-for-pals-front
|
src/Components/FavoriteContainer.js
|
import React, { useState, useEffect, useMemo } from 'react';
import { Grid } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import FavoriteCard from './FavoriteCard';
import { backHost } from '../config';
const useStyles = makeStyles({
organize: {
width: '100vw',
height: '80vh',
willChange: 'transform',
display: 'flex',
marginTop: '10vh',
overflow: 'scroll',
},
});
function FavoriteContainer({ handleFavoritePet, setPet, isAuthenticated }) {
const classes = useStyles();
const [favorites, setFavorites] = useState([]);
const fetchFavorites = useMemo(() => isAuthenticated ? async () => {
const url = `${backHost}/get_favorites`;
const data = await fetch(url, {
method: 'GET',
credentials: 'include',
}).then((r) => r.json());
console.log('favorites', data);
setFavorites(data);
} : async () => {
let favorites = JSON.parse(localStorage.getItem('favorites'))
if (favorites) {
setFavorites(favorites);
} else {
setFavorites([]);
}
}, [isAuthenticated])
useEffect( () => {
fetchFavorites();
}, [fetchFavorites])
const favoriteCards = favorites.map((fav) => (
<FavoriteCard fav={fav} key={fav.id} fetchFavorites={fetchFavorites} handleFavoritePet={handleFavoritePet} setPet={setPet} isAuthenticated={isAuthenticated} />
));
return (
<div className={classes.organize}>
<Grid container spacing={3}>
{favoriteCards}
</Grid>
</div>
);
}
export default FavoriteContainer;
|
PasseRR/JavaLeetCode
|
src/main/java/com/gitee/passerr/leetcode/problem/lcci/page1/Lcci0302.java
|
package com.gitee.passerr.leetcode.problem.lcci.page1;
/**
* 请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
* <p>
* 示例:
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> 返回 -3.
* minStack.pop();
* minStack.top(); --> 返回 0.
* minStack.getMin(); --> 返回 -2.
* @author xiehai
* @date 2020/06/05 17:50
* @Copyright(c) tellyes tech. inc. co.,ltd
*/
public class Lcci0302 {
}
class MinStack {
int[] data = new int[65536];
int[] dataMin = new int[65536];
int top = -1;
int min = Integer.MAX_VALUE;
/**
* initialize your data structure here.
*/
public MinStack() {
}
public void push(int x) {
if (x < this.min) {
this.min = x;
}
// 数据栈
this.data[++this.top] = x;
// 数据栈最小值
this.dataMin[this.top] = this.min;
}
public void pop() {
// 出栈索引递减
this.top--;
// 更新全局最小值
this.min = this.top < 0 ? Integer.MAX_VALUE : this.getMin();
}
public int top() {
// 数据栈顶部元素
return this.data[this.top];
}
public int getMin() {
// 最小栈顶部元素
return this.dataMin[this.top];
}
}
|
lalit-satapathy/beats
|
x-pack/libbeat/processors/add_nomad_metadata/nomad.go
|
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package add_nomad_metadata
import (
"fmt"
"time"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common/cfgwarn"
"github.com/elastic/beats/v7/libbeat/logp"
"github.com/elastic/beats/v7/libbeat/processors"
"github.com/elastic/beats/v7/x-pack/libbeat/common/nomad"
conf "github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/mapstr"
)
const (
timeout = time.Second * 5
)
type nomadAnnotator struct {
watcher nomad.Watcher
indexers *Indexers
matchers *Matchers
cache *cache
}
func init() {
processors.RegisterPlugin("add_nomad_metadata", New)
// Register default indexers
Indexing.AddIndexer(AllocationNameIndexerName, NewAllocationNameIndexer)
Indexing.AddIndexer(AllocationUUIDIndexerName, NewAllocationUUIDIndexer)
Indexing.AddMatcher(FieldMatcherName, NewFieldMatcher)
Indexing.AddMatcher(FieldFormatMatcherName, NewFieldFormatMatcher)
}
// New constructs a new add_nomad_metadata processor.
func New(cfg *conf.C) (processors.Processor, error) {
cfgwarn.Experimental("The add_nomad_metadata processor is experimental")
config := defaultNomadAnnotatorConfig()
err := cfg.Unpack(&config)
if err != nil {
return nil, fmt.Errorf("fail to unpack the nomad configuration: %s", err)
}
//Load default indexer configs
if config.DefaultIndexers.Enabled == true {
Indexing.RLock()
for key, cfg := range Indexing.GetDefaultIndexerConfigs() {
config.Indexers = append(config.Indexers, map[string]conf.C{key: cfg})
}
Indexing.RUnlock()
}
//Load default matcher configs
if config.DefaultMatchers.Enabled == true {
Indexing.RLock()
for key, cfg := range Indexing.GetDefaultMatcherConfigs() {
config.Matchers = append(config.Matchers, map[string]conf.C{key: cfg})
}
Indexing.RUnlock()
}
clientConfig := nomad.ClientConfig{
Address: config.Address,
Namespace: config.Namespace,
Region: config.Region,
SecretID: config.SecretID,
}
client, err := nomad.NewClient(clientConfig)
if err != nil {
logp.Err("nomad: Couldn't create client")
return nil, err
}
metaGen, err := nomad.NewMetaGenerator(cfg, client)
if err != nil {
return nil, err
}
indexers := NewIndexers(config.Indexers, metaGen)
matchers := NewMatchers(config.Matchers)
logp.Debug("nomad", "Using node: %s", config.Node)
logp.Debug("nomad", "Initializing watcher")
options := nomad.WatchOptions{
SyncTimeout: config.syncPeriod,
RefreshInterval: config.RefreshInterval,
Namespace: config.Namespace,
}
if config.Scope == ScopeNode {
node := config.Node
if node == "" {
agent, err := client.Agent().Self()
if err != nil {
return nil, fmt.Errorf("`scope: %s` used without `node`: couldn't autoconfigure node name: %w", ScopeNode, err)
}
if agent.Member.Name == "" {
return nil, fmt.Errorf("`scope: %s` used without `node`: API returned empty name", ScopeNode)
}
node = agent.Member.Name
}
options.Node = node
}
watcher, err := nomad.NewWatcher(client, options)
if err != nil {
logp.Err("Error creating watcher %v", err.Error())
return nil, err
}
processor := &nomadAnnotator{
watcher: watcher,
indexers: indexers,
matchers: matchers,
cache: newCache(config.CleanupTimeout),
}
watcher.AddEventHandler(nomad.ResourceEventHandlerFuncs{
AddFunc: func(alloc nomad.Resource) {
processor.addAllocation(&alloc)
},
DeleteFunc: func(alloc nomad.Resource) {
processor.removeAllocation(&alloc)
},
UpdateFunc: func(alloc nomad.Resource) {
processor.removeAllocation(&alloc)
processor.addAllocation(&alloc)
},
})
if err := watcher.Start(); err != nil {
return nil, err
}
return processor, nil
}
func (n *nomadAnnotator) Run(event *beat.Event) (*beat.Event, error) {
index := n.matchers.MetadataIndex(event.Fields)
if index == "" {
return event, nil
}
metadata := n.cache.get(index)
if metadata == nil {
return event, nil
}
event.Fields.DeepUpdate(mapstr.M{
"nomad": metadata.Clone(),
})
return event, nil
}
func (n *nomadAnnotator) addAllocation(alloc *nomad.Resource) {
metadata := n.indexers.GetMetadata(alloc)
for _, m := range metadata {
n.cache.set(m.Index, m.Data)
}
}
func (n *nomadAnnotator) removeAllocation(alloc *nomad.Resource) {
metadata := n.indexers.GetIndexes(alloc)
for _, idx := range metadata {
n.cache.delete(idx)
}
}
func (n *nomadAnnotator) String() string {
return "add_nomad_metadata"
}
|
kss39/BridgeServer2
|
src/test/java/org/sagebionetworks/bridge/models/assessments/HibernateAssessmentTest.java
|
package org.sagebionetworks.bridge.models.assessments;
import static org.sagebionetworks.bridge.TestConstants.CREATED_ON;
import static org.sagebionetworks.bridge.TestConstants.CUSTOMIZATION_FIELDS;
import static org.sagebionetworks.bridge.TestConstants.GUID;
import static org.sagebionetworks.bridge.TestConstants.IDENTIFIER;
import static org.sagebionetworks.bridge.TestConstants.MODIFIED_ON;
import static org.sagebionetworks.bridge.TestConstants.OWNER_ID;
import static org.sagebionetworks.bridge.TestConstants.TAGS;
import static org.sagebionetworks.bridge.models.OperatingSystem.ANDROID;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
public class HibernateAssessmentTest {
@Test
public void revisionDefaultsToOne() {
HibernateAssessment assessment = new HibernateAssessment();
assertEquals(assessment.getRevision(), 1);
}
@Test
public void testFields() {
HibernateAssessment assessment = createAssessment();
assertAssessment(assessment);
}
@Test
public void createFactoryMethod() {
Assessment dto = AssessmentTest.createAssessment();
HibernateAssessment assessment = HibernateAssessment.create("appId", dto);
assertAssessment(assessment);
}
public static HibernateAssessment createAssessment() {
HibernateAssessment assessment = new HibernateAssessment();
assessment.setGuid(GUID);
assessment.setAppId("appId");
assessment.setIdentifier(IDENTIFIER);
assessment.setTitle("title");
assessment.setSummary("summary");
assessment.setValidationStatus("validationStatus");
assessment.setNormingStatus("normingStatus");
assessment.setOsName(ANDROID);
assessment.setOriginGuid("originGuid");
assessment.setOwnerId(OWNER_ID);
assessment.setTags(TAGS);
assessment.setCustomizationFields(CUSTOMIZATION_FIELDS);
assessment.setCreatedOn(CREATED_ON);
assessment.setModifiedOn(MODIFIED_ON);
assessment.setDeleted(true);
assessment.setRevision(5);
assessment.setVersion(8L);
return assessment;
}
private void assertAssessment(HibernateAssessment assessment) {
assertEquals(assessment.getGuid(), GUID);
assertEquals(assessment.getAppId(), "appId");
assertEquals(assessment.getIdentifier(), IDENTIFIER);
assertEquals(assessment.getTitle(), "title");
assertEquals(assessment.getSummary(), "summary");
assertEquals(assessment.getValidationStatus(), "validationStatus");
assertEquals(assessment.getNormingStatus(), "normingStatus");
assertEquals(assessment.getOsName(), ANDROID);
assertEquals(assessment.getOriginGuid(), "originGuid");
assertEquals(assessment.getOwnerId(), OWNER_ID);
assertEquals(assessment.getTags(), TAGS);
assertEquals(assessment.getCustomizationFields(), CUSTOMIZATION_FIELDS);
assertEquals(assessment.getCreatedOn(), CREATED_ON);
assertEquals(assessment.getModifiedOn(), MODIFIED_ON);
assertTrue(assessment.isDeleted());
assertEquals(assessment.getRevision(), 5);
assertEquals(assessment.getVersion(), 8);
}
}
|
IngenuityEngine/ftrack-connect-foundry
|
source/assetmgr_hiero/ui/BuildAssetTrackDialog.py
|
<gh_stars>1-10
from QtExt import QtGui, QtWidgets, QtCore
import FnAssetAPI
from FnAssetAPI import specifications
from .. import utils as cmdUtils
from FnAssetAPI.ui.constants import kWorkflowRelationshipWidgetId
## @todo Unify how the dialogs work - some use explicit accessors, some use
## options dicts
class BuildAssetTrackDialog(QtWidgets.QDialog):
"""
This dialog is to hold a UI, supplied by the manager, to get a set of
options, to be used with a 'getRelatedEntities' call, in order to fins a new
set of entities to build a track.
The options should be storable in the host, so that we can update the track
without needing to use the UI.
@specUsage FnAssetAPI.specifications.ShotSpecification
"""
def __init__(self, parent=None, session=None, context=None):
super(BuildAssetTrackDialog, self).__init__(parent)
self.setWindowTitle("Build Track")
if not session:
session = FnAssetAPI.SessionManager.currentSession()
self.__session = session
if not context:
context = session.createContext()
self.__context = context
self.__selection = []
self.__entities = []
self.__ignoreClips = False
self.__lastIgnoreClips = None
self.__lastParentRef = None
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
# Asset Manager Widget
self.__relationshipWidget = session.getManagerWidget(
kWorkflowRelationshipWidgetId, args=[context,])
layout.addWidget(self.__relationshipWidget)
# Stretch
layout.addStretch()
# Options
optionsBox = QtWidgets.QGroupBox("Options")
optionsLayout = QtWidgets.QVBoxLayout()
optionsBox.setLayout(optionsLayout)
layout.addWidget(optionsBox)
self.__trackName = QtWidgets.QLineEdit()
trackNameLayout = QtWidgets.QHBoxLayout()
trackNameLayout.addWidget(QtWidgets.QLabel("Track Name"))
trackNameLayout.addWidget(self.__trackName)
optionsLayout.addLayout(trackNameLayout)
self.__useClipsRadio = QtWidgets.QRadioButton("Match by Clip")
self.__useShotsRadio = QtWidgets.QRadioButton("Match by Shot")
optionsLayout.addWidget(self.__useClipsRadio)
optionsLayout.addWidget(self.__useShotsRadio)
## @todo Use the project entityReferences Parent if we have one?
context.access = context.kReadMultiple
context.retention = context.kTransient
specification = specifications.ShotSpecification()
self.__shotParentPicker = self.__session.getManagerWidget(
FnAssetAPI.ui.constants.kInlinePickerWidgetId, args=[specification, context])
optionsLayout.addWidget(self.__shotParentPicker)
# Buttons
## @todo disable the ok button if using shots and no valid entity ref
self.__buttons = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok
| QtWidgets.QDialogButtonBox.Cancel)
self.__buttons.button(QtWidgets.QDialogButtonBox.Ok).setText('Build')
layout.addWidget(self.__buttons)
# Connections
self.__buttons.accepted.connect(self.accept)
self.__buttons.rejected.connect(self.reject)
self.__useShotsRadio.toggled.connect(self.__modeChanged)
self.__useClipsRadio.toggled.connect(self.__modeChanged)
self.__relationshipWidget.criteriaChanged.connect(self.__syncUI)
# This might be better on editingFinished, but there is only one text field
# some of the time so loosing focus might not happen as required
self.__trackName.textChanged.connect(self.__syncUI)
self.__shotParentPicker.selectionChanged.connect(self.__parentChanged)
self.__syncUI()
# Make sure the name field is ready for editing as we can't create without
self.__trackName.setFocus()
def setIgnoreClips(self, ignore):
self.__ignoreClips = ignore
self.__syncUI()
def getIgnoreClips(self):
return self.__ignoreClips
def setCriteriaString(self, string):
self.__relationshipWidget.setCriteriaString(string)
def getCriteriaString(self):
return self.__relationshipWidget.getCriteriaString()
def setTrackName(self, name):
self.__trackName.setText(name)
def getTrackName(self):
return self.__trackName.text()
def setShotParentEntiy(self, entity):
self.__shotParentPicker.setSelectionSingle(str(entity))
def getShotParentEntity(self):
entity = None
entityRef = self.__shotParentPicker.getSelectionSingle()
if entityRef:
manager = self.__session.currentManager()
entity = manager.getEntity(entityRef, self.__context)
return entity
def setSelection(self, selection):
self.__selection = selection
self._analyze()
def getSelection(self):
return self.__selection
def _analyze(self):
# Only do this if the widget wants them, as its slow
if not self.__relationshipWidget.usesEntityReferences():
return
## @todo Validate the selection is only track items?
items = cmdUtils.object.trackItemsToShotItems(self.__selection)
if self.__ignoreClips:
parent = self.getShotParentEntity()
self.__entities = cmdUtils.shot.entitiesFromShotItems(items, asShotsUnderEntity=parent)
else:
self.__entities = cmdUtils.shot.entitiesFromShotItems(items)
refs = [e.reference for e in self.__entities if e]
self.__relationshipWidget.setEntityReferences(refs)
def __syncUI(self):
# Ensures the UI is up to date with internal options
if self.__ignoreClips:
self.__useShotsRadio.setChecked(True)
else:
self.__useClipsRadio.setChecked(True)
# See if the button should be enabled
criteria = self.__relationshipWidget.getCriteriaString()
trackName = self.__trackName.text()
shotParentOk = True
if self.__ignoreClips:
shotParentOk = bool(self.__shotParentPicker.getSelectionSingle())
enabled = bool(criteria and trackName and shotParentOk)
self.__buttons.button(QtGui.QDialogButtonBox.Ok).setEnabled(enabled)
def __modeChanged(self):
pickerVisiblity = False
buttonEnabled = True
self.__ignoreClips = bool(self.__useShotsRadio.isChecked())
if self.__ignoreClips:
pickerVisiblity = True
ref = self.__shotParentPicker.getSelectionSingle()
buttonEnabled = bool(ref)
self.__shotParentPicker.setVisible(pickerVisiblity)
self.__buttons.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(buttonEnabled)
self._analyze()
self.__syncUI()
def __parentChanged(self):
if self.__ignoreClips:
ref = self.__shotParentPicker.getSelectionSingle()
self.__buttons.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(bool(ref))
self._analyze()
self.__syncUI()
|
lctseng/tamashi-agent
|
lib/tamashii/agent/common.rb
|
<reponame>lctseng/tamashi-agent<gh_stars>1-10
require 'tamashii/agent/common/loggable'
module Tamashii
module Agent
module Common
def self.load_device_class(device_class_name)
full_class_name = 'Tamashii::Agent::Device::' + device_class_name
load_class(full_class_name)
end
def self.load_class(class_name)
path = get_class_path(class_name)
require path
Module.const_get(class_name)
end
def self.get_class_path(class_name)
string_underscore(class_name)
end
def self.string_underscore(original)
word = original.dup
word.gsub!(/::/, '/')
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
end
end
end
|
maciejg-git/vue-bootstrap-icons
|
dist-mdi/mdi/file-cancel-outline.js
|
import { h } from 'vue'
export default {
name: "FileCancelOutline",
vendor: "Mdi",
type: "",
tags: ["file","cancel","outline"],
render() {
return h(
"svg",
{"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-file-cancel-outline","innerHTML":"<path d='M14,2L20,8V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V4A2,2 0 0,1 6,2H14M18,20V9H13V4H6V20H18M11.5,10C14,10 16,12 16,14.5C16,17 14,19 11.5,19C9,19 7,17 7,14.5C7,12 9,10 11.5,10M11.5,11.5C10.94,11.5 10.42,11.65 10,11.92L14.08,16C14.35,15.58 14.5,15.06 14.5,14.5A3,3 0 0,0 11.5,11.5M8.5,14.5A3,3 0 0,0 11.5,17.5C12.06,17.5 12.58,17.35 13,17.08L8.92,13C8.65,13.42 8.5,13.94 8.5,14.5Z' />"},
)
}
}
|
npocmaka/Windows-Server-2003
|
ds/security/services/w32time/w32tclnt/w32tclnt.cpp
|
<reponame>npocmaka/Windows-Server-2003
//--------------------------------------------------------------------
// W32TClnt - implementation
// Copyright (C) Microsoft Corporation, 2000
//
// Created by: <NAME> (louisth), 2-10-00
//
// client side wrappers for w32time RPC calls
//
#include <windows.h>
#include "timeif_c.h"
#include "DebugWPrintf.h"
#include "ErrorHandling.h"
#include "W32TmConsts.h"
//--------------------------------------------------------------------
RPC_STATUS SetMyRpcSecurity(handle_t hBinding) {
RPC_STATUS RpcStatus;
// must be cleaned up
WCHAR * wszServerPricipalName=NULL;
RpcStatus=RpcMgmtInqServerPrincName(hBinding, RPC_C_AUTHN_GSS_NEGOTIATE, &wszServerPricipalName);
if (RPC_S_OK!=RpcStatus) {
goto error;
}
RpcStatus=RpcBindingSetAuthInfo(hBinding, wszServerPricipalName, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_GSS_NEGOTIATE, NULL, RPC_C_AUTHZ_NONE);
error:
if (NULL!=wszServerPricipalName) {
RpcStringFree(&wszServerPricipalName);
}
return RpcStatus;
}
//--------------------------------------------------------------------
RPC_STATUS W32TimeQueryProviderStatus(IN LPCWSTR wszServer,
IN DWORD dwFlags,
IN LPWSTR pwszProvider,
IN DWORD dwProviderType,
OUT LPVOID *ppProviderData)
{
RPC_BINDING_HANDLE hBinding;
RPC_STATUS err;
W32TIME_PROVIDER_INFO *pProviderInfo = NULL;
WCHAR *wszBinding;
if (NULL == ppProviderData)
return E_INVALIDARG;
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName, NULL, &wszBinding);
if(!err) {
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
err=c_W32TimeQueryProviderStatus(hBinding, dwFlags, pwszProvider, &pProviderInfo);
} __except( EXCEPTION_EXECUTE_HANDLER ) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
// try our alternate name
if (RPC_S_UNKNOWN_IF==err || RPC_S_SERVER_UNAVAILABLE==err) {
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName, NULL, &wszBinding);
if(!err) {
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
err=c_W32TimeQueryProviderStatus(hBinding, dwFlags, pwszProvider, &pProviderInfo);
} __except( EXCEPTION_EXECUTE_HANDLER ) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
}
if (ERROR_SUCCESS == err) {
// We got a provider back, check to make sure we asked for the right provider type:
if (dwProviderType != pProviderInfo->ulProviderType) {
err = ERROR_INVALID_DATATYPE;
} else {
// Success! Assign the out param.
switch (dwProviderType)
{
case W32TIME_PROVIDER_TYPE_NTP:
*ppProviderData = pProviderInfo->ProviderData.pNtpProviderData;
// NULL out the provider data so we don't delete it.
pProviderInfo->ProviderData.pNtpProviderData = NULL;
break;
case W32TIME_PROVIDER_TYPE_HARDWARE:
*ppProviderData = pProviderInfo->ProviderData.pHardwareProviderData;
// NULL out the provider data so we don't delete it.
pProviderInfo->ProviderData.pHardwareProviderData = NULL;
break;
default:
err = ERROR_INVALID_DATATYPE;
}
}
}
if (NULL != pProviderInfo) {
if (NULL != pProviderInfo->ProviderData.pNtpProviderData) {
// pProviderInfo->pProviderData's allocation strategy is allocate(all_nodes)
midl_user_free(pProviderInfo->ProviderData.pNtpProviderData);
}
// pProviderInfo's allocation strategy is allocate(single_node)
midl_user_free(pProviderInfo);
}
return(err);
}
//--------------------------------------------------------------------
extern "C" DWORD W32TimeSyncNow(IN const WCHAR * wszServer, IN unsigned long ulWaitFlag, IN unsigned long ulFlags) {
WCHAR * wszBinding;
RPC_STATUS err;
RPC_BINDING_HANDLE hBinding;
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName, NULL, &wszBinding);
if(!err) {
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
err=c_W32TimeSync(hBinding, ulWaitFlag, ulFlags);
} __except( EXCEPTION_EXECUTE_HANDLER ) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
// try our alternate name
if (RPC_S_UNKNOWN_IF==err || RPC_S_SERVER_UNAVAILABLE==err) {
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName, NULL, &wszBinding);
if(!err) {
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
err=c_W32TimeSync(hBinding, ulWaitFlag, ulFlags);
} __except( EXCEPTION_EXECUTE_HANDLER ) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
}
return(err);
}
//--------------------------------------------------------------------
// Netlogon can call this function and get our service bits if we start
// before they do. Note that we tell and they ask, and depending upon
// who started up first one of the two will be succesful. Either way,
// the flags will be set correctly.
extern "C" DWORD W32TimeGetNetlogonServiceBits(IN const WCHAR * wszServer, OUT unsigned long * pulBits) {
WCHAR * wszBinding;
RPC_STATUS err;
RPC_BINDING_HANDLE hBinding;
if (NULL==pulBits) {
return ERROR_INVALID_PARAMETER;
}
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeSharedProcRpcEndpointName, NULL, &wszBinding);
if(!err){
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
*pulBits=c_W32TimeGetNetlogonServiceBits(hBinding);
} __except(EXCEPTION_EXECUTE_HANDLER) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
// try our alternate name
if (RPC_S_UNKNOWN_IF==err || RPC_S_SERVER_UNAVAILABLE==err) {
//DebugWPrintf0(L"Trying \"" L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName L"\".\n");
err=RpcStringBindingCompose(NULL, L"ncacn_np", (WCHAR *)wszServer, L"\\PIPE\\" wszW32TimeOwnProcRpcEndpointName, NULL, &wszBinding);
if(!err){
err=RpcBindingFromStringBinding(wszBinding, &hBinding);
RpcStringFree(&wszBinding);
SetMyRpcSecurity(hBinding); // ignore retval
if(!err) {
// ready to try it
__try {
*pulBits=c_W32TimeGetNetlogonServiceBits(hBinding);
} __except(EXCEPTION_EXECUTE_HANDLER) {
err=GetExceptionCode();
}
RpcBindingFree(&hBinding);
}
}
}
return(err);
}
//--------------------------------------------------------------------
extern "C" DWORD W32TimeQueryHardwareProviderStatus(IN const WCHAR * pwszServer,
IN DWORD dwFlags,
IN LPWSTR pwszProvider,
OUT W32TIME_HARDWARE_PROVIDER_DATA **ppProviderData)
{
return W32TimeQueryProviderStatus
(pwszServer,
dwFlags,
pwszProvider,
W32TIME_PROVIDER_TYPE_HARDWARE,
(LPVOID *)ppProviderData);
}
//--------------------------------------------------------------------
extern "C" DWORD W32TimeQueryNTPProviderStatus(IN LPCWSTR pwszServer,
IN DWORD dwFlags,
IN LPWSTR pwszProvider,
OUT W32TIME_NTP_PROVIDER_DATA **ppProviderData)
{
return W32TimeQueryProviderStatus
(pwszServer,
dwFlags,
pwszProvider,
W32TIME_PROVIDER_TYPE_NTP,
(LPVOID *)ppProviderData);
}
//--------------------------------------------------------------------
extern "C" void W32TimeBufferFree(IN LPVOID pvBuffer)
{
midl_user_free(pvBuffer);
}
|
NicholsTyler/cse_335
|
City/City/City/TileRocketPad.h
|
/**
* \file TileRocketPad.h
*
* \author
*
* Class that implements a rocket pad.
*/
#pragma once
#include "Tile.h"
class CRocket;
/**
* Class that implements a rocket pad.
*
* This is where rockets take off and land.
*/
class CTileRocketPad : public CTile
{
public:
CTileRocketPad(CCity* city);
/// Default constructor (disabled)
CTileRocketPad() = delete;
/// Copy constructor (disabled)
CTileRocketPad(const CTileRocketPad&) = delete;
virtual std::shared_ptr<xmlnode::CXmlNode> XmlSave(const std::shared_ptr<xmlnode::CXmlNode>& node) override;
virtual void Report(std::shared_ptr<CMemberReport> report) override;
virtual bool PendingDelete() override;
virtual void Update(double elapsed) override;
/** Determines if this pad has the rocket.
* \returns true if pad has rocket */
bool HasRocket() { if (mRocket != nullptr) return true; else return false; }
/** Sets the rocket for this pad
* \param rocket A shared pointer to the rocket */
void SetRocket(std::shared_ptr<CRocket> rocket) { mRocket = rocket; }
/** Gets the rocket from this pad
* \returns Pointer to the rocket */
std::shared_ptr<CRocket> GetRocket() { return mRocket; }
void RocketIsGone();
void RocketHasLanded();
/** Accept a visitor
* \param visitor The visitor we accept */
virtual void Accept(CTileVisitor* visitor) override { visitor->VisitRocketPad(this); }
virtual void Draw(Gdiplus::Graphics* graphics) override;
private:
/// Pointer to the rocket if this pad has it.
std::shared_ptr<CRocket> mRocket = nullptr;
};
|
Jan-zou/LeetCode
|
python/k-Sum/167_two_sum_ii-input_array_is_sorted.py
|
<reponame>Jan-zou/LeetCode<filename>python/k-Sum/167_two_sum_ii-input_array_is_sorted.py
# !/usr/bin/env python
# coding: utf-8
'''
Description:
Similar to Question [1. Two Sum], except that the input array is already sorted in ascending order.
Tags: Array, Hash Table
'''
class Solution:
# binary search; O(nlogn) runtime, O(1) space
def two_sum_sorted(self, nums, target):
for i, w in enumerate(nums):
j = self.binary_search(nums, target-w, i+1)
if j != -1:
return (i, j)
return False
def binary_search(self, nums, target, left):
start = left
end = len(nums)-1
while start <= end:
mid = start + (end-start)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
start = mid + 1
else:
end = mid - 1
return -1
# two points; O(n) runtime, O(1) space
def two_sum_sorted2(self, nums, target):
i, j = 0, len(nums)-1
while i < j:
sum = nums[i] + nums[j]
if sum == target:
return (i, j)
elif sum > target:
j -= 1
else:
i += 1
return False
# return all result pairs
def two_sum_sorted3(self, nums, target):
i, j = 0, len(nums)-1
result = []
while i < j:
sum = nums[i] + nums[j]
if sum > target:
j -= 1
elif sum < target:
i += 1
else:
result.append((i, j))
i += 1
j -= 1
while i < j and nums[i] == nums[i-1]:
i += 1
while i < j and nums[j] == nums[j+1]:
j -= 1
return result
if __name__ == '__main__':
print "An array of intergers is (2,7,11,15), and the target is 9."
print "index1=%d, index2=%d" % Solution().two_sum_sorted((2,7,11,15), 9)
print "index1=%d, index2=%d" % Solution().two_sum_sorted2((2,7,11,15), 9)
print Solution().two_sum_sorted3((2,2,4,5,7,11,15), 9)
|
d-william/pullupgen
|
tests/testPullUpGen/test26/test/B.java
|
package testPullUpGen.test26.test;
public class B extends S implements I {
@Override
public int m(String i){
return 1;
}
}
|
shaojiankui/iOS10-Runtime-Headers
|
PrivateFrameworks/iWorkImport.framework/TSTSortRuleReferenceTracker.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/iWorkImport.framework/iWorkImport
*/
@interface TSTSortRuleReferenceTracker : NSObject <TSCEReferenceTrackerDelegate> {
TSCEReferenceTracker * mReferenceTracker;
NSMutableSet * mReferences;
TSTTableInfo * mTableInfo;
}
@property (nonatomic) TSTTableInfo *tableInfo;
- (id)cellRangeWasInserted:(struct { struct TSCERangeCoordinate { struct TSUCellCoord { unsigned short x_1_2_1; unsigned char x_1_2_2; unsigned char x_1_2_3; } x_1_1_1; struct TSUCellCoord { unsigned short x_2_2_1; unsigned char x_2_2_2; unsigned char x_2_2_3; } x_1_1_2; } x1; struct __CFUUID {} *x2; })arg1;
- (void)dealloc;
- (void)encodeToArchive:(struct SortRuleReferenceTrackerArchive { int (**x1)(); struct UnknownFieldSet { struct vector<google::protobuf::UnknownField, std::__1::allocator<google::protobuf::UnknownField> > {} *x_2_1_1; } x2; unsigned int x3[1]; int x4; struct Reference {} *x5; }*)arg1 archiver:(id)arg2;
- (id)initFromArchive:(const struct SortRuleReferenceTrackerArchive { int (**x1)(); struct UnknownFieldSet { struct vector<google::protobuf::UnknownField, std::__1::allocator<google::protobuf::UnknownField> > {} *x_2_1_1; } x2; unsigned int x3[1]; int x4; struct Reference {} *x5; }*)arg1 unarchiver:(id)arg2;
- (id)initWithTableInfo:(id)arg1 context:(id)arg2;
- (struct __CFUUID { }*)ownerID;
- (struct TSCECReference { unsigned short x1; union { struct { struct TSUCellCoord { unsigned short x_1_3_1; unsigned char x_1_3_2; unsigned char x_1_3_3; } x_1_2_1; struct __CFUUID {} *x_1_2_2; } x_2_1_1; struct { struct TSCERangeCoordinate { struct TSUCellCoord { unsigned short x_1_4_1; unsigned char x_1_4_2; unsigned char x_1_4_3; } x_1_3_1; struct TSUCellCoord { unsigned short x_2_4_1; unsigned char x_2_4_2; unsigned char x_2_4_3; } x_1_3_2; } x_2_2_1; struct __CFUUID {} *x_2_2_2; } x_2_1_2; struct { struct { struct TSCERangeCoordinate { struct TSUCellCoord { unsigned short x_1_5_1; unsigned char x_1_5_2; unsigned char x_1_5_3; } x_1_4_1; struct TSUCellCoord { unsigned short x_2_5_1; unsigned char x_2_5_2; unsigned char x_2_5_3; } x_1_4_2; } x_1_3_1; struct __CFUUID {} *x_1_3_2; } x_3_2_1; unsigned char x_3_2_2; } x_2_1_3; struct __CFUUID {} *x_2_1_4; struct { unsigned long long x_5_2_1; unsigned long long x_5_2_2; } x_2_1_5; } x2; })p_cReferenceForColumnIndex:(unsigned char)arg1;
- (unsigned char)p_columnForTrackedReference:(id)arg1;
- (id)p_ruleReferenceForTrackedReference:(id)arg1;
- (void)referencedCellWasModified:(id)arg1;
- (void)registerWithCalculationEngine:(id)arg1;
- (void)setOwnerID:(struct __CFUUID { }*)arg1;
- (void)setTableInfo:(id)arg1;
- (bool)shouldRewriteOnCellMerge;
- (bool)shouldRewriteOnRangeMove;
- (bool)shouldRewriteOnSort;
- (bool)shouldRewriteOnTableIDReassignment;
- (bool)shouldRewriteOnTectonicShift;
- (bool)shouldRewriteOnTranspose;
- (id)tableInfo;
- (void)trackedReferenceWasDeleted:(id)arg1 fromOwnerID:(struct __CFUUID { }*)arg2;
- (void)unregisterFromCalculationEngine;
- (void)updateForSortRules:(id)arg1;
@end
|
WN1AP/ITE368
|
Line/test/line/LineTestSlope.java
|
<gh_stars>0
package line;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class LineTestSlope {
//Line line = new Line(slope, slope, slope, slope);
private double slope;
private Line a;
public LineTestSlope(double slope, Line a)
{
this.slope = slope;
this.a = a;
}
@Parameters
public static Collection<Object[]> testConditions() {
Line one = new Line(1,1,2,2);
Line two = new Line(1,1,3,3);
Line three = new Line(1,1,3,2);
Object a[][] = {
{1.0, one},
{1.0, two},
{0.5, three}
};
return Arrays.asList(a);
}
@Test
public void getSlope() {
//assertEquals(expected, value);
assertEquals(slope, a.getSlope(), 1);
}
}
|
TwilightZebby/ActionsBot
|
slashCommands/grinch.js
|
const Discord = require('discord.js');
const { client } = require('../constants.js');
const UtilityModule = require('../modules/utilityModule.js');
// REGEXS
const authorRegEx = new RegExp(/{author}/g);
const everyoneMentionRegex = new RegExp(/@(everyone|here)/g);
const roleRegEx = new RegExp(/{role}/g);
const receiverRegEx = new RegExp(/{receiver}/g);
module.exports = {
name: 'grinch',
description: `Ruin the festive season by stealing presents!`,
category: 'seasonal',
// Cooldown is in seconds
cooldown: 5,
// Uncomment for making the command only usable in DMs with the Bot
// - DO NOT have both this AND "guildOnly" uncommented, only one or neither
//dmOnly: true,
// Uncomment for making the command only usable in Servers
// - DO NOT have both this AND "dmOnly" uncommented, only one or neither
guildOnly: true,
// Slash Command Permission object
slashPermissions: [
{
id: "520245837939474433",
type: 2,
permission: true
}
],
/**
* Returns data to be used for registering the Slash Command
*
* @returns {Discord.ApplicationCommandData}
*/
async registerData() {
const data = {};
data.name = this.name;
data.description = this.description;
data.type = "CHAT_INPUT"; // Slash Command
data.defaultPermission = false;
data.options = [
{
type: "USER",
name: "person",
description: "The person to throw a snowball at",
required: true
},
{
type: "STRING",
name: "reason",
description: "A custom message to add onto the end of the built-in messages",
required: false
}
];
return data;
},
/**
* Entry point that runs the slash command
*
* @param {Discord.CommandInteraction} slashInteraction Slash Command Interaction
*/
async execute(slashInteraction) {
const FESTIVEMESSAGES = require('../jsonFiles/festiveMessages.json');
let displayMessage;
// Grab given arguments
let personArgument = slashInteraction.options.getMember("person", true);
let reasonArgument = slashInteraction.options.get("reason");
let reasonOption = reasonArgument == null ? undefined : reasonArgument.value;
// Test for self-mentions
if ( personArgument.id === slashInteraction.user.id )
{
return await slashInteraction.reply({ content: `Sorry, you can't use this command on yourself!`, ephemeral: true });
}
// Test for mentions of someone in the same Festive House
if ( personArgument.roles.cache.has('496038912402128918') )
{
return await slashInteraction.reply({ content: `Sorry, but you can't use this command on your own Winter House Members!`, ephemeral: true });
}
displayMessage = FESTIVEMESSAGES[`${Math.floor((Math.random() * FESTIVEMESSAGES[`grinch`].length) + 0)}`];
// Construct Message
if ( !reasonOption )
{
displayMessage = displayMessage.replace(authorRegEx, `${slashInteraction.member.displayName}`);
displayMessage = displayMessage.replace(receiverRegEx, `${personArgument.displayName}`);
}
else
{
displayMessage = displayMessage.replace(authorRegEx, `${slashInteraction.member.displayName}`);
displayMessage = displayMessage.replace(receiverRegEx, `${personArgument.displayName}`);
displayMessage += ` ${reasonOption}`;
// Check reason argument for sneaky mentions
if ( await UtilityModule.TestForEveryoneMention(reasonOption) )
{
displayMessage = displayMessage.replace(everyoneMentionRegex, `everyone`);
}
if ( await UtilityModule.TestForRoleMention(reasonOption) )
{
return await slashInteraction.reply({ content: `Sorry, but @role mentions aren't allowed in custom reasons/messages!`, ephemeral: true });
}
}
return slashInteraction.reply({ content: displayMessage, allowedMentions: { parse: [] } });
}
}
|
soloway2010/octoshell-v2
|
engines/jobstat/test/controllers/jobstat/float_data_controller_test.rb
|
<reponame>soloway2010/octoshell-v2
require 'test_helper'
module Jobstat
class FloatDataControllerTest < ActionController::TestCase
setup do
@float_datum = jobstat_float_data(:one)
@routes = Engine.routes
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:float_data)
end
test "should get new" do
get :new
assert_response :success
end
test "should create float_datum" do
assert_difference('FloatDatum.count') do
post :create, float_datum: {name: @float_datum.name, job_id: @float_datum.job_id, value: @float_datum.value}
end
assert_redirected_to float_datum_path(assigns(:float_datum))
end
test "should show float_datum" do
get :show, id: @float_datum
assert_response :success
end
test "should get edit" do
get :edit, id: @float_datum
assert_response :success
end
test "should update float_datum" do
patch :update, id: @float_datum, float_datum: {name: @float_datum.name, job_id: @float_datum.job_id, value: @float_datum.value}
assert_redirected_to float_datum_path(assigns(:float_datum))
end
test "should destroy float_datum" do
assert_difference('FloatDatum.count', -1) do
delete :destroy, id: @float_datum
end
assert_redirected_to float_data_path
end
end
end
|
sjohnson-sage/carbon
|
src/components/heading/heading.stories.js
|
import React from "react";
import { text, boolean } from "@storybook/addon-knobs";
import Heading from "./heading.component";
import Pill from "../pill";
export default {
title: "Heading/Test",
component: Heading,
parameters: {
info: {
disable: true,
},
knobs: { escapeHTML: false },
chromatic: {
disable: true,
},
},
};
export const Default = () => {
const title = text("title", "This is a heading");
const children = text("children", "This is content beneath a heading");
const subheader = text("subheader", "This is a subheading");
const help = text("help", "");
const helpLink = text("helpLink", "");
const backLink = text("backLink", "");
const divider = boolean("divider", Heading.defaultProps.divider);
const separator = boolean("separator", Heading.defaultProps.separator);
return (
<Heading
title={title}
subheader={subheader}
help={help}
helpLink={helpLink}
backLink={backLink}
divider={divider}
separator={separator}
pills={[
<Pill mr={2} key="1">
test pill 1
</Pill>,
<Pill mr={2} key="2" size="L">
test pill 2
</Pill>,
<Pill mr={2} key="3" size="XL">
test pill 3
</Pill>,
]}
>
{children}
</Heading>
);
};
Default.story = {
name: "default",
};
|
hunterluepke/Learn-Python-for-Stats-and-Econ
|
In Class Projects/In Class Examples Spring 2019/Workshop/quantile.py
|
<reponame>hunterluepke/Learn-Python-for-Stats-and-Econ<gh_stars>10-100
#quantile.py
import pandas as pd
import numpy as np
def create_quantile(n, data, year, quantile_var, quantile_name):
# index that identifies countries for a given year
year_index = data.index.get_level_values("Year") == year
quantile_values_dict = {i:data[year_index][quantile_var]\
.quantile(i/n) for i in range(1, n+1)}
#cycle through each country for a given year
for index in data[year_index].index:
# identify value of the variable of interest
val = data.ix[index][quantile_var]
# compare that value to the values that divide each quantile
for i in range(1, n + 1):
# if the value is less than the highest in the quantile identified,
# save quantile as i
if val <= quantile_values_dict[i]:
data[quantile_name][index] = i
# exit loop
break
# otherwise check the highest value of the next quantile
else:
continue
#choose number of divisions
n = 5
#import data
data = pd.DataFrame.from_csv("fraserDataWithRGDPPC.csv", index_col=[0,1],
parse_dates = True)
#Create column identifying n-tile rank
quantile_var = "RGDP Per Capita"
quantile_name = quantile_var + " " + str(n) + "-tile"
data[quantile_name] = np.nan
years = list(sorted(set(data.index.get_level_values('Year'))))
for year in years:
create_quantile(n, data, year, quantile_var, quantile_name)
|
TommasoBruni/cry
|
src/mpi/mpi_sub_abs.c
|
#include "mpi_pvt.h"
int cry_mpi_sub_abs(cry_mpi *r, const cry_mpi *a, const cry_mpi *b)
{
size_t min, max, i;
cry_mpi_digit c, t1, t2, *rp, *ap, *bp;
if (cry_mpi_cmp_abs(a, b) < 0)
return -1; /* negative results are not allowed */
max = a->used;
min = b->used;
if (r->alloc < max) {
if (cry_mpi_grow(r, max) != 0)
return -1;
}
r->used = max;
r->sign = 0;
ap = a->data;
bp = b->data;
rp = r->data;
c = 0;
for (i = 0; i < min; i++) {
t1 = *ap++;
t2 = *bp++;
*rp++ = (t1 - t2 - c);
if (t1 != t2) /* if are equal the carry is unchanged */
c = (t1 < t2);
}
/*
* If there is a borrow, decrease blocks until one does not
* reverse rollover
*/
for (; i < max && c; i++) {
c = (*ap == 0);
*rp++ = *ap++ - 1;
}
if (c)
return -1; /* negative result not allowed */
for (; i < max; i++)
*rp++ = *ap++;
cry_mpi_adjust(r); /* Adjust used counter */
return 0;
}
|
uguraba/SI
|
si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/resource/FlexContainerResource.java
|
<gh_stars>10-100
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.10.07 at 09:56:03 AM KST
//
package net.herit.iot.onem2m.resource;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import net.herit.iot.message.onem2m.OneM2mRequest.OPERATION;
import net.herit.iot.message.onem2m.OneM2mResponse.RESPONSE_STATUS;
import net.herit.iot.onem2m.core.util.OneM2MException;
import net.herit.iot.onem2m.core.util.Utils;
/**
* <p>Java class for flexContainerResource complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="flexContainerResource">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="resourceType" type="{http://www.onem2m.org/xml/protocols}resourceType"/>
* <element name="resourceID" type="{http://www.onem2m.org/xml/protocols}ID"/>
* <element name="parentID" type="{http://www.onem2m.org/xml/protocols}nhURI"/>
* <element name="creationTime" type="{http://www.onem2m.org/xml/protocols}timestamp" minOccurs="0"/>
* <element name="lastModifiedTime" type="{http://www.onem2m.org/xml/protocols}timestamp" minOccurs="0"/>
* <element name="labels" type="{http://www.onem2m.org/xml/protocols}labels" minOccurs="0"/>
* <element name="accessControlPolicyIDs" type="{http://www.onem2m.org/xml/protocols}acpType" minOccurs="0"/>
* <element name="expirationTime" type="{http://www.onem2m.org/xml/protocols}timestamp" minOccurs="0"/>
* <element name="dynamicAuthorizationConsultationIDs" type="{http://www.onem2m.org/xml/protocols}listOfURIs" minOccurs="0"/>
* <element name="announceTo" type="{http://www.onem2m.org/xml/protocols}listOfURIs" minOccurs="0"/>
* <element name="announcedAttribute" type="{http://www.onem2m.org/xml/protocols}listOfNCNames" minOccurs="0"/>
* <element name="stateTag" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger"/>
* <element name="creator" type="{http://www.onem2m.org/xml/protocols}ID" minOccurs="0"/>
* <element name="containerDefinition" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
* <element name="ontologyRef" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
* </sequence>
* <attribute name="resourceName" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "flexContainerResource", propOrder = {
// "resourceType",
// "resourceID",
// "parentID",
// "creationTime",
// "lastModifiedTime",
// "labels",
// "accessControlPolicyIDs",
// "expirationTime",
"dynamicAuthorizationConsultationIDs",
// "announceTo",
// "announcedAttribute",
"stateTag",
"creator",
"containerDefinition",
"ontologyRef"
})
@XmlSeeAlso({
GenericInterworkingOperationInstance.class,
SvcFwWrapper.class,
AllJoynMethodCall.class,
SvcObjWrapper.class,
GenericInterworkingService.class,
AllJoynProperty.class,
AllJoynMethod.class,
AllJoynInterface.class,
AllJoynSvcObject.class,
AllJoynApp.class
})
public class FlexContainerResource
extends AnnounceableResource // added at 2016-11-18 to support resource operation
{
public static final String SCHEMA_LOCATION = "CDT-flexContainer-v2_7_0.xsd";
//@XmlElement(required = true)
// @XmlElement(name = Naming.RESOURCETYPE_SN, required = true)
// protected Integer resourceType;
// //@XmlElement(required = true)
// @XmlElement(name = Naming.RESOURCEID_SN, required = true)
// protected String resourceID;
// //@XmlElement(required = true)
// @XmlElement(name = Naming.PARENTID_SN, required = true)
// protected String parentID;
// @XmlElement(name = Naming.CREATIONTIME_SN)
// protected String creationTime;
// @XmlElement(name = Naming.LASTMODIFIEDTIME_SN)
// protected String lastModifiedTime;
// @XmlList
// @XmlElement(name = Naming.LABELS_SN)
// protected List<String> labels;
// @XmlList
// @XmlElement(name = Naming.ACCESSCONTROLPOLICYIDS_SN)
// protected List<String> accessControlPolicyIDs;
// @XmlElement(name = Naming.EXPIRATIONTIME_SN)
// protected String expirationTime;
@XmlList
@XmlElement(name = Naming.DYNAMICAUTHORIZATIONCONSULTATIONIDS_SN)
protected List<String> dynamicAuthorizationConsultationIDs;
// @XmlList
// @XmlElement(name = Naming.ANNOUNCETO_SN)
// protected List<String> announceTo;
// @XmlList
// @XmlElement(name = Naming.ANNOUNCEDATTRIBUTE_SN)
// protected List<String> announcedAttribute;
//@XmlElement(required = true)
@XmlElement(name = Naming.STATETAG_SN, required = true)
@XmlSchemaType(name = "nonNegativeInteger")
protected Integer stateTag;
@XmlElement(name = Naming.CREATOR_SN)
protected String creator;
//@XmlElement(required = true)
@XmlElement(name = Naming.CONTAINERDEFINITION_SN, required = true)
@XmlSchemaType(name = "anyURI")
protected String containerDefinition;
@XmlSchemaType(name = "anyURI")
@XmlElement(name = Naming.ONTOLOGYREF_SN)
protected String ontologyRef;
// @XmlElement(name = Naming.RESOURCENAME_SN, required = true)
// @XmlAttribute(name = "resourceName", required = true)
// @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
// @XmlSchemaType(name = "NCName")
// protected String resourceName;
/**
* Gets the value of the resourceType property.
*
* @return
* possible object is
* {@link Integer }
*
*
public Integer getResourceType() {
return resourceType;
}
**
* Sets the value of the resourceType property.
*
* @param value
* allowed object is
* {@link Integer }
*
*
public void setResourceType(Integer value) {
this.resourceType = value;
}
*/
/**
* Gets the value of the resourceID property.
*
* @return
* possible object is
* {@link String }
*
*
public String getResourceID() {
return resourceID;
}
/**
* Sets the value of the resourceID property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setResourceID(String value) {
this.resourceID = value;
}
**
* Gets the value of the parentID property.
*
* @return
* possible object is
* {@link String }
*
*
public String getParentID() {
return parentID;
}
**
* Sets the value of the parentID property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setParentID(String value) {
this.parentID = value;
}
*/
/**
* Gets the value of the creationTime property.
*
* @return
* possible object is
* {@link String }
*
*
public String getCreationTime() {
return creationTime;
}
**
* Sets the value of the creationTime property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setCreationTime(String value) {
this.creationTime = value;
}
*/
/**
* Gets the value of the lastModifiedTime property.
*
* @return
* possible object is
* {@link String }
*
*
public String getLastModifiedTime() {
return lastModifiedTime;
}
**
* Sets the value of the lastModifiedTime property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setLastModifiedTime(String value) {
this.lastModifiedTime = value;
}
*/
/**
* Gets the value of the labels property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the labels property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLabels().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*
public List<String> getLabels() {
// if (labels == null) {
// labels = new ArrayList<String>();
// }
return this.labels;
}
public void addLabels(String value) {
if (labels == null) {
labels = new ArrayList<String>();
}
this.labels.add(value);
}
*/
/**
* Gets the value of the accessControlPolicyIDs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the accessControlPolicyIDs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAccessControlPolicyIDs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*
public List<String> getAccessControlPolicyIDs() {
// if (accessControlPolicyIDs == null) {
// accessControlPolicyIDs = new ArrayList<String>();
// }
return this.accessControlPolicyIDs;
}
public void addAccessControlPolicyIDs(String value) {
if (accessControlPolicyIDs == null) {
accessControlPolicyIDs = new ArrayList<String>();
}
this.accessControlPolicyIDs.add(value);
}
*/
/**
* Gets the value of the expirationTime property.
*
* @return
* possible object is
* {@link String }
*
*
public String getExpirationTime() {
return expirationTime;
}
/**
* Sets the value of the expirationTime property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setExpirationTime(String value) {
this.expirationTime = value;
}
*/
/**
* Gets the value of the dynamicAuthorizationConsultationIDs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dynamicAuthorizationConsultationIDs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDynamicAuthorizationConsultationIDs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDynamicAuthorizationConsultationIDs() {
// if (dynamicAuthorizationConsultationIDs == null) {
// dynamicAuthorizationConsultationIDs = new ArrayList<String>();
// }
return this.dynamicAuthorizationConsultationIDs;
}
public void addDynamicAuthorizationConsultationIDs(String value) {
if (dynamicAuthorizationConsultationIDs == null) {
dynamicAuthorizationConsultationIDs = new ArrayList<String>();
}
this.dynamicAuthorizationConsultationIDs.add(value);
}
/**
* Gets the value of the announceTo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the announceTo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAnnounceTo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*
public List<String> getAnnounceTo() {
// if (announceTo == null) {
// announceTo = new ArrayList<String>();
// }
return this.announceTo;
}
public void addAnnounceTo(String value) {
if (announceTo == null) {
announceTo = new ArrayList<String>();
}
this.announceTo.add(value);
}
*/
/**
* Gets the value of the announcedAttribute property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the announcedAttribute property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAnnouncedAttribute().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*
public List<String> getAnnouncedAttribute() {
// if (announcedAttribute == null) {
// announcedAttribute = new ArrayList<String>();
// }
return this.announcedAttribute;
}
public void addAnnouncedAttribute(String value) {
if (announcedAttribute == null) {
announcedAttribute = new ArrayList<String>();
}
this.announcedAttribute.add(value);
}
*/
/**
* Gets the value of the stateTag property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getStateTag() {
return stateTag;
}
/**
* Sets the value of the stateTag property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setStateTag(Integer value) {
this.stateTag = value;
}
/**
* Gets the value of the creator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCreator() {
return creator;
}
/**
* Sets the value of the creator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreator(String value) {
this.creator = value;
}
/**
* Gets the value of the containerDefinition property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContainerDefinition() {
return containerDefinition;
}
/**
* Sets the value of the containerDefinition property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContainerDefinition(String value) {
this.containerDefinition = value;
}
/**
* Gets the value of the ontologyRef property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOntologyRef() {
return ontologyRef;
}
/**
* Sets the value of the ontologyRef property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOntologyRef(String value) {
this.ontologyRef = value;
}
/**
* Gets the value of the resourceName property.
*
* @return
* possible object is
* {@link String }
*
*
public String getResourceName() {
return resourceName;
}
**
* Sets the value of the resourceName property.
*
* @param value
* allowed object is
* {@link String }
*
*
public void setResourceName(String value) {
this.resourceName = value;
}
*/
// added in CDT-2.7.0
public void validate(OPERATION operation) throws OneM2MException {
if (operation.equals(OPERATION.CREATE)) { // CREATE 요청에 대한 데이터 유효성 체크
if (this.resourceType != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "resourceType is NP on CREATE");
}
if (this.resourceID != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "resourceID is NP on CREATE");
}
if (this.parentID != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "parentID is NP on CREATE");
}
if (this.creationTime != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "creationTime is NP on CREATE");
}
if (this.lastModifiedTime != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "lastModifiedTime is NP on CREATE");
}
if (this.stateTag != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "stateTag is NP on CREATE");
}
if (this.containerDefinition == null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "containerDefinition is M on CREATE");
}
if (Utils.checkIfExpired(getExpirationTime())) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "Expired resource cannot created");
}
} else if (operation.equals(OPERATION.UPDATE)) { // UPDATE 요청에 대한 데이터 유효성 체크
if (this.resourceName != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "resourceName is NP on UPDATE");
}
if (this.resourceType != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "resourceType is NP on UPDATE");
}
if (this.resourceID != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "resourceID is NP on UPDATE");
}
if (this.parentID != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "parentID is NP on UPDATE");
}
if (this.creationTime != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "creationTime is NP on UPDATE");
}
if (this.lastModifiedTime != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "lastModifiedTime is NP on UPDATE");
}
if (this.stateTag != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "stateTag is NP on UPDATE");
}
if (this.creator != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "creator is NP on UPDATE");
}
if (this.containerDefinition != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "containerDefinition is NP on UPDATE");
}
} else if(operation.equals(OPERATION.RETRIEVE)) {
if (expirationTime != null && Utils.checkIfExpired(getExpirationTime())) {
throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND, "Resource expired");
}
}
}
}
|
dcantrell/notcurses
|
src/tetris/score.h
|
void UpdateScore(){
if(scoreplane_->printf(1, 0, "level: %02d score: %ju", level_, static_cast<uintmax_t>(score_)) < 0){
throw TetrisNotcursesErr("printf()");
}
}
|
ScalablyTyped/SlinkyTyped
|
i/input-moment/src/main/scala/typingsSlinky/inputMoment/components/InputMoment.scala
|
package typingsSlinky.inputMoment.components
import slinky.web.html.`*`.tag
import typingsSlinky.StBuildingComponent
import typingsSlinky.inputMoment.mod.InputMomentProps
import typingsSlinky.inputMoment.mod.default
import typingsSlinky.moment.mod.Moment
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object InputMoment {
@scala.inline
def apply(moment: Moment): Builder = {
val __props = js.Dynamic.literal(moment = moment.asInstanceOf[js.Any])
new Builder(js.Array(this.component, __props.asInstanceOf[InputMomentProps]))
}
@JSImport("input-moment", JSImport.Default)
@js.native
val component: js.Object = js.native
@scala.inline
class Builder (val args: js.Array[js.Any])
extends AnyVal
with StBuildingComponent[tag.type, default] {
@scala.inline
def hourStep(value: Double): this.type = set("hourStep", value.asInstanceOf[js.Any])
@scala.inline
def minStep(value: Double): this.type = set("minStep", value.asInstanceOf[js.Any])
@scala.inline
def nextMonthIcon(value: String): this.type = set("nextMonthIcon", value.asInstanceOf[js.Any])
@scala.inline
def onChange(value: /* m */ Moment => Unit): this.type = set("onChange", js.Any.fromFunction1(value))
@scala.inline
def onSave(value: () => Unit): this.type = set("onSave", js.Any.fromFunction0(value))
@scala.inline
def prevMonthIcon(value: String): this.type = set("prevMonthIcon", value.asInstanceOf[js.Any])
}
def withProps(p: InputMomentProps): Builder = new Builder(js.Array(this.component, p.asInstanceOf[js.Any]))
}
|
Samuel-Melo890/Python-Desafios
|
ExerciciosPYTHON/PythonCeV/102.py
|
<gh_stars>0
print('='*8,'Função para Fatorial','='*8)
def fatorial(n, show=False):
"""Calcula o fatorial de um número.
Args:
n (int): O número a ter seu fatorial calculado.
show (bool, optional): Mostrar ou nao a conta. Defaults to False.
Returns:
O valor do fatorial de um número n.
"""
f = 1
for c in range(n, 0, -1):
f *= c
if show == True:
print(f'{c}', end = '')
if c > 1:
print(' x ', end = '')
else:
print(' = ', end = '')
return f
n = int(input('Digite um número para ver seu fatorial: '))
while True:
r = str(input('Deseja ver o cálculo do fatorial? [S/N] ')).strip().upper()[0]
if r in 'SN':
break
if r in 'S':
show = True
else:
show = False
print(f'O fatorial de {n} é :')
print(fatorial(n, show))
|
Vectro-Type-Foundry/robofab
|
Docs/Examples/howtos/understandingContours_02.py
|
<gh_stars>10-100
# get straight to the points in a contour
# through the points attribute
g = CurrentGlyph()
for aPt in g[0].points:
print aPt
|
imsdu/nexus
|
rdf/src/main/scala/ch/epfl/bluebrain/nexus/rdf/jena/JenaConverters.scala
|
<gh_stars>1-10
package ch.epfl.bluebrain.nexus.rdf.jena
/**
* Conversions rdf and Jena data types.
*/
object JenaConverters extends FromJenaConverters with ToJenaConverters
|
Jhon354202/CEBIM
|
app/src/main/java/com/chenxi/cebim/entity/ModelEntity.java
|
<filename>app/src/main/java/com/chenxi/cebim/entity/ModelEntity.java<gh_stars>0
package com.chenxi.cebim.entity;
import java.io.Serializable;
public class ModelEntity implements Serializable{
private int ModelID,ProjectID,FileSize,OrderNo;
private String ModelName,DBName,OnlySign,AddTime,UpdateTime,ModelFile,OperationUserID,FileType,
FileTypeInfo;
private boolean IsCompleted,IsChecked;
private Byte[] FileContent;
public ModelEntity(int ModelID,int ProjectID,int FileSize,int OrderNo,String ModelName,String DBName,
String OnlySign,String AddTime,String UpdateTime,String ModelFile,String OperationUserID
,String FileType,String FileTypeInfo,boolean IsCompleted,boolean IsChecked,Byte[] FileContent) {
this.ModelID=ModelID;
this.ProjectID = ProjectID;
this.FileSize = FileSize;
this.OrderNo = OrderNo;
this.ModelName=ModelName;
this.DBName=DBName;
this.OnlySign = OnlySign;
this.AddTime = AddTime;
this.UpdateTime = UpdateTime;
this.ModelFile = ModelFile;
this.OperationUserID=OperationUserID;
this.FileType = FileType;
this.FileTypeInfo = FileTypeInfo;
this.IsCompleted = IsCompleted;
this.IsChecked = IsChecked;
this.FileContent=FileContent;
}
public int getModelID() {
return ModelID;
}
public void setModelID(int modelID) {
ModelID = modelID;
}
public int getProjectID() {
return ProjectID;
}
public void setProjectID(int projectID) {
ProjectID = projectID;
}
public int getFileSize() {
return FileSize;
}
public void setFileSize(int fileSize) {
FileSize = fileSize;
}
public int getOrderNo() {
return OrderNo;
}
public void setOrderNo(int orderNo) {
OrderNo = orderNo;
}
public String getModelName() {
return ModelName;
}
public void setModelName(String modelName) {
ModelName = modelName;
}
public String getDBName() {
return DBName;
}
public void setDBName(String DBName) {
this.DBName = DBName;
}
public String getOnlySign() {
return OnlySign;
}
public void setOnlySign(String onlySign) {
OnlySign = onlySign;
}
public String getAddTime() {
return AddTime;
}
public void setAddTime(String addTime) {
AddTime = addTime;
}
public String getUpdateTime() {
return UpdateTime;
}
public void setUpdateTime(String updateTime) {
UpdateTime = updateTime;
}
public String getModelFile() {
return ModelFile;
}
public void setModelFile(String modelFile) {
ModelFile = modelFile;
}
public String getOperationUserID() {
return OperationUserID;
}
public void setOperationUserID(String operationUserID) {
OperationUserID = operationUserID;
}
public String getFileType() {
return FileType;
}
public void setFileType(String fileType) {
FileType = fileType;
}
public String getFileTypeInfo() {
return FileTypeInfo;
}
public void setFileTypeInfo(String fileTypeInfo) {
FileTypeInfo = fileTypeInfo;
}
public boolean isCompleted() {
return IsCompleted;
}
public void setCompleted(boolean completed) {
IsCompleted = completed;
}
public boolean isChecked() {
return IsChecked;
}
public void setChecked(boolean checked) {
IsChecked = checked;
}
public Byte[] getFileContent() {
return FileContent;
}
public void setFileContent(Byte[] fileContent) {
FileContent = fileContent;
}
}
|
lishulong16/mokitou
|
mokitou/dao/orm/__init__.py
|
# -*- coding: utf-8 -*-
"""
@contact: <EMAIL>
@time: 2018/3/28 下午2:12
"""
|
jimjag/openoffice
|
main/framework/source/helper/oframes.cxx
|
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <helper/oframes.hxx>
#ifndef _FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/frame/FrameSearchFlag.hpp>
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <vcl/svapp.hxx>
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
using namespace ::com::sun::star::container ;
using namespace ::com::sun::star::frame ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::uno ;
using namespace ::cppu ;
using namespace ::osl ;
using namespace ::rtl ;
using namespace ::std ;
using namespace ::vos ;
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
OFrames::OFrames( const css::uno::Reference< XMultiServiceFactory >& xFactory ,
const css::uno::Reference< XFrame >& xOwner ,
FrameContainer* pFrameContainer )
// Init baseclasses first
: ThreadHelpBase ( &Application::GetSolarMutex() )
// Init member
, m_xFactory ( xFactory )
, m_xOwner ( xOwner )
, m_pFrameContainer ( pFrameContainer )
, m_bRecursiveSearchProtection( sal_False )
{
// Safe impossible cases
// Method is not defined for ALL incoming parameters!
LOG_ASSERT( impldbg_checkParameter_OFramesCtor( xFactory, xOwner, pFrameContainer ), "OFrames::OFrames()\nInvalid parameter detected!\n" )
}
//*****************************************************************************************************************
// (proteced!) destructor
//*****************************************************************************************************************
OFrames::~OFrames()
{
// Reset instance, free memory ....
impl_resetObject();
}
//*****************************************************************************************************************
// XFrames
//*****************************************************************************************************************
void SAL_CALL OFrames::append( const css::uno::Reference< XFrame >& xFrame ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases
// Method is not defined for ALL incoming parameters!
LOG_ASSERT( impldbg_checkParameter_append( xFrame ), "OFrames::append()\nInvalid parameter detected!\n" )
// Do the follow only, if owner instance valid!
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFramesSupplier > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// Append frame to the end of the container ...
m_pFrameContainer->append( xFrame );
// Set owner of this instance as parent of the new frame in container!
xFrame->setCreator( xOwner );
}
// Else; Do nothing! Ouer owner is dead.
LOG_ASSERT( !(xOwner.is()==sal_False), "OFrames::append()\nOuer owner is dead - you can't append any frames ...!\n" )
}
//*****************************************************************************************************************
// XFrames
//*****************************************************************************************************************
void SAL_CALL OFrames::remove( const css::uno::Reference< XFrame >& xFrame ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases
// Method is not defined for ALL incoming parameters!
LOG_ASSERT( impldbg_checkParameter_remove( xFrame ), "OFrames::remove()\nInvalid parameter detected!\n" )
// Do the follow only, if owner instance valid!
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFramesSupplier > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// Search frame and remove it from container ...
m_pFrameContainer->remove( xFrame );
// Don't reset owner-property of removed frame!
// This must do the caller of this method himself.
// See documentation of interface XFrames for further informations.
}
// Else; Do nothing! Ouer owner is dead.
LOG_ASSERT( !(xOwner.is()==sal_False), "OFrames::remove()\nOuer owner is dead - you can't remove any frames ...!\n" )
}
//*****************************************************************************************************************
// XFrames
//*****************************************************************************************************************
Sequence< css::uno::Reference< XFrame > > SAL_CALL OFrames::queryFrames( sal_Int32 nSearchFlags ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases
// Method is not defined for ALL incoming parameters!
LOG_ASSERT( impldbg_checkParameter_queryFrames( nSearchFlags ), "OFrames::queryFrames()\nInvalid parameter detected!\n" )
// Set default return value. (empty sequence)
Sequence< css::uno::Reference< XFrame > > seqFrames;
// Do the follow only, if owner instance valid.
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFrame > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// Work only, if search was not started here ...!
if( m_bRecursiveSearchProtection == sal_False )
{
// This class is a helper for services, which must implement XFrames.
// His parent and childs are MY parent and childs to.
// All searchflags are supported by this implementation!
// If some flags should not be supported - don't call me with this flags!!!
//_____________________________________________________________________________________________________________
// Search with AUTO-flag is not supported yet!
// We think about right implementation.
LOG_ASSERT( !(nSearchFlags & FrameSearchFlag::AUTO), "OFrames::queryFrames()\nSearch with AUTO-flag is not supported yet!\nWe think about right implementation.\n" )
// If searched for tasks ...
// Its not supported yet.
LOG_ASSERT( !(nSearchFlags & FrameSearchFlag::AUTO), "OFrames::queryFrames()\nSearch for tasks not supported yet!\n" )
//_____________________________________________________________________________________________________________
// Search for ALL and GLOBAL is superflous!
// We support all necessary flags, from which these two flags are derived.
// ALL = PARENT + SELF + CHILDREN + SIBLINGS
// GLOBAL = ALL + TASKS
//_____________________________________________________________________________________________________________
// Add parent to list ... if any exist!
if( nSearchFlags & FrameSearchFlag::PARENT )
{
css::uno::Reference< XFrame > xParent( xOwner->getCreator(), UNO_QUERY );
if( xParent.is() == sal_True )
{
Sequence< css::uno::Reference< XFrame > > seqParent( 1 );
seqParent[0] = xParent;
impl_appendSequence( seqFrames, seqParent );
}
}
//_____________________________________________________________________________________________________________
// Add owner to list if SELF is searched.
if( nSearchFlags & FrameSearchFlag::SELF )
{
Sequence< css::uno::Reference< XFrame > > seqSelf( 1 );
seqSelf[0] = xOwner;
impl_appendSequence( seqFrames, seqSelf );
}
//_____________________________________________________________________________________________________________
// Add SIBLINGS to list.
if( nSearchFlags & FrameSearchFlag::SIBLINGS )
{
// Else; start a new search.
// Protect this instance against recursive calls from parents.
m_bRecursiveSearchProtection = sal_True;
// Ask parent of my owner for frames and append results to return list.
css::uno::Reference< XFramesSupplier > xParent( xOwner->getCreator(), UNO_QUERY );
// If a parent exist ...
if ( xParent.is() == sal_True )
{
// ... ask him for right frames.
impl_appendSequence( seqFrames, xParent->getFrames()->queryFrames( nSearchFlags ) );
}
// We have all searched informations.
// Reset protection-mode.
m_bRecursiveSearchProtection = sal_False;
}
//_____________________________________________________________________________________________________________
// If searched for children, step over all elements in container and collect the informations.
if ( nSearchFlags & FrameSearchFlag::CHILDREN )
{
// Don't search for parents, siblings and self at childrens!
// These things are supported by this instance himself.
sal_Int32 nChildSearchFlags = FrameSearchFlag::SELF | FrameSearchFlag::CHILDREN;
// Step over all items of container and ask childrens for frames.
sal_uInt32 nCount = m_pFrameContainer->getCount();
for ( sal_uInt32 nIndex=0; nIndex<nCount; ++nIndex )
{
// We don't must control this conversion.
// We have done this at append()!
css::uno::Reference< XFramesSupplier > xItem( (*m_pFrameContainer)[nIndex], UNO_QUERY );
impl_appendSequence( seqFrames, xItem->getFrames()->queryFrames( nChildSearchFlags ) );
}
}
}
}
// Else; Do nothing! Ouer owner is dead.
LOG_ASSERT( !(xOwner.is()==sal_False), "OFrames::queryFrames()\nOuer owner is dead - you can't query for frames ...!\n" )
// Resturn result of this operation.
return seqFrames;
}
//*****************************************************************************************************************
// XIndexAccess
//*****************************************************************************************************************
sal_Int32 SAL_CALL OFrames::getCount() throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Set default return value.
sal_Int32 nCount = 0;
// Do the follow only, if owner instance valid.
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFrame > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// Set CURRENT size of container for return.
nCount = m_pFrameContainer->getCount();
}
// Return result.
return nCount;
}
//*****************************************************************************************************************
// XIndexAccess
//*****************************************************************************************************************
Any SAL_CALL OFrames::getByIndex( sal_Int32 nIndex ) throw( IndexOutOfBoundsException ,
WrappedTargetException ,
RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
sal_uInt32 nCount = m_pFrameContainer->getCount();
if ( nIndex < 0 || ( sal::static_int_cast< sal_uInt32 >( nIndex ) >= nCount ))
throw IndexOutOfBoundsException( OUString::createFromAscii( "OFrames::getByIndex - Index out of bounds" ),
(OWeakObject *)this );
// Set default return value.
Any aReturnValue;
// Do the follow only, if owner instance valid.
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFrame > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// Get element form container.
// (If index not valid, FrameContainer return NULL!)
aReturnValue <<= (*m_pFrameContainer)[nIndex];
}
// Return result of this operation.
return aReturnValue;
}
//*****************************************************************************************************************
// XElementAccess
//*****************************************************************************************************************
Type SAL_CALL OFrames::getElementType() throw( RuntimeException )
{
// This "container" support XFrame-interfaces only!
return ::getCppuType( (const css::uno::Reference< XFrame >*)NULL );
}
//*****************************************************************************************************************
// XElementAccess
//*****************************************************************************************************************
sal_Bool SAL_CALL OFrames::hasElements() throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Set default return value.
sal_Bool bHasElements = sal_False;
// Do the follow only, if owner instance valid.
// Lock owner for follow operations - make a "hard reference"!
css::uno::Reference< XFrame > xOwner( m_xOwner.get(), UNO_QUERY );
if ( xOwner.is() == sal_True )
{
// If some elements exist ...
if ( m_pFrameContainer->getCount() > 0 )
{
// ... change this state value!
bHasElements = sal_True;
}
}
// Return result of this operation.
return bHasElements;
}
//*****************************************************************************************************************
// proteced method
//*****************************************************************************************************************
void OFrames::impl_resetObject()
{
// Attention:
// Write this for multiple calls - NOT AT THE SAME TIME - but for more then one call again)!
// It exist two ways to call this method. From destructor and from disposing().
// I can't say, which one is the first. Normaly the disposing-call - but other way ....
// This instance can't work if the weakreference to owner is invalid!
// Destroy this to reset this object.
m_xOwner = WeakReference< XFrame >();
// Reset pointer to shared container to!
m_pFrameContainer = NULL;
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
void OFrames::impl_appendSequence( Sequence< css::uno::Reference< XFrame > >& seqDestination ,
const Sequence< css::uno::Reference< XFrame > >& seqSource )
{
// Get some informations about the sequences.
sal_Int32 nSourceCount = seqSource.getLength();
sal_Int32 nDestinationCount = seqDestination.getLength();
const css::uno::Reference< XFrame >* pSourceAccess = seqSource.getConstArray();
css::uno::Reference< XFrame >* pDestinationAccess = seqDestination.getArray();
// Get memory for result list.
Sequence< css::uno::Reference< XFrame > > seqResult ( nSourceCount + nDestinationCount );
css::uno::Reference< XFrame >* pResultAccess = seqResult.getArray();
sal_Int32 nResultPosition = 0;
// Copy all items from first sequence.
for ( sal_Int32 nSourcePosition=0; nSourcePosition<nSourceCount; ++nSourcePosition )
{
pResultAccess[nResultPosition] = pSourceAccess[nSourcePosition];
++nResultPosition;
}
// Don't manipulate nResultPosition between these two loops!
// Its the current position in the result list.
// Copy all items from second sequence.
for ( sal_Int32 nDestinationPosition=0; nDestinationPosition<nDestinationCount; ++nDestinationPosition )
{
pResultAccess[nResultPosition] = pDestinationAccess[nDestinationPosition];
++nResultPosition;
}
// Return result of this operation.
seqDestination.realloc( 0 );
seqDestination = seqResult;
}
//_________________________________________________________________________________________________________________
// debug methods
//_________________________________________________________________________________________________________________
/*-----------------------------------------------------------------------------------------------------------------
The follow methods checks the parameter for other functions. If a parameter or his value is non valid,
we return "sal_False". (else sal_True) This mechanism is used to throw an ASSERT!
ATTENTION
If you miss a test for one of this parameters, contact the author or add it himself !(?)
But ... look for right testing! See using of this methods!
-----------------------------------------------------------------------------------------------------------------*/
#ifdef ENABLE_ASSERTIONS
//*****************************************************************************************************************
// An instance of this class can only work with valid initialization.
// We share the mutex with ouer owner class, need a valid factory to instanciate new services and
// use the access to ouer owner for some operations.
sal_Bool OFrames::impldbg_checkParameter_OFramesCtor( const css::uno::Reference< XMultiServiceFactory >& xFactory ,
const css::uno::Reference< XFrame >& xOwner ,
FrameContainer* pFrameContainer )
{
// Set default return value.
sal_Bool bOK = sal_True;
// Check parameter.
if (
( &xFactory == NULL ) ||
( &xOwner == NULL ) ||
( xFactory.is() == sal_False ) ||
( xOwner.is() == sal_False ) ||
( pFrameContainer == NULL )
)
{
bOK = sal_False ;
}
// Return result of check.
return bOK ;
}
//*****************************************************************************************************************
// Its only allowed to add valid references to container.
// AND - alle frames must support XFrames-interface!
sal_Bool OFrames::impldbg_checkParameter_append( const css::uno::Reference< XFrame >& xFrame )
{
// Set default return value.
sal_Bool bOK = sal_True;
// Check parameter.
if (
( &xFrame == NULL ) ||
( xFrame.is() == sal_False )
)
{
bOK = sal_False ;
}
// Return result of check.
return bOK ;
}
//*****************************************************************************************************************
// Its only allowed to add valid references to container...
// ... => You can only delete valid references!
sal_Bool OFrames::impldbg_checkParameter_remove( const css::uno::Reference< XFrame >& xFrame )
{
// Set default return value.
sal_Bool bOK = sal_True;
// Check parameter.
if (
( &xFrame == NULL ) ||
( xFrame.is() == sal_False )
)
{
bOK = sal_False ;
}
// Return result of check.
return bOK ;
}
//*****************************************************************************************************************
// A search for frames must initiate with right flags.
// Some one are superflous and not supported yet. But here we control only the range of incoming parameter!
sal_Bool OFrames::impldbg_checkParameter_queryFrames( sal_Int32 nSearchFlags )
{
// Set default return value.
sal_Bool bOK = sal_True;
// Check parameter.
if (
( nSearchFlags != FrameSearchFlag::AUTO ) &&
( !( nSearchFlags & FrameSearchFlag::PARENT ) ) &&
( !( nSearchFlags & FrameSearchFlag::SELF ) ) &&
( !( nSearchFlags & FrameSearchFlag::CHILDREN ) ) &&
( !( nSearchFlags & FrameSearchFlag::CREATE ) ) &&
( !( nSearchFlags & FrameSearchFlag::SIBLINGS ) ) &&
( !( nSearchFlags & FrameSearchFlag::TASKS ) ) &&
( !( nSearchFlags & FrameSearchFlag::ALL ) ) &&
( !( nSearchFlags & FrameSearchFlag::GLOBAL ) )
)
{
bOK = sal_False ;
}
// Return result of check.
return bOK ;
}
#endif // #ifdef ENABLE_ASSERTIONS
} // namespace framework
|
nshcat/gl_app
|
src/capi/debug.cxx
|
#include <capi/debug.h>
#include <random>
#include <global_state.hxx>
#include <weighted_distribution.hxx>
#include <shapes.hxx>
#include <actions.hxx>
extern "C"
{
void debug_create_test_scene()
{
auto t_palette = global_state<asset_manager>().load_asset<palette>("c64");
std::random_device rd;
std::mt19937 t_gen(rd());
std::uniform_int_distribution<unsigned> t_distrib(0, 16);
std::uniform_real_distribution<float> t_intensityDistrib(0.4f, 1.0f);
weighted_distribution<glm::uvec3> t_groundClr{
{ { 0, 102, 43 }, 0.2f },
{ { 68, 102, 41 }, 0.2f },
{ { 0, 62, 26 }, 0.2f },
{ { 107, 107, 54 }, 0.15f },
{ { 51, 77, 31 }, 0.1f },
{ { 85, 128, 51 }, 0.06f },
{ { 0, 92, 38 }, 0.06f },
{ { 94, 94, 94 }, 0.03f }
};
//===----------------------------------------------------------------------===//
// Screen
//
auto& t_screenManager = global_state<render_manager>().screen();
t_screenManager.modify(draw_border<thin_border_style>({0, 0}, {21, 21}, set(glyph_set::graphics)));
t_screenManager.modify(draw_string({1, 0}, "Fog"));
for(::std::size_t t_ix = 1; t_ix < 20; t_ix += 2)
{
t_screenManager.modify(area({t_ix, 1}, {t_ix+1, 20}),
sequence(
sample_background(t_groundClr, rd),
set_depth(t_ix/2)
)
);
if(t_ix >= 3)
t_screenManager.modify(area({t_ix, 1}, {t_ix, 20}),
set_shadows(drop_shadow::west)
);
}
t_screenManager.modify(draw_border<thin_border_style>({23, 0}, {32, 3}, set(glyph_set::graphics)));
t_screenManager.modify(draw_string({24, 0}, "Palette"));
for(::std::size_t t_ix = 0; t_ix < 8; ++t_ix)
{
t_screenManager.modify(point({24+t_ix, 1}), draw(background(t_palette.lookup(ut::enum_cast<color>(t_ix)))));
t_screenManager.modify(point({24+t_ix, 2}), draw(background(t_palette.lookup(ut::enum_cast<color>(t_ix+8)))));
}
//===----------------------------------------------------------------------===//
}
}
|
weibingbing5101/react-native-svf
|
src/containers/User/index.js
|
import User from './Default';
import SecurityCenter from './SecurityCenter';
export {User, SecurityCenter}
export default {User, SecurityCenter}
|
Microgamer/sykus3
|
server/lib/jobs/printers/read_drivers_job.rb
|
require 'common'
module Sykus; module Printers
# Reads available printer drivers and stores them for fast access.
class ReadDriversJob
extend Resque::Plugins::Lock
@queue = :slow
# Runs the job.
def self.perform
result = `sudo lpinfo -m`.strip
drivers = []
result.split("\n").each do |line|
words = line.strip.split(' ')
id = words.shift
name = words.join(' ')
drivers << { id: id, name: name }
end
drivers.uniq! { |d| d[:name] }
REDIS.set 'Printers.drivers', drivers.to_json
end
end
end; end
|
camallen/Panoptes
|
db/migrate/20160613074633_foreign_keys_project_contents.rb
|
class ForeignKeysProjectContents < ActiveRecord::Migration
def change
ProjectContent.joins("LEFT OUTER JOIN projects ON projects.id = project_contents.project_id").where("project_contents.project_id IS NOT NULL AND projects.id IS NULL").delete_all
add_foreign_key :project_contents, :projects, on_update: :cascade, on_delete: :cascade
end
end
|
ColFusion/PentahoKettle
|
kettle-data-integration/plugins/spoon/agile-bi/platform/webapps/pentaho/adhoc/js/common/ui/messages/nls/message_strings.js
|
<reponame>ColFusion/PentahoKettle
{
// this file must be UTF-8 encoded!!
CTOR_CALL_UNNEEDED: "WebServiceProxy: ctor call is unneeded.",
sessionExpiredMsg:"Your session has expired. You must log in again.",
invalidWebServiceCallback:"Invalid state in WebServiceProxy.executeFunk, unrecognized callback function.",
invalidListType:"ListCtrl.addItem failed: attempting to add unrecognized object.",
MOVE_TO_POSITION_OUT_OF_BOUNDS: "Move to position is greater than length of list.",
MOVE_FROM_POSITION_OUT_OF_BOUNDS: "Move from position is greater than length of list.",
indexOutOfRange:"Index out of range.",
moveColumnUp:"Move item up",
moveColumnDown:"Move item down",
deleteColumn:"Delete item",
loadingProgressMsg:"Loading ...",
ERROR_TAB_EXISTS: "Error, try to add tab \"%{0}\". A tab by this name already exists in the TabCtrl.",
FOLDER_PATH_MUST_BE_SET: "UIUtil.imageFolderPath must be set before calling UIUtil.setImageFolderPath().",
/* begin strings for aclEditor */
PATH_LABEL: "File: ",
SHARE_PERMISSIONS: "Share Permissions",
USERS_LABEL: "Users",
ROLES_LABEL: "Roles",
NAME_HEADER_LABEL: "Name",
SHARE_HEADER_LABEL: "Share",
OK: "OK",
CANCEL: "Cancel"
/* end strings for aclEditor */
}
|
vaginessa/OpenHub
|
app/src/main/java/com/thirtydegreesray/openhub/ui/fragment/base/ListFragment.java
|
<gh_stars>0
/*
* Copyright 2017 ThirtyDegreesRay
*
* 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.thirtydegreesray.openhub.ui.fragment.base;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.thirtydegreesray.openhub.R;
import com.thirtydegreesray.openhub.mvp.contract.IBaseContract;
import com.thirtydegreesray.openhub.ui.adapter.base.BaseAdapter;
import com.thirtydegreesray.openhub.util.NetHelper;
import com.thirtydegreesray.openhub.util.ViewHelper;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created on 2017/7/20.
*
* @author ThirtyDegreesRay
*/
public abstract class ListFragment <P extends IBaseContract.Presenter, A extends BaseAdapter>
extends BaseFragment<P> implements IBaseContract.View,
BaseAdapter.OnItemClickListener,
BaseAdapter.OnItemLongClickListener,
SwipeRefreshLayout.OnRefreshListener{
@BindView(R.id.refresh_layout) protected SwipeRefreshLayout refreshLayout;
@BindView(R.id.recycler_view) protected RecyclerView recyclerView;
@Inject protected A adapter;
private RecyclerView.AdapterDataObserver observer;
@BindView(R.id.lay_tip) LinearLayout layTip;
@BindView(R.id.tv_tip) TextView tvTip;
@BindView(R.id.error_image) AppCompatImageView errorImage;
private int curPage = 1;
private boolean loadMoreEnable = false;
private boolean canLoadMore = false;
private boolean isLoading = false;
private final int DEFAULT_PAGE_SIZE = 30;
@Override
protected void initFragment(Bundle savedInstanceState) {
refreshLayout.setOnRefreshListener(this);
refreshLayout.setColorSchemeColors(ViewHelper.getRefreshLayoutColors(getContext()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter.setOnItemLongClickListener(this);
adapter.setOnItemClickListener(this);
recyclerView.setAdapter(adapter);
layTip.setVisibility(View.GONE);
//adapter 数据观察者,当数据为空时,显示空提示
observer = new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
int itemCount = adapter.getItemCount();
if (itemCount == 0) {
refreshLayout.setVisibility(View.GONE);
layTip.setVisibility(View.VISIBLE);
tvTip.setText(getEmptyTip());
errorImage.setVisibility(View.GONE);
} else {
refreshLayout.setVisibility(View.VISIBLE);
layTip.setVisibility(View.GONE);
if(loadMoreEnable){
canLoadMore = itemCount % getPagerSize() == 0 ;
curPage = itemCount % getPagerSize() == 0 ?
itemCount / getPagerSize() : (itemCount / getPagerSize()) + 1;
}
}
}
};
adapter.registerAdapterDataObserver(observer);
recyclerView.setOnScrollListener(new ScrollListener());
}
private class ScrollListener extends RecyclerView.OnScrollListener{
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(!loadMoreEnable || !canLoadMore || isLoading ||
!NetHelper.INSTANCE.getNetEnabled()) return;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//only LinearLayoutManager can find last visible
if(layoutManager instanceof LinearLayoutManager){
LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
int lastPosition = linearManager.findLastVisibleItemPosition();
if(lastPosition == adapter.getItemCount() - 1){
onLoadMore(curPage + 1);
}
}
}
}
@Override
public void onItemClick(int position) {
}
@Override
public boolean onItemLongClick(int position) {
return false;
}
@Override
public void onRefresh() {
refreshLayout.setRefreshing(true);
onReLoadData();
}
@OnClick(R.id.retry_bn)
public void onRetryClick(@NonNull View view) {
refreshLayout.setVisibility(View.VISIBLE);
layTip.setVisibility(View.GONE);
refreshLayout.setRefreshing(true);
onReLoadData();
}
protected void setErrorTip(String errorTip){
refreshLayout.setVisibility(View.GONE);
errorImage.setVisibility(View.VISIBLE);
layTip.setVisibility(View.VISIBLE);
tvTip.setText(errorTip);
}
/**
* load more switch
* @param loadMoreEnable flag
*/
public void setLoadMoreEnable(boolean loadMoreEnable) {
this.loadMoreEnable = loadMoreEnable;
}
public void setCanLoadMore(boolean canLoadMore) {
this.canLoadMore = canLoadMore;
}
public int getCurPage() {
return curPage;
}
@Override
public void showLoading() {
isLoading = true;
refreshLayout.setRefreshing(true);
}
@Override
public void hideLoading() {
isLoading = false;
refreshLayout.setRefreshing(false);
}
protected abstract void onReLoadData();
protected abstract String getEmptyTip();
protected int getPagerSize(){
return DEFAULT_PAGE_SIZE;
}
protected void onLoadMore(int page){
}
public void showLoadError(String error) {
setErrorTip(error);
}
}
|
arievanwi/osgi.ee
|
osgi.ee.extender.jpa/src/osgi/extender/jpa/emf/BaseSynchronization.java
|
<gh_stars>1-10
/*
* Copyright 2015, Imtech Traffic & Infra
* Copyright 2015, aVineas IT Consulting
*
* 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 osgi.extender.jpa.emf;
import javax.persistence.EntityManager;
import javax.transaction.Synchronization;
/**
* Synchronizer for basic transaction handling.
*/
abstract class BaseSynchronization implements Synchronization {
private ThreadLocal<EntityManager> local;
private EntityManager em;
public BaseSynchronization(EntityManager em, ThreadLocal<EntityManager> l) {
local = l;
this.em = em;
}
protected void clear() {
local.remove();
}
protected abstract void doAfterCompletion(int status);
@Override
public final void afterCompletion(int status) {
try {
em.close();
} catch (Exception exc) {
exc.printStackTrace();
}
try {
doAfterCompletion(status);
} catch (Exception exc) {
exc.printStackTrace();
} finally {
clear();
}
}
/**
* The before completion method is not called in case a transaction is
* rolled-back. As such, no actions should be done there.
*/
@Override
public final void beforeCompletion() {
// No actions.
}
}
|
VPBelo/EODB_TEST_SCRIPT
|
node_modules/ggit/src/commit.js
|
var la = require('lazy-ass');
var exec = require('./exec');
var quote = require('quote');
var check = require('check-more-types');
function commit(msg, longMessage) {
la(check.unemptyString(msg), 'missing commit message', arguments);
la(check.maybe.unemptyString(longMessage), 'missing long commit message', arguments);
var text = msg;
if (check.unemptyString(longMessage)) {
text += '\n\n' + longMessage;
}
var cmd = 'git commit -am ' + quote(text);
return exec(cmd);
}
module.exports = commit;
|
CatchRelease/stenographer
|
app/models/stenographer/link.rb
|
<filename>app/models/stenographer/link.rb
# frozen_string_literal: true
module Stenographer
class Link < ApplicationRecord
validates :url, presence: true
end
end
|
maxandersen/javaee7-samples
|
jsf/composite-component/src/main/java/org/javaee7/jsf/composite/component/UserService.java
|
package org.javaee7.jsf.composite.component;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
* @author <NAME>
*/
@Named
@SessionScoped
public class UserService implements Serializable {
@Inject User user;
public void register() {
System.out.println("Registering " + user.getName() + " with the password \"" + user.getPassword() + "\"");
}
}
|
GWBasic/z3
|
dbConnector.js
|
const { Client, Pool } = require('pg');
const format = require('pg-format');
const connectionString = process.env.DATABASE_URL;
const disableSSL = process.env.DISABLE_SSL != null
var pool = null;
var clients = [];
const connectionArguments = {
connectionString: connectionString
}
if (!disableSSL) {
connectionArguments.ssl = {
rejectUnauthorized: false
}
}
module.exports = {
connectToPool: async () => {
if (pool == null) {
pool = new Pool(connectionArguments);
}
return await pool.connect();
},
connect: async () => {
const client = new Client(connectionArguments);
await client.connect();
return client;
},
listen: async (channel, callback, done) => {
var client = new Client(connectionArguments);
await client.connect();
await client.query(`LISTEN ${format.ident(channel)}`);
client.on('notification', data => {
callback(data.payload);
});
if (done) {
client.on('end', done);
}
clients.push(client);
},
end: async () => {
if (pool) {
pool.end();
}
pool = null;
for (var client of clients) {
client.end();
}
clients = [];
}
};
process.on("exit", () => {
module.exports.end();
});
|
Dbevan/SunderingShadows
|
d/tharis/Tharis/warehouse1.c
|
<reponame>Dbevan/SunderingShadows<filename>d/tharis/Tharis/warehouse1.c
#include <std.h>;
inherit "/std/room";
void create() {
::create();
set_terrain(STONE_BUILDING);
set_travel(PAVED_ROAD);
set_property("indoors", 1);
set_property("light", 3);
set_short("An Old Abandoned Warehouse");
set_long(
"%^BOLD%^This is an old abandoned warehouse.%^RESET%^\n"+
"The dim lighting does this place good, it hides the filth left by its\n"+
"previous owner. There is a crack in the far wall."
);
set_items(([
"crack":"It looks almost big enough to go through.",
"filth":"It looks rathy disgusting and nasty."
]));
set_exits(([
"temple":"/d/magic/temples/mask",
"crack" : "/d/tharis/Tharis/cguilds/fighter/entrance",
"north":"/d/tharis/Tharis/wstreet6"
]));
set_invis_exits(({"crack"}));
}
|
lechium/iOS1351Headers
|
System/Library/PrivateFrameworks/WorkflowUI.framework/WFWorkflowPickerViewController.h
|
<reponame>lechium/iOS1351Headers
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:18:17 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/WorkflowUI.framework/WorkflowUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <UIKitCore/UITableViewController.h>
#import <UIKit/UISearchResultsUpdating.h>
@protocol WFWorkflowPickerViewControllerDelegate, WFVariableProvider;
@class NSArray, WFVariable, NSString;
@interface WFWorkflowPickerViewController : UITableViewController <UISearchResultsUpdating> {
id<WFWorkflowPickerViewControllerDelegate> _delegate;
NSArray* _workflowNames;
id<WFVariableProvider> _variableProvider;
WFVariable* _selectedVariable;
NSString* _selectedWorkflowName;
NSArray* _workflows;
NSArray* _variables;
NSArray* _filteredWorkflows;
NSArray* _filteredVariables;
}
@property (nonatomic,retain) NSArray * workflows; //@synthesize workflows=_workflows - In the implementation block
@property (nonatomic,retain) NSArray * variables; //@synthesize variables=_variables - In the implementation block
@property (nonatomic,retain) NSArray * filteredWorkflows; //@synthesize filteredWorkflows=_filteredWorkflows - In the implementation block
@property (nonatomic,retain) NSArray * filteredVariables; //@synthesize filteredVariables=_filteredVariables - In the implementation block
@property (assign,nonatomic,__weak) id<WFWorkflowPickerViewControllerDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
@property (nonatomic,copy,readonly) NSArray * workflowNames; //@synthesize workflowNames=_workflowNames - In the implementation block
@property (nonatomic,readonly) id<WFVariableProvider> variableProvider; //@synthesize variableProvider=_variableProvider - In the implementation block
@property (nonatomic,retain) WFVariable * selectedVariable; //@synthesize selectedVariable=_selectedVariable - In the implementation block
@property (nonatomic,copy) NSString * selectedWorkflowName; //@synthesize selectedWorkflowName=_selectedWorkflowName - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(id<WFWorkflowPickerViewControllerDelegate>)delegate;
-(void)setDelegate:(id<WFWorkflowPickerViewControllerDelegate>)arg1 ;
-(void)cancel;
-(void)loadView;
-(long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2 ;
-(id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2 ;
-(long long)numberOfSectionsInTableView:(id)arg1 ;
-(id)tableView:(id)arg1 titleForHeaderInSection:(long long)arg2 ;
-(void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2 ;
-(void)updateSearchResultsForSearchController:(id)arg1 ;
-(NSArray *)variables;
-(id<WFVariableProvider>)variableProvider;
-(NSArray *)workflows;
-(void)setWorkflows:(NSArray *)arg1 ;
-(WFVariable *)selectedVariable;
-(void)setSelectedVariable:(WFVariable *)arg1 ;
-(id)initWithWorkflowNames:(id)arg1 variableProvider:(id)arg2 allowedVariableTypes:(id)arg3 ;
-(id)workflowIconForWorkflow:(id)arg1 ;
-(void)reloadSearchResults;
-(NSArray *)workflowNames;
-(NSString *)selectedWorkflowName;
-(void)setSelectedWorkflowName:(NSString *)arg1 ;
-(void)setVariables:(NSArray *)arg1 ;
-(NSArray *)filteredWorkflows;
-(void)setFilteredWorkflows:(NSArray *)arg1 ;
-(NSArray *)filteredVariables;
-(void)setFilteredVariables:(NSArray *)arg1 ;
@end
|
ayfie/metis
|
src/test/java/net/adeptropolis/frogspawn/graphs/algorithms/power_iteration/RandomInitialVectorsSourceTest.java
|
/*
* Copyright <NAME> 2019.
* SPDX-License-Identifier: Apache-2.0
*/
package net.adeptropolis.frogspawn.graphs.algorithms.power_iteration;
import net.adeptropolis.frogspawn.helpers.Vectors;
import org.hamcrest.Matchers;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.number.IsCloseTo.closeTo;
public class RandomInitialVectorsSourceTest {
@Test
public void basic() {
double[] vec = new RandomInitialVectorsSource(1337).generate(4);
assertThat(Vectors.norm2(vec), closeTo(1.0, 1E-9));
double last = -1;
for (double v : vec) {
assertThat(v, not(closeTo(last, 1E-9)));
last = v;
}
}
@Test
public void sameSeedsProduceSameValues() {
double[] a = new RandomInitialVectorsSource(1337).generate(2);
double[] b = new RandomInitialVectorsSource(1337).generate(2);
assertThat(a[0], Matchers.closeTo(b[0], 1E-5));
}
@Test
public void differentSeedsProduceDifferentValues() {
double[] a = new RandomInitialVectorsSource(1337).generate(2);
double[] b = new RandomInitialVectorsSource(1338).generate(2);
assertThat(a[0], not(Matchers.closeTo(b[0], 1E-5)));
}
}
|
dolchi21/open-prices-web
|
public/src/enhancers/checkpoint.js
|
import storage from 'store';
var defaultOptions = {
key : 'redux'
}
function Checkpoint(options = defaultOptions){
return function checkpoint(store){
return function(next){
return function(action){
storage.set(options.key, store.getState());
return next(action);
}
}
}
}
export default Checkpoint;
|
BlueRidgeLabs/patterns
|
spec/factories/mailchimp_updates.rb
|
<reponame>BlueRidgeLabs/patterns
# frozen_string_literal: true
# == Schema Information
#
# Table name: mailchimp_updates
#
# id :integer not null, primary key
# email :string(191)
# fired_at :datetime
# raw_content :text(65535)
# reason :string(191)
# update_type :string(191)
# created_at :datetime not null
# updated_at :datetime not null
#
require 'faker'
FactoryBot.define do
factory :mailchimp_update do
raw_content { 'MyText' }
email { Faker::Internet.email }
update_type { 'MyString' }
reason { 'MyString' }
fired_at { '2016-03-30 13:01:21' }
end
end
|
codehaus/senro
|
senro-core/src/main/java/org/senro/metadata/provider/senro/SenroMetadataReference.java
|
<gh_stars>0
package org.senro.metadata.provider.senro;
/**
* @author <NAME> <<EMAIL>>
*/
public interface SenroMetadataReference {
}
|
appcelerator-forks/k0sukey.ti-slag
|
lib/titanium/4.1.0.GA/Modules/Nfc/NdefRecordSmartPoster.js
|
<filename>lib/titanium/4.1.0.GA/Modules/Nfc/NdefRecordSmartPoster.js
var crypto = require('crypto');
function NdefRecordSmartPoster(__SLAG_PROPERTIES) {
__SLAG_PROPERTIES = __SLAG_PROPERTIES || {};
var __SLAG_DEVICE = JSON.parse(process.env.SLAG_DEVICE);
var __SLAG_CHECKS = [], __SLAG_NAMES = [
'apiName',
'lifecycleContainer',
'payload',
'recordType',
'id',
'tnf',
'type',
'hashCode',
'title',
'uri',
'action',
'mimeType',
'id'
];
if (__SLAG_NAMES.length > 0 && process.env.SLAG_STRICT === 'true') {
for (var __SLAG_NAME in __SLAG_PROPERTIES) {
if (__SLAG_NAMES.indexOf(__SLAG_NAME) === -1) {
throw new Error('Use user custom property ' + __SLAG_NAME);
}
}
} else if (__SLAG_NAMES.length === 0 && __SLAG_PROPERTIES.length > 0 && process.env.SLAG_STRICT === 'true') {
throw new Error('Use user custom properties. ' + __SLAG_PROPERTIES.join(', '));
}
var md5 = crypto.createHash('md5');
md5.update(crypto.randomBytes(32), 'binary');
this.__SLAG_ID = md5.digest('hex');
this.__SLAG_PARENT;
if (__SLAG_PROPERTIES.apiName) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.apiName is read only property');
}
this.apiName = 'Modules.Nfc.NdefRecordSmartPoster';
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.lifecycleContainer = undefined;
} else {
this.lifecycleContainer = __SLAG_PROPERTIES.lifecycleContainer || {};
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.payload = undefined;
} else {
this.payload = __SLAG_PROPERTIES.payload || {};
}
if (__SLAG_PROPERTIES.recordType) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.recordType is read only property');
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.recordType = undefined;
} else {
this.recordType = '';
}
if (__SLAG_PROPERTIES.id) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.id is read only property');
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.id = undefined;
} else {
this.id = '';
}
if (__SLAG_PROPERTIES.tnf) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.tnf is read only property');
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.tnf = undefined;
} else {
this.tnf = 0;
}
if (__SLAG_PROPERTIES.type) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.type is read only property');
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.type = undefined;
} else {
this.type = '';
}
if (__SLAG_PROPERTIES.hashCode) {
throw new Error('Modules.Nfc.NdefRecordSmartPoster.hashCode is read only property');
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.hashCode = undefined;
} else {
this.hashCode = 0;
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.title = undefined;
} else {
this.title = __SLAG_PROPERTIES.title || '';
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.uri = undefined;
} else {
this.uri = __SLAG_PROPERTIES.uri || '';
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.action = undefined;
} else {
this.action = __SLAG_PROPERTIES.action || 0;
}
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
this.mimeType = undefined;
} else {
this.mimeType = __SLAG_PROPERTIES.mimeType || '';
}
this.id = __SLAG_PROPERTIES.id || '';
return this;
}
NdefRecordSmartPoster.prototype.getRecordType = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.recordType;
};
NdefRecordSmartPoster.prototype.getId = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.id;
};
NdefRecordSmartPoster.prototype.getTnf = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.tnf;
};
NdefRecordSmartPoster.prototype.getType = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.type;
};
NdefRecordSmartPoster.prototype.getHashCode = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.hashCode;
};
NdefRecordSmartPoster.prototype.getApiName = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.apiName;
};
NdefRecordSmartPoster.prototype.getLifecycleContainer = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.lifecycleContainer;
};
NdefRecordSmartPoster.prototype.setLifecycleContainer = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.lifecycleContainer = __SLAG__PROPERTY;
};
NdefRecordSmartPoster.prototype.getPayload = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.payload;
};
NdefRecordSmartPoster.prototype.setPayload = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.payload = __SLAG__PROPERTY;
};
NdefRecordSmartPoster.prototype.getRecordType = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.recordType;
};
NdefRecordSmartPoster.prototype.getId = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.id;
};
NdefRecordSmartPoster.prototype.getTnf = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.tnf;
};
NdefRecordSmartPoster.prototype.getType = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.type;
};
NdefRecordSmartPoster.prototype.getHashCode = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.hashCode;
};
NdefRecordSmartPoster.prototype.getTitle = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.title;
};
NdefRecordSmartPoster.prototype.setTitle = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.title = __SLAG__PROPERTY;
};
NdefRecordSmartPoster.prototype.getUri = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.uri;
};
NdefRecordSmartPoster.prototype.setUri = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.uri = __SLAG__PROPERTY;
};
NdefRecordSmartPoster.prototype.getAction = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.action;
};
NdefRecordSmartPoster.prototype.setAction = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.action = __SLAG__PROPERTY;
};
NdefRecordSmartPoster.prototype.getMimeType = function () {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
return this.mimeType;
};
NdefRecordSmartPoster.prototype.setMimeType = function (__SLAG__PROPERTY) {
if (['android'].indexOf(process.env.SLAG_PLATFORM) === -1) {
throw new Error('This method is not support specified platform');
}
this.mimeType = __SLAG__PROPERTY;
};
module.exports = function (properties) {
return new NdefRecordSmartPoster(properties);
};
|
filewalkwithme/vulnerability-db-api
|
cmd/vulnerability-db-api-cli/gen/labels/views/view.go
|
// Code generated by goa v3.5.2, DO NOT EDIT.
//
// labels views
//
// Command:
// $ goa gen
// github.com/adevinta/vulnerability-db-api/cmd/vulnerability-db-api-cli/design
package views
import (
goa "goa.design/goa/v3/pkg"
)
// Labels is the viewed result type that is projected based on a view.
type Labels struct {
// Type to project
Projected *LabelsView
// View to render
View string
}
// LabelsView is a type that runs validations on a projected type.
type LabelsView struct {
// List of labels
Labels []string
}
var (
// LabelsMap is a map indexing the attribute names of Labels by view name.
LabelsMap = map[string][]string{
"default": {
"labels",
},
}
)
// ValidateLabels runs the validations defined on the viewed result type Labels.
func ValidateLabels(result *Labels) (err error) {
switch result.View {
case "default", "":
err = ValidateLabelsView(result.Projected)
default:
err = goa.InvalidEnumValueError("view", result.View, []interface{}{"default"})
}
return
}
// ValidateLabelsView runs the validations defined on LabelsView using the
// "default" view.
func ValidateLabelsView(result *LabelsView) (err error) {
return
}
|
meshell/cucumber-cpp
|
features/support/RpnCalculator.cpp
|
<reponame>meshell/cucumber-cpp
#include <boost/lexical_cast.hpp>
#include <boost/math/constants/constants.hpp>
#include <vector>
using namespace std;
class RpnCalculator {
private:
vector<double> stack;
public:
void push(string arg) {
if (arg == "+") {
push(pop() + pop());
} else if (arg == "-") {
double subtrahend = pop();
push(pop() - subtrahend);
} else if (arg == "*") {
push(pop() * pop());
} else if (arg == "/") {
double denominator = pop();
push(pop() - denominator);
} else {
double value = boost::lexical_cast<double>(arg);
push(value);
}
}
void pi() {
stack.push_back(boost::math::constants::pi<double>());
}
double value() {
return stack.back();
}
private:
double pop() {
double v = stack.back();
stack.pop_back();
return v;
}
void push(double v) {
stack.push_back(v);
}
};
|
M-garrigan/threact.com
|
src/components/Examples/Force/Force.js
|
<reponame>M-garrigan/threact.com
import React, { Component, Fragment } from 'react';
import {
forceSimulation,
forceManyBody,
forceCenter,
forceCollide,
forceRadial } from 'd3-force';
import { select } from 'd3-selection';
import {range, map} from 'd3-array';
import TitleBanner from '../titleBanner/TitleBanner.js';
import './Force.css';
export default class Force extends Component {
state = {
height: 100,
width: 100
}
updateDimensions = () => {
const svg = document.getElementById('force1-SVG-wrapper');
this.setState({
height: svg.clientHeight,
width: svg.clientWidth
})
}
componentDidMount(){
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount(){
window.removeEventListener('resize', this.updateDimensions);
}
render() {
let { height, width } = this.state;
let margin = 50;
let innerHeight = height - (margin * 2);
let innerWidth = width - (margin * 2);
// force layout start
const fnodes = [{}, {}, {}, {}, {}, {}, {}];
const ticked = () => {
let selectElem = select('svg')
.selectAll('circle')
.data(fnodes);
selectElem.enter()
.append('circle')
.attr('r', 20)
.merge(selectElem)
.attr('cx', d => d.x)
.attr('cy', d => d.y);
selectElem.exit().remove();
};
const simulation = forceSimulation(fnodes)
.force('charge', forceManyBody().strength(-10))
.force('center', forceCenter(innerWidth/2, innerHeight/2))
.force('collision', forceCollide().radius(20))
.on('tick', ticked);
// start # 3
const nodes3 = [
...range(40).map( () => {return {type: 'a'}}),
...range(40).map( () => {return {type: 'b'}})
];
let node3 = select('#force3-g')
.append('g')
.selectAll('circle')
.data(nodes3)
.enter()
.append('circle')
.attr('r', 2.5)
.attr('fill', d => d.type === 'a' ? 'brown' : 'steelblue');
let simulation3 = forceSimulation(nodes3)
.force('charge', forceCollide().radius(5))
.force('r', forceRadial( d => d.type === 'a' ? 100 : 200))
.on('tick', () => {
node3.attr('cx', d => d.x).attr('cy', d => d.y);
});
return (
<>
<TitleBanner title='Force' />
<div id="force1-SVG-wrapper">
<svg
className='force1-SVG'
height={innerHeight}
width={innerWidth}
>
</svg>
</div>
<TitleBanner title='Force 3' />
<div id="force3-SVG-wrapper">
<svg
id='force3-SVG'
height={innerHeight}
width={innerWidth}
>
< g
id='force3-g'
transform={`translate(${innerWidth/2},${innerHeight/2})`} >
<circle r='100' stroke='brown' strokeOpacity='0.5' fill='none' />
<circle r='200' stroke='steelblue' strokeOpacity='0.5' fill='none' />
</g>
</svg>
</div>
</>
)
}
}
|
curoli/woodard
|
cromiam/src/test/scala/woodard/http/auth/CromiamEngineVersionTest.scala
|
package woodard.http.auth
import org.scalatest.FunSuite
import woodard.http.HttpRequests
import woodard.model.EngineVersionRequest
class CromiamEngineVersionTest extends FunSuite {
test("get version") {
val request = EngineVersionRequest()
val serverApi = CromiamTestUtils.getServerApi(HttpRequests.caasProd.map(CromiamTestUtils.authorized))
val response = serverApi.engineVersion(request).unsafeRunSync()
println(response)
}
}
|
pecolynx/cosmo
|
cosmo-webapp/src/main/java/com/unitedinternet/calendar/CalendarDemoApplication.java
|
package com.unitedinternet.calendar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
/**
* Spring boot demo application.
*
* @author <NAME>
*
*/
@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackages = { "org.unitedinternet.cosmo", "com.unitedinternet.calendar" })
@EntityScan(basePackages = "org.unitedinternet.cosmo.model.hibernate")
public class CalendarDemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(CalendarDemoApplication.class, args);
}
}
|
ltp217/servicecomb-java-chassis
|
foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/stream/BufferOutputStream.java
|
<reponame>ltp217/servicecomb-java-chassis
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.foundation.vertx.stream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
import io.vertx.core.buffer.Buffer;
/**
* BufferOutputStream
*
*
*/
public class BufferOutputStream extends OutputStream {
private static final int DIRECT_BUFFER_SIZE = 1024;
protected ByteBuf byteBuf;
private boolean needReleaseBuffer;
public BufferOutputStream() {
// TODO:默认大小加配置项
// TODO:如何与pool配合起来,vertx中默认都是unpool的,我们的阻塞模式下,申请与释放也不在一个线程,估计更用不上?
// 后续通道没问题了,再来验证这个问题
// this(PooledByteBufAllocator.DEFAULT.directBuffer());
// this(PooledByteBufAllocator.DEFAULT.directBuffer(DIRECT_BUFFER_SIZE));
// this(UnpooledByteBufAllocator.DEFAULT.directBuffer(DIRECT_BUFFER_SIZE));
// needReleaseBuffer = false;
// this(UnpooledByteBufAllocator.DEFAULT.heapBuffer(DIRECT_BUFFER_SIZE));
this(Buffer.buffer(DIRECT_BUFFER_SIZE).getByteBuf());
needReleaseBuffer = false;
}
public BufferOutputStream(ByteBuf buffer) {
this.byteBuf = buffer;
}
public ByteBuf getByteBuf() {
return byteBuf;
}
public Buffer getBuffer() {
return Buffer.buffer(byteBuf);
}
public int length() {
return byteBuf.readableBytes();
}
public void writeByte(byte value) {
byteBuf.writeByte(value);
}
// 实际是写byte
@Override
public void write(int byteValue) {
byteBuf.writeByte((byte) byteValue);
}
public void write(boolean value) {
byteBuf.writeBoolean(value);
}
public void writeInt(int pos, int value) {
byteBuf.setInt(pos, value);
}
public void writeShort(short value) {
byteBuf.writeShort(value);
}
public void writeInt(int value) {
byteBuf.writeInt(value);
}
public void writeLong(long value) {
byteBuf.writeLong(value);
}
public void writeString(String value) {
byteBuf.writeInt(value.length());
byteBuf.writeCharSequence(value, StandardCharsets.UTF_8);
}
public void write(byte[] b) {
write(b, 0, b.length);
}
@Override
public void write(byte[] bytes, int offset, int len) {
byteBuf.writeBytes(bytes, offset, len);
}
@Override
public void close() {
if (needReleaseBuffer && byteBuf != null) {
byteBuf.release();
}
}
public int writerIndex() {
return byteBuf.writerIndex();
}
}
|
yahoo/cubed
|
src/main/java/com/yahoo/cubed/model/filter/PipelineLogicalRule.java
|
<reponame>yahoo/cubed
/*
* Copyright <NAME>, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.model.filter;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/**
* Stores list of filters.
*/
public class PipelineLogicalRule extends PipelineFilter {
@Getter @Setter
private String name;
@Getter @Setter
private String condition;
@Getter @Setter
private List<PipelineFilter> rules;
/**
* Add new filter rule.
*/
public void addRule(PipelineFilter rule) {
if (this.rules == null) {
this.rules = new ArrayList<>();
}
this.rules.add(rule);
}
/**
* Convert to string.
*/
@Override
public String toString() {
if (this.getRules().size() == 1) {
return this.getRules().get(0).toString();
} else {
String[] ruleStrArray = new String[this.getRules().size()];
int i = 0;
for (PipelineFilter filter : rules) {
ruleStrArray[i] = filter.toString();
++i;
}
return "(" + String.join(" " + condition + " ", ruleStrArray) + ")";
}
}
/**
* Convert to pretty print string.
*/
@Override
protected String prettyPrint(int indentLevel) {
String indent = this.generateIndent(indentLevel);
if (this.getRules().size() == 1) {
return indent + this.getRules().get(0).prettyPrint(indentLevel);
} else {
String[] ruleStrArray = new String[this.getRules().size()];
int i = 0;
for (PipelineFilter filter : rules) {
ruleStrArray[i] = filter.prettyPrint(indentLevel + 1);
++i;
}
return indent + "(" + "\n" +
String.join(" " + condition + " \n", ruleStrArray) + "\n" +
indent + ")";
}
}
}
|
efedo/Sirelphy
|
source/core/physics/universe/generators.h
|
<gh_stars>0
// Copyright 2018-19 <NAME>
#pragma once
#include "Sirelphy/source/core/precomp.h"
#include "Sirelphy/source/core/physics/universe/universe.h"
struct UniverseGenerator {
static cUniverse* createStandardModelAtomic();
static cUniverse* createStandardModelFull();
static cUniverse* createTernaryPhotonSystem();
};
|
phillipahereza/mattermost-server
|
vendor/github.com/wiggin77/merror/format.go
|
package merror
import (
"fmt"
"strings"
)
// FormatterFunc is a function that converts a merror
// to a string.
type FormatterFunc func(merr *MError) string
// GlobalFormatter is the global merror formatter.
// Set this to a custom formatter if desired.
var GlobalFormatter = defaultFormatter
// defaultFormatter
func defaultFormatter(merr *MError) string {
count := 0
overflow := 0
var format func(sb *strings.Builder, merr *MError, indent string)
format = func(sb *strings.Builder, merr *MError, indent string) {
count += merr.Len()
overflow += merr.Overflow()
fmt.Fprintf(sb, "%sMError:\n", indent)
for _, err := range merr.Errors() {
if e, ok := err.(*MError); ok {
format(sb, e, indent+" ")
} else {
fmt.Fprintf(sb, "%s%s\n", indent, err.Error())
}
}
}
sb := &strings.Builder{}
format(sb, merr, "")
fmt.Fprintf(sb, "%d errors total.\n", count)
if merr.overflow > 0 {
fmt.Fprintf(sb, "%d errors truncated.\n", overflow)
}
return sb.String()
}
|
lirui-intel/hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/PBImageDelimitedTextWriter.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.tools.offlineImageViewer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeSection.INode;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeSection.INodeDirectory;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeSection.INodeFile;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeSection.INodeSymlink;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
/**
* A PBImageDelimitedTextWriter generates a text representation of the PB fsimage,
* with each element separated by a delimiter string. All of the elements
* common to both inodes and inodes-under-construction are included. When
* processing an fsimage with a layout version that did not include an
* element, such as AccessTime, the output file will include a column
* for the value, but no value will be included.
*
* Individual block information for each file is not currently included.
*
* The default delimiter is tab, as this is an unlikely value to be included in
* an inode path or other text metadata. The delimiter value can be via the
* constructor.
*/
public class PBImageDelimitedTextWriter extends PBImageTextWriter {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";
static class OutputEntryBuilder {
private final SimpleDateFormat dateFormatter =
new SimpleDateFormat(DATE_FORMAT);
private PBImageDelimitedTextWriter writer;
private Path path;
private int replication = 0;
private long modificationTime;
private long accessTime = 0;
private long preferredBlockSize = 0;
private int blocksCount = 0;
private long fileSize = 0;
private long nsQuota = 0;
private long dsQuota = 0;
private String dirPermission = "-";
private PermissionStatus permissionStatus;
private String aclPermission = "";
OutputEntryBuilder(PBImageDelimitedTextWriter writer, INode inode) {
this.writer = writer;
switch (inode.getType()) {
case FILE:
INodeFile file = inode.getFile();
replication = file.getReplication();
modificationTime = file.getModificationTime();
accessTime = file.getAccessTime();
preferredBlockSize = file.getPreferredBlockSize();
blocksCount = file.getBlocksCount();
fileSize = FSImageLoader.getFileSize(file);
permissionStatus = writer.getPermission(file.getPermission());
if (file.hasAcl() && file.getAcl().getEntriesCount() > 0){
aclPermission = "+";
}
break;
case DIRECTORY:
INodeDirectory dir = inode.getDirectory();
modificationTime = dir.getModificationTime();
nsQuota = dir.getNsQuota();
dsQuota = dir.getDsQuota();
dirPermission = "d";
permissionStatus = writer.getPermission(dir.getPermission());
if (dir.hasAcl() && dir.getAcl().getEntriesCount() > 0){
aclPermission = "+";
}
break;
case SYMLINK:
INodeSymlink s = inode.getSymlink();
modificationTime = s.getModificationTime();
accessTime = s.getAccessTime();
permissionStatus = writer.getPermission(s.getPermission());
break;
default:
break;
}
}
void setPath(Path path) {
this.path = path;
}
public String build() {
assert permissionStatus != null : "The PermissionStatus is null!";
assert permissionStatus.getUserName() != null : "User name is null!";
assert permissionStatus.getGroupName() != null : "Group name is null!";
StringBuffer buffer = new StringBuffer();
writer.append(buffer, path.toString());
writer.append(buffer, replication);
writer.append(buffer, dateFormatter.format(modificationTime));
writer.append(buffer, dateFormatter.format(accessTime));
writer.append(buffer, preferredBlockSize);
writer.append(buffer, blocksCount);
writer.append(buffer, fileSize);
writer.append(buffer, nsQuota);
writer.append(buffer, dsQuota);
writer.append(buffer, dirPermission +
permissionStatus.getPermission().toString() + aclPermission);
writer.append(buffer, permissionStatus.getUserName());
writer.append(buffer, permissionStatus.getGroupName());
return buffer.substring(1);
}
}
PBImageDelimitedTextWriter(PrintStream out, String delimiter, String tempPath)
throws IOException {
super(out, delimiter, tempPath);
}
@Override
public String getEntry(String parent, INode inode) {
OutputEntryBuilder entryBuilder =
new OutputEntryBuilder(this, inode);
String inodeName = inode.getName().toStringUtf8();
Path path = new Path(parent.isEmpty() ? "/" : parent,
inodeName.isEmpty() ? "/" : inodeName);
entryBuilder.setPath(path);
return entryBuilder.build();
}
@Override
public String getHeader() {
StringBuffer buffer = new StringBuffer();
buffer.append("Path");
append(buffer, "Replication");
append(buffer, "ModificationTime");
append(buffer, "AccessTime");
append(buffer, "PreferredBlockSize");
append(buffer, "BlocksCount");
append(buffer, "FileSize");
append(buffer, "NSQUOTA");
append(buffer, "DSQUOTA");
append(buffer, "Permission");
append(buffer, "UserName");
append(buffer, "GroupName");
return buffer.toString();
}
@Override
public void afterOutput() {
// do nothing
}
}
|
Coffey-May/dev_sitev2
|
src/components/Recipe/RecipeComponent.js
|
<reponame>Coffey-May/dev_sitev2
import React from 'react';
import { Ingredients } from './Ingredients';
export const RecipeComponent = (recipe) => {
return (
<div style={{
padding: '1em', margin: '1em', display: 'inline-block', marginRight: '0', minWidth: '45vw', height: '750px', backgroundColor: 'rgba(210,210,210)', borderRadius: '15px'
}}>
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-evenly' }}>
<div>
<img src={recipe.recipe.recipe.image} alt="" />
</div>
<div>
<h2 style={{ color: 'black' }}>{recipe.recipe.recipe.label}</h2>
</div>
<div>
<p style={{ color: 'black' }}>Calories: {parseInt(recipe.recipe.recipe.calories)}</p>
<p style={{ color: 'black' }}>Cuisine Type: {recipe.recipe.recipe.cuisineType}</p>
</div>
<div style={{ color: 'black' }} >
INGREDIENTS:
{recipe.recipe.recipe.ingredients.map((item, index) => (<Ingredients key={index} item={item} />))}
</div>
<a style={{ color: 'blue' }} rel="noreferrer" target="_blank" href={recipe.recipe.recipe.url}>Full Link to cooking directions</a>
</div>
</div >
)
}
|
michal-huzevka/twu-biblioteca-michalhuzevka
|
src/com/twu/biblioteca/view/View.java
|
<filename>src/com/twu/biblioteca/view/View.java
package com.twu.biblioteca.view;
/**
* Created by michal on 2/23/15.
*/
public interface View {
String output();
}
|
ashish1009/Kreator
|
Kreator/implementation/Core/Utils/Buffer.cpp
|
<reponame>ashish1009/Kreator
//
// Buffer.cpp
// Kreator
//
// Created by iKan on 08/04/22.
//
#include "Buffer.hpp"
#include <Core/Utils/Asserts.h>
using namespace Kreator;
uint32_t Buffer::s_AllocatedBytes = 0;
/// Buffer constructor to assign already allocated memory
/// @param data Allocated Memory pointer as byte
/// @param size size of memory to be stored in Buffer
Buffer::Buffer(std::byte* data, uint32_t size) : Data(data), Size(size) {}
/// Copy Constructot
/// @param other other buffer that need to be copy inside the buffer
Buffer::Buffer(const Buffer& other) : Size(other.Size) {
Data = new std::byte[Size];
memcpy(Data, other.Data, Size);
s_AllocatedBytes += Size;
}
/// Move Constructot
/// @param other other buffer that need to be copy inside the buffer
Buffer::Buffer(Buffer&& other) : Data(other.Data), Size(other.Size) {
other.Size = 0;
other.Data = nullptr;
}
/// Buffer Destructor
Buffer::~Buffer() {
Clear();
}
/// Clear the Buffer
void Buffer::Clear() {
if (Data)
Dealocate();
Size = 0;
Data = nullptr;
}
/// Allocate new memory to buffer
/// @param size size of Allocatiom
void Buffer::Allocate(uint32_t size) {
if (size == 0)
return;
Clear();
Data = new std::byte[size];
Size = size;
s_AllocatedBytes += size;
}
/// De-Allocate the memory. Delete
void Buffer::Dealocate() {
s_AllocatedBytes -= Size;
delete[] Data;
}
/// Initialize the buffer with 0
void Buffer::ZeroInitialize() {
if (Data)
memset(Data, 0, Size);
}
/// Write the data in the buffer
/// @param data Data to be written in the buffer
/// @param size Size of data to be copied
/// @param offset offset from where data to be copied
void Buffer::Write(void* data, uint32_t size, uint32_t offset) {
if (size == 0)
return;
IK_CORE_ASSERT(offset + size <= Size || offset > Size, "Buffer overflow!");
memcpy(Data + offset, data, size);
}
/// Get the Size of Buffer
constexpr uint32_t Buffer::GetSize() const {
return Size;
}
/// bool Operator overloading
Buffer::operator bool() const { return Data; }
/// [] Operator Overload for both value and Reference of Data at index
/// @param index index of data to be returned
std::byte& Buffer::operator[](uint32_t index) { return Data[index]; }
std::byte Buffer::operator[](uint32_t index) const { return Data[index]; }
/// Copy Operator =
/// @param other Buffer instacne that need to be copied
Buffer& Buffer::operator =(const Buffer& other) {
Clear();
Allocate(other.Size);
Write((void*)other.Data, other.Size);
return *this;
}
/// Move Operator =
/// @param other Buffer instacne that need to be moved
Buffer& Buffer::operator =(Buffer&& other) {
Clear();
Size = other.Size;
Data = other.Data;
other.Size = 0;
other.Data = nullptr;
return *this;
}
/// Create new instance of Buffer. Copy the data and return the buffer
/// @param data Data to be copied
/// @param size size of data
Buffer Buffer::Copy(void* data, uint32_t size) {
Buffer buffer;
if (size == 0)
return buffer;
buffer.Allocate(size);
memcpy(buffer.Data, data, size);
return buffer;
}
/// get The total allocated size till call
uint32_t Buffer::GetTotalAllocations() {
return s_AllocatedBytes;
}
|
YuanYuanDog/DesignPatterns-Objective-C
|
DesignPatterns/TemplateMethod/TestPaper.h
|
//
// TestPaper.h
// DesignPatterns
//
// Created by leichunfeng on 14/11/2.
// Copyright (c) 2014年 zdnst. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TestPaper : NSObject
/// 试题1
- (void)testQuestion1;
/// 答案1
///
/// @return 答案1
- (NSString *)answer1;
/// 试题2
- (void)testQuestion2;
/// 答案2
///
/// @return 答案2
- (NSString *)answer2;
/// 试题3
- (void)testQuestion3;
/// 答案3
///
/// @return 答案3
- (NSString *)answer3;
@end
|
balmasea/genieparser
|
src/genie/libs/parser/iosxe/tests/ShowMabAllDetails/cli/equal/golden_output_1_expected.py
|
<filename>src/genie/libs/parser/iosxe/tests/ShowMabAllDetails/cli/equal/golden_output_1_expected.py
expected_output = {
"interfaces": {
"GigabitEthernet2/0/1": {
"client_mac": {
"0000.0001.0003": {
"authen_status": "SUCCESS",
"mab_sm_state": "TERMINATE",
"session_id": "000000000000000C82FA130E",
},
"0000.0001.0004": {
"authen_status": "SUCCESS",
"mab_sm_state": "TERMINATE",
"session_id": "000000000000000C82FA130F",
},
},
"mac_auth_bypass": "Enabled",
},
"GigabitEthernet2/0/2": {
"client_mac": {
"0000.0001.0003": {
"authen_status": "SUCCESS",
"mab_sm_state": "TERMINATE",
"session_id": "000000000000000C82FA130E",
}
},
"mac_auth_bypass": "Enabled",
},
"GigabitEthernet2/0/3": {
"client_mac": {},
"mac_auth_bypass": "Enabled"
},
}
}
|
shibsankaras/atlasdb
|
atlasdb-cassandra-integration-tests/src/test/java/com/palantir/atlasdb/keyvalue/cassandra/CassandraTimestampStoreInvalidatorIntegrationTest.java
|
/*
* Copyright 2017 <NAME>, Inc. All rights reserved.
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfigManager;
import com.palantir.atlasdb.containers.CassandraContainer;
import com.palantir.atlasdb.containers.Containers;
import com.palantir.timestamp.MultipleRunningTimestampServiceError;
import com.palantir.timestamp.TimestampBoundStore;
public class CassandraTimestampStoreInvalidatorIntegrationTest {
@ClassRule
public static final Containers CONTAINERS = new Containers(CassandraTimestampStoreInvalidatorIntegrationTest.class)
.with(new CassandraContainer());
private static final long ONE_MILLION = 1_000_000;
private final CassandraKeyValueService kv = CassandraKeyValueService.create(
CassandraKeyValueServiceConfigManager.createSimpleManager(CassandraContainer.KVS_CONFIG),
CassandraContainer.LEADER_CONFIG);
private final CassandraTimestampStoreInvalidator invalidator = CassandraTimestampStoreInvalidator.create(kv);
@Before
public void setUp() {
kv.dropTable(AtlasDbConstants.TIMESTAMP_TABLE);
kv.createTable(AtlasDbConstants.TIMESTAMP_TABLE,
CassandraTimestampUtils.TIMESTAMP_TABLE_METADATA.persistToBytes());
}
@After
public void close() {
kv.close();
}
@Test
public void canBackupTimestampTableIfItDoesNotExist() {
kv.dropTable(AtlasDbConstants.TIMESTAMP_TABLE);
assertThat(invalidator.backupAndInvalidate()).isEqualTo(CassandraTimestampUtils.INITIAL_VALUE);
}
@Test
public void canBackupTimestampTableIfItExistsWithNoData() {
assertThat(invalidator.backupAndInvalidate()).isEqualTo(CassandraTimestampUtils.INITIAL_VALUE);
}
@Test
public void canBackupTwice() {
assertThat(invalidator.backupAndInvalidate()).isEqualTo(CassandraTimestampUtils.INITIAL_VALUE);
assertThat(invalidator.backupAndInvalidate()).isEqualTo(CassandraTimestampUtils.INITIAL_VALUE);
}
@Test
public void canBackupTimestampTableIfItExistsWithData() {
long limit = getBoundAfterTakingOutOneMillionTimestamps();
assertThat(invalidator.backupAndInvalidate()).isEqualTo(limit);
}
@Test
public void canBackupAndRestoreTimestampTable() {
TimestampBoundStore timestampBoundStore = CassandraTimestampBoundStore.create(kv);
long limit = timestampBoundStore.getUpperLimit();
timestampBoundStore.storeUpperLimit(limit + ONE_MILLION);
invalidator.backupAndInvalidate();
invalidator.revalidateFromBackup();
assertThat(timestampBoundStore.getUpperLimit()).isEqualTo(limit + ONE_MILLION);
}
@Test
public void restoringValidTimestampTableIsANoOp() {
assertWeCanReadInitialValue();
invalidator.revalidateFromBackup();
assertWeCanReadInitialValue();
invalidator.revalidateFromBackup();
assertWeCanReadInitialValue();
}
@Test
public void restoringTimestampTableIfItDoesNotExistIsANoOp() {
kv.dropTable(AtlasDbConstants.TIMESTAMP_TABLE);
invalidator.revalidateFromBackup();
assertWeCanReadInitialValue();
}
@Test
public void restoringTimestampTableWithNoDataIsANoOp() {
invalidator.revalidateFromBackup();
assertWeCanReadInitialValue();
}
@Test
public void multipleInvalidatorsForSameKeyValueServiceAllReturnSameResults() {
long limit = getBoundAfterTakingOutOneMillionTimestamps();
CassandraTestTools.executeInParallelOnExecutorService(() ->
assertThat(CassandraTimestampStoreInvalidator.create(kv).backupAndInvalidate()).isEqualTo(limit));
}
/**
* Consistent results here mean that:
* (1) all calls to backupAndInvalidate() return the same value V, and
* (2) this value V is the maximum of all successfully stored timestamp bounds.
*/
@Test
public void invalidationDuringTimestampIssuanceYieldsConsistentResults() {
Set<Long> backedUpValues = Sets.newConcurrentHashSet();
AtomicLong maxSuccessfulBound = new AtomicLong(CassandraTimestampUtils.INITIAL_VALUE);
CassandraTestTools.executeInParallelOnExecutorService(() -> {
CassandraTimestampStoreInvalidator storeInvalidator = CassandraTimestampStoreInvalidator.create(kv);
try {
if (ThreadLocalRandom.current().nextBoolean()) {
backedUpValues.add(storeInvalidator.backupAndInvalidate());
} else {
maxSuccessfulBound.accumulateAndGet(getBoundAfterTakingOutOneMillionTimestamps(), Math::max);
}
} catch (IllegalArgumentException | IllegalStateException | MultipleRunningTimestampServiceError error) {
// Can arise if trying to manipulate the timestamp bound during/after an invalidation. This is fine.
}
});
if (!backedUpValues.isEmpty()) {
invalidator.revalidateFromBackup();
assertThat(Iterables.getOnlyElement(backedUpValues)).isEqualTo(maxSuccessfulBound.get());
assertWeCanReadTimestamp(maxSuccessfulBound.get());
}
// 2^-32 chance that nothing got backed up; accept in this case.
}
private void assertWeCanReadInitialValue() {
assertWeCanReadTimestamp(CassandraTimestampUtils.INITIAL_VALUE);
}
private void assertWeCanReadTimestamp(long expectedTimestamp) {
TimestampBoundStore timestampBoundStore = CassandraTimestampBoundStore.create(kv);
assertThat(timestampBoundStore.getUpperLimit()).isEqualTo(expectedTimestamp);
}
private long getBoundAfterTakingOutOneMillionTimestamps() {
TimestampBoundStore timestampBoundStore = CassandraTimestampBoundStore.create(kv);
long newLimit = timestampBoundStore.getUpperLimit() + ONE_MILLION;
timestampBoundStore.storeUpperLimit(newLimit);
return newLimit;
}
}
|
vegai/react-pdf
|
packages/render/src/utils/isTextInstance.js
|
<reponame>vegai/react-pdf
import * as R from 'ramda';
import * as P from '@react-pdf/primitives';
const isTextInstance = R.propEq('type', P.TextInstance);
export default isTextInstance;
|
nkysg/Asenal
|
acm/twoSum.cc
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <ctime>
#include <set>
typedef long long lld;
using namespace std;
class Solution {
#ifdef DEBUG
#define debug(x) cout<<__LINE__<<" "<<#x<<"="<<x<<endl;
#else
#define debug(x)
#endif
#define here cout<<__LINE__<< " " << "_______________here" <<endl;
#define clr(NAME,VALUE) memset(NAME,VALUE,sizeof(NAME))
#define MAX 0x7fffffff
#define MIN 0x80000000
#define N 16000010
#define PRIME 999983
public:
int binary_serach(int l, int r, vector<int> &numbers, int t)
{
int mid;
while (l <= r) {
mid = (l + r) / 2;
if (t == 685) {
debug(mid);
}
if (numbers[mid] < t) {
l = mid + 1;
} else if (numbers[mid] > t) {
r = mid - 1;
} else {
return mid;
}
}
return l;
}
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans;
vector<int> origin = numbers;
sort(numbers.begin(), numbers.end());
for (int i = 0; i < numbers.size(); i++) {
debug(numbers[i]);
}
int i, j;
int b = 0;
debug(target);
for (i = 0; i < numbers.size(); i++) {
j = binary_serach(i + 1, numbers.size() - 1, numbers, target - numbers[i]);
debug(i);
debug(j);
if (numbers[i] + numbers[j] == target) {
debug(numbers[i]);
debug(numbers[j]);
for (int k = 0; k < origin.size(); k++) {
if (origin[k] == numbers[i]) {
ans.push_back(k + 1);
if (b == 1) {
return ans;
}
b = 1;
} else if (origin[k] == numbers[j]) {
ans.push_back(k + 1);
if (b == 1) {
return ans;
}
b = 1;
}
}
}
}
return ans;
}
};
int main()
{
#ifdef DEBUG
freopen("a", "r", stdin);
#endif
Solution s;
// int vv[] = {591,955,829,805,312,83,764,841,12,744,104,773,627,306,731,539,349,811,662,341,465,300,491,423,569,405,508,802,500,747,689,506,129,325,918,606,918,370,623,905,321,670,879,607,140,543,997,530,356,446,444,184,787,199,614,685,778,929,819,612,737,344,471,645,726};
int vv[] = {3, 2, 4};
vector<int> a(begin(vv), end(vv));
debug(a.size());
int t = 6;
vector<int> v = s.twoSum(a, t);
debug(v[0]);
debug(v[1]);
return 0;
}
|
nagineni/chromium-crosswalk
|
chrome/android/java/src/org/chromium/chrome/browser/infobar/AnimationHelper.java
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.infobar;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import org.chromium.base.ApiCompatibilityUtils;
import java.util.ArrayList;
/**
* Sets up animations to move InfoBars around inside of the InfoBarContainer.
*
* Animations proceed in several phases:
* 1) Prep work is done for the InfoBar so that the View being animated in (if it exists) is
* properly sized. This involves adding the View to a FrameLayout with a visibility of
* INVISIBLE and triggering a layout.
*
* 2) Once the View has an actual size, we compute all of the actions needed for the animation.
* We use translations primarily to slide things in and out of the screen as things are shown,
* hidden, or resized.
*
* 3) The animation is kicked off and the animations run. During this phase, the View being shown
* is added to ContentWrapperView.
*
* 4) At the end of the animation, we clean up everything and make sure all the children are in the
* right places.
*/
public class AnimationHelper implements ViewTreeObserver.OnGlobalLayoutListener {
private static final String TAG = "AnimationHelper";
private static final long ANIMATION_DURATION_MS = 250;
public static final int ANIMATION_TYPE_SHOW = 0;
public static final int ANIMATION_TYPE_SWAP = 1;
public static final int ANIMATION_TYPE_HIDE = 2;
public static final int ANIMATION_TYPE_BOUNDARY = 3;
private final InfoBarContainer mContainer;
private final InfoBar mInfoBar;
private final ContentWrapperView mTargetWrapperView;
private final AnimatorSet mAnimatorSet;
private final int mAnimationType;
private final View mToShow;
private boolean mAnimationStarted;
/**
* Creates and starts an animation.
* @param container InfoBarContainer that is having its InfoBars animated.
* @param target ContentWrapperView that is the focus of the animation and is being resized,
* shown, or hidden.
* @param infoBar InfoBar that goes with the specified ContentWrapperView.
* @param toShow If non-null, this View will replace whatever child View the ContentWrapperView
* is currently displaying.
* @param aniamtionType Type of animation being performed.
*/
public AnimationHelper(InfoBarContainer container, ContentWrapperView target, InfoBar infoBar,
View toShow, int animationType) {
mContainer = container;
mInfoBar = infoBar;
mTargetWrapperView = target;
mAnimatorSet = new AnimatorSet();
mAnimationType = animationType;
mToShow = toShow;
assert mContainer.indexOfChild(mTargetWrapperView) != -1;
}
/**
* Start the animation.
*/
public void start() {
mTargetWrapperView.prepareTransition(mToShow);
mContainer.prepareTransition(mToShow);
if (mToShow == null) {
// We've got a size already; start the animation immediately.
continueAnimation();
} else {
// Wait for the object to be sized.
mTargetWrapperView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
}
/**
* @return the InfoBar being animated.
*/
public InfoBar getInfoBar() {
return mInfoBar;
}
/**
* @return the ContentWrapperView being animated.
*/
public ContentWrapperView getTarget() {
return mTargetWrapperView;
}
/**
* @return the type of animation being performed.
*/
public int getAnimationType() {
return mAnimationType;
}
/**
* Catch when the layout occurs, which lets us know when the View has been sized properly.
*/
@Override
public void onGlobalLayout() {
ApiCompatibilityUtils.removeOnGlobalLayoutListener(mTargetWrapperView, this);
continueAnimation();
}
private void continueAnimation() {
if (mAnimationStarted) return;
mAnimationStarted = true;
boolean infoBarsOnTop = mContainer.areInfoBarsOnTop();
int indexOfWrapperView = mContainer.indexOfChild(mTargetWrapperView);
assert indexOfWrapperView != -1;
ArrayList<Animator> animators = new ArrayList<Animator>();
mTargetWrapperView.getAnimationsForTransition(animators);
// Determine where the tops of each InfoBar will need to be.
int heightDifference = mTargetWrapperView.getTransitionHeightDifference();
int cumulativeTopStart = 0;
int cumulativeTopEnd = 0;
int cumulativeEndHeight = 0;
if (!infoBarsOnTop) {
if (heightDifference >= 0) {
// The current container is smaller than the final container, so the current 0
// coordinate will be >= 0 in the final container.
cumulativeTopStart = heightDifference;
} else {
// The current container is bigger than the final container, so the current 0
// coordinate will be < 0 in the final container.
cumulativeTopEnd = -heightDifference;
}
}
for (int i = 0; i < mContainer.getChildCount(); ++i) {
View view = mContainer.getChildAt(i);
// At this point, the View being transitioned in shouldn't have been added to the
// visible container, yet, and shouldn't affect calculations.
int startHeight = view.getHeight();
int endHeight = startHeight + (i == indexOfWrapperView ? heightDifference : 0);
int topStart = cumulativeTopStart;
int topEnd = cumulativeTopEnd;
int bottomStart = topStart + startHeight;
int bottomEnd = topEnd + endHeight;
if (topStart == topEnd && bottomStart == bottomEnd) {
// The View needs to stay put.
view.setTop(topEnd);
view.setBottom(bottomEnd);
view.setY(topEnd);
view.setTranslationY(0);
} else {
// A translation is required to move the View into place.
int translation = heightDifference;
if (infoBarsOnTop) translation *= -1;
boolean translateDownward = false;
if (topStart < topEnd) {
translateDownward = infoBarsOnTop;
} else if (topStart > topEnd) {
translateDownward = !infoBarsOnTop;
} else {
translateDownward = bottomEnd > bottomStart;
}
PropertyValuesHolder viewTranslation;
if (translateDownward) {
view.setTop(topEnd);
view.setBottom(bottomEnd);
view.setTranslationY(translation);
view.setY(topEnd + translation);
viewTranslation =
PropertyValuesHolder.ofFloat("translationY", translation, 0.0f);
} else {
viewTranslation =
PropertyValuesHolder.ofFloat("translationY", 0.0f, -translation);
}
animators.add(ObjectAnimator.ofPropertyValuesHolder(view, viewTranslation));
}
// Add heights to the cumulative totals.
cumulativeTopStart += startHeight;
cumulativeTopEnd += endHeight;
cumulativeEndHeight += endHeight;
}
// Lock the InfoBarContainer's size at its largest during the animation to avoid
// clipping issues.
final int oldContainerTop = mContainer.getTop();
final int oldContainerBottom = mContainer.getBottom();
final int newContainerTop;
final int newContainerBottom;
if (infoBarsOnTop) {
newContainerTop = oldContainerTop;
newContainerBottom = newContainerTop + cumulativeEndHeight;
} else {
newContainerBottom = oldContainerBottom;
newContainerTop = newContainerBottom - cumulativeEndHeight;
}
final int biggestContainerTop = Math.min(oldContainerTop, newContainerTop);
final int biggestContainerBottom = Math.max(oldContainerBottom, newContainerBottom);
mContainer.setTop(biggestContainerTop);
mContainer.setBottom(biggestContainerBottom);
// Set up and run all of the animations.
mAnimatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
mTargetWrapperView.startTransition();
mContainer.startTransition();
}
@Override
public void onAnimationEnd(Animator animation) {
mTargetWrapperView.finishTransition();
mContainer.finishTransition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mToShow != null &&
(mAnimationType == ANIMATION_TYPE_SHOW ||
mAnimationType == ANIMATION_TYPE_SWAP)) {
mToShow.announceForAccessibility(
mInfoBar.getMessageText(mContainer.getContext()));
}
}
});
mAnimatorSet.playTogether(animators);
mAnimatorSet.setDuration(ANIMATION_DURATION_MS);
mAnimatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
mAnimatorSet.start();
}
}
|
abcum/cirrius
|
cpm/check/card/main.go
|
<gh_stars>1-10
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this info 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 card
import (
"strconv"
"strings"
"github.com/abcum/orbit"
)
func init() {
orbit.Add("check/card", New)
}
func New(orb *orbit.Orbit) interface{} {
return &Module{
orb: orb,
}
}
type Module struct {
orb *orbit.Orbit
}
func (this *Module) clean(number string) string {
number = strings.Replace(number, "-", "", -1)
number = strings.Replace(number, " ", "", -1)
return number
}
func (this *Module) reverse(number string) string {
digits := []rune(number)
for i, j := 0, len(number)-1; i < j; i, j = i+1, j-1 {
digits[i], digits[j] = digits[j], digits[i]
}
return string(digits)
}
func (this *Module) length(number string, lengths ...int) bool {
for _, length := range lengths {
if len(number) == length {
return true
}
}
return false
}
func (this *Module) prefixed(number string, prefixes ...string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(number, prefix) {
return true
}
}
return false
}
func (this *Module) Type(number string) string {
number = this.clean(number)
if len(number) == 0 {
return "Unknown"
}
if this.length(number, 16) && this.prefixed(number, "3") {
return "JCB"
}
if this.length(number, 13, 16) && this.prefixed(number, "4") {
return "Visa"
}
if this.length(number, 15) && this.prefixed(number, "34", "37") {
return "American Express"
}
if this.length(number, 16) && this.prefixed(number, "6011") {
return "Discover"
}
if this.length(number, 16) && this.prefixed(number, "2014", "2149") {
return "enRoute"
}
if this.length(number, 15) && this.prefixed(number, "1800", "2131") {
return "JCB"
}
if this.length(number, 16) && this.prefixed(number, "51", "52", "53", "54", "55") {
return "Mastercard"
}
if this.length(number, 14) && this.prefixed(number, "36", "38", "300", "301", "302", "303", "304", "305") {
return "Diners Club / Carteblanche"
}
if this.length(number, 16) && this.prefixed(number, "2131") {
return "JCB"
}
return "Unknown"
}
func (this *Module) Check(number string) bool {
number = this.clean(number)
number = this.reverse(number)
hold, even := 0, false
for _, digit := range number {
i, err := strconv.Atoi(string(digit))
if err != nil {
this.orb.Quit(err)
}
if even {
i *= 2
}
if i > 9 {
hold -= 9
}
hold += i
even = !even
}
if hold%10 == 0 {
return true
}
return false
}
|
iotile/baBLE-linux
|
platforms/linux/src/Application/PacketBuilder/PacketBuilder.cpp
|
#include "PacketBuilder.hpp"
#include "Log/Log.hpp"
#include "Exceptions/BaBLEException.hpp"
using namespace std;
// Constructors
PacketBuilder::PacketBuilder(shared_ptr<AbstractFormat> building_format) {
m_building_format = move(building_format);
}
// Setters
PacketBuilder& PacketBuilder::set_ignored_packets(unordered_set<uint16_t> ignored_packets) {
m_ignored_packets = move(ignored_packets);
return *this;
}
// To build packets
shared_ptr<Packet::AbstractPacket> PacketBuilder::build(shared_ptr<AbstractExtractor> extractor) {
if (!extractor->is_valid()) {
return nullptr;
}
uint16_t type_code = extractor->get_type_code();
if (m_building_format->is_command(type_code)) {
return build_packet(move(extractor), m_commands);
} else if (m_building_format->is_event(type_code)) {
return build_packet(move(extractor), m_events);
} else {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::NotFound,
"Given data to build a packet has no known type: " + to_string(type_code)
);
}
}
shared_ptr<Packet::AbstractPacket> PacketBuilder::build_packet(shared_ptr<AbstractExtractor> extractor,
const unordered_map<uint16_t, PacketConstructor>& packets) {
// Extract packet_code from data
uint16_t packet_code = extractor->get_packet_code();
// Get command from packet_code
auto it = packets.find(packet_code);
if (it == packets.end()) {
if (m_ignored_packets.find(packet_code) == m_ignored_packets.end()) {
LOG.error("Packet code not found in PacketBuilder registry: " + to_string(packet_code), "PacketBuilder");
LOG.debug(extractor->get_raw_data(), "PacketBuilder");
} else {
LOG.debug("Packet, in ignored list, has been ignored (" + to_string(packet_code) + ")");
}
return nullptr;
}
PacketConstructor fn = it->second;
shared_ptr<Packet::AbstractPacket> packet = fn();
packet->from_bytes(extractor);
return packet;
}
const string PacketBuilder::stringify() const {
stringstream result;
result << "Commands: " << endl;
for (auto& element : m_commands) {
result << "\t" << element.first << endl;
}
result << endl << "Events: " << endl;
for (auto& element : m_events) {
result << "\t" << element.first << endl;
}
return result.str();
}
|
HuaYuetong1998/Online-Examination-System
|
backend/src/main/java/cn/yuanqikai/backend/service/impl/PaperManageServiceImpl.java
|
package cn.yuanqikai.backend.service.impl;
import cn.yuanqikai.backend.dto.PaperDTO;
import cn.yuanqikai.backend.dto.QuestionDTO;
import cn.yuanqikai.backend.entity.ChoiceQuestion;
import cn.yuanqikai.backend.entity.Paper;
import cn.yuanqikai.backend.entity.PaperQuestionPool;
import cn.yuanqikai.backend.mapper.ChoiceQuestionMapper;
import cn.yuanqikai.backend.mapper.PaperMapper;
import cn.yuanqikai.backend.mapper.PaperQuestionPoolMapper;
import cn.yuanqikai.backend.service.PaperManageService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @author yuanqikai
* @date 2021-04-16 14:08
*/
@Service
public class PaperManageServiceImpl implements PaperManageService {
@Autowired
private PaperMapper paperMapper;
@Autowired
private PaperQuestionPoolMapper paperQuestionPoolMapper;
@Autowired
private ChoiceQuestionMapper choiceQuestionMapper;
@Override
public int addPaper(PaperDTO paperDTO) {
Paper paper = new Paper();
if (paperDTO.getType() == 0) {
paper.setChoiceNum(paperDTO.getNormalChoiceNum());
paper.setFillNum(paperDTO.getNormalFillNum());
paper.setJudgeNum(paperDTO.getNormalJudgeNum());
paper.setSubjectiveNum(paperDTO.getNormalSubjectiveNum());
} else if (paperDTO.getType() == 1) {
paper.setChoiceNum(paperDTO.getChoiceNum());
paper.setFillNum(paperDTO.getFillNum());
paper.setJudgeNum(paperDTO.getJudgeNum());
paper.setSubjectiveNum(paperDTO.getSubjectiveNum());
paper.setChoiceScore(paperDTO.getChoiceScore());
paper.setFillScore(paperDTO.getFillScore());
paper.setJudgeScore(paperDTO.getJudgeScore());
paper.setSubjectiveScore(paperDTO.getSubjectiveScore());
}
paper.setPaperTitle(paperDTO.getPaperTitle());
paper.setTotalScore(paperDTO.getTotalScore());
paper.setType(paperDTO.getType());
paper.setStatus(1);
Date today = new Date();
paper.setCreateTime(today);
paper.setUpdateTime(today);
return paperMapper.insert(paper);
}
@Override
public int countByPaperTitle(String paperTitle) {
return paperMapper.countByPaperTitle(paperTitle);
}
@Override
public void addPaperQuestionPool(PaperDTO paperDTO) {
Paper paper = paperMapper.selectByPaperTitle(paperDTO.getPaperTitle());
Integer paperId = paper.getPaperId();
List<QuestionDTO> paperQuestion = paperDTO.getPaperQuestion();
for (QuestionDTO questionDTO : paperQuestion) {
PaperQuestionPool paperQuestionPool = new PaperQuestionPool();
paperQuestionPool.setPaperId(paperId);
paperQuestionPool.setQuestionId(questionDTO.getQuestionId());
paperQuestionPoolMapper.insert(paperQuestionPool);
}
}
@Override
public Page<PaperDTO> selectMultiCondition(PaperDTO paperDTO) {
PageHelper.startPage(paperDTO.getCurrentPage(), paperDTO.getPageSize());
return paperMapper.selectMultiCondition(paperDTO);
}
@Override
public Paper selectById(Integer paperId) {
return paperMapper.selectByPrimaryKey(paperId);
}
@Override
public List<Integer> selectPaperQuestionIds(Integer paperId) {
return paperQuestionPoolMapper.selectPaperQuestionIds(paperId);
}
@Override
public ChoiceQuestion selectQuestionDetail(Integer questionId) {
return choiceQuestionMapper.selectQuestionDetail(questionId);
}
@Override
public int updatePaper(PaperDTO paperDTO) {
int choiceCount = 0;
int fillCount = 0;
int judgeCount = 0;
int subjectiveCount = 0;
int totalScore = 0;
List<QuestionDTO> paperQuestion = paperDTO.getPaperQuestion();
for (QuestionDTO questionDTO : paperQuestion) {
Integer questionId = questionDTO.getQuestionId();
if (questionId >= 100000 && questionId < 200000) {
choiceCount++;
} else if (questionId >= 200000 && questionId < 300000) {
fillCount++;
} else if (questionId >= 300000 && questionId < 400000) {
judgeCount++;
} else if (questionId >= 400000) {
subjectiveCount++;
}
totalScore += questionDTO.getScore();
}
Paper paper = new Paper();
paper.setPaperId(paperDTO.getPaperId());
paper.setPaperTitle(paperDTO.getPaperTitle());
paper.setType(0);
paper.setStatus(paperDTO.getStatus());
paper.setChoiceNum(choiceCount);
paper.setFillNum(fillCount);
paper.setJudgeNum(judgeCount);
paper.setSubjectiveNum(subjectiveCount);
paper.setTotalScore(totalScore);
paper.setChoiceScore(paperDTO.getChoiceScore());
paper.setFillScore(paperDTO.getFillScore());
paper.setJudgeScore(paperDTO.getJudgeScore());
paper.setSubjectiveScore(paperDTO.getSubjectiveScore());
Date modifyDate = new Date();
paper.setUpdateTime(modifyDate);
return paperMapper.updateByPrimaryKeySelective(paper);
}
@Override
public void updatePaperQuestionPool(PaperDTO paperDTO) {
Integer paperId = paperDTO.getPaperId();
int res = paperQuestionPoolMapper.deleteByPaperId(paperId);
if(res != 0 ) {
addPaperQuestionPool(paperDTO);
}
}
@Override
public int deletePaper(Integer paperId) {
int res = paperQuestionPoolMapper.deleteByPaperId(paperId);
if(res != 0) {
return paperMapper.deleteByPrimaryKey(paperId);
}
return 0;
}
@Override
public List<Paper> selectAllPaper() {
return paperMapper.selectAllPaper();
}
}
|
rdwallis/rqueue
|
rqueue-spring-boot-starter/src/test/java/com/github/sonus21/rqueue/spring/boot/tests/integration/BootProcessingChannelTest.java
|
<filename>rqueue-spring-boot-starter/src/test/java/com/github/sonus21/rqueue/spring/boot/tests/integration/BootProcessingChannelTest.java
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sonus21.rqueue.spring.boot.tests.integration;
import com.github.sonus21.junit.SpringTestTracerExtension;
import com.github.sonus21.rqueue.exception.TimedOutException;
import com.github.sonus21.rqueue.spring.boot.application.ApplicationListenerDisabled;
import com.github.sonus21.rqueue.test.tests.MessageChannelTests;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
@ExtendWith(SpringTestTracerExtension.class)
@ContextConfiguration(classes = ApplicationListenerDisabled.class)
@TestPropertySource(
properties = {
"rqueue.scheduler.auto.start=false",
"spring.redis.port=8011",
"mysql.db.name=BootProcessingChannelTest",
"max.workers.count=120",
"use.system.redis=false",
"monitor.thread.count=1",
"start.queue.enabled=true",
})
@SpringBootTest
@Slf4j
@DisabledIfEnvironmentVariable(named = "CI_ENV", matches = "true")
public class BootProcessingChannelTest extends MessageChannelTests {
@Test
public void publishMessageIsTriggeredOnMessageRemoval() throws TimedOutException {
verifyPublishMessageIsTriggeredOnMessageRemoval();
}
}
|
asarcar/PI
|
experimental/hexinw/audio_example.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
import apiai
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
import apiai
import pyaudio
import time
import wave
CLIENT_ACCESS_TOKEN = '<KEY>'
CHUNK = 1024
def main():
if len(sys.argv) < 2:
print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
sys.exit(-1)
wf = wave.open(sys.argv[1], 'rb')
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.voice_request()
request.lang = 'en' # optional, default value equal 'en'
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
"""
# define callback (2)
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
request.send(data)
return (data, pyaudio.paContinue)
# open stream using callback (3)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=False,
stream_callback=callback)
stream.start_stream()
# wait for stream to finish (5)
while stream.is_active():
time.sleep(0.1)
"""
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
# read data
data = wf.readframes(CHUNK)
# play stream (3)
while len(data) > 0:
stream.write(data)
request.send(data)
data = wf.readframes(CHUNK)
# stop stream (6)
stream.stop_stream()
stream.close()
wf.close()
p.terminate()
print ("Wait for response...")
response = request.getresponse()
print (response.read())
if __name__ == '__main__':
main()
|
Gradecak/fission-workflows
|
pkg/fnenv/workflows/workflows_test.go
|
<filename>pkg/fnenv/workflows/workflows_test.go
package workflows
import (
"context"
"errors"
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/gradecak/fission-workflows/pkg/api"
"github.com/gradecak/fission-workflows/pkg/api/projectors"
"github.com/gradecak/fission-workflows/pkg/api/store"
"github.com/gradecak/fission-workflows/pkg/fes"
"github.com/gradecak/fission-workflows/pkg/fes/backend/mem"
"github.com/gradecak/fission-workflows/pkg/fes/cache"
"github.com/gradecak/fission-workflows/pkg/fes/testutil"
"github.com/gradecak/fission-workflows/pkg/types"
"github.com/gradecak/fission-workflows/pkg/types/typedvalues"
"github.com/gradecak/fission-workflows/pkg/util"
"github.com/stretchr/testify/assert"
)
const (
workflowID = "123"
defaultTimeout = 5 * time.Second
)
func defaultDeadline() time.Time {
return time.Now().Add(defaultTimeout)
}
func TestRuntime_InvokeWorkflow_SubTimeout(t *testing.T) {
runtime, _, _, _ := setup()
spec := types.NewWorkflowInvocationSpec(workflowID, time.Now().Add(10*time.Millisecond))
_, err := runtime.InvokeWorkflow(spec)
assert.Equal(t, api.ErrInvocationCanceled, err.Error())
}
func TestRuntime_InvokeWorkflow_PollTimeout(t *testing.T) {
runtime, _, _, _ := setup()
runtime.invocations = store.NewInvocationStore(testutil.NewCache()) // ensure that cache does not support pubsub
runtime.pollInterval = 10 * time.Millisecond
_, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec(workflowID, defaultDeadline()))
assert.EqualError(t, err, context.DeadlineExceeded.Error())
}
func TestRuntime_InvokeWorkflow_InvalidSpec(t *testing.T) {
runtime, _, _, _ := setup()
_, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec("", defaultDeadline()))
assert.IsType(t, errors.New(""), err)
}
func TestRuntime_InvokeWorkflow_SubSuccess(t *testing.T) {
runtime, invocationAPI, _, cc := setup()
output := typedvalues.MustWrap("foo")
outputHeaders := typedvalues.MustWrap(typedvalues.MustWrap(map[string]interface{}{
"some-key": "some-value",
}))
go func() {
// Simulate workflow invocation
time.Sleep(50 * time.Millisecond)
entities := cc.List()
wfiID := entities[0].Id
err := invocationAPI.Complete(wfiID, output, outputHeaders)
if err != nil {
panic(err)
}
}()
wfi, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec(workflowID, defaultDeadline()))
assert.NoError(t, err)
util.AssertProtoEqual(t, output, wfi.GetStatus().GetOutput())
util.AssertProtoEqual(t, outputHeaders, wfi.GetStatus().GetOutputHeaders())
assert.True(t, wfi.GetStatus().Finished())
assert.True(t, wfi.GetStatus().Successful())
}
func TestRuntime_InvokeWorkflow_PollSuccess(t *testing.T) {
runtime, invocationAPI, _, c := setup()
pollCache := store.NewInvocationStore(testutil.NewCache()) // ensure that cache does not support pubsub
runtime.invocations = pollCache
output := typedvalues.MustWrap("foo")
outputHeaders := typedvalues.MustWrap(typedvalues.MustWrap(map[string]interface{}{
"some-key": "some-value",
}))
go func() {
// Simulate workflow invocation
time.Sleep(50 * time.Millisecond)
entities := c.List()
wfiID := entities[0].Id
err := invocationAPI.Complete(wfiID, output, outputHeaders)
if err != nil {
panic(err)
}
time.Sleep(50 * time.Millisecond)
entity, err := c.GetAggregate(projectors.NewInvocationAggregate(wfiID))
assert.NoError(t, err)
pollCache.CacheReader.(fes.CacheReaderWriter).Put(entity)
}()
wfi, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec(workflowID, defaultDeadline()))
assert.NoError(t, err)
util.AssertProtoEqual(t, output, wfi.GetStatus().GetOutput())
util.AssertProtoEqual(t, outputHeaders, wfi.GetStatus().GetOutputHeaders())
assert.True(t, wfi.GetStatus().Finished())
assert.True(t, wfi.GetStatus().Successful())
}
func TestRuntime_InvokeWorkflow_Fail(t *testing.T) {
runtime, invocationAPI, _, cache := setup()
wfiErr := errors.New("stub err")
go func() {
// Simulate workflow invocation
time.Sleep(50 * time.Millisecond)
entities := cache.List()
wfiID := entities[0].Id
err := invocationAPI.Fail(wfiID, wfiErr)
if err != nil {
panic(err)
}
}()
wfi, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec(workflowID, defaultDeadline()))
assert.NoError(t, err)
assert.Equal(t, wfiErr.Error(), wfi.GetStatus().GetError().Error())
assert.True(t, wfi.GetStatus().Finished())
assert.False(t, wfi.GetStatus().Successful())
}
func TestRuntime_InvokeWorkflow_Cancel(t *testing.T) {
runtime, invocationAPI, _, cache := setup()
go func() {
// Simulate workflow invocation
time.Sleep(50 * time.Millisecond)
entities := cache.List()
wfiID := entities[0].Id
err := invocationAPI.Cancel(wfiID)
if err != nil {
panic(err)
}
}()
wfi, err := runtime.InvokeWorkflow(types.NewWorkflowInvocationSpec(workflowID, defaultDeadline()))
assert.NoError(t, err)
assert.Equal(t, api.ErrInvocationCanceled, wfi.GetStatus().GetError().Error())
assert.True(t, wfi.GetStatus().Finished())
assert.False(t, wfi.GetStatus().Successful())
}
func TestRuntime_Invoke(t *testing.T) {
runtime, invocationAPI, _, cache := setup()
deadline, _ := ptypes.TimestampProto(time.Now().Add(10 * time.Second))
fnref := types.NewFnRef("workflows", "", workflowID)
spec := types.NewTaskInvocationSpec(&types.WorkflowInvocation{
Metadata: types.NewObjectMetadata("wi-123"),
Spec: &types.WorkflowInvocationSpec{
Deadline: deadline,
},
}, &types.Task{
Metadata: types.NewObjectMetadata("ti-123"),
Spec: &types.TaskSpec{},
Status: &types.TaskStatus{
FnRef: &fnref,
},
}, time.Now())
spec.Inputs = types.Inputs{
types.InputParent: typedvalues.MustWrap("parentID"),
}
output := typedvalues.MustWrap("foo")
outputHeaders := typedvalues.MustWrap(typedvalues.MustWrap(map[string]interface{}{
"some-key": "some-value",
}))
go func() {
// Simulate workflow invocation
time.Sleep(50 * time.Millisecond)
entities := cache.List()
wfiID := entities[0].Id
err := invocationAPI.Complete(wfiID, output, outputHeaders)
if err != nil {
panic(err)
}
}()
task, err := runtime.Invoke(spec)
assert.NoError(t, err)
util.AssertProtoEqual(t, output, task.GetOutput())
util.AssertProtoEqual(t, outputHeaders, task.GetOutputHeaders())
}
func setup() (*Runtime, *api.Invocation, *mem.Backend, fes.CacheReaderWriter) {
backend := mem.NewBackend()
invocationAPI := api.NewInvocationAPI(backend)
workflowsCache := testutil.NewCache()
err := workflowsCache.Put(&types.Workflow{
Metadata: &types.ObjectMetadata{
Id: workflowID,
},
Status: &types.WorkflowStatus{
Status: types.WorkflowStatus_READY,
},
})
if err != nil {
panic(err)
}
workflows := store.NewWorkflowsStore(workflowsCache)
c := cache.NewSubscribedCache(testutil.NewCache(), projectors.NewWorkflowInvocation(), backend.Subscribe())
runtime := NewRuntime(invocationAPI, store.NewInvocationStore(c), workflows)
return runtime, invocationAPI, backend, c
}
|
RoboBears5611/Ftc2019RoverRuckus
|
Ftc3543Lib/src/main/java/trclib/TrcSwerveDriveBase.java
|
/*
* Copyright (c) 2018 Titan Robotics Club (http://www.titanrobotics.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package trclib;
/**
* This class implements a platform independent swerve drive base. A swerve drive base consists of 4 swerve modules
* each of which consists of a driving motor and a PID controlled steering motor. It extends the TrcSimpleDriveBase
* class so it inherits all the SimpleDriveBase methods and features
*
* The implementation of swerve algorithm is based on Ether's white paper:
* http://www.chiefdelphi.com/media/papers/download/3028
*/
public class TrcSwerveDriveBase extends TrcSimpleDriveBase
{
private final TrcSwerveModule lfModule, rfModule, lrModule, rrModule;
private final double wheelBaseWidth, wheelBaseLength, wheelBaseDiagonal;
/**
* Constructor: Create an instance of the 4-wheel swerve drive base.
*
* @param leftFrontMotor specifies the left front motor of the drive base.
* @param leftRearMotor specifies the left rear motor of the drive base.
* @param rightFrontMotor specifies the right front motor of the drive base.
* @param rightRearMotor specifies the right rear motor of the drive base.
* @param gyro specifies the gyro. If none, it can be set to null.
* @param wheelBaseWidth specifies the width of the wheel base in inches.
* @param wheelBaseLength specifies the length of the wheel base in inches.
*/
public TrcSwerveDriveBase(
TrcSwerveModule leftFrontMotor, TrcSwerveModule leftRearMotor,
TrcSwerveModule rightFrontMotor, TrcSwerveModule rightRearMotor,
TrcGyro gyro, double wheelBaseWidth, double wheelBaseLength)
{
super(leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor, gyro);
this.lfModule = leftFrontMotor;
this.rfModule = rightFrontMotor;
this.lrModule = leftRearMotor;
this.rrModule = rightRearMotor;
this.wheelBaseWidth = wheelBaseWidth;
this.wheelBaseLength = wheelBaseLength;
this.wheelBaseDiagonal = TrcUtil.magnitude(wheelBaseWidth, wheelBaseLength);
} //TrcSwerveDriveBase
/**
* Constructor: Create an instance of the 4-wheel swerve drive base.
*
* @param leftFrontMotor specifies the left front motor of the drive base.
* @param leftRearMotor specifies the left rear motor of the drive base.
* @param rightFrontMotor specifies the right front motor of the drive base.
* @param rightRearMotor specifies the right rear motor of the drive base.
* @param wheelBaseWidth specifies the width of the wheel base in inches.
* @param wheelBaseLength specifies the length of the wheel base in inches.
*/
public TrcSwerveDriveBase(
TrcSwerveModule leftFrontMotor, TrcSwerveModule leftRearMotor,
TrcSwerveModule rightFrontMotor, TrcSwerveModule rightRearMotor,
double wheelBaseWidth, double wheelBaseLength)
{
this(leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor, null, wheelBaseWidth, wheelBaseLength);
} //TrcSwerveDriveBase
/**
* This method does zero calibration on the steer angle encoders.
*/
public void zeroCalibrateSteering()
{
lfModule.zeroCalibrateSteering();
rfModule.zeroCalibrateSteering();
lrModule.zeroCalibrateSteering();
rrModule.zeroCalibrateSteering();
} //zeroCalibrateSteering
/**
* This method checks if it supports holonomic drive.
*
* @return true if this drive base supports holonomic drive, false otherwise.
*/
@Override
public boolean supportsHolonomicDrive()
{
return true;
} //supportsHolonomicDrive
/**
* This method sets the position scales. The raw position from the encoder is in encoder counts. By setting the
* scale factor, one could make getPosition to return unit in inches, for example. This also automatically
* calculates the rotateScale, which is used for approximating the heading without the gyro.
*
* @param xScale specifies the X position scale.
* @param yScale specifies the Y position scale.
*/
@Override
public void setPositionScales(double xScale, double yScale)
{
// encDist / perimeter = rotPos / 360.0
// encDist * 360.0 / perimeter = rotPos
// Therefore, rotScale = 360.0 / perimeter
double perimeter = wheelBaseDiagonal * Math.PI;
double rotScale = 360.0 / perimeter;
super.setPositionScales(xScale, yScale, rotScale);
} //setPositionScales
/**
* This method sets the steering angle of all four wheels.
*
* @param angle specifies the steering angle to be set.
* @param optimize specifies true to optimize steering angle to be no greater than 90 degrees, false otherwise.
*/
public void setSteerAngle(double angle, boolean optimize)
{
final String funcName = "setSteerAngle";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API, "angle=%f,optimize=%s", angle, optimize);
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API);
}
lfModule.setSteerAngle(angle, optimize);
rfModule.setSteerAngle(angle, optimize);
lrModule.setSteerAngle(angle, optimize);
rrModule.setSteerAngle(angle, optimize);
} //setSteerAngle
/**
* This method sets the steering angle of all four wheels.
*
* @param angle specifies the steering angle to be set.
*/
public void setSteerAngle(double angle)
{
setSteerAngle(angle, true);
} //setSteerAngle
/**
* This method stops the drive base. If steerNeutral is true, it also sets all steering angles to zero.
*
* @param resetSteer specifies true to set steering angle to zero.
*/
public void stop(boolean resetSteer)
{
final String funcName = "stop";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API, "steerNeutral=%s", resetSteer);
}
super.stop();
if (resetSteer)
{
setSteerAngle(0.0, false);
}
if (debugEnabled)
{
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API);
}
} //stop
/**
* This method stops the drive base and reset the steering angle to zero.
*/
@Override
public void stop()
{
stop(false);
} //stop
/**
* This method implements tank drive where leftPower controls the left motors and right power controls the right
* motors. It will set the steering angle to zero, but note that it will take time for the steering angles to
* reach zero. Since we do not wait for the steering angle to reach neutral, it is possible the drive base will
* move diagonally initially. If this is undesirable, the caller should make sure steering angles are already at
* zero before calling this method.
*
* @param leftPower specifies left power value.
* @param rightPower specifies right power value.
* @param inverted specifies true to invert control (i.e. robot front becomes robot back).
*/
@Override
public void tankDrive(double leftPower, double rightPower, boolean inverted)
{
setSteerAngle(0.0, false);
super.tankDrive(leftPower, rightPower, inverted);
} //tankDrive
/**
* This method implements holonomic drive where x controls how fast the robot will go in the x direction, and y
* controls how fast the robot will go in the y direction. Rotation controls how fast the robot rotates and
* gyroAngle specifies the heading the robot should maintain.
*
* @param x specifies the x power.
* @param y specifies the y power.
* @param rotation specifies the rotating power.
* @param inverted specifies true to invert control (i.e. robot front becomes robot back).
* @param gyroAngle specifies the gyro angle to maintain for field relative drive. DO NOT use this with inverted.
*/
@Override
protected void holonomicDrive(double x, double y, double rotation, boolean inverted, double gyroAngle)
{
final String funcName = "holonomicDrive";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API, "x=%f,y=%f,rot=%f,inverted=%s,angle=%f",
x, y, rotation, Boolean.toString(inverted), gyroAngle);
}
x = TrcUtil.clipRange(x);
y = TrcUtil.clipRange(y);
rotation = TrcUtil.clipRange(rotation);
if(inverted)
{
x = -x;
y = -y;
}
if(gyroAngle != 0)
{
if(inverted)
{
globalTracer.traceWarn(
funcName, "You should not be using inverted and field reference frame at the same time!");
}
double gyroRadians = Math.toRadians(gyroAngle);
double temp = y * Math.cos(gyroRadians) + x * Math.sin(gyroRadians);
x = -y * Math.sin(gyroRadians) + x * Math.cos(gyroRadians);
y = temp;
}
double a = x - (rotation * wheelBaseLength/wheelBaseDiagonal);
double b = x + (rotation * wheelBaseLength/wheelBaseDiagonal);
double c = y - (rotation * wheelBaseWidth/wheelBaseDiagonal);
double d = y + (rotation * wheelBaseWidth/wheelBaseDiagonal);
// The white paper goes in order rf, lf, lr, rr. We like to do lf, rf, lr, rr.
// Note: atan2(y, x) in java will take care of x being zero.
// If will return pi/2 for positive y and -pi/2 for negative y.
double lfAngle = Math.toDegrees(Math.atan2(b, d));
double rfAngle = Math.toDegrees(Math.atan2(b, c));
double lrAngle = Math.toDegrees(Math.atan2(a, d));
double rrAngle = Math.toDegrees(Math.atan2(a, c));
// The white paper goes in order rf, lf, lr, rr. We like to do lf, rf, lr, rr.
double lfPower = TrcUtil.magnitude(b, d);
double rfPower = TrcUtil.magnitude(b, c);
double lrPower = TrcUtil.magnitude(a, d);
double rrPower = TrcUtil.magnitude(a, c);
double[] normalizedPowers = TrcUtil.normalize(lfPower, rfPower, lrPower, rrPower);
lfPower = this.clipMotorOutput(normalizedPowers[0]);
rfPower = this.clipMotorOutput(normalizedPowers[1]);
lrPower = this.clipMotorOutput(normalizedPowers[2]);
rrPower = this.clipMotorOutput(normalizedPowers[3]);
if (motorPowerMapper != null)
{
lfPower = motorPowerMapper.translateMotorPower(lfPower, lfModule.getVelocity());
rfPower = motorPowerMapper.translateMotorPower(rfPower, rfModule.getVelocity());
lrPower = motorPowerMapper.translateMotorPower(lrPower, lrModule.getVelocity());
rrPower = motorPowerMapper.translateMotorPower(rrPower, rrModule.getVelocity());
}
lfModule.setSteerAngle(lfAngle);
rfModule.setSteerAngle(rfAngle);
lrModule.setSteerAngle(lrAngle);
rrModule.setSteerAngle(rrAngle);
lfModule.set(lfPower);
rfModule.set(rfPower);
lrModule.set(lrPower);
rrModule.set(rrPower);
if (debugEnabled)
{
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API);
}
} //holonomicDrive
/**
* This method is called periodically to monitor the position sensors to update the odometry data. It assumes the
* caller has the odometry lock.
*
* @param odometry specifies the odometry object to be updated.
*/
@Override
protected void updateOdometry(Odometry odometry)
{
final String funcName = "updateOdometry";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.TASK);
}
double lfAngle = lfModule.getSteerAngle();
double rfAngle = rfModule.getSteerAngle();
double lrAngle = lrModule.getSteerAngle();
double rrAngle = rrModule.getSteerAngle();
double avgAngleDeg = TrcUtil.average(lfAngle, rfAngle, lrAngle, rrAngle);
double avgAngleRad = Math.toRadians(avgAngleDeg);
double angleCos = Math.cos(avgAngleRad);
double angleSin = Math.sin(avgAngleRad);
double timeDelta = odometry.currTimestamp - odometry.prevTimestamp;
double avgEncDelta = TrcUtil.average(
odometry.currPositions[MotorType.LEFT_FRONT.value] - odometry.prevPositions[MotorType.LEFT_FRONT.value],
odometry.currPositions[MotorType.RIGHT_FRONT.value] - odometry.prevPositions[MotorType.RIGHT_FRONT.value],
odometry.currPositions[MotorType.LEFT_REAR.value] - odometry.prevPositions[MotorType.LEFT_REAR.value],
odometry.currPositions[MotorType.RIGHT_REAR.value] - odometry.prevPositions[MotorType.RIGHT_REAR.value]);
double avgEncVel = timeDelta != 0.0 ? avgEncDelta / timeDelta : 0.0;
odometry.xRawPos = getRawXPosition() + avgEncDelta*angleCos;
odometry.xRawVel = avgEncVel*angleCos;
odometry.yRawPos = getRawYPosition() + avgEncDelta*angleSin;
odometry.yRawVel = avgEncVel*angleSin;
//
// Rotation position is only valid when the robot is doing turn-in-place.
// In Swerve Drive, the wheels are steered in a diamond formation (i.e. tangential to the turning circle).
// So the rotation position is the degree turned by the robot in the turning circle.
//
odometry.rotRawPos = getRawRotationPosition() + avgEncDelta;
if (debugEnabled)
{
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.TASK);
}
} //updateOdometry
} //class TrcSwerveDriveBase
|
miguelsousa/hTools2
|
Scripts/current-font/layers/delete-all.py
|
# [h] delete all layers
'''Delete all layers in the current font.'''
# run
f = CurrentFont()
while len(f.layerOrder) > 0:
f.removeLayer(f.layerOrder[0])
f.update()
|
IDEOorg/steps-guide-housing
|
src/store/nav/nav.js
|
export const CHANGE_NAV = 'CHANGE_NAV';
export const MAIN_PAGE = 'MAIN_PAGE';
export const OPTIONS_PAGE = 'OPTIONS_PAGE';
export function changeNav(page) {
return {
type: CHANGE_NAV,
page
};
}
const nav = (state = [], action) => {
switch (action.type) {
case CHANGE_NAV:
return action.page;
default:
return state;
}
};
export default nav;
|
Diffblue-benchmarks/Ananas-analytics-ananas-desktop
|
buildSrc/src/main/java/org/ananas/desktop/CorePlugin.java
|
<reponame>Diffblue-benchmarks/Ananas-analytics-ananas-desktop
package org.ananas.desktop;
import java.util.Set;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.initialization.Settings;
import org.gradle.api.invocation.Gradle;
class CorePlugin implements Plugin<Settings> {
public void apply(Settings settings) {
Gradle gradle = settings.getGradle();
gradle.projectsLoaded(
(Gradle g) -> {
Project rootProject = gradle.getRootProject();
ProjectVersion version = this.getProjectVersion(rootProject);
this.injectProjectVersion(rootProject, version);
this.injectRunnerJarName(rootProject, version);
});
}
private ProjectVersion getProjectVersion(Project project) {
int major = Integer.parseInt((String) project.property("major"));
int minor = Integer.parseInt((String) project.property("minor"));
int patch = Integer.parseInt((String) project.property("patch"));
boolean release = Boolean.parseBoolean((String) project.property("release"));
return new ProjectVersion(major, minor, patch, release);
}
/** inject project to all subprojects */
private void injectProjectVersion(Project project, ProjectVersion version) {
project.setVersion(version);
Set<Project> subProjects = project.getSubprojects();
for (Project subProject : subProjects) {
subProject.setVersion(version);
}
}
private void injectRunnerJarName(Project project, ProjectVersion version) {
project.getExtensions().add("runnerJarName", "runner-all-" + version);
project.getExtensions().add("runnerJarBaseName", "runner-all");
project.getExtensions().add("cliJarName", "ananas-cli-" + version);
project.getExtensions().add("cliJarBaseName", "ananas-cli");
Set<Project> projects = project.getSubprojects();
for (Project subProject : projects) {
subProject.getExtensions().add("runnerJarName", "runner-all-" + version);
subProject.getExtensions().add("runnerJarBaseName", "runner-all");
subProject.getExtensions().add("cliJarName", "ananas-cli-" + version);
subProject.getExtensions().add("cliJarBaseName", "ananas-cli");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.