text stringlengths 1 1.05M |
|---|
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT 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/MIT
* 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 model
import (
"configcenter/src/framework/common"
"configcenter/src/framework/core/output/module/client"
"configcenter/src/framework/core/types"
)
// check the interface
var _ Attribute = (*attribute)(nil)
// attribute the metadata structure definition of the model attribute
type attribute struct {
OwnerID string `field:"bk_supplier_account"`
ObjectID string `field:"bk_obj_id"`
PropertyID string `field:"bk_property_id"`
PropertyName string `field:"bk_property_name"`
PropertyGroup string `field:"bk_property_group"`
PropertyIndex int `field:"bk_property_index"`
Unit string `field:"unit"`
Placeholder string `field:"placeholder"`
IsEditable bool `field:"editable"`
IsPre bool `field:"ispre"`
IsRequired bool `field:"isrequired"`
IsReadOnly bool `field:"isreadonly"`
IsOnly bool `field:"isonly"`
IsSystem bool `field:"bk_issystem"`
IsAPI bool `field:"bk_isapi"`
PropertyType string `field:"bk_property_type"`
Option interface{} `field:"option"`
Description string `field:"description"`
Creator string `field:"creator"`
id int
}
func (cli *attribute) ToMapStr() types.MapStr {
return common.SetValueToMapStrByTags(cli)
}
func (cli *attribute) search() ([]types.MapStr, error) {
// construct the search condition
cond := common.CreateCondition().Field(PropertyID).Eq(cli.PropertyID)
cond.Field(ObjectID).Eq(cli.ObjectID)
cond.Field(SupplierAccount).Eq(cli.OwnerID)
// search all objects by condition
dataItems, err := client.GetClient().CCV3(client.Params{SupplierAccount: cli.OwnerID}).Attribute().SearchObjectAttributes(cond)
return dataItems, err
}
func (cli *attribute) IsExists() (bool, error) {
items, err := cli.search()
if nil != err {
return false, err
}
return 0 != len(items), nil
}
func (cli *attribute) Create() error {
id, err := client.GetClient().CCV3(client.Params{SupplierAccount: cli.OwnerID}).Attribute().CreateObjectAttribute(cli.ToMapStr())
if nil != err {
return err
}
cli.id = id
return nil
}
func (cli *attribute) Update() error {
dataItems, err := cli.search()
if nil != err {
return err
}
// update the exists one
for _, item := range dataItems {
item.Set(PropertyName, cli.PropertyName)
item.Set(PropertyGroup, cli.PropertyGroup)
item.Set(PropertyIndex, cli.PropertyIndex)
item.Set(Unit, cli.Unit)
item.Set(PlaceHolder, cli.Placeholder)
item.Set(IsEditable, cli.IsEditable)
item.Set(IsRequired, cli.IsRequired)
item.Set(IsReadOnly, cli.IsReadOnly)
item.Set(IsOnly, cli.IsOnly)
item.Set(IsApi, cli.IsAPI)
item.Set(PropertyType, cli.PropertyType)
item.Set(Option, cli.Option)
item.Set(Description, cli.Description)
id, err := item.Int("id")
if nil != err {
return err
}
cond := common.CreateCondition()
cond.Field(ObjectID).Eq(cli.ObjectID).Field(SupplierAccount).Eq(cli.OwnerID).Field(PropertyID).Eq(cli.PropertyID).Field("id").Eq(id)
if err = client.GetClient().CCV3(client.Params{SupplierAccount: cli.OwnerID}).Attribute().UpdateObjectAttribute(item, cond); nil != err {
return err
}
}
return nil
}
func (cli *attribute) Save() error {
if exists, err := cli.IsExists(); nil != err {
return err
} else if exists {
return cli.Update()
}
return cli.Create()
}
func (cli *attribute) SetObjectID(objectID string) {
cli.ObjectID = objectID
}
func (cli *attribute) GetObjectID() string {
return cli.ObjectID
}
func (cli *attribute) SetID(id string) {
cli.PropertyID = id
}
func (cli *attribute) GetRecordID() int {
return cli.id
}
func (cli *attribute) GetID() string {
return cli.PropertyID
}
func (cli *attribute) SetName(name string) {
cli.PropertyName = name
}
func (cli *attribute) GetName() string {
return cli.PropertyName
}
func (cli *attribute) SetUnit(unit string) {
cli.Unit = unit
}
func (cli *attribute) GetUnit() string {
return cli.Unit
}
func (cli *attribute) SetPlaceholder(placeHolder string) {
cli.Placeholder = placeHolder
}
func (cli *attribute) GetPlaceholder() string {
return cli.Placeholder
}
func (cli *attribute) SetEditable() {
cli.IsEditable = true
}
func (cli *attribute) GetEditable() bool {
return cli.IsEditable
}
func (cli *attribute) SetNonEditable() {
cli.IsEditable = false
}
func (cli *attribute) SetRequired() {
cli.IsRequired = true
}
func (cli *attribute) SetNonRequired() {
cli.IsRequired = false
}
func (cli *attribute) GetRequired() bool {
return cli.IsRequired
}
func (cli *attribute) SetKey(isKey bool) {
cli.IsOnly = isKey
}
func (cli *attribute) GetKey() bool {
return cli.IsOnly
}
func (cli *attribute) SetOption(option interface{}) {
cli.Option = option
}
func (cli *attribute) GetOption() interface{} {
return cli.Option
}
func (cli *attribute) SetDescrition(des string) {
cli.Description = des
}
func (cli *attribute) GetDescription() string {
return cli.Description
}
func (cli *attribute) SetType(dataType FieldDataType) {
cli.PropertyType = string(dataType)
}
func (cli *attribute) GetType() FieldDataType {
return FieldDataType(cli.PropertyType)
}
|
<filename>src/http.c
#ifndef HTTP_C
#define HTTP_C
#include "http.h"
#include "linkedList.c"
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <strings.h>
inline ERROR_CODE http_initRequest(HTTP_Request* request, const char* url, const uint_fast64_t urlLength, void* buffer, const uint_fast64_t bufferSize, const char version[] , const HTTP_RequestType requestType){
ERROR_CODE error;
if((error = http_initRequest_(request, buffer, bufferSize, requestType)) != ERROR_NO_ERROR){
return ERROR(error);
}
http_setHTTP_Version((HTTP_Response*)(request), version);
request->urlLength = urlLength;
request->requestURL = malloc(sizeof(request->requestURL) * (urlLength + 1));
if(request->requestURL == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(request->requestURL, url, urlLength);
request->requestURL[urlLength] = '\0';
return ERROR(error);
}
inline ERROR_CODE http_initRequest_(HTTP_Request* request, void* buffer, const uint_fast64_t bufferSize, const HTTP_RequestType requestType){
memset(request, 0, sizeof(*request));
request->data = buffer;
request->bufferSize = bufferSize;
ERROR_CODE error;
error = linkedList_init(&request->headerFields);
request->type = requestType;
return ERROR(error);
}
inline ERROR_CODE http_initResponse(HTTP_Response* response, void* buffer, const uint_fast64_t bufferSize){
memset(response, 0, sizeof(*response));
response->data = buffer;
response->bufferSize = bufferSize;
ERROR_CODE error;
error = linkedList_init(&response->headerFields);
response->statusCode = -1;
return ERROR(error);
}
inline ERROR_CODE http_initheaderField(HTTP_HeaderField* headerField, char* name, const uint_fast64_t nameLength, char* value, const uint_fast64_t valueLength){
headerField->name = name;
headerField->nameLength = nameLength;
headerField->value = value;
headerField->valueLength = valueLength;
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE http_addHeaderField(HTTP_Request* request, char* name, const uint_fast64_t nameLength, char* value, const uint_fast64_t valueLength){
#define HTTP_MAX_HEADER_FIELDS 32
if(request->headerFields.length == HTTP_MAX_HEADER_FIELDS){
return ERROR(ERROR_MAX_HEADER_FIELDS_REACHED);
}
HTTP_HeaderField* headerField = malloc(sizeof(*headerField));
if(headerField == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
http_initheaderField(headerField, name, nameLength, value, valueLength);
linkedList_add(&request->headerFields, headerField);
#undef HTTP_MAX_HEADER_FIELDS
return ERROR(ERROR_NO_ERROR);
}
inline HTTP_HeaderField* http_getHeaderField(HTTP_Request* request, char* name){
HTTP_HeaderField* ret = NULL;
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
const uint_fast64_t nameLength = strlen(name);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncasecmp(name, headerField->name, nameLength) == 0){
ret = headerField;
break;
}
}
return ret;
}
inline ERROR_CODE http_closeConnection(int_fast32_t sockFD){
if(close(sockFD) != 0){
return ERROR(ERROR_FAILED_TO_CLOSE_SOCKET);
}
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Clean up error handling/clarify error console output.
ERROR_CODE http_openConnection(int_fast32_t* sockFD, const char* url, const uint_fast16_t port){
struct addrinfo addressHints = {0};
// AF_INET6 == force IPv6.
// Aparently the linux subsystem for Windoof does not like AF_UNSPEC & returns '0.0.0.0' for every getaddrinfo call if we do not force IPv4 via 'AF_INET'.
addressHints.ai_family = AF_INET;
addressHints.ai_socktype = SOCK_STREAM;
// Convert port to service string.
char service[UTIL_FORMATTED_NUMBER_LENGTH];
// util_formatNumber(service, UTIL_FORMATTED_NUMBER_LENGTH, port);
snprintf(service, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST16 "", port);
struct addrinfo* serverInfo;
int error;
if((error = getaddrinfo(url, service, &addressHints, &serverInfo)) != 0){
UTIL_LOG_ERROR_("GetaddrInfo:'%s'.", gai_strerror(error));
freeaddrinfo(serverInfo);
return ERROR(ERROR_FAILED_TO_RETRIEVE_ADDRESS_INFORMATION);
}
struct addrinfo* sockInfo;
// Loop through all returned internet addresses.
for(sockInfo = serverInfo; sockInfo != NULL; sockInfo = sockInfo->ai_next){
// Create communication endpoint with internet address.
if((*sockFD = socket(sockInfo->ai_family, sockInfo->ai_socktype, sockInfo->ai_protocol)) == -1){
continue;
}
// Connect file discriptor with internet address.
if(connect(*sockFD, sockInfo->ai_addr, sockInfo->ai_addrlen) == -1) {
UTIL_LOG_ERROR_("Connect:'%s'.", strerror(errno));
close(*sockFD);
*sockFD = -1;
continue;
}
break;
}
if(sockInfo == NULL){
UTIL_LOG_ERROR_("Failed to connect to '%s:%s'.", url, service);
freeaddrinfo(serverInfo);
return ERROR(ERROR_FAILED_TO_CONNECT);
}
freeaddrinfo(serverInfo);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_sendRequest(HTTP_Request* request, HTTP_Response* response, const int_fast32_t connection){
int_fast64_t bufferSize = request->bufferSize - request->dataLength;
char* buffer = (char*) (request->data + request->dataLength);
// Request line.
uint_fast64_t writeOffset = snprintf(buffer, request->bufferSize, "%s %s %s\r\n",
http_getRequestType(request->type),
request->requestURL,
request->httpVersion
);
// Content-Length.
char* contentLength = malloc(sizeof(*contentLength) * UTIL_FORMATTED_NUMBER_LENGTH);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
const uint_fast64_t contentLengthLength = snprintf(contentLength, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST64 "", request->dataLength);
char* _contentLength = malloc(sizeof(*_contentLength) * 16);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(_contentLength, "Content-Length", 16);
http_addHeaderField(request, _contentLength, 16, contentLength, contentLengthLength);
// HeaderFields.
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
writeOffset += snprintf(buffer + writeOffset, request->bufferSize - writeOffset, "%s: %s\r\n",
headerField->name,
headerField->value
);
bufferSize -= writeOffset;
}
writeOffset += snprintf(buffer + writeOffset, request->bufferSize - writeOffset, "\r\n");
buffer[writeOffset] = '\0';
bufferSize -= writeOffset + 1;
// Thats bad, we just have overwritten data in the request.
if(bufferSize < 0){
return ERROR(ERROR_HTTP_REQUEST_SIZE_EXCEEDED);
}
// Send request.
if(send(connection, buffer, writeOffset, MSG_NOSIGNAL) != (int_fast64_t) writeOffset){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
if(send(connection, request->data, request->dataLength, MSG_NOSIGNAL) != (int_fast64_t) request->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
// Receive response.
ERROR_CODE error;
error = http_receiveResponse(response, connection);
if(error != ERROR_NO_ERROR){
return error;
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_sendResponse(HTTP_Response* response, const int_fast32_t connection){
int_fast64_t bufferSize = !response->staticContent ? (response->bufferSize - response->dataLength) : response->bufferSize;
char* buffer = (char*) (response->data + (response->staticContent ? 0 : response->dataLength));
const int_fast16_t statusCode = http_getStatusCode(response->statusCode);
// Response line.
uint_fast64_t writeOffset = snprintf(buffer, response->bufferSize, "%*.*s %" PRIdFAST16 " %s\r\n",
8, 8, response->httpVersion,
statusCode,
http_getStatusMsg(response->statusCode)
);
// TODO:(jan) Clean this up.
// Content-Type:.
const char tType[] = "Content-Type";
const uint_fast64_t tTypeLength = strlen(tType);
char* contentType = malloc(sizeof(*contentType) * (tTypeLength + 1));
if(contentType == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(contentType, tType, tTypeLength + 1);
uint_fast64_t contentTypeLength;
const char* contentTypeString = http_contentTypeToString(response->contentType, &contentTypeLength);
char* _contentTypeString = malloc(sizeof(_contentTypeString) * (contentTypeLength + 1));
if(_contentTypeString == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(_contentTypeString, contentTypeString, contentTypeLength);
_contentTypeString[contentTypeLength] = '\0';
http_addHeaderField((HTTP_Request*) response, contentType, strlen(contentType), _contentTypeString, contentTypeLength);
// Content-Length.
char* contentLength = malloc(sizeof(*contentLength) * UTIL_FORMATTED_NUMBER_LENGTH);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
const uint_fast64_t contentLengthLength = snprintf(contentLength, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST64 "", response->dataLength);
const char cType[] = "Content-Length";
const uint_fast64_t _contentLengthLength = strlen(cType);
char* _contentLength = malloc(sizeof(*_contentLength) * (_contentLengthLength + 1));
if(_contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(_contentLength, cType, _contentLengthLength + 1);
http_addHeaderField((HTTP_Request*) response, _contentLength, strlen(_contentLength), contentLength, contentLengthLength);
const char* const serverMessage = "Herder Web-Server";
HTTP_ADD_HEADER_FIELD((*response), Server, serverMessage);
// HeaderFields.
LinkedListIterator it;
linkedList_initIterator(&it, &response->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
writeOffset += snprintf(buffer + writeOffset, response->bufferSize - writeOffset, "%s: %s\r\n",
headerField->name,
headerField->value
);
bufferSize -= writeOffset;
}
writeOffset += snprintf(buffer + writeOffset, response->bufferSize - writeOffset, "\r\n");
buffer[writeOffset] = '\0';
bufferSize -= writeOffset + 1;
// Thats bad, we just have overwritten data in the response.
if(bufferSize < 0){
return ERROR(ERROR_HTTP_RESPONSE_SIZE_EXCEEDED);
}
// Send response.
if(send(connection, buffer, writeOffset, MSG_NOSIGNAL) != (int_fast64_t) writeOffset){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
if(!response->staticContent){
if(send(connection, response->data, response->dataLength, MSG_NOSIGNAL) != (int_fast64_t) response->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
}else{
if(send(connection, response->cacheObject->data, response->dataLength, MSG_NOSIGNAL) != (int_fast64_t) response->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
}
return ERROR(ERROR_NO_ERROR);
}
HTTP_StatusCode http_translateStatusCode(const int_fast16_t statusCode){
switch(statusCode){
case 100:{
return _100_CONTINUE;
}
case 101:{
return _101_SWITCHING_PROTOCOLS;
}
case 102:{
return _102_PROCESSING;
}
case 200:{
return _200_OK;
}
case 201:{
return _201_CREATED;
}
case 202:{
return _202_ACCEPTED;
}
case 203:{
return _203_NON_AUTHORATIVE_INFORMATION;
}
case 204:{
return _204_NO_CONTENT;
}
case 205:{
return _205_RESET_CONTROL;
}
case 206:{
return _206_PARTIAL_CONTENT;
}
case 207:{
return _207_MULTI_STATUS;
}
case 208:{
return _208_ALREADY_REPORTED;
}
case 226:{
return _226_IM_USED;
}
case 300:{
return _300_MULTIPLE_CHOICES;
}
case 301:{
return _301_MOVED_PERMANENTLY;
}
case 302:{
return _302_FOUND;
}
case 303:{
return _303_SEE_OTHER;
}
case 304:{
return _304_NOT_MODIFIED;
}
case 305:{
return _305_USE_PROXY;
}
case 307:{
return _307_TEMPORARY_REDIRECT;
}
case 308:{
return _308_PERMANENT_REDIRECT;
}
case 400:{
return _400_BAD_REQUEST;
}
case 401:{
return _401_UNAUTHORIZED;
}
case 402:{
return _402_PAYMENT_REQUIRED;
}
case 403:{
return _403_FORBIDDEN;
}
case 404:{
return _404_NOT_FOUND;
}
case 405:{
return _405_METHOD_NOT_ALLOWED;
}
case 406:{
return _406_NOT_ACCEPTABLE;
}
case 407:{
return _407_PROXY_AUTHENTICATION_REQUIRED;
}
case 408:{
return _408_REQUEST_TIMEOUT;
}
case 409:{
return _409_CONFLICT;
}
case 410:{
return _410_GONE;
}
case 411:{
return _411_LENGTH_REQUIRED;
}
case 412:{
return _412_PRECONDITION_FAILED;
}
case 413:{
return _413_PAYLOAD_TOO_LARGE;
}
case 414:{
return _414_REQUEST_URI_TOO_LARGE;
}
case 415:{
return _415_UNSUPPORTED_MEDIA_TYPE;
}
case 416:{
return _416_REQUEST_RANGE_NOT_SATISFIABLE;
}
case 417:{
return _417_EXPECTATION_FAILED;
}
case 418:{
return _418_IM_A_TEAPOT;
}
case 421:{
return _421_MISDIRECTED_REQUEST;
}
case 422:{
return _422_UNPROCESSABLE_ENTITY;
}
case 423:{
return _423_LOCKED;
}
case 424:{
return _424_FAILED_DEPENDENCY;
}
case 426:{
return _426_UPGRADE_REQUIRED;
}
case 428:{
return _428_PRECONDITION_REQUIRED;
}
case 429:{
return _429_TOO_MANY_REQUESTS;
}
case 431:{
return _431_REQUEST_HEADER_FIELD_TOO_LARGE;
}
case 444:{
return _444_CONNECTION_CLOSED_WITHOUT_RESPONSE;
}
case 451:{
return _451_UNAVAILABLE_FOR_LEAGAL_REASON;
}
case 499:{
return _499_CLIENT_CLOSED_REQUEST;
}
case 500:{
return _500_INTERNAL_SERVER_ERROR;
}
case 501:{
return _501_NOT_IMPLEMENTED;
}
case 502:{
return _502_BAD_GATEWAY;
}
case 503:{
return _503_SERVICE_UYNAVAILABLE;
}
case 504:{
return _504_GATEWAY_TIMEOUT;
}
case 505:{
return _505_HTTP_VERSION_NOT_SUPPORTED;
}
case 506:{
return _506_VARIANT_ALSO_NEGOTIATES;
}
case 507:{
return _507_INSUFFIECENT_STORAGE;
}
case 508:{
return _508_LOOP_DETECTED;
}
case 510:{
return _510_NOT_EXTENDED;
}
case 511:{
return _511_NETWORK_AUTHENTICATION_REQUIRED;
}
case 599:{
return _599_NETWORK_CONNECTION_TIMEOUT_ERROR;
}
default:{
UTIL_LOG_CRITICAL_("[%" PRIdFAST16"] Unsupported HTTP status code.", statusCode);
return _500_INTERNAL_SERVER_ERROR;
}
}
}
ERROR_CODE http_receiveResponse(HTTP_Response* response, const int_fast32_t connection){
char* buffer = (char*) response->data;
int_fast64_t bytesRead;
if((bytesRead = read(connection, buffer, response->bufferSize)) == -1){
return ERROR(ERROR_READ_ERROR);
}
if(bytesRead == 0){
return ERROR(ERROR_EMPTY_RESPONSE);
}else if(bytesRead ==(int_fast64_t) response->bufferSize){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}else if(bytesRead < 3/*RequestType*/ + 3/*Spaces*/ + 2/*Line delimiter*/ + 1/*RequestURL*/ + 8/*Version*/){
return ERROR(ERROR_INSUFICIENT_MESSAGE_LENGTH);
}
// RequestLine.
int_fast64_t i;
for(i = 1; i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
int_fast64_t posSplitBegin = 0;
int_fast64_t posSplitEnd;
// Version.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
const char* const version = buffer;
const uint_fast64_t versionLength = posSplitEnd;
if(strncmp(version, HTTP_VERSION_1_1, versionLength) != 0){
return ERROR(ERROR_VERSION_MISSMATCH);
}
posSplitBegin = posSplitEnd + 1;
// StatusCode.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
const char* const statusCode = buffer + posSplitBegin;
errno = 0;
char* endPtr;
response->statusCode = strtol(statusCode, &endPtr, 10/*Decimal*/);
if((response->statusCode == 0 && endPtr == statusCode) || (errno == ERANGE && (response->statusCode == LONG_MIN || response->statusCode == LONG_MAX))){
return ERROR(ERROR_INVALID_STATUS_CODE);
}
response->statusCode = http_translateStatusCode(response->statusCode);
posSplitBegin = posSplitEnd + 1;
// StatusMessage.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
response->statusMsg = buffer + posSplitBegin;
response->statusMsgLength = posSplitEnd - posSplitBegin;
break;
}
}
i++;
// HeaderFields.
int_fast64_t posSplitBegin = i;
int_fast64_t posSplitEnd;
for(;i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
// No need to check for index underflow, because we need atleast two "\r\n" in the buffer to even get here.
if(buffer[i - 2] == '\n' && buffer[i - 3] == '\r'){
break;
}
posSplitEnd = i - 1;
char* line = buffer + posSplitBegin;
uint_fast64_t lineLength = posSplitEnd - posSplitBegin;
const int_fast64_t lineSplit = util_findFirst(line, lineLength, ':');
if(lineSplit == -1){
// Copy current line onto stack to add limiting '\0' for printing.
char* _line = alloca(lineLength + 1);
memcpy(_line, line, lineLength);
_line[lineLength] = '\0';
UTIL_LOG_ERROR_("Failed to parse '%s'.", _line);
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
uint_fast64_t nameLength = lineSplit;
char* name = malloc(sizeof(*name) * (nameLength + 1));
if(name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(name, line, nameLength);
name[nameLength] = '\0';
uint64_t valueLength = lineLength - (lineSplit + 1);
char* value = malloc(sizeof(*value) * (valueLength + 1));
if(value == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(value, line + lineSplit + 1, valueLength);
value[valueLength] = '\0';
util_trim(value, valueLength);
posSplitBegin = i + 1;
if(strncmp(name, "Content-Length:", nameLength) == 0){
char* endPtr;
int_fast64_t contentLength;
contentLength = strtol(value, &endPtr, 10/*Decimal*/);
errno = 0;
if((contentLength == 0 && endPtr == value) || (errno == ERANGE && (contentLength == LONG_MIN || contentLength == LONG_MAX))){
return ERROR(ERROR_INVALID_CONTENT_LENGTH);
}
response->dataLength = contentLength;
}
// TODO: (jan) Use a chunk of the processing buffer to store headerField structs.
// Because the headerFields are at the beginning of both structs, we should be fine casting between the types.
http_addHeaderField((HTTP_Request*) response, name, nameLength, value, valueLength);
}
}
uint_fast64_t bufferSize = bytesRead;
if(i + response->dataLength > (uint_fast64_t) bytesRead){
bytesRead += read(connection, buffer + bytesRead, HTTP_PROCESSING_BUFFER_SIZE - bytesRead);
bufferSize = bytesRead - bufferSize;
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else{
if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}
}
}
// Data.
response->data = (int_fast8_t*) (buffer + i + 1);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_receiveRequest(HTTP_Request* request, const int_fast32_t connection){
char* buffer = (char*) request->data;
int_fast64_t bytesRead = read(connection, buffer, HTTP_PROCESSING_BUFFER_SIZE);
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}else if(bytesRead < 3/*RequestType*/ + 3/*Spaces*/ + 2/*Line delimiter*/ + 1/*RequestURL*/ + 8/*Version*/){
return ERROR(ERROR_INSUFICIENT_MESSAGE_LENGTH);
}
// RequestLine.
int_fast64_t i;
for(i = 1; i < bytesRead; i++){
if(buffer[i - 1] == '\n' && buffer[i - 2] == '\r'){
int_fast64_t posSplitBegin = 0;
int_fast64_t posSplitEnd;
// RequestType.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
if(posSplitEnd == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
const char* const requestType = buffer;
const uint_fast64_t requestTypeLength = posSplitEnd;
request->type = http_parseRequestType(requestType, requestTypeLength);
posSplitBegin = posSplitEnd + 1;
// RequestURL.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
if(posSplitEnd == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
request->urlLength = posSplitEnd;
if(request->urlLength == 0){
return ERROR_(ERROR_INVALID_REQUEST_URL, "URL length can't be '%" PRIuFAST16 "'.", request->urlLength);
}
request->requestURL = malloc(sizeof(*request->requestURL) * request->urlLength + 1);
if(request->requestURL == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(request->requestURL, buffer + posSplitBegin, request->urlLength);
request->requestURL[request->urlLength] = '\0';
posSplitBegin += posSplitEnd + 1;
const int_fast64_t getParameterOffset = util_findFirst(request->requestURL, request->urlLength, '?');
if(getParameterOffset != -1){
request->requestURL[getParameterOffset] = '\0';
request->getParameterLength = request->urlLength - getParameterOffset;
request->urlLength = getParameterOffset;
request->getParameter = request->requestURL + (getParameterOffset + 1);
}
// Version.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
const char* const version = buffer + posSplitBegin;
const uint_fast64_t versionLength = posSplitEnd;
if(strncmp(version, HTTP_VERSION_1_1, versionLength) != 0){
return ERROR(ERROR_VERSION_MISSMATCH);
}
break;
}
}
// HeaderFields.
uint_fast64_t posLineBegin = i;
for(;i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
if(buffer[i - 2] == '\n' && buffer[i - 3] == '\r'){
// Skip trailing '\n'.
i++;
break;
}
char* line = buffer + posLineBegin;
uint_fast64_t lineLength = i - posLineBegin;
const int_fast64_t nameLength = util_findFirst(line, lineLength,':');
if(nameLength == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
char* name = malloc(sizeof(*name) * nameLength);
if(name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(name, line, nameLength);
// Move line beginning after ':'
line += nameLength + 1;
lineLength -= nameLength + 1;
// Skip trailing whitespace
if(isspace(*line) != 0){
line++;
lineLength--;
}
const int_fast64_t valueLength = lineLength;
if(valueLength == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
char* value = malloc(sizeof(*value) * valueLength);
if(value == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(value, line, valueLength);
if(strncmp(name, "Content-Length:", nameLength) == 0){
errno = 0;
char* endPtr;
int_fast64_t contentLength;
contentLength = strtol(value, &endPtr, 10/*Decimal*/);
if((contentLength == 0 && endPtr == value) || (errno == ERANGE && (contentLength == LONG_MIN || contentLength == LONG_MAX))){
return ERROR(ERROR_INVALID_CONTENT_LENGTH);
}
request->dataLength = contentLength;
}
http_addHeaderField(request, name, nameLength, value, valueLength);
posLineBegin = i + 1;
}
}
// We have not read the whole request, because of the way we handle/send request header and data in 'http_sendRequest'.
uint_fast64_t bufferSize = bytesRead;
if(i + request->dataLength > (uint_fast64_t) bytesRead){
bytesRead += read(connection, buffer + bytesRead, HTTP_PROCESSING_BUFFER_SIZE - bytesRead);
bufferSize = bytesRead - bufferSize;
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else{
if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}
}
}
// Data.
request->data = (int_fast8_t*) (buffer + i);
return ERROR(ERROR_NO_ERROR);
}
void http_freeHTTP_Request(HTTP_Request* request){
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
free(headerField->name);
free(headerField->value);
free(headerField);
}
free(request->requestURL);
linkedList_free(&request->headerFields);
}
void http_freeHTTP_Response(HTTP_Response* response){
LinkedListIterator it;
linkedList_initIterator(&it, &response->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
free(headerField->name);
free(headerField->value);
free(headerField);
}
linkedList_free(&response->headerFields);
}
/*
printf("#define HASH_GET %d\n", util_hashString("GET"));
printf("#define HASH_HEAD %d\n", util_hashString("HEAD"));
printf("#define HASH_POST %d\n", util_hashString("POST"));
printf("#define HASH_PUT %d\n", util_hashString("PUT"));
printf("#define HASH_DELETE %d\n", util_hashString("DELETE"));
printf("#define HASH_TRACE %d\n", util_hashString("TRACE"));
printf("#define HASH_OPTIONS %d\n", util_hashString("OPTIONS"));
printf("#define HASH_CONNECT %d\n", util_hashString("CONNECT"));
printf("#define HASH_PATCH %d\n", util_hashString("PATCH"));
*/
HTTP_RequestType http_parseRequestType(const char* const type, const uint_fast64_t length){
#define HASH_GET 591093270
#define HASH_HEAD 942011328
#define HASH_POST -1319429824
#define HASH_PUT 666496399
#define HASH_DELETE 617851755
#define HASH_TRACE 1359153669
#define HASH_OPTIONS -1168929634
#define HASH_CONNECT -431736502
#define HASH_PATCH 867751912
HTTP_RequestType ret = REQUEST_TYPE_UNKNOWN;
switch(util_hashString(type, length)){
case HASH_GET:{
ret = REQUEST_TYPE_GET;
break;
}
case HASH_POST:{
ret = REQUEST_TYPE_POST;
break;
}
case HASH_HEAD:{
ret = REQUEST_TYPE_HEAD;
break;
}
case HASH_PUT:{
ret = REQUEST_TYPE_PUT;
break;
}
case HASH_DELETE:{
ret = REQUEST_TYPE_DELETE;
break;
}
case HASH_TRACE:{
ret = REQUEST_TYPE_TRACE;
break;
}
case HASH_OPTIONS:{
ret =REQUEST_TYPE_OPTIONS;
break;
}
case HASH_CONNECT:{
ret = REQUEST_TYPE_CONNECT;
break;
}
case HASH_PATCH:{
ret = REQUEST_TYPE_PATCH;
break;
}
default:{
UTIL_LOG_ERROR_("Unknown request type:'%s'.", type);
break;
}
}
#undef HASH_GET
#undef HASH_HEAD
#undef HASH_POST
#undef HASH_PUT
#undef HASH_DELETE
#undef HASH_TRACE
#undef HASH_OPTIONS
#undef HASH_CONNECT
#undef HASH_PATCH
return ret;
}
local const char* const HTTP_STATUS_MESSAGE_MAPPING_ARRAY[] = {
"Continue",
"Switching Protocols",
"Processing",
"OK",
"Created",
"Accepted",
"Non-authoritative Information",
"No Content",
"Reset Content",
"Partial Content",
"Multi-Status",
"Already Reported",
"IM Used",
"Multiple Choices",
"Moved Permanently",
"Found",
"See Other",
"Not Modified",
"Use Proxy",
"Temporary Redirect",
"Permanent Redirect",
"Bad Request",
"Unauthorized",
"Payment Required",
"Forbidden",
"Not Found",
"Method Not Allowed",
"Not Acceptable",
"Proxy Authentication Required",
"Request Timeout",
"Conflict",
"Gone",
"Length Required",
"Precondition Failed",
"Payload Too Large",
"Request-URI Too Long",
"Unsupported Media Type",
"Requested Range Not Satisfiable",
"Expectation Failed",
"I'm a teapot",
"Misdirected Request",
"Unprocessable Entity",
"Locked",
"Failed Dependency",
"Upgrade Required",
"Precondition Required",
"Too Many Requests",
"Request Header Fields Too Large",
"Connection Closed Without Response",
"Unavailable For Legal Reasons",
"Client Closed Request",
"Internal Server Error",
"Not Implemented",
"Bad Gateway",
"Service Unavailable",
"Gateway Timeout",
"HTTP Version Not Supported",
"Variant Also Negotiates",
"Insufficient Storage",
"Loop Detected",
"Not Extended",
"Network Authentication Required",
"Network Connect Timeout Error"
};
inline const char* http_getStatusMsg(HTTP_StatusCode statusCode){
return HTTP_STATUS_MESSAGE_MAPPING_ARRAY[statusCode];
}
local const char* HTTP_REQUEST_TYPE_MAPPING_ARRAY[] = {
"UNKNOWN",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"OPTIONS",
"CONNECT",
"PATCH"
};
inline const char* http_getRequestType(HTTP_RequestType requestType){
return HTTP_REQUEST_TYPE_MAPPING_ARRAY[requestType];
}
local const int_fast16_t HTTP_STATUS_CODE_MAPPING_ARRAY[] = {
100,
101,
102,
200,
201,
202,
203,
204,
205,
206,
207,
208,
226,
300,
301,
302,
303,
304,
305,
307,
308,
400,
401,
402,
403,
404,
405,
406,
407,
408,
409,
410,
411,
412,
413,
414,
415,
416,
417,
418,
421,
422,
423,
424,
426,
428,
429,
431,
444,
451,
499,
500,
501,
502,
503,
504,
505,
506,
507,
508,
510,
511,
599
};
inline int_fast16_t http_getStatusCode(HTTP_StatusCode statusCode){
return HTTP_STATUS_CODE_MAPPING_ARRAY[statusCode];
}
inline void http_setHTTP_Version(HTTP_Response* response, const char version[]){
memcpy(response->httpVersion, version, 9);
}
typedef struct{
const char* name;
const uint_fast64_t length;
}ContentType;
local const ContentType HTTP_CONTENT_TYPE_MAPPING_ARRAY[] = {
{"TEXT/HTML", 9},
{"text/css", 8},
{"application/javascript", 22},
{"application/json", 16},
{"application/zip", 15},
{"iamge/jpeg", 10},
{"image/png", 9},
{"image/svg+xml", 13},
{"image/x-icon", 12}
};
inline const char* http_contentTypeToString(const HTTP_ContentType contentType, uint_fast64_t* length){
const ContentType _contentType = HTTP_CONTENT_TYPE_MAPPING_ARRAY[contentType];
*length = _contentType.length;
return _contentType.name;
}
// printf("#define HASH_TXT %d\n", util_hashString("txt", 3));
// printf("#define HASH_HTML %d\n", util_hashString("html", 4));
// printf("#define HASH_CSS %d\n", util_hashString("css", 3));
// printf("#define HASH_JS %d\n", util_hashString("js", 2));
// printf("#define HASH_JPG %d\n", util_hashString("jpg", 3));
// printf("#define HASH_PNG %d\n", util_hashString("png", 3));
// printf("#define HASH_SVG %d\n", util_hashString("svg", 3));
// printf("#define HASH_ICO %d\n", util_hashString("ico", 3));
// printf("#define HASH_ZIP %d\n", util_hashString("zip", 3));
inline HTTP_ContentType http_getContentType(const char* fileExtension, const uint_fast64_t fileExtensionLength){
#define HASH_TXT 966206576
#define HASH_HTML 542175051
#define HASH_CSS 825432995
#define HASH_JS 6953609
#define HASH_JPG 883066721
#define HASH_PNG 932504553
#define HASH_SVG 957813860
#define HASH_ICO 873952437
#define HASH_ZIP 1014791617
switch(util_hashString(fileExtension, fileExtensionLength)){
case HASH_CSS :{
return HTTP_CONTENT_TYPE_TEXT_CSS;
break;
}
case HASH_JS :{
return HTTP_CONTENT_TYPE_APPLICATION_JAVASCRIPT;
break;
}
case HASH_PNG :{
return HTTP_CONTENT_TYPE_IMAGE_PNG;
break;
}
case HASH_JPG :{
return HTTP_CONTENT_TYPE_IMAGE_JPG;
break;
}
case HASH_SVG :{
return HTTP_CONTENT_TYPE_IMAGE_SVG;
break;
}
case HASH_ICO:{
return HTTP_CONTENT_TYPE_IMAGE_ICON;
break;
}
case HASH_HTML:
case HASH_TXT:
default:{
return HTTP_CONTENT_TYPE_TEXT_HTML;
break;
}
}
#undef HASH_TXT
#undef HASH_HTML
#undef HASH_CSS
#undef HASH_JS
#undef HASH_JPG
#undef HASH_PNG
#undef HASH_SVG
#undef HASH_ICO
#undef HASH_ZIP
}
#endif |
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import React, { cloneElement, Children, Component } from 'react';
import { compose } from 'recompose';
import { withTheme } from 'styled-components';
import { colorIsDark, normalizeBackground, normalizeColor } from '../../utils';
import { defaultProps } from '../../default-props';
import { Box } from '../Box';
import { withFocus, withForwardRef } from '../hocs';
import { StyledButton } from './StyledButton';
var isDarkBackground = function isDarkBackground(props) {
var backgroundColor = normalizeBackground(normalizeColor(props.color || props.theme.button.primary.color || props.theme.global.colors.control || 'brand', props.theme), props.theme);
return colorIsDark(backgroundColor, props.theme);
};
var Button =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Button, _Component);
function Button(props) {
var _this;
_this = _Component.call(this, props) || this;
_defineProperty(_assertThisInitialized(_this), "state", {});
_defineProperty(_assertThisInitialized(_this), "onMouseOver", function (event) {
var onMouseOver = _this.props.onMouseOver;
_this.setState({
hover: true
});
if (onMouseOver) {
onMouseOver(event);
}
});
_defineProperty(_assertThisInitialized(_this), "onMouseOut", function (event) {
var onMouseOut = _this.props.onMouseOut;
_this.setState({
hover: false
});
if (onMouseOut) {
onMouseOut(event);
}
});
var children = props.children,
icon = props.icon,
label = props.label;
if ((icon || label) && children) {
console.warn('Button should not have children if icon or label is provided');
}
return _this;
}
var _proto = Button.prototype;
_proto.render = function render() {
var _this$props = this.props,
a11yTitle = _this$props.a11yTitle,
color = _this$props.color,
forwardRef = _this$props.forwardRef,
children = _this$props.children,
disabled = _this$props.disabled,
icon = _this$props.icon,
gap = _this$props.gap,
fill = _this$props.fill,
focus = _this$props.focus,
href = _this$props.href,
label = _this$props.label,
onClick = _this$props.onClick,
plain = _this$props.plain,
primary = _this$props.primary,
reverse = _this$props.reverse,
theme = _this$props.theme,
type = _this$props.type,
as = _this$props.as,
rest = _objectWithoutPropertiesLoose(_this$props, ["a11yTitle", "color", "forwardRef", "children", "disabled", "icon", "gap", "fill", "focus", "href", "label", "onClick", "plain", "primary", "reverse", "theme", "type", "as"]);
var hover = this.state.hover;
var buttonIcon = icon; // only change color if user did not specify the color themselves...
if (primary && icon && !icon.props.color) {
buttonIcon = cloneElement(icon, {
color: theme.global.colors.text[isDarkBackground(this.props) ? 'dark' : 'light']
});
}
var domTag = !as && href ? 'a' : as;
var first = reverse ? label : buttonIcon;
var second = reverse ? buttonIcon : label;
var contents;
if (first && second) {
contents = React.createElement(Box, {
direction: "row",
align: "center",
justify: "center",
gap: gap
}, first, second);
} else if (typeof children === 'function') {
contents = children({
hover: hover,
focus: focus
});
} else {
contents = first || second || children;
} // the key events are covered by withFocus()
/* eslint-disable jsx-a11y/mouse-events-have-key-events */
return React.createElement(StyledButton, _extends({}, rest, {
as: domTag,
ref: forwardRef,
"aria-label": a11yTitle,
colorValue: color,
disabled: disabled,
hasIcon: !!icon,
gap: gap,
hasLabel: !!label,
fillContainer: fill,
focus: focus,
href: href,
onClick: onClick,
onMouseOver: this.onMouseOver,
onMouseOut: this.onMouseOut,
pad: !plain,
plain: typeof plain !== 'undefined' ? plain : Children.count(children) > 0 || icon && !label,
primary: primary,
type: !href ? type : undefined
}), contents);
};
return Button;
}(Component);
_defineProperty(Button, "defaultProps", {
type: 'button',
focusIndicator: true,
gap: 'small'
});
Object.setPrototypeOf(Button.defaultProps, defaultProps);
var ButtonDoc;
if (process.env.NODE_ENV !== 'production') {
ButtonDoc = require('./doc').doc(Button); // eslint-disable-line global-require
}
var ButtonWrapper = compose(withFocus(), withTheme, withForwardRef)(ButtonDoc || Button);
export { ButtonWrapper as Button }; |
var FreqStack = function() {
this.maxFreq = 0;
this.freqMap = {};
this.stackMap = {};
};
/**
* @param {number} x
* @return {void}
*/
FreqStack.prototype.push = function(x) {
if (this.freqMap[x] == null) {
this.freqMap[x] = 1;
} else {
this.freqMap[x]++;
}
this.maxFreq = Math.max(this.maxFreq, this.freqMap[x]);
if (this.stackMap[this.freqMap[x]] == null) {
this.stackMap[this.freqMap[x]] = [x];
} else {
this.stackMap[this.freqMap[x]].push(x);
}
};
/**
* @return {number}
*/
FreqStack.prototype.pop = function() {
const stack = this.stackMap[this.maxFreq];
const v = stack.pop();
this.freqMap[v]--;
if (stack.length == 0) {
this.maxFreq--;
}
return v;
};
/**
* Your FreqStack object will be instantiated and called as such:
* var obj = new FreqStack()
* obj.push(x)
* var param_2 = obj.pop()
*/
/**
* 找到出现频率最大的值,出栈,然后更新出现频率最大的值。压入一个值时,再次更新出现频率最大的值。
* 例如,[5,7,5,7,4,5] 依次入栈,
* 接着执行 pop 操作,
* 这时要先找出出现频率最大的值,5,然后移出栈。接着更新频率最大的值。
* 三个难点:
* 第一,如何维护这个出现频率最大的值。
* 第二,如何如何在做出栈操作时,维护好数组。
* 第三,这个频率最大的值如何和栈联系起来,即,如何在栈中找到这个数。
*
* 换一个思路,
* 不去关心这个出现频率最大的值,而是关心这个频率。而这个频率又映射了达到这个频率的数字,所组成的
* 栈。
*/
|
<filename>scripts/thumbnail.js
let hashCode = s => Math.abs(s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0))
/**
* Thumbnail Helper
* @description Get the thumbnail url from a post
* @example
* <%- thumbnail(post) %>
*/
hexo.extend.helper.register("thumbnail", function(post) {
return post.thumbnail || post.banner || "";
});
hexo.extend.tag.register("obs", function(args) {
let id = args[0];
let hash = hashCode(id);
return `
<div id="note_${hash}"></div>
<script type="module">
import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";
import define from "${id}";
const runtime = new Runtime();
const main = runtime.module(define, Inspector.into(document.querySelector('#note_${hash}')));
</script>`;
});
|
class LogProcessor:
@staticmethod
def format_tags(entry):
# Initialize an empty list to store formatted key-value pairs
tag = []
# Iterate through each key-value pair in the entry dictionary
for arg in entry:
# Format the key-value pair and append it to the tag list
tag.append("{0!s}={1!s}".format(arg, entry[arg]))
# Join the formatted key-value pairs with commas and return the resulting string
return ','.join(tag)
@staticmethod
def format_time(entry):
# Convert the 'time' value in the entry dictionary to a float, then to an integer, and return it
return int(float(entry['time'])) |
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# load and prepare the dataset
X = np.load('X.npy');
y = np.load('y.npy');
# create and fit the SVM model
model = SVC()
model.fit(X, y)
# get predictions from the model
predictions = model.predict(X)
# evaluate the model
acc = accuracy_score(y, predictions)
print("Accuracy: ", acc) |
#!/bin/sh
exec docker-compose run crawler "$@"
|
import { Router } from 'https://deno.land/x/oak@v6.0.0/mod.ts'
import { getBooks, getBook, addBook, updateBook, deleteBook } from './controller.ts'
const router = new Router()
router.get('/books', getBooks)
.get('/books/:isbn', getBook)
.post('/books', addBook)
.put('/books/:isbn', updateBook)
.delete('/books/:isbn', deleteBook)
export default router
|
from bs4 import BeautifulSoup
def extract_metadata(html_content: str) -> dict:
metadata = {}
soup = BeautifulSoup(html_content, 'html.parser')
meta_tags = soup.find_all('meta')
for tag in meta_tags:
if 'http-equiv' in tag.attrs:
metadata['content-type'] = tag['content']
elif 'name' in tag.attrs:
if tag['name'] == 'description':
metadata['description'] = tag['content']
elif tag['name'] == 'keywords':
metadata['keywords'] = tag['content']
metadata['title'] = soup.title.string
return metadata |
import React from "react"
const Testimonial = ({quote, attribution}) => {
return (
<div>
<blockquote className=" p-4 text-xl italic border-l-4 bg-neutral-100 text-neutral-600 border-primary quote">
<p className="mb-4">
{quote}
</p>
{ attribution && <cite>
<a
className="text-sm float-right"
// href="..."
// target="_blank"
// rel="noopener noreferrer"
>
{attribution}
</a>
</cite>}
</blockquote>
</div>
)
}
export default Testimonial
|
const textToImage = require('text-to-image');
const Randomath = require('randomath');
const math = new Randomath();
const mongo = require('mongodb');
const url = process.env.MONGO;
module.exports = () => (ctx) => {
// Add true answer to database
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
let db = client.db('randomath');
db.collection('users').find({ "id": ctx.from.id }).toArray((err, data) => {
db.collection('users').updateOne({ "id": ctx.from.id }, { $set: { "true_answers" : data[0].true_answers + 1, "last_time_used": new Date().getTime(), "addition": data[0].addition + 1 } }, (err, result) => {
if (err) return console.error(err);
});
});
});
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
let db = client.db('randomath');
db.collection('users').find({ "id": ctx.from.id }).toArray((err, data) => {
let difficulty = data[0].difficulty;
let sample = math.getRandomAdd(1, difficulty);
textToImage.generate(`\n${sample[0].example}`, {
maxWidth: 720,
fontSize: 100,
fontFamily: 'Helvetica',
fontWeight: 'bold',
textAlign: 'center',
lineHeight: 70,
customHeight: 250,
margin: 10,
bgColor: "#309f5e",
textColor: "#f1f1e9"
}).then(async function (dataUri) {
let length = dataUri.length
let imagestring = dataUri.slice(21, length);
let image = { source: Buffer.from(imagestring, 'base64') }
let trueAnswer = sample[0].answer;
let answerDataF = 'wrong1';
let answerDataS = 'wrong2';
let answerDataT = 'wrong3';
if (sample[0].answers[0] === trueAnswer) {
answerDataF = 'right_add';
} else if (sample[0].answers[1] === trueAnswer) {
answerDataS = 'right_add';
} else if (sample[0].answers[2] === trueAnswer) {
answerDataT = 'right_add';
}
await ctx.editMessageMedia({ type: 'photo', media: image})
ctx.editMessageReplyMarkup({
inline_keyboard: [[
{text: sample[0].answers[0], callback_data: answerDataF},
{text: sample[0].answers[1], callback_data: answerDataS},
{text: sample[0].answers[2], callback_data: answerDataT}
],
[
{text: '❌ Stop', callback_data: 'back:train'}
]]
})
});
ctx.answerCbQuery('✅ Correct!');
})
})
} |
package server
import (
"io/ioutil"
"net/http"
"path/filepath"
"time"
"github.com/ant0ine/go-json-rest/rest"
"github.com/gbtouch/screen-server/log"
"gopkg.in/yaml.v2"
)
type Config struct {
DB map[string][]string `yaml:"db,omitempty"`
ServiceUrl []string `yaml:"configserivce"`
}
var Settings Config
func check(e error) {
if e != nil {
logger.Log.Error("Server err: %v", e)
}
}
func loadConfig() {
filename, _ := filepath.Abs("./config.yaml")
yamlFile, err := ioutil.ReadFile(filename)
check(err)
err = yaml.Unmarshal(yamlFile, &Settings)
check(err)
}
//Open makes screen_server open
func Open() {
logger.Init()
logger.Log.Debug("Start Screen Server")
logger.Log.Info("loading local config")
loadConfig()
logger.Log.Info("loaded")
logger.Log.Info("--------------------")
logger.Log.Info("connect mongo db")
Mongo.InitDB()
logger.Log.Info("connected")
logger.Log.Info("--------------------")
logger.Log.Info("loading resource&layouts")
if Mongo.DB != nil {
Resources.Load(Mongo.DB)
Layouts.Load(Mongo.DB)
logger.Log.Info("loaded")
} else {
logger.Log.Error("connect to mongodb failed")
}
logger.Log.Info("--------------------")
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
&rest.Route{"GET", "/resource", getResourceHandler},
&rest.Route{"POST", "/resource", setResourceHandler},
&rest.Route{"GET", "/layouts", getLayoutsHandler},
&rest.Route{"POST", "/layout", setLayoutHandler},
&rest.Route{"POST", "/layout/current", setCurrentLayoutHandler},
&rest.Route{"PATCH", "/layout/current", updateCurrentLayoutHandler},
&rest.Route{"POST", "/layout/:id/resource", updateLayoutResourceHandler},
&rest.Route{"POST", "/error", notifyErrorHandler},
&rest.Route{"POST", "/control/heartbeat", setHeartbeatHandler},
&rest.Route{"POST", "/display/heartbeat", setHeartbeatHandler},
)
check(err)
api.SetApp(router)
//Mock()
server = newSocketServer()
ticker := time.NewTicker(time.Second * 30)
go func() {
for t := range ticker.C {
logger.Log.Debug("time:", t)
logger.Log.Debug("clients:", clients.Map)
}
}()
http.Handle("/", api.MakeHandler())
http.Handle("/socket.io/", server)
err = http.ListenAndServe(":8080", nil)
check(err)
logger.Log.Info("Start Screen Server")
}
|
#!/bin/bash
dieharder -d 12 -g 51 -S 2135964576
|
#!/bin/sh
##
# Updates git template of all repos in a given directory, recursively.
#
#
# Configs
#
template="$HOME/.git-template"
## Print usage message
usage() {
cat <<USAGE
USAGE: $0 [-h] [-t TEMPLATE] DIR
Updates git template of all repos, recursively from a given directory DIR.
DIR is the folder containing repos. This directory is searched for repos,
recursively.
Options:
-h print this usage message
-t path to the template directory. default: $template
USAGE
}
#
# Here the script starts ...
#
# Parse options
while getopts "e:hiv" opt
do
case $opt in
h) usage; exit 0;;
e) template="$OPTARG";;
?) usage; exit 2;;
esac
done
shift $((OPTIND - 1))
# Check positional arguments
if [ $# -ne 1 ]; then
echo "Missing position argument: DIR"
usage
exit 2
fi
# Save positional arguments
d=$1
# Test for existence
if [ ! -d "${d}" ]; then
echo "Directory \"${d}\" does not exist!"
exit 2
fi
# Find .git directories
repodirs=$(find "$d" -type d -name ".git")
if [ "$repodirs" = "" ]
then
echo "No repos in this directory."
exit 0
fi
# Remove .git directory from path
#repodirs=$(echo "$repodirs" | sed "s/\(.*\).git/\1/")
# Go through all repo-directories and sync
set -x # print commands as they are executed
for dir in ${repodirs}; do
rsync --archive --verbose --compress --cvs-exclude "$template"/hooks/ "$dir"/hooks --delete
done
|
<reponame>supsi-dacd-isaac/cosmos-apps
/* eslint-disable */
import { Reader, util, configure, Writer } from 'protobufjs/minimal';
import * as Long from 'long';
export const protobufPackage = 'supsidacdisaac.tsdb.tsdb';
const baseMsgCreateTimeseries = { creator: '', location: '', signal: '' };
export const MsgCreateTimeseries = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.location !== '') {
writer.uint32(18).string(message.location);
}
if (message.signal !== '') {
writer.uint32(26).string(message.signal);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgCreateTimeseries };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.location = reader.string();
break;
case 3:
message.signal = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgCreateTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.location !== undefined && object.location !== null) {
message.location = String(object.location);
}
else {
message.location = '';
}
if (object.signal !== undefined && object.signal !== null) {
message.signal = String(object.signal);
}
else {
message.signal = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.location !== undefined && (obj.location = message.location);
message.signal !== undefined && (obj.signal = message.signal);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgCreateTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.location !== undefined && object.location !== null) {
message.location = object.location;
}
else {
message.location = '';
}
if (object.signal !== undefined && object.signal !== null) {
message.signal = object.signal;
}
else {
message.signal = '';
}
return message;
}
};
const baseMsgCreateTimeseriesResponse = { id: 0 };
export const MsgCreateTimeseriesResponse = {
encode(message, writer = Writer.create()) {
if (message.id !== 0) {
writer.uint32(8).uint64(message.id);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgCreateTimeseriesResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.id = longToNumber(reader.uint64());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgCreateTimeseriesResponse };
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
return message;
},
toJSON(message) {
const obj = {};
message.id !== undefined && (obj.id = message.id);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgCreateTimeseriesResponse };
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
return message;
}
};
const baseMsgUpdateTimeseries = { creator: '', id: 0, location: '', signal: '' };
export const MsgUpdateTimeseries = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.id !== 0) {
writer.uint32(16).uint64(message.id);
}
if (message.location !== '') {
writer.uint32(26).string(message.location);
}
if (message.signal !== '') {
writer.uint32(34).string(message.signal);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgUpdateTimeseries };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.id = longToNumber(reader.uint64());
break;
case 3:
message.location = reader.string();
break;
case 4:
message.signal = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgUpdateTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
if (object.location !== undefined && object.location !== null) {
message.location = String(object.location);
}
else {
message.location = '';
}
if (object.signal !== undefined && object.signal !== null) {
message.signal = String(object.signal);
}
else {
message.signal = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.id !== undefined && (obj.id = message.id);
message.location !== undefined && (obj.location = message.location);
message.signal !== undefined && (obj.signal = message.signal);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgUpdateTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
if (object.location !== undefined && object.location !== null) {
message.location = object.location;
}
else {
message.location = '';
}
if (object.signal !== undefined && object.signal !== null) {
message.signal = object.signal;
}
else {
message.signal = '';
}
return message;
}
};
const baseMsgUpdateTimeseriesResponse = {};
export const MsgUpdateTimeseriesResponse = {
encode(_, writer = Writer.create()) {
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgUpdateTimeseriesResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_) {
const message = { ...baseMsgUpdateTimeseriesResponse };
return message;
},
toJSON(_) {
const obj = {};
return obj;
},
fromPartial(_) {
const message = { ...baseMsgUpdateTimeseriesResponse };
return message;
}
};
const baseMsgDeleteTimeseries = { creator: '', id: 0 };
export const MsgDeleteTimeseries = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.id !== 0) {
writer.uint32(16).uint64(message.id);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgDeleteTimeseries };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.id = longToNumber(reader.uint64());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgDeleteTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.id !== undefined && (obj.id = message.id);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgDeleteTimeseries };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
return message;
}
};
const baseMsgDeleteTimeseriesResponse = {};
export const MsgDeleteTimeseriesResponse = {
encode(_, writer = Writer.create()) {
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgDeleteTimeseriesResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_) {
const message = { ...baseMsgDeleteTimeseriesResponse };
return message;
},
toJSON(_) {
const obj = {};
return obj;
},
fromPartial(_) {
const message = { ...baseMsgDeleteTimeseriesResponse };
return message;
}
};
const baseMsgCreateMeasure = { creator: '', timeseriesID: '', ts: '', value: '' };
export const MsgCreateMeasure = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.timeseriesID !== '') {
writer.uint32(18).string(message.timeseriesID);
}
if (message.ts !== '') {
writer.uint32(26).string(message.ts);
}
if (message.value !== '') {
writer.uint32(34).string(message.value);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgCreateMeasure };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.timeseriesID = reader.string();
break;
case 3:
message.ts = reader.string();
break;
case 4:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgCreateMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.timeseriesID !== undefined && object.timeseriesID !== null) {
message.timeseriesID = String(object.timeseriesID);
}
else {
message.timeseriesID = '';
}
if (object.ts !== undefined && object.ts !== null) {
message.ts = String(object.ts);
}
else {
message.ts = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
}
else {
message.value = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.timeseriesID !== undefined && (obj.timeseriesID = message.timeseriesID);
message.ts !== undefined && (obj.ts = message.ts);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgCreateMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.timeseriesID !== undefined && object.timeseriesID !== null) {
message.timeseriesID = object.timeseriesID;
}
else {
message.timeseriesID = '';
}
if (object.ts !== undefined && object.ts !== null) {
message.ts = object.ts;
}
else {
message.ts = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
}
else {
message.value = '';
}
return message;
}
};
const baseMsgCreateMeasureResponse = { id: 0 };
export const MsgCreateMeasureResponse = {
encode(message, writer = Writer.create()) {
if (message.id !== 0) {
writer.uint32(8).uint64(message.id);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgCreateMeasureResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.id = longToNumber(reader.uint64());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgCreateMeasureResponse };
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
return message;
},
toJSON(message) {
const obj = {};
message.id !== undefined && (obj.id = message.id);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgCreateMeasureResponse };
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
return message;
}
};
const baseMsgUpdateMeasure = { creator: '', id: 0, timeseriesID: '', ts: '', value: '' };
export const MsgUpdateMeasure = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.id !== 0) {
writer.uint32(16).uint64(message.id);
}
if (message.timeseriesID !== '') {
writer.uint32(26).string(message.timeseriesID);
}
if (message.ts !== '') {
writer.uint32(34).string(message.ts);
}
if (message.value !== '') {
writer.uint32(42).string(message.value);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgUpdateMeasure };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.id = longToNumber(reader.uint64());
break;
case 3:
message.timeseriesID = reader.string();
break;
case 4:
message.ts = reader.string();
break;
case 5:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgUpdateMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
if (object.timeseriesID !== undefined && object.timeseriesID !== null) {
message.timeseriesID = String(object.timeseriesID);
}
else {
message.timeseriesID = '';
}
if (object.ts !== undefined && object.ts !== null) {
message.ts = String(object.ts);
}
else {
message.ts = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
}
else {
message.value = '';
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.id !== undefined && (obj.id = message.id);
message.timeseriesID !== undefined && (obj.timeseriesID = message.timeseriesID);
message.ts !== undefined && (obj.ts = message.ts);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgUpdateMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
if (object.timeseriesID !== undefined && object.timeseriesID !== null) {
message.timeseriesID = object.timeseriesID;
}
else {
message.timeseriesID = '';
}
if (object.ts !== undefined && object.ts !== null) {
message.ts = object.ts;
}
else {
message.ts = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
}
else {
message.value = '';
}
return message;
}
};
const baseMsgUpdateMeasureResponse = {};
export const MsgUpdateMeasureResponse = {
encode(_, writer = Writer.create()) {
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgUpdateMeasureResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_) {
const message = { ...baseMsgUpdateMeasureResponse };
return message;
},
toJSON(_) {
const obj = {};
return obj;
},
fromPartial(_) {
const message = { ...baseMsgUpdateMeasureResponse };
return message;
}
};
const baseMsgDeleteMeasure = { creator: '', id: 0 };
export const MsgDeleteMeasure = {
encode(message, writer = Writer.create()) {
if (message.creator !== '') {
writer.uint32(10).string(message.creator);
}
if (message.id !== 0) {
writer.uint32(16).uint64(message.id);
}
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgDeleteMeasure };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.creator = reader.string();
break;
case 2:
message.id = longToNumber(reader.uint64());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object) {
const message = { ...baseMsgDeleteMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = String(object.creator);
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = Number(object.id);
}
else {
message.id = 0;
}
return message;
},
toJSON(message) {
const obj = {};
message.creator !== undefined && (obj.creator = message.creator);
message.id !== undefined && (obj.id = message.id);
return obj;
},
fromPartial(object) {
const message = { ...baseMsgDeleteMeasure };
if (object.creator !== undefined && object.creator !== null) {
message.creator = object.creator;
}
else {
message.creator = '';
}
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
}
else {
message.id = 0;
}
return message;
}
};
const baseMsgDeleteMeasureResponse = {};
export const MsgDeleteMeasureResponse = {
encode(_, writer = Writer.create()) {
return writer;
},
decode(input, length) {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgDeleteMeasureResponse };
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_) {
const message = { ...baseMsgDeleteMeasureResponse };
return message;
},
toJSON(_) {
const obj = {};
return obj;
},
fromPartial(_) {
const message = { ...baseMsgDeleteMeasureResponse };
return message;
}
};
export class MsgClientImpl {
constructor(rpc) {
this.rpc = rpc;
}
CreateTimeseries(request) {
const data = MsgCreateTimeseries.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'CreateTimeseries', data);
return promise.then((data) => MsgCreateTimeseriesResponse.decode(new Reader(data)));
}
UpdateTimeseries(request) {
const data = MsgUpdateTimeseries.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'UpdateTimeseries', data);
return promise.then((data) => MsgUpdateTimeseriesResponse.decode(new Reader(data)));
}
DeleteTimeseries(request) {
const data = MsgDeleteTimeseries.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'DeleteTimeseries', data);
return promise.then((data) => MsgDeleteTimeseriesResponse.decode(new Reader(data)));
}
CreateMeasure(request) {
const data = MsgCreateMeasure.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'CreateMeasure', data);
return promise.then((data) => MsgCreateMeasureResponse.decode(new Reader(data)));
}
UpdateMeasure(request) {
const data = MsgUpdateMeasure.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'UpdateMeasure', data);
return promise.then((data) => MsgUpdateMeasureResponse.decode(new Reader(data)));
}
DeleteMeasure(request) {
const data = MsgDeleteMeasure.encode(request).finish();
const promise = this.rpc.request('supsidacdisaac.tsdb.tsdb.Msg', 'DeleteMeasure', data);
return promise.then((data) => MsgDeleteMeasureResponse.decode(new Reader(data)));
}
}
var globalThis = (() => {
if (typeof globalThis !== 'undefined')
return globalThis;
if (typeof self !== 'undefined')
return self;
if (typeof window !== 'undefined')
return window;
if (typeof global !== 'undefined')
return global;
throw 'Unable to locate global object';
})();
function longToNumber(long) {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long;
configure();
}
|
<gh_stars>1-10
import { CommonModule } from '@angular/common';
import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { MapViewComponent } from './components/map-view/map-view.component';
import {
SceneViewComponent
} from './components/scene-view/scene-view.component';
import { EsriLoaderGuard } from './services/esri-loader-guard';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
MapViewComponent,
SceneViewComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
HttpClientJsonpModule,
NgbModule,
AppRoutingModule
],
bootstrap: [AppComponent],
providers: [
EsriLoaderGuard
]
})
export class AppModule {}
|
package intercept.server;
import intercept.framework.Command;
import intercept.framework.Presenter;
import intercept.framework.UriMatcher;
import java.util.LinkedList;
import java.util.List;
public class Dispatcher {
public final List<DispatchEntry<Presenter>> presenterRegistry;
public final List<DispatchEntry<Command>> commandRegistry;
public Dispatcher() {
presenterRegistry = new LinkedList<DispatchEntry<Presenter>>();
commandRegistry = new LinkedList<DispatchEntry<Command>>();
}
public void dispatchGetRequest(WebContext context) {
context.present(presenterRegistry, context);
}
public void dispatchPostRequest(WebContext context) {
context.executeCommand(commandRegistry, context);
}
public void register(UriMatcher matcher, Presenter presenter) {
presenterRegistry.add(new DispatchEntry(matcher, presenter));
}
public void register(UriMatcher matcher, Command command) {
commandRegistry.add(new DispatchEntry(matcher, command));
}
public void register(UriMatcher matcher, Presenter presenter, Command command) {
register(matcher, presenter);
register(matcher, command);
}
}
|
package edu.pdx.cs410J.seung2;
import edu.pdx.cs410J.InvokeMainTestCase;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Tests the functionality in the {@link Project1} main class.
*/
public class Project1IT extends InvokeMainTestCase {
/**
* Invokes the main method of {@link Project1} with the given arguments.
*/
private MainMethodResult invokeMain(String... args) {
return invokeMain( Project1.class, args );
}
/**
* Tests that invoking the main method with no arguments issues an error
*/
@Test
public void testNoCommandLineArguments() {
MainMethodResult result = invokeMain("");
assertThat(result.getExitCode(), equalTo(1));
assertThat(result.getTextWrittenToStandardError(), containsString("Missing command line arguments"));
}
/**
* Tests that invoking the -README option corrrectly works
*/
@Test
public void dashReadmeOptionPrintsOnlyReadme() {
MainMethodResult result = invokeMain("-README");
assertThat(result.getExitCode(), equalTo(0));
assertThat(result.getTextWrittenToStandardOut(), equalTo(Project1.README + "\n"));
assertThat(result.getTextWrittenToStandardError(), equalTo(""));
}
/**
* Tests that invoking -print option with PhoneBill and PhoneCall information correctly initializes both
*/
@Test
public void dashPrintOptionsPrintsNewlyCreatedPhoneCall() {
String caller = "123-456-7890";
String callee = "234-567-8901";
String startDate = "07/04/2018";
String startTime = "6:24";
String endDate = "07/04/2018";
String endTime = "6:48";
MainMethodResult result =
invokeMain("-print", "My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(0));
String phoneCallToString = String.format("Phone call from %s to %s from %s %s to %s %s",
caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getTextWrittenToStandardOut(), equalTo(phoneCallToString + "\n"));
}
/**
* Provided testing by the professor
*/
@Test
public void validCommandLineWithNoDashPrintOptionPrintsNothingToStandardOut() {
String caller = "123-456-7890";
String callee = "234-567-8901";
String startDate = "07/04/2018";
String startTime = "6:24";
String endDate = "07/04/2018";
String endTime = "6:48";
MainMethodResult result =
invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
String phoneCallToString = String.format("Phone call from %s to %s from %s %s to %s %s",
caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(0));
assertThat(result.getTextWrittenToStandardOut(), equalTo(phoneCallToString + "\n"));
assertThat(result.getTextWrittenToStandardError(), equalTo(""));
}
/**
* Testing starting/ending date formatting
* - Not using "-"
* - Incorrect input digits for month, date, and year
* - Non integer
* - More than three input for date
*/
@Test
public void incorrectDateForm(){
String caller = "123-456-7890";
String callee = "234-567-8901";
String startDate = "07-04/2018";
String startTime = "6:24";
String endDate = "07/04/2018";
String endTime = "6:48";
// Testing incorrect date format "/" instead of "-"
MainMethodResult result =
invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing incorrect year length - 3 instead of 4
startDate = "07/04/218";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing incorrect month digit - 3 instead of 2
startDate = "004/04/2018";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing incorrect date digit - 3 instead of 2
startDate = "07/104/2018";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing non-integer input
startDate = "07/04aa/2018";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing more input
startDate = "07/04/2018/22";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
}
/**
* Testing caller/callee number formatting
* - Not using "-"
* - Non integer
* - Four dashes with information instead of three dashes
*/
@Test
public void incorrectNumberForm(){
String caller = "123.456-7890";
String callee = "234-567-8901";
String startDate = "07/04/2018";
String startTime = "6:24";
String endDate = "07/04/2018";
String endTime = "6:48";
// Testing incorrect number format - "." instead of "-"
MainMethodResult result =
invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing non-integer input
caller = "123-45d-4555";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing phone number that has more than three sections
caller = "123-453-4555-222";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
}
/**
* Testing starting/ending time formatting
* - Not using ":"
* - Incorrect input digits for hour and min
* - Non integer
* - More input than hour and min value - "07:06:03"
*/
@Test
public void incorrectTimeForm(){
String caller = "123-456-7890";
String callee = "234-567-8901";
String startDate = "07/04/2018";
String startTime = "6-24";
String endDate = "07/04/2018";
String endTime = "6:48";
// Testing incorrect time format - "-" instead of ":"
MainMethodResult result =
invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing incorrect hour digit - 3 instead of less than 3
startTime = "006:24";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing incorrect min digit - 3 instead of less than 3
startTime = "06:024";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing non-integer input
startTime = "06:a24";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
// Testing more than hour and min input
startTime = "06:24:22";
result = invokeMain("My Customer", caller, callee, startDate, startTime, endDate, endTime);
assertThat(result.getExitCode(), equalTo(1));
}
}
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 19 01:24:45 2017
@author: heitor
"""
from netpyne import sim, specs
import numpy as np
from matplotlib import pyplot as plt
import nerlabmodel as ner
import time
times=[]
freqs = np.array([])
forces = np.array([])
cells_vs = np.array([])
summa = np.array([])
#plt.figure()
import sys
mutype = sys.argv[1]
#mutype = 'S'
if mutype == "S" or mutype =="s":
i_range = np.logspace(np.log10(6),np.log10(25), 15) # S
elif mutype == "FR" or mutype == "fr":
i_range = np.logspace(np.log10(13),np.log10(56), 15) # FR
elif mutype == "FF" or mutype == "ff":
i_range = np.logspace(np.log10(22),np.log10(58), 15) # FF
for i_stim in i_range:
start = time.time()
netParams = specs.NetParams()
simConfig = specs.SimConfig()
netParams.popParams['Pop1'] = {'cellType': 'MED',
'cellModel': 'NAPP',
'numCells': 1}
cellRule = {'conds': {'cellType': 'MED', 'cellModel': 'NAPP'},
'secs': {'soma': {'geom': {'diam': 80, 'L': 80, 'Ra': 70,
'cm': 1, 'nseg': 1},
'mechs': {'napp': {'gnabar': 0.05,
'gnapbar': 0.00052,
'gkfbar': 0.0028,
'gksbar': 0.018,
'mact': 13.0,
'rinact': 0.025,
'el': 0.0,
'vtraub': 0.0,
'gl': 1/1100.0}},
'ions': {'na': {'e': 120},
'k': {'e': -10}},
'vinit': 0},
'dend': {'geom': {'diam': 52.0, 'L': 6150.0, 'Ra': 70.0,
'cm': 1, 'nseg': 1},
'topol': {'parentSec': 'soma',
'parentX': 0,
'childX': 1},
'mechs': {'pas': {'g': 1/12550.0, 'e': 0.0}},
# 'ions': {'caL': {'e': 140}},
'vinit': 0}}}
netParams.cellParams['HHNapp'] = cellRule
netParams.stimSourceParams['Istep'] = {'type': 'IClamp_X',
'sig_type': 1,
'delay': 20,
'dur': 2000,
'amp': i_stim
}
netParams.stimTargetParams['Istep->Pop1'] = {'source': 'Istep',
'conds': {'cellType': 'MED',
'cellModel': 'NAPP'},
'sec': 'soma',
'loc': 0.5}
simConfig.duration = 4*1e3
simConfig.dt = 0.05
simConfig.seeds = {'conn': 1, 'stim': 1, 'loc': 1}
simConfig.createNEURONObj = True
simConfig.createPyStruct = True
simConfig.verbose = False
simConfig.recordCells = ['all']
simConfig.recordTraces = {'v_soma': {'sec':'soma', 'loc': 0.5, 'var': 'v'}}
simConfig.recordStim = True
simConfig.recordStep = simConfig.dt
simConfig.filename = 'Netpyne-cell_output'
simConfig.saveTxt = True
#simConfig.analysis['plotRaster'] = True
#simConfig.analysis['plotTraces'] = {'include': [0,1,2], 'oneFigPer': 'trace'}
#simConfig.analysis['plot2Dnet'] = True # Plot 2D net cells and connections
data = sim.create(netParams=netParams, simConfig=simConfig, output=True)
soma = data[1][0].secs.soma.hSec
dend = data[1][0].secs.dend.hSec
# mutype = 's'
if mutype == "S" or mutype =="s":
ner.mus(soma, dend)
elif mutype == "FR" or mutype == "fr":
ner.mufr(soma, dend)
elif mutype == "FF" or mutype == "ff":
ner.muff(soma, dend)
sim.simulate()
sim.analyze()
t = np.arange(0, simConfig.duration+simConfig.dt, simConfig.dt)
v_list = list()
for i in data[0]['Pop1'].cellGids:
cell = 'cell_'+str(i)
v_list.append(np.array(data[4]['v_soma'][cell].to_python()))
cells_v = np.array(v_list).transpose()
spkt, spkv = ner.getSpikes(t, cells_v, 20, output=True, plotRaster=False, newfigure=False)
force = ner.forceSOF(spkt, t, mutype)
vel_cond = 45. # m/s
axon_len = 0.6 # m
atrasoAx = axon_len/vel_cond
spktAx = spkt+ atrasoAx
freq = 1000./np.diff(spkt[:,1:]).mean()
max_force = force[:,int(1000/t[1]):int(1500/t[1])].mean()
freqs = np.append(freqs, freq)
forces = np.append(forces, max_force)
cells_vs = np.append(cells_vs, cells_v)
summa = np.append(summa, force)
print "force.shape", force.shape
# plt.plot(t, force)
print i_stim, freq#, max_force
if freq>100:
break
end = time.time()
times.append([i_stim, end-start])
print times
np.savetxt("freq"+mutype+".txt",freqs)
np.savetxt("force"+mutype+".txt",forces)
print("Saved "+mutype+" data.")
|
<reponame>hongdongni/swt-bling
package com.readytalk.examples.swt;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public interface SwtBlingExample {
public void run(Display display, Shell shell);
}
|
#! /bin/bash
# customize device environment (e.g. DNS_NAME)
env49rc=/service-config/iot-home/.env49rc
if [ -f $env49rc ]; then
echo sourcing $env49rc ...
source $env49rc
fi
# set default dns: iot49.local
export DNS_NAME=${DNS_NAME:=iot49}
export IP=$(curl -s -X GET --header "Content-Type:application/json" \
"$BALENA_SUPERVISOR_ADDRESS/v1/device?apikey=$BALENA_SUPERVISOR_API_KEY" | \
jq -r ".ip_address")
export HOST_NAME=$(curl -s -X GET --header "Content-Type:application/json" \
"$BALENA_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$BALENA_SUPERVISOR_API_KEY" | \
jq ".network.hostname")
HOST_NAME="${HOST_NAME%\"}"
HOST_NAME="${HOST_NAME#\"}"
# install default configuration
if [[ ! -f /etc/nginx/.config_v1 ]]; then
cp -r /usr/local/src/nginx/* /etc/nginx/
chown -R 1000:100 /etc/nginx/html
cp /etc/nginx/htpasswd /etc/nginx/htpasswd.default
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.default
echo 'nginx config v1 installed' >/etc/nginx/.config_v1
fi
# configuration for self-signed certificate
mkdir -p /etc/nginx/ssl
cat << EOF >/etc/nginx/ssl/cert.conf
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = CA
L = San Francisco
O = Electronics for IoT
OU = iot49-${DNS_NAME}
CN = iot49-${DNS_NAME}
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${DNS_NAME}.local
DNS.2 = $IP
IP.1 = $IP
EOF
# set name for dns advertising & create certificate
if [[ $HOST_NAME != $DNS_NAME || ! -f /etc/nginx/ssl/cert.crt ]]; then
curl -X PATCH --header "Content-Type:application/json" \
--data '{"network": {"hostname": "'"$DNS_NAME"'" } }' \
"$BALENA_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$BALENA_SUPERVISOR_API_KEY"
cd /etc/nginx/ssl
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
-keyout cert.key -out cert.crt -config cert.conf
openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt -passout pass:
cp cert.crt /etc/nginx/html
fi
# start the server
nginx -g "daemon off;"
|
#!/bin/bash
mkdir -p "$PREFIX/bin"
export MACHTYPE=x86_64
export BINDIR=$(pwd)/bin
export L="${LDFLAGS}"
mkdir -p "$BINDIR"
(cd kent/src/lib && make)
(cd kent/src/htslib && make)
(cd kent/src/jkOwnLib && make)
(cd kent/src/hg/lib && make)
(cd kent/src/hg/mouseStuff/chainToAxt && make)
cp bin/chainToAxt "$PREFIX/bin"
chmod +x "$PREFIX/bin/chainToAxt"
|
# Get a line of input
,:>,;
1=b # base = 1
0=n # num = 0
# Convert string into base 10 integer
< :
'0'--
> $b ** > $n ++ ) =n <
'0'++
> $b > a** =b < # base *= 10
<
;
$n p # Print number
0a P # Add trailing newline
|
<reponame>alemesa1991/School-Projects<gh_stars>0
// http://definedbehavior.blogspot.ca/2011/08/value-semantics-copy-elision.html
// elision
// noun
// 1The omission of a sound or syllable when speaking (as in I’m, let’s): the shortening of words by elision [count noun]: conversational elisions
// 1.1 [count noun] An omission of a passage in a book, speech, or film: the movie’s elisions and distortions have been carefully thought out
// 2The process of joining together or merging things, especially abstract ideas: unease at the elision of so many vital questions
#include <iostream>
using namespace std;
typedef double type;
void f( type arg ) {
std::cout << arg << "\n";
}
type g() {
return type();
}
void g1( type const & ref )
{
}
void g2( type arg )
{
type copy(arg);
// operate on copy // operate on arg
}
type f2() {
return type();
}
type g3( type arg ) {
return arg;
}
int main() {
type x;
f( x );
type const & ref = g();
type x2 = g3( f2() );
}
|
define({
onPostShow : function (){
const ntf = new kony.mvc.Navigation("frmMain");
ntf.navigate();
kony.application.dismissLoadingScreen();
}
}); |
sum = 0
for (i in 1:16){
sum = sum + (1/2) ^ (i-1)
}
print(sum) |
import subprocess
def start_msfdb():
try:
subprocess.run(['msfdb', 'start'], check=True)
print("Metasploit Framework Database started successfully")
except subprocess.CalledProcessError as e:
print(f"Error starting Metasploit Framework Database: {e}")
def launch_msfconsole(resource_file):
try:
subprocess.run(['msfconsole', '-r', resource_file], check=True)
print(f"Metasploit console launched with resource file {resource_file}")
except subprocess.CalledProcessError as e:
print(f"Error launching Metasploit console: {e}")
if __name__ == "__main__":
start_msfdb()
launch_msfconsole("hashdump.rc") |
struct InstructionCostTable {
// Define the structure of the InstructionCostTable
}
fn inject_and_cmp(app_name: &str, cost_table: &InstructionCostTable) {
// Implement the logic to inject and compare the usage of instructions
}
fn metering_app2() {
inject_and_cmp("app2", &InstructionCostTable::new());
} |
#!/bin/bash
########## Links the scripts in this directory into ~/bin so they show up in the PATH and can be called anywehre.
BIN=$(cd ~/bin; pwd)
HERE=`pwd`;
for f in $(ls *.sh)
do
if [ $f != "deploy.sh" ]; then
#delete the existing link if it exists
[ -a "$BIN/$f" ] && rm -f "$BIN/$f"
ln -s "$HERE/$f" "$BIN/$f"
fi
done |
#!/bin/bash
tar --exclude='.DS_Store' -cvzf Elm.tgz Elm.docset
|
import pyperclip
import re
usa_phone_regex = re.compile(r'''(
(\d{3}|\(\d{3}\))?
(\s|-|\.)?
(\d{3})
(\s|-|\.)
(\d{4})
(\s*(ext|x|ext.)\s*(\d{2,5}))?
)''', re.VERBOSE)
email_regex = re.compile(r'''(
[a-zA-Z0-9._%+-]+
@
[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2,4})
)''', re.VERBOSE)
text = str(pyperclip.paste())
matches = []
for groups in usa_phone_regex.findall(text):
phone_number = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phone_number += " x" + groups[8]
matches.append(phone_number)
for groups in email_regex.findall(text):
matches.append(groups[0])
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Phone Number and Emails Copied to clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers or emails found.')
|
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Calculate the area of a circle
private void btnArea_Click(object sender, EventArgs e)
{
double radius;
radius = double.Parse(txtRadius.Text);
double area = Math.PI * Math.Pow(radius, 2);
lblOutput.Text = string.Format("The Area of the circle = {0:0.00}", area);
}
} |
#!/bin/bash
set -e
context=$(kubectl config get-contexts --output name | grep automated-clearing-house)
# assume this is ran from the root of moov-io/infra
files=(
envs/oss/apps/10-achfuzz.yml
envs/oss/apps/17-imagecashletterfuzz.yml
envs/oss/apps/18-wirefuzz.yml
envs/oss/apps/19-metro2fuzz.yml
envs/oss/apps/20-iso8583fuzz.yml
)
for file in "${files[@]}"
do
kubectl --context "$context" delete -f "$file"
kubectl --context "$context" apply -f "$file"
done
|
export declare function stripUndefinedProperties<T = any>(obj: Record<string, T>): Record<string, T>;
|
import random
def shuffle_array(arr):
"""This function takes an array as input, and shuffles its elements randomly."""
random.shuffle(arr)
return arr
# Test array
arr = [1,2,3,4,5,6,7]
# Shuffle array
result = shuffle_array(arr)
print("Array after shuffling:", result) |
#!/bin/sh -l
sh -c "echo Hello World , my name is $INPUT_MY_NAME"
|
<reponame>LarsBehrenberg/e-wallet<gh_stars>0
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Grid, Checkbox, Card, Button, Tooltip } from '@material-ui/core';
import avatar1 from '../../../assets/images/avatars/avatar1.jpg';
import avatar7 from '../../../assets/images/avatars/avatar7.jpg';
import AccountBalanceWalletOutlinedIcon from '@material-ui/icons/AccountBalanceWalletOutlined';
import AlarmAddOutlinedIcon from '@material-ui/icons/AlarmAddOutlined';
import CakeOutlinedIcon from '@material-ui/icons/CakeOutlined';
import ContactsOutlinedIcon from '@material-ui/icons/ContactsOutlined';
import SettingsTwoToneIcon from '@material-ui/icons/SettingsTwoTone';
import ViewCompactTwoToneIcon from '@material-ui/icons/ViewCompactTwoTone';
export default function LivePreviewExample() {
return (
<>
<Grid container spacing={6}>
<Grid item xl={6}>
<Card className="card-box pt-4">
<div className="card-tr-actions">
<Checkbox color="primary" id="checkboxProjects3" />
</div>
<div className="d-flex align-items-center px-4 mb-3">
<div className="avatar-icon-wrapper rounded mr-3">
<div className="d-block p-0 avatar-icon-wrapper m-0 d-100">
<div className="rounded overflow-hidden">
<img alt="..." className="img-fluid" src={avatar1} />
</div>
</div>
</div>
<div className="w-100">
<a
href="#/"
onClick={(e) => e.preventDefault()}
className="font-weight-bold font-size-lg"
title="...">
<NAME>
</a>
<span className="text-black-50 d-block pb-1">
Freelance Designer, Mutual Inc.
</span>
<div className="d-flex align-items-center pt-2">
<Button size="small" className="btn-primary mr-3 shadow-none">
Chat
</Button>
<Button size="small" className="btn-neutral-success">
View
</Button>
</div>
</div>
</div>
<div className="my-3 font-size-sm p-3 mx-4 bg-secondary rounded-sm">
<div className="d-flex justify-content-between">
<span className="font-weight-bold">Email:</span>
<span className="text-black-50"><EMAIL></span>
</div>
<div className="d-flex justify-content-between py-2">
<span className="font-weight-bold">Job Description:</span>
<span className="text-black-50">Project Manager</span>
</div>
<div className="d-flex justify-content-between">
<span className="font-weight-bold">Location:</span>
<span className="text-black-50">San Francisco, USA</span>
</div>
</div>
<div className="d-flex align-items-center justify-content-center flex-wrap mb-1 mx-2">
<div className="w-50 p-3">
<Button
href="#/"
onClick={(e) => e.preventDefault()}
className="d-block btn-gradient bg-night-sky text-left px-4 py-3 w-100 rounded-lg shadow-none">
<div>
<AccountBalanceWalletOutlinedIcon className="h1 d-block my-2 text-warning" />
<div className="font-weight-bold font-size-md font-size-md">
Reports
</div>
<div className="font-size-md mb-1 opacity-8">
Monthly Stats
</div>
</div>
</Button>
</div>
<div className="w-50 p-3">
<Button
href="#/"
onClick={(e) => e.preventDefault()}
className="d-block btn-gradient bg-midnight-bloom text-left px-4 py-3 w-100 rounded-lg shadow-none">
<div>
<AlarmAddOutlinedIcon className="h1 d-block my-2 text-success" />
<div className="font-weight-bold font-size-md font-size-md">
Statistics
</div>
<div className="font-size-md mb-1 opacity-8">
Customers stats
</div>
</div>
</Button>
</div>
<div className="w-50 p-3">
<Button
href="#/"
onClick={(e) => e.preventDefault()}
className="d-block btn-gradient bg-vicious-stance text-left px-4 py-3 w-100 rounded-lg shadow-none">
<div>
<CakeOutlinedIcon className="h1 d-block my-2 text-danger" />
<div className="font-weight-bold font-size-md font-size-md">
Projects
</div>
<div className="font-size-md mb-1 opacity-8">
Manage servers
</div>
</div>
</Button>
</div>
<div className="w-50 p-3">
<Button
href="#/"
onClick={(e) => e.preventDefault()}
className="d-block btn-gradient bg-royal text-left px-4 py-3 w-100 rounded-lg shadow-none">
<div>
<ContactsOutlinedIcon className="h1 d-block my-2 text-first" />
<div className="font-weight-bold font-size-md font-size-md">
Tasks
</div>
<div className="font-size-md mb-1 opacity-8">
Pending items
</div>
</div>
</Button>
</div>
</div>
</Card>
</Grid>
<Grid item xl={6}>
<Card className="card-box pt-4 mb-5">
<div className="card-tr-actions">
<Tooltip title="Send Message" placement="top" arrow>
<Button
size="small"
className="btn-neutral-dark d-40 p-0 btn-icon">
<span className="btn-wrapper--icon">
<FontAwesomeIcon icon={['far', 'envelope']} />
</span>
</Button>
</Tooltip>
</div>
<div className="text-center">
<div className="avatar-icon-wrapper rounded-circle m-0">
<div className="d-block p-0 avatar-icon-wrapper m-0 d-90">
<div className="rounded-circle overflow-hidden">
<img alt="..." className="img-fluid" src={avatar7} />
</div>
</div>
</div>
<div>
<div className="badge badge-neutral-success my-2 text-success font-size-sm px-4 py-1 h-auto">
Online
</div>
</div>
<h3 className="font-weight-bold mt-3"><NAME></h3>
<p className="mb-0 text-black-50">
Senior Frontend Developer at <b>Google Inc.</b>
</p>
<div className="pt-3">
<Tooltip title="Github">
<Button className="btn-github d-50 m-2 p-0">
<span className="btn-wrapper--icon">
<FontAwesomeIcon
icon={['fab', 'github']}
className="font-size-lg"
/>
</span>
</Button>
</Tooltip>
<Tooltip title="Instagram" arrow>
<Button className="btn-instagram d-50 m-2 p-0">
<span className="btn-wrapper--icon">
<FontAwesomeIcon
icon={['fab', 'instagram']}
className="font-size-lg"
/>
</span>
</Button>
</Tooltip>
<Tooltip title="Google" arrow>
<Button className="btn-google d-50 m-2 p-0">
<span className="btn-wrapper--icon">
<FontAwesomeIcon
icon={['fab', 'google']}
className="font-size-lg"
/>
</span>
</Button>
</Tooltip>
</div>
<div className="d-flex p-4 bg-secondary card-footer mt-4 flex-wrap">
<div className="w-50 p-2">
<Button
href="#/"
fullWidth
onClick={(e) => e.preventDefault()}
variant="outlined"
className="card card-box d-block text-left p-3 text-primary">
<div>
<ViewCompactTwoToneIcon className="h1 d-block my-2 text-primary" />
<div className="font-weight-bold font-size-md text-black">
Reports
</div>
<div className="font-size-md mb-1 text-black opacity-8">
Monthly Stats
</div>
</div>
</Button>
</div>
<div className="w-50 p-2">
<Button
href="#/"
fullWidth
onClick={(e) => e.preventDefault()}
variant="outlined"
className="card card-box d-block text-left p-3 text-warning">
<div>
<SettingsTwoToneIcon className="h1 d-block my-2 text-warning" />
<div className="font-weight-bold font-size-md text-black">
Statistics
</div>
<div className="font-size-md mb-1 text-black opacity-8">
Customers stats
</div>
</div>
</Button>
</div>
</div>
</div>
</Card>
</Grid>
</Grid>
</>
);
}
|
<script>
// define the API endpoint and API key
var apiURL = "https://example.com/profile/get?apikey=<example_api_key>";
// code to make a request to the API endpoint
fetch(apiURL)
.then(response => response.json())
.then(data => {
// code to parse and display data in the page
const profile = data.profile;
const template = `
<h2>User Profile</h2>
Name: ${profile.name} <br>
Age: ${profile.age} <br>
Location: ${profile.location} <br>
`;
document.getElementById("profile-container").innerHTML = template;
});
</script> |
#!/usr/bin/env bash
# `niv update` puts base32 "nix hashes" (https://nixos.wiki/wiki/Nix_Hash) in nix/sources.json.
# These hashes can't be compared trivially with equivalent hashes output by shasum -a 256.
# This script converts the needed base32 hashes into base16 hashes that can be trivially compared.
#
# This script also makes it so there is no build-time dependency on jq (in addition to nix).
#
# Run this script when updating agent-rs, replica, ic-starter, or ic-ref in nix/sources.json.
set -e
which jq >/dev/null || ( echo "Please install jq in order to run this script." ; exit 1 )
which nix >/dev/null || ( echo "Please install nix in order to run this script." ; exit 1 )
SDK_ROOT_DIR="$( cd -- "$(dirname -- "$( dirname -- "${BASH_SOURCE[0]}" )" )" &> /dev/null && pwd )"
DFX_ASSET_SOURCES="$SDK_ROOT_DIR/scripts/dfx-asset-sources.sh"
NIX_SOURCES_JSON="$SDK_ROOT_DIR/nix/sources.json"
read_sha256_from_nix_sources() {
KEY="$1"
SHA256_BASE32=$(jq -r .'"'"$KEY"'".sha256' "$NIX_SOURCES_JSON")
nix-hash --to-base16 --type sha256 "$SHA256_BASE32"
}
read_url_from_nix_sources() {
KEY="$1"
jq -r .'"'"$KEY"'".url' "$NIX_SOURCES_JSON"
}
normalize_varname() {
echo "$1" | tr '[:lower:]-' '[:upper:]_'
}
write_sha256() {
KEY="$1"
SHA256=$(read_sha256_from_nix_sources "$KEY")
NAME=$(normalize_varname "${KEY}_SHA256")
echo "$NAME=\"$SHA256\"" >>"$DFX_ASSET_SOURCES"
}
write_url() {
KEY="$1"
URL=$(read_url_from_nix_sources "$KEY")
NAME=$(normalize_varname "${KEY}_URL")
echo "$NAME=\"$URL\"" >>"$DFX_ASSET_SOURCES"
}
write_var() {
VALUE=$(jq -r .'"'"$1"'"."'"$2"'"' "$NIX_SOURCES_JSON")
NAME=$(normalize_varname "${1}_${2}")
echo "$NAME=\"$VALUE\"" >>"$DFX_ASSET_SOURCES"
}
echo "# generated by write-dfx-asset-sources.sh" >"$DFX_ASSET_SOURCES"
for name in "ic-ref" "ic-starter" "motoko" "replica";
do
for platform in "darwin" "linux";
do
write_sha256 "${name}-x86_64-${platform}"
write_url "${name}-x86_64-${platform}"
done
done
write_var "icx-proxy" "branch"
write_var "icx-proxy" "rev"
write_var "icx-proxy" "repo"
write_var "motoko-base" "branch"
write_var "motoko-base" "rev"
|
mod common;
use common::*;
use rand::{thread_rng, Rng};
fn miyaguchi_preneel_compression(block: u128, key: u128, cv: u128) -> u128 {
let x = block ^ cv;
let y = encrypt_block_cipher(x, key);
let cv_new = y ^ block;
cv_new
}
fn encrypt_block_cipher(data: u128, key: u128) -> u128 {
// Implement the block cipher encryption logic here
// This could be a simple substitution-permutation network (SPN) or any other block cipher algorithm
// For the purpose of this problem, assume a simple XOR operation as a placeholder
data ^ key
}
#[test]
fn test_miyaguchi_preneel_compression() {
let block = 0x0123456789abcdef0123456789abcdef;
let key = 0x11111111111111111111111111111111;
let cv = 0x22222222222222222222222222222222;
let expected_result = 0x33333333333333333333333333333333;
assert_eq!(miyaguchi_preneel_compression(block, key, cv), expected_result);
} |
#!/bin/bash
set -e
set -u
set -x
. ./common.sh
/usr/bin/env python3.8 --version | grep -q " 3.[6789]"
if [ "$?" != "0" ]; then
if /usr/bin/env python3.8 --version; then
echo "WARNING:: Creating the Briefcase-based Xcode project for iOS requires Python 3.6+."
echo "We will proceed anyway -- but if you get errors, try switching to Python 3.6+."
else
echo "ERROR: Python3.6+ is required"
exit 1
fi
fi
/usr/bin/env python3.8 -m pip show setuptools > /dev/null
if [ "$?" != "0" ]; then
echo "ERROR: Please install setuptools like so: sudo python3.8 -m pip install briefcase"
exit 2
fi
/usr/bin/env python3.8 -m pip show briefcase > /dev/null
if [ "$?" != "0" ]; then
echo "ERROR: Please install briefcase like so: sudo python3.8 -m pip install briefcase"
exit 3
fi
/usr/bin/env python3.8 -m pip show cookiecutter > /dev/null
if [ "$?" != "0" ]; then
echo "ERROR: Please install cookiecutter like so: sudo python3.8 -m pip install cookiecutter"
exit 4
fi
/usr/bin/env python3.8 -m pip show pbxproj > /dev/null
if [ "$?" != "0" ]; then
echo "ERROR: Please install pbxproj like so: sudo python3.8 -m pip install pbxproj"
exit 5
fi
pod > /dev/null
if [ "$?" != "0" ]; then
echo "ERROR: Please install pod command-line tools"
exit 4
fi
set +x
if [ -d iOS ]; then
echo "Warning: 'iOS' directory exists. All modifications will be lost if you continue."
echo "Continue? [y/N]?"
read reply
if [ "$reply" != "y" ]; then
echo "Fair enough. Exiting..."
exit 0
fi
echo "Cleaning up old iOS dir..."
rm -rf iOS
fi
if [ -d ${compact_name}/electrum ]; then
echo "Deleting old ${compact_name}/onekey..."
rm -fr ${compact_name}/electrum
fi
if [ -d ${compact_name}/api ]; then
echo "Deleting old ${compact_name}/api..."
rm -fr ${compact_name}/api
fi
if [ -d ${compact_name}/trezorlib ]; then
echo "Deleting old ${compact_name}/trezorlib..."
rm -fr ${compact_name}/trezorlib
fi
echo "Pulling 'onekey' libs into project from ../electrum ..."
if [ ! -d ../electrum/locale ]; then
(cd .. && contrib/make_locale && cd ios)
if [ "$?" != 0 ]; then
echo ERROR: Could not build locales
exit 1
fi
fi
cp -fpR ../electrum ${compact_name}/electrum
cp -fpR ../trezor/python-trezor/src/trezorlib ${compact_name}/trezorlib
cp -fpR ../electrum_gui ${compact_name}/api
echo "Removing electrum/tests..."
rm -fr ${compact_name}/onekey/electrum/tests
find ${compact_name} -name '*.pyc' -exec rm -f {} \;
echo ""
echo "Building Briefcase-Based iOS Project..."
echo ""
if [ ! -e ${HOME}/.briefcase/Python-3.8-iOS-support.b3.tar ]; then
curl -C -L "https://briefcase-support.org/python?platform=iOS&version=3.8" -o ${HOME}/.briefcase/Python-3.8-iOS-support.b3.tar
fi
python3.8 setup.py ios --support-pkg=${HOME}/.briefcase/Python-3.8-iOS-support.b3.tar
if [ "$?" != 0 ]; then
echo "An error occurred running setup.py"
exit 4
fi
# No longer needed: they fixed the bug. But leaving it here in case bug comes back!
#cd iOS && ln -s . Support ; cd .. # Fixup for broken Briefcase template.. :/
infoplist="iOS/${compact_name}/${compact_name}-Info.plist"
if [ -f "${infoplist}" ]; then
echo ""
echo "Adding custom keys to ${infoplist} ..."
echo ""
plutil -insert "NSAppTransportSecurity" -xml '<dict><key>NSAllowsArbitraryLoads</key><true/></dict>' -- ${infoplist}
if [ "$?" != "0" ]; then
echo "Encountered error adding custom key NSAppTransportSecurity to plist!"
exit 1
fi
#plutil -insert "UIBackgroundModes" -xml '<array><string>fetch</string></array>' -- ${infoplist}
#if [ "$?" != "0" ]; then
# echo "Encountered error adding custom key UIBackgroundModes to plist!"
# exit 1
#fi
longver=`git describe --tags`
if [ -n "$longver" ]; then
shortver=`echo "$longver" | cut -f 1 -d -`
plutil -replace "CFBundleVersion" -string "$longver" -- ${infoplist} && plutil -replace "CFBundleShortVersionString" -string "$shortver" -- ${infoplist}
if [ "$?" != "0" ]; then
echo "Encountered error adding custom keys to plist!"
exit 1
fi
fi
# UILaunchStoryboardName -- this is required to get proper iOS screen sizes due to iOS being quirky AF
if [ -e "Resources/LaunchScreen.storyboard" ]; then
plutil -insert "UILaunchStoryboardName" -string "LaunchScreen" -- ${infoplist}
if [ "$?" != "0" ]; then
echo "Encountered an error adding LaunchScreen to Info.plist!"
exit 1
fi
fi
# Camera Usage key -- required!
plutil -insert "NSCameraUsageDescription" -string "The camera is needed to scan QR codes" -- ${infoplist}
# Bluetooth Usage key -- required!! added by sweepmonkli
plutil -insert "NSBluetoothAlwaysUsageDescription" -string "The Bluetooth is needed to communication with our hardware." -- ${infoplist}
# Stuff related to being able to open .txn and .txt files (open transaction from context menu in other apps)
plutil -insert "CFBundleDocumentTypes" -xml '<array><dict><key>CFBundleTypeIconFiles</key><array/><key>CFBundleTypeName</key><string>Transaction</string><key>LSItemContentTypes</key><array><string>public.plain-text</string></array><key>LSHandlerRank</key><string>Owner</string></dict></array>' -- ${infoplist}
plutil -insert "UTExportedTypeDeclarations" -xml '<array><dict><key>UTTypeConformsTo</key><array><string>public.plain-text</string></array><key>UTTypeDescription</key><string>Transaction</string><key>UTTypeIdentifier</key><string>com.c3-soft.OneKey.txn</string><key>UTTypeSize320IconFile</key><string>signed@2x</string><key>UTTypeSize64IconFile</key><string>signed</string><key>UTTypeTagSpecification</key><dict><key>public.filename-extension</key><array><string>txn</string><string>txt</string></array></dict></dict></array>' -- ${infoplist}
plutil -insert "UTImportedTypeDeclarations" -xml '<array><dict><key>UTTypeConformsTo</key><array><string>public.plain-text</string></array><key>UTTypeDescription</key><string>Transaction</string><key>UTTypeIdentifier</key><string>com.c3-soft.OneKey.txn</string><key>UTTypeSize320IconFile</key><string>signed@2x</string><key>UTTypeSize64IconFile</key><string>signed</string><key>UTTypeTagSpecification</key><dict><key>public.filename-extension</key><array><string>txn</string><string>txt</string></array></dict></dict></array>' -- ${infoplist}
plutil -insert 'CFBundleURLTypes' -xml '<array><dict><key>CFBundleTypeRole</key><string>Viewer</string><key>CFBundleURLName</key><string>onekey</string><key>CFBundleURLSchemes</key><array><string>onekey</string></array></dict></array>' -- ${infoplist}
plutil -replace 'UIRequiresFullScreen' -bool NO -- ${infoplist}
plutil -insert 'NSFaceIDUsageDescription' -string 'FaceID is used for wallet authentication' -- ${infoplist}
plutil -insert 'ITSAppUsesNonExemptEncryption' -bool NO -- ${infoplist}
# Un-comment the below to enforce only portrait orientation mode on iPHone
#plutil -replace "UISupportedInterfaceOrientations" -xml '<array><string>UIInterfaceOrientationPortrait</string></array>' -- ${infoplist}
# Because we are using FullScreen = NO, we must support all interface orientations
plutil -replace 'UISupportedInterfaceOrientations' -xml '<array><string>UIInterfaceOrientationPortrait</string><string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string><string>UIInterfaceOrientationPortraitUpsideDown</string></array>' -- ${infoplist}
plutil -insert 'UIViewControllerBasedStatusBarAppearance' -bool NO -- ${infoplist}
plutil -insert 'UIStatusBarStyle' -string 'UIStatusBarStyleLightContent' -- ${infoplist}
plutil -insert 'NSPhotoLibraryAddUsageDescription' -string 'Required to save QR images to the photo library' -- ${infoplist}
plutil -insert 'NSPhotoLibraryUsageDescription' -string 'Required to save QR images to the photo library' -- ${infoplist}
plutil -insert 'LSSupportsOpeningDocumentsInPlace' -bool NO -- ${infoplist}
fi
if [ -d overrides/ ]; then
echo ""
echo "Applying overrides..."
echo ""
(cd overrides && cp -fpR * ../iOS/ && cd ..)
fi
stupid_launch_image_grr="iOS/${compact_name}/Images.xcassets/LaunchImage.launchimage"
if [ -d "${stupid_launch_image_grr}" ]; then
echo ""
echo "Removing deprecated LaunchImage stuff..."
echo ""
rm -fvr "${stupid_launch_image_grr}"
fi
xcode_file="${xcode_target}.xcodeproj/project.pbxproj"
echo ""
echo "Mogrifying Xcode .pbxproj file to use iOS 10.0 deployment target..."
echo ""
sed -E -i original1 's/(.*)IPHONEOS_DEPLOYMENT_TARGET = [0-9.]+(.*)/\1IPHONEOS_DEPLOYMENT_TARGET = 11.0\2/g' "iOS/${xcode_file}" && \
sed -n -i original2 '/ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME/!p' "iOS/${xcode_file}"
if [ "$?" != 0 ]; then
echo "Error modifying Xcode project file iOS/$xcode_file... aborting."
exit 1
else
echo ".pbxproj mogrifid ok."
fi
echo ""
echo "Adding HEADER_SEARCH_PATHS to Xcode .pbxproj..."
echo ""
python3.8 -m pbxproj flag -t "${xcode_target}" iOS/"${xcode_file}" -- HEADER_SEARCH_PATHS '"$(SDK_DIR)"/usr/include/libxml2'
if [ "$?" != 0 ]; then
echo "Error adding libxml2 to HEADER_SEARCH_PATHS... aborting."
exit 1
fi
resources=Resources/*
if [ -n "$resources" ]; then
echo ""
echo "Adding Resurces/ and CustomCode/ to project..."
echo ""
cp -fRa Resources CustomCode podfile iOS/
(cd iOS && python3.8 -m pbxproj folder -t "${xcode_target}" -r -i "${xcode_file}" Resources)
if [ "$?" != 0 ]; then
echo "Error adding Resources to iOS/$xcode_file... aborting."
exit 1
fi
(cd iOS && python3.8 -m pbxproj folder -t "${xcode_target}" -r -i "${xcode_file}" CustomCode)
if [ "$?" != 0 ]; then
echo "Error adding CustomCode to iOS/$xcode_file... aborting."
exit 1
fi
fi
so_crap=`find iOS/app_packages -iname \*.so -print`
if [ -n "$so_crap" ]; then
echo ""
echo "Deleting .so files in app_packages since they don't work anyway on iOS..."
echo ""
for a in $so_crap; do
rm -vf $a
done
fi
echo ""
echo "Modifying main.m to include PYTHONIOENCODING=UTF-8..."
echo ""
main_m="iOS/${compact_name}/main.m"
cat Support/main.m > ${main_m}
pch="iOS/${compact_name}/${compact_name}-Prefix.pch"
echo '
// Prefix header
//
// The contents of this file are implicitly included at the beginning of every source file.
//
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iOS SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "OneKeyImport.h"
#endif
' > ${pch}
echo ""
echo "Copying google protobuf paymentrequests.proto to app lib dir..."
echo ""
cp -fa ${compact_name}/electrum/*.proto iOS/app/${compact_name}/electrum/
if [ "$?" != "0" ]; then
echo "** WARNING: Failed to copy google protobuf .proto file to app lib dir!"
fi
if [ ! -d iOS/Support ]; then
mkdir iOS/Support
fi
mv iOS/BZip2 iOS/OpenSSL iOS/Python iOS/XZ iOS/VERSIONS iOS/Support/
cp -fa ${compact_name}/CFFI iOS/app/${compact_name}/CFFI
cp -fa ${compact_name}/bitarray iOS/app/${compact_name}/bitarray
cp -fa ${compact_name}/LRU iOS/app/${compact_name}/LRU
cp -fa ${compact_name}/cytoolz iOS/app/${compact_name}/cytoolz
cp -fRa Support/site-package/ iOS/app_packages/
cp -fRa ../electrum/lnwire iOS/app/${compact_name}/electrum
rm -fr ${compact_name}/electrum/*
rm -fr ${compact_name}/trezorlib/*
rm -fr ${compact_name}/api/*
find iOS/app/${compact_name} -name '*.pyc' -exec rm -f {} \;
cd iOS && pod install
if [ "$?" != "0" ]; then
echo "Encountered an error when execute pod install!"
exit 1
fi
# Can add this back when it works uniformly without issues
# /usr/bin/env ruby update_project.rb
echo ''
echo '**************************************************************************'
echo '* *'
echo '* Operation Complete. An Xcode project has been generated in "iOS/" *'
echo '* *'
echo '**************************************************************************'
echo ''
echo ' IMPORTANT!'
echo ' Now you need to either manually add the library libxml2.tbd to the '
echo ' project under "General -> Linked Frameworks and Libraries" *or* '
echo ' run the ./update_project.rb script which will do it for you.'
echo ' Either of the above are needed to prevent build errors! '
echo ''
echo ' Also note:'
echo ' Modifications to files in iOS/ will be clobbered the next '
echo ' time this script is run. If you intend on modifying the '
echo ' program in Xcode, be sure to copy out modifications from iOS/ '
echo ' manually or by running ./copy_back_changes.sh.'
echo ''
echo ' Caveats for App Store & Ad-Hoc distribution:'
echo ' "Release" builds submitted to the app store fail unless the '
echo ' following things are done in "Build Settings" in Xcode: '
echo ' - "Strip Debug Symbols During Copy" = NO '
echo ' - "Strip Linked Product" = NO '
echo ' - "Strip Style" = Debugging Symbols '
echo ' - "Enable Bitcode" = NO '
echo ' - "Valid Architectures" = arm64 '
echo ' - "Symbols Hidden by Default" = NO '
echo ''
|
<gh_stars>1-10
// Scope inline CSS.
ScopedCss.applyTo(document.body);
// Activate all rendered components.
Backbone.Component.activateAll($("body"));
// Prevents weird animations from happening on page load.
document.addEventListener("DOMContentLoaded", function() {
if (!location.hash) {
location.hash = 1;
}
window.setTimeout(function() {
document.body.classList.remove("preload");
}, 50);
});
// Enable left/right controls.
document.addEventListener("keyup", function(evt) {
var keyCode = evt.keyCode;
var index = Number(location.hash.slice(1)) || 1;
var slideItems = document.querySelectorAll("slide-item");
var isLeft = keyCode === 37;
// If the left button, right button, or space button (acting like right) are
// pressed, update the location.
if (isLeft || keyCode === 39 || keyCode === 32) {
// Increment or decrement based on the direction.
index = index - (isLeft ? 1 : -1);
// Never below 0.
index = index < 1 ? 1 : index;
// Never greater than the number of items.
index = index > slideItems.length ? slideItems.length : index;
// Update with the correct index.
location.hash = index;
}
}, true);
|
<filename>src/test/scala/com/tzavellas/coeus/core/WebModuleLoaderTest.scala
/* - Coeus web framework -------------------------
*
* Licensed under the Apache License, Version 2.0.
*
* Author: <NAME>
*/
package com.tzavellas.coeus.core
import javax.servlet.ServletConfig
import org.junit.Test
import org.junit.Assert._
import org.springframework.mock.web.MockServletConfig
import config.WebModule
class WebModuleLoaderTest {
import WebModuleLoaderTest._
val servletConfig = new MockServletConfig("sweb-test")
@Test(expected=classOf[javax.servlet.ServletException])
def no_param_named_web_module_in_servlet_config() {
loadModule()
}
@Test(expected=classOf[javax.servlet.ServletException])
def module_class_not_found() {
setModuleParam("not a class name")
loadModule()
}
@Test(expected=classOf[javax.servlet.ServletException])
def module_class_is_not_a_WebModule() {
servletConfig.addInitParameter(paramName, "java.util.ArrayList")
loadModule()
}
@Test(expected=classOf[IllegalStateException])
def unwrap_any_exceptions_when_instantiating_the_module_class_via_reflection() {
setModuleParam(classOf[ErroneousWebModule].getName)
loadModule()
}
@Test
def successfully_load_the_web_module() {
setModuleParam(classOf[EmptyWebModule].getName)
val module = loadModule()
assertEquals(false, module.hideResources)
assertTrue(module.controllers.result.isEmpty)
assertFalse(module.interceptors.result.isEmpty)
}
def paramName = WebModuleLoader.webModuleParamName
def loadModule() = WebModuleLoader.load(servletConfig)
def setModuleParam(moduleClass: String) {
servletConfig.addInitParameter(paramName, moduleClass)
}
}
object WebModuleLoaderTest {
class EmptyWebModule(sc: ServletConfig) extends WebModule(sc)
class ErroneousWebModule(sc: ServletConfig) extends WebModule(sc) {
throw new IllegalStateException
}
}
|
<filename>eco-commerce/src/main/java/com/ecocommerce/controller/UserController.java
package com.ecocommerce.controller;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.weaver.PerTypeWithinTargetTypeMunger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.ecocommerce.DTO.PanierDTO;
import com.ecocommerce.DTO.ProduitDTO;
import com.ecocommerce.DTO.UserDTO;
import com.ecocommerce.Entity.Panier;
import com.ecocommerce.Entity.Produit;
import com.ecocommerce.Entity.Users;
import com.ecocommerce.service.UserService;
import com.ecocommerce.utile.JwtGetToken;
import com.ecocommerce.utile.MyUserPrincipal;
@RestController
public class UserController {
@Autowired
UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/SignIn")
public UserDTO inscription(@RequestBody UserDTO userDTO) {
return this.userService.saveUser(userDTO);
}
@PostMapping("/login")
public ResponseEntity<UserDTO> login(@RequestBody UserDTO userDTO) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDTO.getEmail(), userDTO.getPassword());
Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
MyUserPrincipal us = (MyUserPrincipal) authentication.getPrincipal();
if (authentication != null && authentication.isAuthenticated()) {
String token = JwtGetToken.getJWTToken(userDTO.getEmail());
userDTO.setId(us.getUser().getId());
if (us.getUser().getPanier() != null) {
userDTO.setPanierDto(this.panierToPanierDTO(us.getUser().getPanier()));
}
userDTO.setNom(us.getUser().getNom());
userDTO.setPrenom(us.getUser().getPrenom());
userDTO.setToken(token);
userDTO.setPassword(null);
return new ResponseEntity<UserDTO>(userDTO,HttpStatus.OK);
}
return null;
}
@GetMapping("/deconnexion")
public void controleurDeconnection(HttpServletRequest request,HttpServletResponse res) throws IOException {
request.getSession().invalidate();
res.sendRedirect("/login");
}
@GetMapping("/utilisateurs")
public List<UserDTO> listeUser(){
return this.userService.listeUsers();
}
public PanierDTO panierToPanierDTO(Panier pan) {
return PanierDTO.builder()
.id(pan.getId())
.produits(pan.getProduits()
.stream()
.map(x -> this.produitToProduitDTO(x)).collect(Collectors.toList())).build();
}
public Panier panierDTOToPanier(PanierDTO pan) {
return Panier.builder()
.id(pan.getId())
.produits(pan.getProduits()
.stream()
.map(x -> this.produitDtoToProduit(x)).collect(Collectors.toList())).build();
}
private ProduitDTO produitToProduitDTO(Produit prd){
return ProduitDTO.builder()
.id(prd.getId())
.image(prd.getImage())
.nom(prd.getNom())
.prix(prd.getPrix())
.description(prd.getDescription()).build();
}
private Produit produitDtoToProduit(ProduitDTO prd){
return Produit.builder()
.image(prd.getImage())
.nom(prd.getNom())
.prix(prd.getPrix())
.description(prd.getDescription()).build();
}
}
|
package com.foxconn.iot.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.foxconn.iot.entity.UserEntity;
import com.foxconn.iot.entity.UserVo;
public interface UserRepository extends JpaRepository<UserEntity, Long> {
UserEntity findById(long id);
UserEntity findByNo(String no);
@Query(value = "select new com.foxconn.iot.entity.UserVo(a.id, a.no, a.name, a.email, a.openId, a.icivetId, a.phone, a.ext, a.avatarUrl, a.status, a.createOn, a.company.id, a.company.name) from UserEntity a")
Page<UserVo> query(Pageable pageable);
@Query(value = "select new com.foxconn.iot.entity.UserVo(a.id, a.no, a.name, a.email, a.openId, a.icivetId, a.phone, a.ext, a.avatarUrl, a.status, a.createOn, a.company.id, a.company.name) "
+ "from UserEntity a where a.company.id in (select b.descendant from CompanyRelationEntity b where b.ancestor=:companyid)")
Page<UserVo> queryByCompanyId(@Param("companyid") long companyid, Pageable pageble);
@Modifying
@Query(value = "update UserEntity a set a.status=:status where a.id=:id")
void updateStatusById(@Param("status") int status, @Param("id") long id);
@Modifying
@Query(value = "update UserEntity a set a.pwd=:<PASSWORD>, a.modify=1 where a.id=:id")
void updatePwdById(@Param("pwd") String pwd, @Param("id") long id);
@Modifying
@Query(value = "update UserEntity a set a.pwd=:<PASSWORD>, a.modify=0 where a.id=:id")
void resetPwd(@Param("pwd") String pwd, @Param("id") long id);
@Query(value = "select b.ancestor from UserEntity a inner join CompanyRelationEntity b on a.company.id = b.descendant where a.id=:userid order by b.depth desc")
List<Long> queryCompanyRelations(@Param("userid") long userid);
@Query(value = "select a.name from tb_role a left join tb_user_role b on a.id = b.role_id where b.user_id=:userid and a.status=0", nativeQuery = true)
List<Object> queryRoles(@Param("userid") long userid);
@Query(value = "select a.name from tb_permission a left join tb_role_permission b on a.id = b.permission_id left join tb_user_role c on b.role_id = c.role_id left join tb_role d on c.role_id=d.id where c.user_id=userid and a.status=0 and d.status=0", nativeQuery = true)
List<Object> queryPermissions(@Param("userid") long userid);
}
|
var _;
_ = setTimeout.length;
_ = setTimeout.name;
_ = setTimeout.prototype;
setTimeout.length = {};
setTimeout.name = {};
setTimeout.prototype = {};
|
import React, { useRef, useState } from 'react'
import cn from 'classnames'
import Link from '../../../Link'
import { OtherToolsPopup, CommunityPopup } from '../Popup'
import { ReactComponent as ArrowUpSVG } from '../../../../../static/img/arrow-up-icon.svg'
import { ReactComponent as ArrowDownSVG } from '../../../../../static/img/arrow-down-icon.svg'
import { logEvent } from '../../../../utils/front/plausible'
import { getFirstPage } from '../../../../utils/shared/sidebar'
const docsPage = getFirstPage()
import * as styles from './styles.module.css'
type PopupName = 'CommunityPopup' | 'OtherToolsPopup'
interface INavLinkData {
href: string
eventType: string
text: string
}
interface INavLinkPopupData {
text: string
popup: PopupName
}
const navLinkItemsData: Array<INavLinkData | INavLinkPopupData> = [
{
href: '/features',
eventType: 'features',
text: 'Features'
},
{
href: docsPage,
eventType: 'doc',
text: 'Doc'
},
{
href: '/blog',
eventType: 'blog',
text: 'Blog'
},
{
text: 'Community',
popup: 'CommunityPopup'
},
{
href: '/support',
eventType: 'support',
text: 'Support'
},
{
text: 'Other Tools',
popup: 'OtherToolsPopup'
}
]
const isPopup = (
item: INavLinkData | INavLinkPopupData
): item is INavLinkPopupData => (item as INavLinkPopupData).popup !== undefined
const LinkItems: React.FC = ({}) => {
const [isCommunityPopupOpen, setIsCommunityPopupOpen] = useState(false)
const [isOtherToolsPopupOpen, setIsOtherToolsPopupOpen] = useState(false)
const communityPopupContainerEl = useRef<HTMLLIElement>(null)
const otherToolsPopupContainerEl = useRef<HTMLLIElement>(null)
let pageCloseEventListener: () => void = () => null
let keyupCloseEventListener: () => void = () => null
const closeAllPopups = (): void => {
setIsCommunityPopupOpen(false)
setIsOtherToolsPopupOpen(false)
pageCloseEventListener()
keyupCloseEventListener()
}
const handlePageClick = (event: MouseEvent): void => {
if (
!communityPopupContainerEl.current ||
!otherToolsPopupContainerEl.current
) {
return
}
if (
!communityPopupContainerEl.current.contains(event.target as Node) &&
!otherToolsPopupContainerEl.current.contains(event.target as Node)
) {
closeAllPopups()
}
}
const handlePageKeyup = (event: KeyboardEvent): void => {
if (event.key === 'Escape') {
closeAllPopups()
}
}
const setupPopupEventListeners = (): void => {
document.addEventListener('click', handlePageClick)
document.addEventListener('keyup', handlePageKeyup)
pageCloseEventListener = (): void =>
document.removeEventListener('click', handlePageClick)
keyupCloseEventListener = (): void =>
document.removeEventListener('keyup', handlePageKeyup)
}
const openCommunityPopup = (): void => {
setupPopupEventListeners()
setIsCommunityPopupOpen(true)
}
const openOtherToolsPopup = (): void => {
setupPopupEventListeners()
setIsOtherToolsPopupOpen(true)
}
const toggleCommunityPopup = (): void => {
setIsOtherToolsPopupOpen(false)
if (isCommunityPopupOpen) {
closeAllPopups()
} else {
openCommunityPopup()
}
}
const toggleOtherToolsPopup = (): void => {
setIsCommunityPopupOpen(false)
if (isOtherToolsPopupOpen) {
closeAllPopups()
} else {
openOtherToolsPopup()
}
}
return (
<ul className={styles.linksList}>
{navLinkItemsData.map((item, i) => (
<li
key={i}
className={styles.linkItem}
ref={
isPopup(item)
? item.popup === 'OtherToolsPopup'
? otherToolsPopupContainerEl
: communityPopupContainerEl
: undefined
}
>
{isPopup(item) ? (
<>
<button
onClick={
item.popup === 'OtherToolsPopup'
? toggleOtherToolsPopup
: toggleCommunityPopup
}
className={cn(
styles.link,
(item.popup === 'OtherToolsPopup'
? isOtherToolsPopupOpen
: isCommunityPopupOpen) && styles.open
)}
>
{item.text}
<ArrowDownSVG
className={cn(styles.linkIcon, styles.arrowDownIcon)}
/>
<ArrowUpSVG
className={cn(styles.linkIcon, styles.arrowUpIcon)}
/>
</button>
{item.popup === 'OtherToolsPopup' ? (
<OtherToolsPopup
closePopup={closeAllPopups}
isVisible={isOtherToolsPopupOpen}
/>
) : (
<CommunityPopup
closePopup={closeAllPopups}
isVisible={isCommunityPopupOpen}
/>
)}
</>
) : (
<Link
onClick={(): void => logEvent('Nav', { Item: item.eventType })}
href={item.href}
className={styles.link}
>
{item.text}
</Link>
)}
</li>
))}
</ul>
)
}
export default LinkItems
|
#!/bin/bash
#
# script to fetch pak sets
#
# make sure that non-existing variables are not ignored
set -u
# fall back to "/tmp" if TEMP is not set
TEMP=${TEMP:-/tmp}
# parameter: url and filename
do_download(){
if which curl >/dev/null; then
curl -L "$1" > "$2" || {
echo "Error: download of file $2 failed (curl returned $?)" >&2
rm -f "$2"
exit 4
}
else
if which wget >/dev/null; then
wget -q -N "$1" -O "$2" || {
echo "Error: download of file $2 failed (wget returned $?)" >&2
rm -f "$2"
exit 4
}
else
echo "Error: Neither curl or wget are available on your system, please install either and try again!" >&2
exit 6
fi
fi
}
# two parameter, url, zipfilename
DownloadInstallZip(){
echo "downloading from $1"
do_download "$1" "$TEMP/$2"
echo "installing from $2"
# first try to extract all files in simutrans/
unzip -o -C -q "$TEMP/$2" "simutrans/*" -d . 2> /dev/null
if [ $? -eq 11 ]; then
# no simutrans folder in the zipfile
# unzip directly into simutrans/
unzip -o -C -q "$TEMP/$2" -d simutrans
fi
rm "$TEMP/$2"
}
# generated list of pak sets
paksets=( \
"http://downloads.sourceforge.net/project/simutrans/pak64/120-4/simupak64-120-4.zip" \
"https://www.simutrans-germany.com/pak.german/pak64.german_0-112-3-10_full.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak64.japan/120-0/simupak64.japan-120-0-1.zip" \
"http://github.com/wa-st/pak-nippon/releases/download/v0.3.0/pak.nippon-v0.3.0.zip" \
"http://downloads.sourceforge.net/project/simutrans/pakHAJO/pakHAJO_102-2-2/pakHAJO_0-102-2-2.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak96.comic/pak96.comic%20for%20111-3/pak96.comic-0.4.10-plus.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak128/pak128%20for%20ST%20120.2.2%20%282.7%2C%20minor%20changes%29/pak128.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak128.britain/pak128.Britain%20for%20120-1/pak128.Britain.1.17-120-1.zip" \
"http://downloads.sourceforge.net/project/simutrans/PAK128.german/PAK128.german_0.10.x_for_ST_120.x/PAK128.german_0.10.4_for_ST_120.x.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak192.comic/pak192comic%20for%20120-2-2/pak192.comic.0.5.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak32.comic/pak32.comic%20for%20102-0/pak32.comic_102-0.zip" \
"http://downloads.sourceforge.net/project/simutrans/pak64.contrast/pak64.Contrast_910.zip" \
"http://hd.simutrans.com/release/PakHD_v04B_100-0.zip" \
"http://pak128.jpn.org/souko/pak128.japan.120.0.cab" \
"http://downloads.sourceforge.net/project/simutrans/pak64.scifi/pak64.scifi_112.x_v0.2.zip" \
"http://downloads.sourceforge.net/project/ironsimu/pak48.Excentrique/v018/pak48-excentrique_v018.zip" \
)
tgzpaksets=( \
"http://simutrans.bilkinfo.de/pak64.ho-scale-latest.tar.gz" \
)
choices=()
installpak=()
echo "-- Choose at least one of these paks --"
let setcount=0
let choicecount=0
let "maxcount = ${#paksets[*]}"
while [ "$setcount" -lt "$maxcount" ]; do
installpak[choicecount]=0
urlname=${paksets[$setcount]}
zipname="${urlname##http*\/}"
choicename="${zipname%.zip}"
choicename="${choicename/simupak/pak}"
choices[choicecount]=$choicename
let "setcount += 1"
let "choicecount += 1"
echo "${choicecount}) ${choicename}"
done
while true; do
read -p "Which paks to install? (enter number or (i) to install or (x) to exit)" pak
#exit?
if [[ $pak = [xX] ]]; then
exit
fi
# test if installation now
if [[ $pak = [iI] ]]; then
echo "You will install now"
let setcount=0
while [ $setcount -lt $choicecount ]; do
if [ ${installpak[$setcount]} -gt 0 ]; then
let "displaycount=$setcount+1"
echo "${displaycount}) ${choices[$setcount]}"
fi
let "setcount += 1"
done
read -p "Is this correct? (y/n)" yn
if [[ $yn = [yY] ]]; then
break
fi
# edit again
echo "-- Choose again one of these paks --"
let setcount=0
while [ $setcount -lt $choicecount ]; do
echo "${setcount}) ${choices[$setcount]}"
let "setcount += 1"
done
let "pak=0"
fi
# otherwise it should be a number
if [[ $pak =~ ^[0-9]+$ ]]; then
let "setcount=pak-1"
if [ $setcount -lt $choicecount ]; then
if [ $setcount -ge 0 ]; then
status=${installpak[$setcount]}
if [ $status -lt 1 ]; then
echo "adding ${choices[$setcount]}"
installpak[$setcount]=1
else
echo "not installing ${choices[$setcount]}"
installpak[$setcount]=0
fi
fi
fi
fi
done
# first the regular pak sets
pushd ..
let setcount=0
let "maxcount = ${#paksets[*]}"
while [ "$setcount" -lt "$maxcount" ]; do
if [ "${installpak[$setcount]}" -gt 0 ]; then
urlname=${paksets[$setcount]}
zipname="${urlname##http*\/}"
DownloadInstallZip "$urlname" "$zipname"
fi
let "setcount += 1"
done
exit
|
require 'rake'
require 'rake/tasklib'
module Rake
class CscTask < TaskLib
# Name of the main, top level task. (default is :nunit)
attr_accessor :name, :files, :compiler, :flags, :config, :refs
def initialize(name=:nunit) # :yield: self
@name = name
compiler = "mcs"
compiler = "csc" if /win32/.match( RUBY_PLATFORM )
yield self if block_given?
define
end
def define
task name do
flaglist = ""
flags.each { |f| flaglist << " /#{f}" } if flags
reflist = "/reference:%s" % refs.join( "," ) if refs
files.each do |library|
sh "#{@compiler} #{flaglist} #{config} #{reflist}"
end
end
self
end
def reflist
end
def config
"/#{@config}" if @config && @config.downcase == "debug"
end
end
end
|
import { registerPlugin } from "@capacitor/core";
const SpeechRecognition = registerPlugin("SpeechRecognition", {
web: () => import("./web").then((m) => new m.SpeechRecognitionWeb()),
});
export * from "./definitions";
export { SpeechRecognition };
//# sourceMappingURL=index.js.map
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-ST/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-ST/1024+0+512-LMPI-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_within_sentences_low_pmi_first_two_thirds_sixth --eval_function penultimate_sixth_eval |
import config
import functions
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from configparser import ConfigParser
def init(update, context):
r1 = ConfigParser()
r1.read('settings.ini')
keyboard = [[InlineKeyboardButton("Mercatino 📦", url='t.me/AOSPItaliashop')],
[InlineKeyboardButton("Somme Regole 📜", url='https://telegra.ph/Google-Pixel-Italia-07-29')]]
reply_markup = InlineKeyboardMarkup(keyboard)
for new in update.message.new_chat_members:
# ==========================
# Quick check on new members
# [1] chinese characters
# [2] arabic characters
# [3] (work in progress)
# ==========================
chinese = functions.chinese_characters.init(update, context, r1, new)
arabic = functions.arabic_characters.init(update, context, r1, new)
if chinese == True or arabic == True:
print('ban triggered on new user')
else:
if str(new.username).lower() == config.bot_username:
txt = functions.general.txtReader('welcome_bot')
context.bot.send_message(update.message.chat_id, text=txt, parse_mode='HTML')
else:
txt = functions.general.txtReader('welcome')
net = '<a href="t.me/aospitalianet">Network</a>'
try:
name = new.username
except:
name = new.first_name
update.message.reply_text(str(txt).format(name,update.message.chat.title, net), reply_markup=reply_markup, parse_mode='HTML') |
var employeesWithSalaryGreaterThanOrEqualTo50K =
from employee in Employee
where employee.salary >= 50000
select employee; |
<filename>back/src/main/java/com/java110/things/Controller/parkingArea/ParkingBoxController.java
package com.java110.things.Controller.parkingArea;
import com.alibaba.fastjson.JSONObject;
import com.java110.things.Controller.BaseController;
import com.java110.things.entity.parkingArea.ParkingBoxDto;
import com.java110.things.entity.response.ResultDto;
import com.java110.things.service.parkingBox.IParkingBoxService;
import com.java110.things.util.Assert;
import com.java110.things.util.BeanConvertUtil;
import com.java110.things.util.SeqUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName ParkingBoxController
* @Description TODO 停车场信息控制类
* @Author wuxw
* @Date 2020/5/16 10:36
* @Version 1.0
* add by wuxw 2020/5/16
**/
@RestController
@RequestMapping(path = "/api/parkingBox")
public class ParkingBoxController extends BaseController {
@Autowired
private IParkingBoxService parkingBoxServiceImpl;
/**
* 添加停车场接口类
*
* @param param 请求报文 包括停车场 前台填写信息
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/saveParkingBox", method = RequestMethod.POST)
public ResponseEntity<String> saveParkingBox(@RequestBody String param, HttpServletRequest request) throws Exception {
JSONObject paramObj = super.getParamJson(param);
Assert.hasKeyAndValue(paramObj, "boxName", "请求报文中未包含停车场编号");
Assert.hasKeyAndValue(paramObj, "tempCarIn", "请求报文中未包含停车场编号");
Assert.hasKeyAndValue(paramObj, "fee", "请求报文中未包含停车场编号");
Assert.hasKeyAndValue(paramObj, "blueCarIn", "请求报文中未包含停车场编号");
Assert.hasKeyAndValue(paramObj, "yelowCarIn", "请求报文中未包含停车场编号");
Assert.hasKeyAndValue(paramObj, "communityId", "请求报文中未包含小区信息");
ParkingBoxDto parkingBoxDto = BeanConvertUtil.covertBean(paramObj, ParkingBoxDto.class);
parkingBoxDto.setBoxId(SeqUtil.getId());
ResultDto resultDto = parkingBoxServiceImpl.saveParkingBox(parkingBoxDto);
return super.createResponseEntity(resultDto);
}
/**
* 更细用户
*
* @param param 请求报文
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/updateParkingBox", method = RequestMethod.POST)
public ResponseEntity<String> updateParkingBox(@RequestBody String param) throws Exception {
JSONObject paramObj = super.getParamJson(param);
Assert.hasKeyAndValue(paramObj, "boxId", "请求报文中未包含停车场ID");
Assert.hasKeyAndValue(paramObj, "communityId", "请求报文中未包含小区信息");
ResultDto resultDto = parkingBoxServiceImpl.updateParkingBox(BeanConvertUtil.covertBean(paramObj, ParkingBoxDto.class));
return super.createResponseEntity(resultDto);
}
/**
* 添加停车场接口类
*
* @param boxId 页数
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/getParkingBoxs", method = RequestMethod.GET)
public ResponseEntity<String> getParkingBoxs(@RequestParam(value = "boxId", required = false) String boxId,
@RequestParam(value = "communityId") String communityId,
HttpServletRequest request) throws Exception {
ParkingBoxDto parkingBoxDto = new ParkingBoxDto();
parkingBoxDto.setBoxId(boxId);
parkingBoxDto.setCommunityId(communityId);
ResultDto resultDto = parkingBoxServiceImpl.getParkingBox(parkingBoxDto);
return super.createResponseEntity(resultDto);
}
/**
* 删除停车场 动作
*
* @param paramIn 入参
* @return
* @throws Exception
*/
@RequestMapping(path = "/deleteParkingBox", method = RequestMethod.POST)
public ResponseEntity<String> deleteParkingBox(@RequestBody String paramIn) throws Exception {
JSONObject paramObj = super.getParamJson(paramIn);
Assert.hasKeyAndValue(paramObj, "boxId", "请求报文中未包含boxId");
ResultDto resultDto = parkingBoxServiceImpl.deleteParkingBox(BeanConvertUtil.covertBean(paramObj, ParkingBoxDto.class));
return super.createResponseEntity(resultDto);
}
}
|
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items) |
#! /bin/bash
if [ "${AZUREENABLE:-null}" == "null" ] && [ "${AZUREACCOUNTNAME:-null}" != "null" ] && [ "${AZUREACCOUNTKEY:-null}" != "null" ] && [ "${AZURECONTAINER:-null}" != "null" ]; then
echo "Enable azure" >&2
export AZUREENABLE=true
fi |
<filename>src/components/PlayBtn.js
import React from 'react';
class PlayBtn extends React{
constructor(){
super();
this.state = {
init:{
autoPlay: true,
volume: 1,
fullScreen: false,
time: 0,
}
};
}
componentDidMount(){
}
render(){
return(
<div>
<div>
<span>ball</span>
<span>bar</span>
</div>
<div>
<span>play/pause</span>
<span>time</span>
<span>volume</span>
<span>fullscreen</span>
</div>
</div>
)
}
} |
git clone https://github.com/singleron-RD/CeleScope.git
conda create -n celescope
conda activate celescope
conda install --file conda_pkgs.txt --channel conda-forge --channel bioconda --channel r --channel imperial-college-research-computing
pip install celescope
|
#pragma once
// MESSAGE DPL_TM PACKING
#define MAVLINK_MSG_ID_DPL_TM 166
MAVPACKED(
typedef struct __mavlink_dpl_tm_t {
uint64_t timestamp; /*< [ms] When was this logged*/
float servo_position; /*< [deg] DPL servo position (angle)*/
uint8_t fsm_state; /*< Current state of the dpl controller*/
uint8_t cutters_enabled; /*< Cutters state (enabled/disabled)*/
}) mavlink_dpl_tm_t;
#define MAVLINK_MSG_ID_DPL_TM_LEN 14
#define MAVLINK_MSG_ID_DPL_TM_MIN_LEN 14
#define MAVLINK_MSG_ID_166_LEN 14
#define MAVLINK_MSG_ID_166_MIN_LEN 14
#define MAVLINK_MSG_ID_DPL_TM_CRC 161
#define MAVLINK_MSG_ID_166_CRC 161
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_DPL_TM { \
166, \
"DPL_TM", \
4, \
{ { "timestamp", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_dpl_tm_t, timestamp) }, \
{ "fsm_state", NULL, MAVLINK_TYPE_UINT8_T, 0, 12, offsetof(mavlink_dpl_tm_t, fsm_state) }, \
{ "cutters_enabled", NULL, MAVLINK_TYPE_UINT8_T, 0, 13, offsetof(mavlink_dpl_tm_t, cutters_enabled) }, \
{ "servo_position", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_dpl_tm_t, servo_position) }, \
} \
}
#else
#define MAVLINK_MESSAGE_INFO_DPL_TM { \
"DPL_TM", \
4, \
{ { "timestamp", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_dpl_tm_t, timestamp) }, \
{ "fsm_state", NULL, MAVLINK_TYPE_UINT8_T, 0, 12, offsetof(mavlink_dpl_tm_t, fsm_state) }, \
{ "cutters_enabled", NULL, MAVLINK_TYPE_UINT8_T, 0, 13, offsetof(mavlink_dpl_tm_t, cutters_enabled) }, \
{ "servo_position", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_dpl_tm_t, servo_position) }, \
} \
}
#endif
/**
* @brief Pack a dpl_tm message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param timestamp [ms] When was this logged
* @param fsm_state Current state of the dpl controller
* @param cutters_enabled Cutters state (enabled/disabled)
* @param servo_position [deg] DPL servo position (angle)
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_dpl_tm_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint64_t timestamp, uint8_t fsm_state, uint8_t cutters_enabled, float servo_position)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_DPL_TM_LEN];
_mav_put_uint64_t(buf, 0, timestamp);
_mav_put_float(buf, 8, servo_position);
_mav_put_uint8_t(buf, 12, fsm_state);
_mav_put_uint8_t(buf, 13, cutters_enabled);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_DPL_TM_LEN);
#else
mavlink_dpl_tm_t packet;
packet.timestamp = timestamp;
packet.servo_position = servo_position;
packet.fsm_state = fsm_state;
packet.cutters_enabled = cutters_enabled;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_DPL_TM_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_DPL_TM;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
}
/**
* @brief Pack a dpl_tm message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param timestamp [ms] When was this logged
* @param fsm_state Current state of the dpl controller
* @param cutters_enabled Cutters state (enabled/disabled)
* @param servo_position [deg] DPL servo position (angle)
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_dpl_tm_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint64_t timestamp,uint8_t fsm_state,uint8_t cutters_enabled,float servo_position)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_DPL_TM_LEN];
_mav_put_uint64_t(buf, 0, timestamp);
_mav_put_float(buf, 8, servo_position);
_mav_put_uint8_t(buf, 12, fsm_state);
_mav_put_uint8_t(buf, 13, cutters_enabled);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_DPL_TM_LEN);
#else
mavlink_dpl_tm_t packet;
packet.timestamp = timestamp;
packet.servo_position = servo_position;
packet.fsm_state = fsm_state;
packet.cutters_enabled = cutters_enabled;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_DPL_TM_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_DPL_TM;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
}
/**
* @brief Encode a dpl_tm struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param dpl_tm C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_dpl_tm_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_dpl_tm_t* dpl_tm)
{
return mavlink_msg_dpl_tm_pack(system_id, component_id, msg, dpl_tm->timestamp, dpl_tm->fsm_state, dpl_tm->cutters_enabled, dpl_tm->servo_position);
}
/**
* @brief Encode a dpl_tm struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param dpl_tm C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_dpl_tm_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_dpl_tm_t* dpl_tm)
{
return mavlink_msg_dpl_tm_pack_chan(system_id, component_id, chan, msg, dpl_tm->timestamp, dpl_tm->fsm_state, dpl_tm->cutters_enabled, dpl_tm->servo_position);
}
/**
* @brief Send a dpl_tm message
* @param chan MAVLink channel to send the message
*
* @param timestamp [ms] When was this logged
* @param fsm_state Current state of the dpl controller
* @param cutters_enabled Cutters state (enabled/disabled)
* @param servo_position [deg] DPL servo position (angle)
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_dpl_tm_send(mavlink_channel_t chan, uint64_t timestamp, uint8_t fsm_state, uint8_t cutters_enabled, float servo_position)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_DPL_TM_LEN];
_mav_put_uint64_t(buf, 0, timestamp);
_mav_put_float(buf, 8, servo_position);
_mav_put_uint8_t(buf, 12, fsm_state);
_mav_put_uint8_t(buf, 13, cutters_enabled);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DPL_TM, buf, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
#else
mavlink_dpl_tm_t packet;
packet.timestamp = timestamp;
packet.servo_position = servo_position;
packet.fsm_state = fsm_state;
packet.cutters_enabled = cutters_enabled;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DPL_TM, (const char *)&packet, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
#endif
}
/**
* @brief Send a dpl_tm message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_dpl_tm_send_struct(mavlink_channel_t chan, const mavlink_dpl_tm_t* dpl_tm)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_dpl_tm_send(chan, dpl_tm->timestamp, dpl_tm->fsm_state, dpl_tm->cutters_enabled, dpl_tm->servo_position);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DPL_TM, (const char *)dpl_tm, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
#endif
}
#if MAVLINK_MSG_ID_DPL_TM_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_dpl_tm_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint64_t timestamp, uint8_t fsm_state, uint8_t cutters_enabled, float servo_position)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint64_t(buf, 0, timestamp);
_mav_put_float(buf, 8, servo_position);
_mav_put_uint8_t(buf, 12, fsm_state);
_mav_put_uint8_t(buf, 13, cutters_enabled);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DPL_TM, buf, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
#else
mavlink_dpl_tm_t *packet = (mavlink_dpl_tm_t *)msgbuf;
packet->timestamp = timestamp;
packet->servo_position = servo_position;
packet->fsm_state = fsm_state;
packet->cutters_enabled = cutters_enabled;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DPL_TM, (const char *)packet, MAVLINK_MSG_ID_DPL_TM_MIN_LEN, MAVLINK_MSG_ID_DPL_TM_LEN, MAVLINK_MSG_ID_DPL_TM_CRC);
#endif
}
#endif
#endif
// MESSAGE DPL_TM UNPACKING
/**
* @brief Get field timestamp from dpl_tm message
*
* @return [ms] When was this logged
*/
static inline uint64_t mavlink_msg_dpl_tm_get_timestamp(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint64_t(msg, 0);
}
/**
* @brief Get field fsm_state from dpl_tm message
*
* @return Current state of the dpl controller
*/
static inline uint8_t mavlink_msg_dpl_tm_get_fsm_state(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 12);
}
/**
* @brief Get field cutters_enabled from dpl_tm message
*
* @return Cutters state (enabled/disabled)
*/
static inline uint8_t mavlink_msg_dpl_tm_get_cutters_enabled(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 13);
}
/**
* @brief Get field servo_position from dpl_tm message
*
* @return [deg] DPL servo position (angle)
*/
static inline float mavlink_msg_dpl_tm_get_servo_position(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Decode a dpl_tm message into a struct
*
* @param msg The message to decode
* @param dpl_tm C-struct to decode the message contents into
*/
static inline void mavlink_msg_dpl_tm_decode(const mavlink_message_t* msg, mavlink_dpl_tm_t* dpl_tm)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
dpl_tm->timestamp = mavlink_msg_dpl_tm_get_timestamp(msg);
dpl_tm->servo_position = mavlink_msg_dpl_tm_get_servo_position(msg);
dpl_tm->fsm_state = mavlink_msg_dpl_tm_get_fsm_state(msg);
dpl_tm->cutters_enabled = mavlink_msg_dpl_tm_get_cutters_enabled(msg);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_DPL_TM_LEN? msg->len : MAVLINK_MSG_ID_DPL_TM_LEN;
memset(dpl_tm, 0, MAVLINK_MSG_ID_DPL_TM_LEN);
memcpy(dpl_tm, _MAV_PAYLOAD(msg), len);
#endif
}
|
def calculate_subtraction(nums):
return nums[0] - nums[-1] |
<filename>AndroidNanoDegreeProjectCapstone/Phase2/app/src/main/java/io/github/marcelbraghetto/dailydeviations/framework/foundation/core/BaseViewModel.java
package io.github.marcelbraghetto.dailydeviations.framework.foundation.core;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.github.marcelbraghetto.dailydeviations.features.application.MainApp;
/**
* Created by <NAME> on 02/12/15.
*
* Base class for view model classes.
*/
public abstract class BaseViewModel<T> implements Destroyable {
/**
* This field can be accessed by the child class and
* have commands sent via it.
*/
protected T mActionDelegate;
private final Class<T> mClazz;
private final String mInstanceId;
/**
* Initialise the instance with the given class type
* that represents the logic delegate.
*
* @param clazz type of the delegate contract.
*/
public BaseViewModel(@NonNull Class<T> clazz) {
mClazz = clazz;
resetDelegate();
mInstanceId = MainApp.getDagger().getAppStringsProvider().generateGUID();
}
/**
* Connect the logic actionDelegate to the given actionDelegate
* instance, via the weak wrapper so it won't hold
* a strong reference to it and so it also won't
* through NPE when calling methods on the actionDelegate
* that is not connected to anything.
*
* @param actionDelegate to assign as the logic actionDelegate.
*/
public void setActionDelegate(@Nullable T actionDelegate) {
mActionDelegate = WeakWrapper.wrap(actionDelegate, mClazz);
}
@Override
public void destroy() {
resetDelegate();
}
@NonNull
protected String getInstanceId() {
return mInstanceId;
}
/**
* Resetting the delegate basically just wraps it
* with a weak wrapper with null as the target.
*/
private void resetDelegate() {
mActionDelegate = WeakWrapper.wrapEmpty(mClazz);
}
} |
package models;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.List;
public class CartItem
{
@Id @GeneratedValue(strategy= GenerationType.IDENTITY)
private int productId;
private String productName;
private int quantity;
private BigDecimal unitPrice;
private int categortyId;
private BigDecimal total;
public int getProductId()
{
return productId;
}
public int getQuantity()
{
return quantity;
}
public BigDecimal getUnitPrice()
{
return unitPrice;
}
public String getProductName()
{
return productName;
}
public void setProductId(int productId)
{
this.productId = productId;
}
public void setProductName(String productName)
{
this.productName = productName;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public void setUnitPrice(BigDecimal unitPrice)
{
this.unitPrice = unitPrice;
}
public int getCategortyId()
{
return categortyId;
}
public void setCategortyId(int categortyId)
{
this.categortyId = categortyId;
}
public static String toJSON (List<CartItem> cartItems)
{
ObjectMapper mapper = new ObjectMapper();
String json = null;
try
{
json = mapper.writeValueAsString(cartItems);
}
catch(Exception e)
{
e.printStackTrace();
}
return json;
}
public static List<CartItem> fromJSON(String json)
{
ObjectMapper mapper = new ObjectMapper();
List<CartItem> cartItems = null;
try
{
cartItems = mapper.readValue(json, new TypeReference<List<CartItem>>(){});
}
catch (Exception e)
{
e.printStackTrace();
}
return cartItems;
}
public BigDecimal getTotal()
{
return total;
}
public void setTotal(BigDecimal total)
{
this.total = total;
}
}
|
<reponame>art-0007/MyChessbase<filename>app/helpers/application_helper.rb
# frozen_string_literal: true
module ApplicationHelper
include Pagy::Frontend
def pagination(obj)
raw(pagy_bootstrap_nav(obj)) if obj.pages > 1
end
def currently_at(current_page = '')
render partial: 'shared/menu', locals: { current_page: current_page }
end
def nav_tab(title, url, options = {})
current_page = options.delete :current_page
css_class = current_page == title ? 'text-secondary' : 'text-white'
options[:class] = if options[:class]
"#{options[:class]} #{css_class}"
else
css_class
end
link_to title, url, options
end
def full_title(page_title = '')
base_title = 'MyChessbase'
if page_title.present?
"#{page_title} | #{base_title}"
else
base_title
end
end
def puzzle_complexities
PuzzleCategory.complexities.keys.map do |complexity|
[complexity.titleize, complexity]
end
end
end
|
import predictionio
def rank_items_for_users(user_ids, item_ids):
result = {}
client = predictionio.EngineClient("http://localhost:8000")
for user_id in user_ids:
print("Rank item 1 to 5 for user ", user_id)
try:
user_rankings = client.send_query({"user": user_id, "items": item_ids})
result[user_id] = [(item_id, rank) for item_id, rank in zip(item_ids, user_rankings)]
except predictionio.NotFoundError:
result[user_id] = []
return result
# Example usage
user_ids = ["1", "2", "3", "4", "5", "NOT_EXIST_USER"]
item_ids = ["1", "2", "3", "4", "5"]
result = rank_items_for_users(user_ids, item_ids)
print(result) |
<reponame>rifflearning/riffdata-server
interface MeetingCreateData {
title: string,
room_name: string,
context?: string,
meeting_type?: string,
$addToSet: {
active_participants: string,
participants: Participant,
},
}
interface MeetingEvent {
participant_id: string,
time: number,
event_type: string,
meeting_id?: string,
room_name?: string,
title?: string,
meeting_start_ts?: number,
display_name?: string,
context?: string,
meeting_type?: string,
}
interface Participant {
participant_id: string,
display_name: string,
}
interface Utterance {
meeting_id: string,
participant_id: string,
start: number,
end: number,
volumes?: { time: number, vol: number }[],
}
export {
MeetingCreateData,
MeetingEvent,
Participant,
Utterance,
};
|
# {{ pillar['file_header'] }}
# Company: {{ pillar['company'] }}
# sysadmin: {{ pillar['sysadmin'] }} <{{ pillar['sysadmin_email'] }}>
#
## CIS ## 9.1.13 Find SUID System Executables (Not Scored)
RESPONSE=$(df --local -P | awk {'if (NR!=1) print $6'} | xargs -I '{}' find '{}' -xdev -nogroup -ls)
if [ "$RESPONSE" != '' ]; then
CHANGED="yes"
COMMENT="--WARNING-- there are some old files/folders with no group account: see page: 167 of CIS_Red_Hat_Enterprise_Linux_6_Benchmark_v1.1.0.pdf"
else
CHANGED="no"
COMMENT="No un-grouped files"
fi
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=$CHANGED comment='$COMMENT'" |
<filename>ddtrace/internal/wrapping.py
import sys
from types import FunctionType
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import cast
from six import PY3
try:
from typing import Protocol
except ImportError:
from typing_extensions import Protocol # type: ignore[misc]
from bytecode import Bytecode
from bytecode import Compare
from bytecode import CompilerFlags
from bytecode import Instr
from bytecode import Label
from .compat import PYTHON_VERSION_INFO as PY
class WrapperFunction(Protocol):
"""A wrapped function."""
__dd_wrapped__ = None # type: Optional[FunctionType]
__dd_wrappers__ = None # type: Optional[Dict[Any, Any]]
def __call__(self, *args, **kwargs):
pass
Wrapper = Callable[[FunctionType, Tuple[Any], Dict[str, Any]], Any]
def wrap_bytecode(wrapper, wrapped):
# type: (Wrapper, FunctionType) -> Bytecode
"""Wrap a function with a wrapper function.
The wrapper function expects the wrapped function as the first argument,
followed by the tuple of arguments and the dictionary of keyword arguments.
The nature of the wrapped function is also honored, meaning that a generator
function will return a generator function, and a coroutine function will
return a coroutine function, and so on. The signature is also preserved to
avoid breaking, e.g., usages of the ``inspect`` module.
"""
def compare_exc(label, lineno):
"""Compat helper for comparing exceptions."""
return (
Instr("COMPARE_OP", Compare.EXC_MATCH, lineno=lineno)
if PY < (3, 9)
else Instr("JUMP_IF_NOT_EXC_MATCH", label, lineno=lineno)
)
def jump_if_false(label, lineno):
"""Compat helper for jumping if false after comparing exceptions."""
return Instr("POP_JUMP_IF_FALSE", label, lineno=lineno) if PY < (3, 9) else Instr("NOP", lineno=lineno)
def end_finally(lineno):
"""Compat helper for ending finally blocks."""
if PY < (3, 9):
return Instr("END_FINALLY", lineno=lineno)
elif PY < (3, 10):
return Instr("RERAISE", lineno=lineno)
return Instr("RERAISE", 0, lineno=lineno)
code = wrapped.__code__
lineno = code.co_firstlineno
varargs = bool(code.co_flags & CompilerFlags.VARARGS)
varkwargs = bool(code.co_flags & CompilerFlags.VARKEYWORDS)
nargs = code.co_argcount
argnames = code.co_varnames[:nargs]
try:
kwonlyargs = code.co_kwonlyargcount
except AttributeError:
kwonlyargs = 0
kwonlyargnames = code.co_varnames[nargs : nargs + kwonlyargs]
varargsname = code.co_varnames[nargs + kwonlyargs] if varargs else None
varkwargsname = code.co_varnames[nargs + kwonlyargs + varargs] if varkwargs else None
# Push the wrapper function that is to be called and the wrapped function to
# be passed as first argument.
instrs = [
Instr("LOAD_CONST", wrapper, lineno=lineno),
Instr("LOAD_CONST", wrapped, lineno=lineno),
]
# Build the tuple of all the positional arguments
if nargs:
instrs.extend([Instr("LOAD_FAST", argname, lineno=lineno) for argname in argnames])
instrs.append(Instr("BUILD_TUPLE", nargs, lineno=lineno))
if varargs:
instrs.extend(
[
Instr("LOAD_FAST", varargsname, lineno=lineno),
Instr("INPLACE_ADD", lineno=lineno),
]
)
elif varargs:
instrs.append(Instr("LOAD_FAST", varargsname, lineno=lineno))
else:
instrs.append(Instr("BUILD_TUPLE", 0, lineno=lineno))
# Prepare the keyword arguments
if kwonlyargs:
for arg in kwonlyargnames:
instrs.extend(
[
Instr("LOAD_CONST", arg, lineno=lineno),
Instr("LOAD_FAST", arg, lineno=lineno),
]
)
instrs.append(Instr("BUILD_MAP", kwonlyargs, lineno=lineno))
if varkwargs:
instrs.extend(
[
Instr("DUP_TOP", lineno=lineno),
Instr("LOAD_ATTR", "update", lineno=lineno),
Instr("LOAD_FAST", varkwargsname, lineno=lineno),
Instr("CALL_FUNCTION", 1, lineno=lineno),
Instr("POP_TOP", lineno=lineno),
]
)
elif varkwargs:
instrs.append(Instr("LOAD_FAST", varkwargsname, lineno=lineno))
else:
instrs.append(Instr("BUILD_MAP", 0, lineno=lineno))
# Call the wrapper function with the wrapped function, the positional and
# keyword arguments, and return the result.
instrs.extend(
[
Instr("CALL_FUNCTION", 3, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
]
)
# If the function has special flags set, like the generator, async generator
# or coroutine, inject unraveling code before the return opcode.
if CompilerFlags.GENERATOR & code.co_flags and not (CompilerFlags.COROUTINE & code.co_flags):
stopiter = Label()
loop = Label()
genexit = Label()
exc = Label()
propagate = Label()
# DEV: This is roughly equivalent to
#
# __ddgen = wrapper(wrapped, args, kwargs)
# __ddgensend = __ddgen.send
# try:
# value = next(__ddgen)
# except StopIteration:
# return
# while True:
# try:
# tosend = yield value
# except GeneratorExit:
# return __ddgen.close()
# except:
# return __ddgen.throw(*sys.exc_info())
# try:
# value = __ddgensend(tosend)
# except StopIteration:
# return
#
instrs[-1:-1] = [
Instr("DUP_TOP", lineno=lineno),
Instr("STORE_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "send", lineno=lineno),
Instr("STORE_FAST", "__ddgensend", lineno=lineno),
Instr("LOAD_CONST", next, lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
loop,
Instr("SETUP_EXCEPT" if PY < (3, 8) else "SETUP_FINALLY", stopiter, lineno=lineno),
Instr("CALL_FUNCTION", 1, lineno=lineno),
Instr("POP_BLOCK", lineno=lineno),
Instr("SETUP_EXCEPT" if PY < (3, 8) else "SETUP_FINALLY", genexit, lineno=lineno),
Instr("YIELD_VALUE", lineno=lineno),
Instr("POP_BLOCK", lineno=lineno),
Instr("LOAD_FAST", "__ddgensend", lineno=lineno),
Instr("ROT_TWO", lineno=lineno),
Instr("JUMP_ABSOLUTE", loop, lineno=lineno),
stopiter, # except StpIteration:
Instr("DUP_TOP", lineno=lineno),
Instr("LOAD_CONST", StopIteration, lineno=lineno),
compare_exc(propagate, lineno),
jump_if_false(propagate, lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
propagate,
end_finally(lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
genexit, # except GeneratorExit:
Instr("DUP_TOP", lineno=lineno),
Instr("LOAD_CONST", GeneratorExit, lineno=lineno),
compare_exc(exc, lineno),
jump_if_false(exc, lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "close", lineno=lineno),
Instr("CALL_FUNCTION", 0, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
exc, # except:
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "throw", lineno=lineno),
Instr("LOAD_CONST", sys.exc_info, lineno=lineno),
Instr("CALL_FUNCTION", 0, lineno=lineno),
Instr("CALL_FUNCTION_VAR" if PY < (3, 6) else "CALL_FUNCTION_EX", 0, lineno=lineno),
]
elif PY3:
if CompilerFlags.COROUTINE & code.co_flags:
# DEV: This is just
# >>> return await wrapper(wrapped, args, kwargs)
instrs[-1:-1] = [
Instr("GET_AWAITABLE", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("YIELD_FROM", lineno=lineno),
]
elif CompilerFlags.ASYNC_GENERATOR & code.co_flags:
stopiter = Label()
loop = Label()
genexit = Label()
exc = Label()
propagate = Label()
# DEV: This is roughly equivalent to
#
# __ddgen = wrapper(wrapped, args, kwargs)
# __ddgensend = __ddgen.asend
# try:
# value = await _ddgen.__anext__()
# except StopAsyncIteration:
# return
# while True:
# try:
# tosend = yield value
# except GeneratorExit:
# __ddgen.close()
# except:
# __ddgen.throw(*sys.exc_info())
# try:
# value = await __ddgensend(tosend)
# except StopAsyncIteration:
# return
#
instrs[-1:-1] = [
Instr("DUP_TOP", lineno=lineno),
Instr("STORE_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "asend", lineno=lineno),
Instr("STORE_FAST", "__ddgensend", lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "__anext__", lineno=lineno),
Instr("CALL_FUNCTION", 0, lineno=lineno),
loop,
Instr("GET_AWAITABLE", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("SETUP_EXCEPT" if PY < (3, 8) else "SETUP_FINALLY", stopiter, lineno=lineno),
Instr("YIELD_FROM", lineno=lineno),
Instr("POP_BLOCK", lineno=lineno),
Instr("SETUP_EXCEPT" if PY < (3, 8) else "SETUP_FINALLY", genexit, lineno=lineno),
Instr("YIELD_VALUE", lineno=lineno),
Instr("POP_BLOCK", lineno=lineno),
Instr("LOAD_FAST", "__ddgensend", lineno=lineno),
Instr("ROT_TWO", lineno=lineno),
Instr("CALL_FUNCTION", 1, lineno=lineno),
Instr("JUMP_ABSOLUTE", loop, lineno=lineno),
stopiter, # except StopAsyncIteration:
Instr("DUP_TOP", lineno=lineno),
Instr("LOAD_CONST", StopAsyncIteration, lineno=lineno),
compare_exc(propagate, lineno),
jump_if_false(propagate, lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
propagate, # finally:
end_finally(lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
genexit, # except GeneratorExit:
Instr("DUP_TOP", lineno=lineno),
Instr("LOAD_CONST", GeneratorExit, lineno=lineno),
compare_exc(exc, lineno),
jump_if_false(exc, lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "aclose", lineno=lineno),
Instr("CALL_FUNCTION", 0, lineno=lineno),
Instr("GET_AWAITABLE", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("YIELD_FROM", lineno=lineno),
Instr("POP_EXCEPT", lineno=lineno),
Instr("RETURN_VALUE", lineno=lineno),
exc, # except:
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("POP_TOP", lineno=lineno),
Instr("LOAD_FAST", "__ddgen", lineno=lineno),
Instr("LOAD_ATTR", "athrow", lineno=lineno),
Instr("LOAD_CONST", sys.exc_info, lineno=lineno),
Instr("CALL_FUNCTION", 0, lineno=lineno),
Instr("CALL_FUNCTION_EX", 0, lineno=lineno),
Instr("GET_AWAITABLE", lineno=lineno),
Instr("LOAD_CONST", None, lineno=lineno),
Instr("YIELD_FROM", lineno=lineno),
Instr("POP_EXCEPT", lineno=lineno),
]
return Bytecode(instrs)
def wrap(f, wrapper):
# type: (FunctionType, Wrapper) -> WrapperFunction
"""Wrap a function with a wrapper.
The wrapper expects the function as first argument, followed by the tuple
of positional arguments and the dict of keyword arguments.
Note that this changes the behavior of the original function with the
wrapper function, instead of creating a new function object.
"""
wrapped = FunctionType(
f.__code__,
f.__globals__,
"<wrapped>",
f.__defaults__,
f.__closure__,
)
if PY3:
wrapped.__kwdefaults__ = f.__kwdefaults__
code = wrap_bytecode(wrapper, wrapped)
code.freevars = f.__code__.co_freevars
code.name = f.__code__.co_name
code.filename = f.__code__.co_filename
code.flags = f.__code__.co_flags
code.argcount = f.__code__.co_argcount
try:
code.posonlyargcount = f.__code__.co_posonlyargcount
except AttributeError:
pass
nargs = code.argcount
try:
code.kwonlyargcount = f.__code__.co_kwonlyargcount
nargs += code.kwonlyargcount
except AttributeError:
pass
nargs += bool(code.flags & CompilerFlags.VARARGS) + bool(code.flags & CompilerFlags.VARKEYWORDS)
code.argnames = f.__code__.co_varnames[:nargs]
f.__code__ = code.to_code()
wf = cast(WrapperFunction, f)
wf.__dd_wrapped__ = wrapped
return wf
def unwrap(wrapper):
# type: (WrapperFunction) -> FunctionType
"""Unwrap a wrapped function.
This is the reverse of :func:`wrap`.
"""
try:
wrapped = cast(FunctionType, wrapper.__dd_wrapped__)
assert wrapped, "Wrapper has wrapped function"
if wrapped.__name__ == "<wrapped>":
f = cast(FunctionType, wrapper)
f.__code__ = wrapped.__code__
del wrapper.__dd_wrapped__
except (IndexError, AttributeError):
return cast(FunctionType, wrapper)
return f
|
<filename>examples/scroll-cnode/router/router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import TopicList from '../pages/topic/List'
import TopicDetail from '../pages/topic/Detail'
Vue.use(VueRouter)
const RouterView = {
render (h) {
return h('router-view')
}
}
const router = new VueRouter({
routes: [
{
path: '/',
component: RouterView,
children: [
{
path: '',
name: 'topic-list',
component: TopicList
},
{
path: '/:id',
name: 'topic-detail',
component: TopicDetail
}
]
}
]
})
export default router
|
import React, {useState} from 'react';
const Form = () => {
const [number1, setNumber1] = useState(0);
const [number2, setNumber2] = useState(0);
const [sum, setSum] = useState(0);
const onClick = () => {
setSum(number1 + number2);
};
return (
<div>
<input
value={number1}
onChange={(e) => setNumber1(Number(e.target.value))}
type='number'
/>
<input
value={number2}
onChange={(e) => setNumber2(Number(e.target.value))}
type='number'
/>
<button onClick={onClick}>Add</button>
<p> {sum} </p>
</div>
);
};
export default Form; |
// 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 apisix
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestItemUnmarshalJSON(t *testing.T) {
var items node
emptyData := `
{
"key": "test",
"nodes": {}
}
`
err := json.Unmarshal([]byte(emptyData), &items)
assert.Nil(t, err)
emptyData = `
{
"key": "test",
"nodes": {"a": "b", "c": "d"}
}
`
err = json.Unmarshal([]byte(emptyData), &items)
assert.Equal(t, err.Error(), "unexpected non-empty object")
emptyArray := `
{
"key": "test",
"nodes": []
}
`
err = json.Unmarshal([]byte(emptyArray), &items)
assert.Nil(t, err)
}
func TestItemConvertRoute(t *testing.T) {
item := &item{
Key: "/apisix/routes/001",
Value: json.RawMessage(`
{
"upstream_id": "13",
"service_id": "14",
"host": "foo.com",
"uri": "/shop/133/details",
"methods": ["GET", "POST"]
}
`),
}
r, err := item.route("qa")
assert.Nil(t, err)
assert.Equal(t, *r.UpstreamId, "13")
assert.Equal(t, *r.ServiceId, "14")
assert.Equal(t, *r.Host, "foo.com")
assert.Equal(t, *r.Path, "/shop/133/details")
assert.Equal(t, *r.Methods[0], "GET")
assert.Equal(t, *r.Methods[1], "POST")
assert.Nil(t, r.Name)
assert.Equal(t, *r.FullName, "qa_unknown")
}
|
#!/usr/bin/env bash
# get userinfo
# set environment variables
[[ -f ./env ]] && source ./env
ENDPOINT="https://anypoint.mulesoft.com/accounts/api/v2/oauth2/userinfo"
curl -Lks ${ENDPOINT} \
-H "Authorization: Bearer ${TOKEN}" \
| jq
|
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { Wrapper } from '../../../test/test.helpers';
import ConfirmDialog from '../index';
describe('ConfirmDialog ui component tests', () => {
it('Should add icon in ConfirmDialog when get icon props', () => {
const { getByTestId } = render(
<Wrapper>
<ConfirmDialog
visibility
title="for test"
description="for test"
acceptTitle="for test"
dismissTitle="for test"
icon={
<svg height="100" width="100" data-testid="confirmIcon">
<circle
cx="50"
cy="50"
r="40"
stroke="black"
strokeWidth="3"
fill="red"
/>
</svg>
}
onClose={() => console.log('test')}
onDismiss={() => console.log('test')}
onAccept={() => console.log('test')}
/>
</Wrapper>,
);
const confirmIcon = getByTestId('confirmIcon');
expect(getByTestId('modalWrapper')).toContainElement(confirmIcon);
});
});
|
<gh_stars>0
module Erp
class ApplicationMailer < ActionMailer::Base
default from: "<EMAIL>"
layout 'mailer'
private
def send_email(email, subject)
#@todo static email!!
delivery_options = {
address: 'smtp.gmail.com',
port: 587,
domain: 'hcmut.edu.vn',
user_name: '<EMAIL>',
password: '<PASSWORD>@#$',
authentication: 'plain',
enable_starttls_auto: true
}
mail(to: email,
subject: subject,
delivery_method_options: delivery_options)
end
end
end
|
<reponame>MS-React/form-validation<gh_stars>0
import React from 'react';
import { shallow } from 'enzyme';
import UsersForm from './UsersForm';
function setup(props) {
return shallow(<UsersForm {...props} />);
}
describe('<UsersForm /> component', () => {
it('renders itself', () => {
// Arrange Act
const wrapper = setup({
onChange: () => {},
user: {},
validation: {}
});
// Assert
expect(wrapper.find('form')).toHaveLength(1);
expect(wrapper.find('FormInput')).toHaveLength(4);
});
it('should render form input with the right props', () => {
// Arrange Act
const wrapper = setup({
onChange: () => {},
user: {},
validation: {
isValid: false,
name: {
isValid: false,
message: 'Error name'
},
email: {
isValid: false,
message: 'Error email'
},
phone: {
isValid: false,
message: 'Error phone'
},
skypeId: {
isValid: false,
message: 'Error skype ID'
}
}
});
// Assert
expect(wrapper.find('FormInput').at(0).props()).toMatchObject({
feedback: 'Error name',
invalid: true
});
expect(wrapper.find('FormInput').at(1).props()).toMatchObject({
feedback: 'Error email',
invalid: true
});
expect(wrapper.find('FormInput').at(2).props()).toMatchObject({
feedback: 'Error phone',
invalid: true
});
expect(wrapper.find('FormInput').at(3).props()).toMatchObject({
feedback: 'Error skype ID',
invalid: true
});
});
});
|
One approach to classify text based on its sentiment is using supervised machine learning. In supervised machine learning, a labeled dataset containing text and its associated sentiment is used to train a classification model. The classification model can then be used to classify the sentiment of a new piece of text. |
#!/bin/sh
git pull origin main
git lfs prune
make -C services/data-pipeline-dashboard restart
date >> services/webhook/update-times.log
|
<filename>voogasalad_util/src/voogasalad/example/reflection/Counter.java
package voogasalad.example.reflection;
import java.util.Arrays;
// simple mutable class to reflect upon
public class Counter {
private String myLabel;
private int myValue;
public Counter () {
this("Counter", 0);
}
public Counter (String label) {
this(label, 0);
}
public Counter (String label, int value) {
myLabel = label;
myValue = value;
}
public Counter (String label, int ... value) {
this(label, Arrays.stream(value).sum());
}
public void next () {
next(1);
}
public void next (int increment) {
myValue += increment;
}
public void next (int ... increment) {
next(Arrays.stream(increment).sum());
}
public int getValue () {
return myValue;
}
public String toString () {
return myLabel + ": " + myValue;
}
}
|
#!/bin/bash
#-------------------------------------------------------
# file: init.sh
# comment: Install and manage the certificate signed by the sites
# https://www.sslforfree.com
# https://zerossl.com
# https://gethttpsforfree.com
# Also creates the certificate in JKS format.
# author: Aecio Pires <aeciopires@gmail.com>
# date: 24-abr-2018
# revision: Aecio Pires <aeciopires@gmail.com>
# last updated: 30-abr-2018, 09:47
#-------------------------------------------------------
#By default tasks take arguments as environment variables, prefixed with PT
# (short for Puppet Tasks)
# https://github.com/puppetlabs/tasks-hands-on-lab/tree/master/5-writing-tasks
#----------------------------------------------------
function isroot(){
MYUID=$(id | cut -d= -f2 | cut -d\( -f1)
[ "$MYUID" -eq 0 ] && echo YES && return 0 || echo NO && return 1
}
#------------------------------------------------------------
function install_essential_packages(){
PACKAGES="$1"
echo "[INFO] Installing necessary packages..."
case "$LINUXDISTRO" in
DEBIAN|UBUNTU)
sudo apt-get update > /dev/null 2>&1
sudo apt-get install -y $PACKAGES > /dev/null 2>&1
;;
CENTOS|REDHAT)
yum -y install $PACKAGES > /dev/null 2>&1
;;
*)
echo "[ERROR] I don't know how to install packages [$PACKAGES] in this \
distro: $LINUXDISTRO." && exit 3
;;
esac
}
#------------------------------------------------------------
function check_essential_commands(){
PACKAGES="$1"
echo "[INFO] Checking in the system the essential commands for the script..."
for file in "$PACKAGES" ; do
if [ ! -f "$file" ] ; then
echo "[ERROR] File not found: \"$file\""
return 3
fi
done
return 0
}
#-----------------------------------------------------------
function get_linux_distro(){
LINUXDISTRO=UNKNOWN
grep "CentOS" /etc/redhat-release > /dev/null 2>&1 && LINUXDISTRO=CENTOS
grep "Red Hat" /etc/redhat-release > /dev/null 2>&1 && LINUXDISTRO=REDHAT
grep "Debian" /etc/issue > /dev/null 2>&1 && LINUXDISTRO=DEBIAN
grep "Ubuntu" /etc/issue > /dev/null 2>&1 && LINUXDISTRO=UBUNTU
echo $LINUXDISTRO
}
#------------------------------------------------------------
function test_distro_suport(){
echo "[INFO] Testing script compatibility with distro..."
case "$LINUXDISTRO" in
CENTOS|REDHAT|DEBIAN|UBUNTU)
echo "[INFO] Support OK: $LINUXDISTRO"
;;
*)
echo "[ERROR] This script is not ready to run in the distro $LINUXDISTRO."
exit 5
;;
esac
}
#-----------------------------------------------
#-----------------------------------------------
# MAIN
#-----------------------------------------------
#-----------------------------------------------
# Declaracao de variaveis
PACKAGES="wget openssl keytool"
BINARIES="/usr/bin/wget /usr/bin/openssl /usr/bin/keytool"
CMDLINE=$(readlink --canonicalize --no-newline "$BASH_SOURCE")
PROGFILENAME=$(basename "$BASH_SOURCE")
PROGDIRNAME=$(dirname $(readlink -f "$BASH_SOURCE"))
LINUXDISTRO=$(get_linux_distro)
DATA=`date +%Y%m%d_%H-%M`
#Variaveis defaults caso estejam vazias
PT_certs_dir=${PT_certs_dir:-'/etc/sslfree'}
PT_keystore_file=${PT_keystore_file:-'/etc/sslfree/keystore.jks'}
PT_cacerts_file=${PT_cacerts_file:-'/etc/sslfree/cacerts.jks'}
PT_download_ca_cert=${PT_download_ca_cert:-'https://192.168.0.1/cert/ca_bundle.crt'}
PT_ca_cert=${PT_ca_cert:-'ca_bundle.crt'}
PT_download_host_cert_key=${PT_download_host_cert_key:-'https://192.168.0.1/cert/private.key'}
PT_host_cert_key=${PT_host_cert_key:-'private.key'}
PT_download_host_cert_crt=${PT_download_host_cert_crt:-'https://192.168.0.1/cert/certificate.crt'}
PT_host_cert_crt=${PT_host_cert_crt:-'certificate.crt'}
PT_cert_alias=${PT_cert_alias:-'sslfree'}
PT_host_cert_pass=${PT_host_cert_pass:-''}
PT_ca_cert_alias=${PT_ca_cert_alias:-'ca_sslfree'}
PT_java_cacert=${PT_java_cacert:-'/usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts'}
PT_keystore_pass_default=${PT_keystore_pass_default:-'changeit'}
PT_keystore_pass=${PT_keystore_pass:-'changeit'}
#------------------------------------------------------------
# Detecta se eh um usuario com poderes de root que esta executando o script
#if [ $(isroot) = NO ] ; then
# echo "voce deve ser root para executar este script."
# echo "execute o comando \"sudo $CMDLINE\""
# exit 4
#fi
# Detecta se a distro GNU/Linux eh suportada
test_distro_suport
# Checa os comandos essenciais a execucao do script
if ! check_essential_commands $BINARIES ; then
install_essential_packages $PACKAGES
check_essential_commands $BINARIES|| exit 3
fi
# Backp do diretorio de certificados
sudo mkdir -p "$PT_certs_dir"
sudo cp -R "$PT_certs_dir" "$PT_certs_dir"-backup-$DATA;
# Download dos certificados
echo "[INFO] Downloading the certificates..."
sudo wget --no-check-certificate -q "$PT_download_ca_cert" \
-O "$PT_certs_dir/$PT_ca_cert"
sudo wget --no-check-certificate -q "$PT_download_host_cert_key" \
-O "$PT_certs_dir/$PT_host_cert_key"
sudo wget --no-check-certificate -q "$PT_download_host_cert_crt" \
-O "$PT_certs_dir/$PT_host_cert_crt"
echo "[INFO] Verifying that the certificates exist..."
sudo chmod -R 755 "$PT_certs_dir"
if [ -f "$PT_certs_dir/$PT_ca_cert" ] ; then
if [ -z "$PT_certs_dir/$PT_ca_cert" ] ; then
echo "[ERROR] File empty: '$PT_certs_dir/$PT_ca_cert'"
exit 15
fi
else
echo "[ERROR] File not found: '$PT_certs_dir/$PT_ca_cert'"
exit 14
fi
if [ -f "$PT_certs_dir/$PT_host_cert_key" ] ; then
if [ -z "$PT_certs_dir/$PT_host_cert_key" ] ; then
echo "[ERROR] File empty: '$PT_certs_dir/$PT_host_cert_key'"
exit 17
fi
else
echo "[ERROR] File not found: '$PT_certs_dir/$PT_host_cert_key'"
exit 16
fi
if [ -f "$PT_certs_dir/$PT_host_cert_crt" ] ; then
if [ -z "$PT_certs_dir/$PT_host_cert_crt" ] ; then
echo "[ERROR] File empty: '$PT_certs_dir/$PT_host_cert_crt'"
exit 19
fi
else
echo "[ERROR] File not found: '$PT_certs_dir/$PT_host_cert_crt'"
exit 18
fi
if [ -f "$PT_keystore_file" ] ; then
if [ ! -z "$PT_keystore_file" ] ; then
# Removendo o certificado caso ja exista
if sudo keytool -list -keystore "$PT_keystore_file" -alias "$PT_cert_alias" \
-v -storepass "$PT_keystore_pass" -noprompt > /dev/null 2>&1; then
sudo keytool -delete -keystore "$PT_keystore_file" -alias "$PT_cert_alias" \
-storepass "$PT_keystore_pass" -noprompt > /dev/null 2>&1;
fi
else
echo "[ERROR] File empty: '$PT_keystore_file'"
exit 7
fi
#else
# echo "[ERROR] File not found: '$PT_keystore_file'"
# exit 6
fi
echo "[INFO] Deploying the certificates in '$PT_certs_dir'..."
# Adicionando o certificado no keystore
sudo openssl pkcs12 -export -name "$PT_cert_alias" -in "$PT_certs_dir/$PT_host_cert_crt" \
-inkey "$PT_certs_dir/$PT_host_cert_key" -out "$PT_certs_dir/keystore.p12" -password pass:"$PT_host_cert_pass"
sudo keytool -importkeystore -destkeystore "$PT_keystore_file" \
-srckeystore "$PT_certs_dir/keystore.p12" -srcstoretype pkcs12 -alias "$PT_cert_alias" \
-deststorepass "$PT_keystore_pass" -srcstorepass "$PT_host_cert_pass"
# Alterando a senha da chave privada para ser igual a do keystore.
sudo keytool -keypasswd -keypass "$PT_host_cert_pass" -alias "$PT_cert_alias" \
-keystore "$PT_keystore_file" -storepass "$PT_keystore_pass" \
-new "$PT_keystore_pass"
if [ -f "$PT_cacerts_file" ] ; then
if [ ! -z "$PT_cacerts_file" ] ; then
# Removendo o certificado caso ja exista
if sudo keytool -list -keystore "$PT_cacerts_file" -alias "$PT_ca_cert_alias" \
-v -storepass "$PT_keystore_pass" -noprompt > /dev/null 2>&1; then
sudo keytool -delete -keystore "$PT_cacerts_file" -alias "$PT_ca_cert_alias" \
-storepass "$PT_keystore_pass" -noprompt > /dev/null 2>&1
fi
else
echo "[ERROR] File empty: '$PT_cacerts_file'"
exit 9
fi
#else
# echo "[ERROR] File not found: '$PT_cacerts_file'"
# exit 8
fi
echo "[INFO] Deploying the CA certificates in '$PT_certs_dir'..."
# Adicionando o certificado do CA no cacerts
sudo keytool -import -v -trustcacerts -alias "$PT_ca_cert_alias" -file "$PT_certs_dir/$PT_ca_cert" \
-keystore "$PT_cacerts_file" -storepass "$PT_keystore_pass" -noprompt
# Adicionando o certificado do trustore do Java
sudo cp -R "$PT_java_cacert" "$PT_java_cacert"-backup-$DATA
if [ -f "$PT_java_cacert" ] ; then
if [ ! -z "$PT_java_cacert" ] ; then
# Removendo o certificado caso ja exista
if sudo keytool -list -keystore "$PT_java_cacert" -alias "$PT_ca_cert_alias" \
-v -storepass "$PT_keystore_pass_default" -noprompt > /dev/null 2>&1; then
sudo keytool -delete -keystore "$PT_java_cacert" -alias "$PT_ca_cert_alias" \
-storepass "$PT_keystore_pass_default" -noprompt > /dev/null 2>&1
fi
else
echo "[ERROR] File empty: '$PT_java_cacert'"
exit 11
fi
else
echo "[ERROR] File not found: '$PT_java_cacert'"
exit 10
fi
echo "[INFO] Deploying the CA certificate in '$PT_java_cacert'..."
sudo keytool -import -v -trustcacerts -alias "$PT_ca_cert_alias" \
-file "$PT_certs_dir/$PT_ca_cert" -keystore "$PT_java_cacert" \
-storepass "$PT_keystore_pass_default" -noprompt
if [ -f "$PT_java_cacert" ] ; then
if [ ! -z "$PT_java_cacert" ] ; then
# Removendo o certificado caso ja exista
if sudo keytool -list -keystore "$PT_java_cacert" -alias "$PT_cert_alias" \
-v -storepass "$PT_keystore_pass_default" -noprompt > /dev/null 2>&1; then
sudo keytool -delete -keystore "$PT_java_cacert" -alias "$PT_cert_alias" \
-storepass "$PT_keystore_pass_default" -noprompt > /dev/null 2>&1
fi
else
echo "[ERROR] File empty: '$PT_java_cacert'"
exit 11
fi
else
echo "[ERROR] File not found: '$PT_java_cacert'"
exit 10
fi
echo "[INFO] Deploying the certificate in '$PT_java_cacert'..."
sudo keytool -import -v -trustcacerts -alias "$PT_cert_alias" \
-file "$PT_certs_dir/$PT_host_cert_crt" -keystore "$PT_java_cacert" \
-storepass "$PT_keystore_pass_default" -noprompt
# Ajustando as permissoes de acesso
echo "[INFO] Setting permissions for '$PT_certs_dir' directory access..."
sudo chown -R root:root "$PT_certs_dir"
sudo chmod -R 755 "$PT_certs_dir"
sudo chmod -R 750 "$PT_certs_dir/$PT_host_cert_key";
|
package pubsub
import (
"context"
"github.com/ethereum/go-ethereum/log"
"github.com/go-redis/redis/v8"
"github.com/soulmachine/coinsignal/utils"
)
type Publisher struct {
rdb *redis.Client
ctx context.Context
}
func NewPublisher(ctx context.Context, redis_url string) *Publisher {
rdb := utils.NewRedisClient(redis_url)
return &Publisher{rdb, ctx}
}
func (publisher *Publisher) Publish(channel, msg string) {
err := publisher.rdb.Publish(publisher.ctx, channel, msg).Err()
if err != nil {
log.Error(err.Error())
}
}
func (publisher *Publisher) Close() {
publisher.rdb.Close()
}
|
#!/bin/bash
git clone --depth=1 https://github.com/sthima/libstapsdt
cd libstapsdt
make
cp out/libstapsdt.so.0 src/libstapsdt.h /out
|
#!/bin/bash
set -o errexit -o nounset
rustup target add thumbv6m-none-eabi
# `sval` builds
printf "\n\n---- sval ----\n\n"
cargo build --target=thumbv6m-none-eabi
printf "\n\n---- sval with fmt ----\n\n"
cargo build --target=thumbv6m-none-eabi --features fmt
printf "\n\n---- sval with serde_no_std ----\n\n"
cargo build --target=thumbv6m-none-eabi --features serde_no_std
# sval_json builds
pushd json
printf "\n\n---- sval_json ----\n\n"
cargo build --target=thumbv6m-none-eabi
popd
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-SS/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-SS/1024+0+512-N-VB-FILL-1 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_nouns_and_verbs_fill_first_two_thirds_full --eval_function last_element_eval |
<filename>tools/src/mindustry/tools/ScriptStubGenerator.java
package mindustry.tools;
import arc.*;
import arc.struct.Array;
import arc.struct.*;
import arc.files.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.graphics.g2d.TextureAtlas.*;
import arc.math.*;
import arc.util.*;
import mindustry.gen.*;
import org.reflections.*;
import org.reflections.scanners.*;
import org.reflections.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
public class ScriptStubGenerator{
public static void main(String[] args){
String base = "mindustry";
Array<String> blacklist = Array.with("plugin", "mod", "net", "io", "tools");
Array<String> nameBlacklist = Array.with("ClassAccess");
Array<Class<?>> whitelist = Array.with(Draw.class, Fill.class, Lines.class, Core.class, TextureAtlas.class, TextureRegion.class, Time.class, System.class, PrintStream.class,
AtlasRegion.class, String.class, Mathf.class, Angles.class, Color.class, Runnable.class, Object.class, Icon.class, Tex.class,
Sounds.class, Musics.class, Call.class, Texture.class, TextureData.class, Pixmap.class, I18NBundle.class, Interval.class, DataInput.class, DataOutput.class,
DataInputStream.class, DataOutputStream.class, Integer.class, Float.class, Double.class, Long.class, Boolean.class, Short.class, Byte.class, Character.class);
Array<String> nopackage = Array.with("java.lang", "java");
List<ClassLoader> classLoadersList = new LinkedList<>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false), new ResourcesScanner())
.setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
.filterInputsBy(new FilterBuilder()
.include(FilterBuilder.prefix("mindustry"))
.include(FilterBuilder.prefix("arc.func"))
.include(FilterBuilder.prefix("arc.struct"))
.include(FilterBuilder.prefix("arc.scene"))
.include(FilterBuilder.prefix("arc.math"))
));
Array<Class<?>> classes = Array.with(reflections.getSubTypesOf(Object.class));
classes.addAll(reflections.getSubTypesOf(Enum.class));
classes.addAll(whitelist);
classes.sort(Structs.comparing(Class::getName));
classes.removeAll(type -> type.isSynthetic() || type.isAnonymousClass() || type.getCanonicalName() == null || Modifier.isPrivate(type.getModifiers())
|| blacklist.contains(s -> type.getName().startsWith(base + "." + s + ".")) || nameBlacklist.contains(type.getSimpleName()));
classes.distinct();
ObjectSet<String> used = ObjectSet.with();
StringBuilder result = new StringBuilder("//Generated class. Do not modify.\n");
result.append("\n").append(new Fi("core/assets/scripts/base.js").readString()).append("\n");
for(Class type : classes){
if(used.contains(type.getPackage().getName()) || nopackage.contains(s -> type.getName().startsWith(s))) continue;
result.append("importPackage(Packages.").append(type.getPackage().getName()).append(")\n");
used.add(type.getPackage().getName());
}
//Log.info(result);
new Fi("core/assets/scripts/global.js").writeString(result.toString());
}
}
|
using System;
public class Program
{
public static void Main()
{
int[] array1 = {1, 2, 3};
int[] array2 = {2, 3, 4};
foreach (int n in GetCommonElements(array1, array2))
Console.WriteLine(n);
}
static int[] GetCommonElements(int[] array1, int[] array2)
{
int i = 0;
int j = 0;
var result = new List<int>();
while (i < array1.Length && j < array2.Length)
{
if (array1[i] == array2[j])
{
result.Add(array1[i]);
i++;
j++;
}
else if (array1[i] < array2[j])
i++;
else
j++;
}
return result.ToArray();
}
} |
class DataParser {
constructor(dataString) {
this.dataString = dataString;
}
parseString() {
// Convert the data string to an object
const parsedData = JSON.parse(this.dataString);
// Return the parsed data
return parsedData;
}
} |
import * as Icon from './SvgStrings';
import * as Helpers from './HelperFunctions';
export { Icon, Helpers };
|
function handleRemovalAndNotification(id, message, status) {
$('#tb-' + id).remove();
<?= \appxq\sdii\helpers\SDNoty::show('message', 'status') ?>;
} |
/* Generated by the protocol buffer compiler. DO NOT EDIT! */
/* Generated from: github.com/TheThingsNetwork/api/protocol/lorawan/device_address.proto */
#ifndef PROTOBUF_C_github_2ecom_2fTheThingsNetwork_2fapi_2fprotocol_2florawan_2fdevice_5faddress_2eproto__INCLUDED
#define PROTOBUF_C_github_2ecom_2fTheThingsNetwork_2fapi_2fprotocol_2florawan_2fdevice_5faddress_2eproto__INCLUDED
#include <protobuf-c/protobuf-c.h>
PROTOBUF_C__BEGIN_DECLS
#if PROTOBUF_C_VERSION_NUMBER < 1003000
# error This file was generated by a newer version of protoc-c which is incompatible with your libprotobuf-c headers. Please update your headers.
#elif 1003003 < PROTOBUF_C_MIN_COMPILER_VERSION
# error This file was generated by an older version of protoc-c which is incompatible with your libprotobuf-c headers. Please regenerate this file with a newer version of protoc-c.
#endif
#include "github.com/gogo/protobuf/gogoproto/gogo.pb-c.h"
typedef struct _Lorawan__PrefixesRequest Lorawan__PrefixesRequest;
typedef struct _Lorawan__PrefixesResponse Lorawan__PrefixesResponse;
typedef struct _Lorawan__PrefixesResponse__PrefixMapping Lorawan__PrefixesResponse__PrefixMapping;
typedef struct _Lorawan__DevAddrRequest Lorawan__DevAddrRequest;
typedef struct _Lorawan__DevAddrResponse Lorawan__DevAddrResponse;
/* --- enums --- */
/* --- messages --- */
struct _Lorawan__PrefixesRequest
{
ProtobufCMessage base;
};
#define LORAWAN__PREFIXES_REQUEST__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&lorawan__prefixes_request__descriptor) \
}
struct _Lorawan__PrefixesResponse__PrefixMapping
{
ProtobufCMessage base;
/*
* The prefix that can be used
*/
char *prefix;
/*
* Usage constraints of this prefix (see activation_constraints in device.proto)
*/
size_t n_usage;
char **usage;
};
#define LORAWAN__PREFIXES_RESPONSE__PREFIX_MAPPING__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&lorawan__prefixes_response__prefix_mapping__descriptor) \
, (char *)protobuf_c_empty_string, 0,NULL }
struct _Lorawan__PrefixesResponse
{
ProtobufCMessage base;
/*
* The prefixes that are in use or available
*/
size_t n_prefixes;
Lorawan__PrefixesResponse__PrefixMapping **prefixes;
};
#define LORAWAN__PREFIXES_RESPONSE__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&lorawan__prefixes_response__descriptor) \
, 0,NULL }
struct _Lorawan__DevAddrRequest
{
ProtobufCMessage base;
/*
* The usage constraints (see activation_constraints in device.proto)
*/
size_t n_usage;
char **usage;
};
#define LORAWAN__DEV_ADDR_REQUEST__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&lorawan__dev_addr_request__descriptor) \
, 0,NULL }
struct _Lorawan__DevAddrResponse
{
ProtobufCMessage base;
ProtobufCBinaryData dev_addr;
};
#define LORAWAN__DEV_ADDR_RESPONSE__INIT \
{ PROTOBUF_C_MESSAGE_INIT (&lorawan__dev_addr_response__descriptor) \
, {0,NULL} }
/* Lorawan__PrefixesRequest methods */
void lorawan__prefixes_request__init
(Lorawan__PrefixesRequest *message);
size_t lorawan__prefixes_request__get_packed_size
(const Lorawan__PrefixesRequest *message);
size_t lorawan__prefixes_request__pack
(const Lorawan__PrefixesRequest *message,
uint8_t *out);
size_t lorawan__prefixes_request__pack_to_buffer
(const Lorawan__PrefixesRequest *message,
ProtobufCBuffer *buffer);
Lorawan__PrefixesRequest *
lorawan__prefixes_request__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void lorawan__prefixes_request__free_unpacked
(Lorawan__PrefixesRequest *message,
ProtobufCAllocator *allocator);
/* Lorawan__PrefixesResponse__PrefixMapping methods */
void lorawan__prefixes_response__prefix_mapping__init
(Lorawan__PrefixesResponse__PrefixMapping *message);
/* Lorawan__PrefixesResponse methods */
void lorawan__prefixes_response__init
(Lorawan__PrefixesResponse *message);
size_t lorawan__prefixes_response__get_packed_size
(const Lorawan__PrefixesResponse *message);
size_t lorawan__prefixes_response__pack
(const Lorawan__PrefixesResponse *message,
uint8_t *out);
size_t lorawan__prefixes_response__pack_to_buffer
(const Lorawan__PrefixesResponse *message,
ProtobufCBuffer *buffer);
Lorawan__PrefixesResponse *
lorawan__prefixes_response__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void lorawan__prefixes_response__free_unpacked
(Lorawan__PrefixesResponse *message,
ProtobufCAllocator *allocator);
/* Lorawan__DevAddrRequest methods */
void lorawan__dev_addr_request__init
(Lorawan__DevAddrRequest *message);
size_t lorawan__dev_addr_request__get_packed_size
(const Lorawan__DevAddrRequest *message);
size_t lorawan__dev_addr_request__pack
(const Lorawan__DevAddrRequest *message,
uint8_t *out);
size_t lorawan__dev_addr_request__pack_to_buffer
(const Lorawan__DevAddrRequest *message,
ProtobufCBuffer *buffer);
Lorawan__DevAddrRequest *
lorawan__dev_addr_request__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void lorawan__dev_addr_request__free_unpacked
(Lorawan__DevAddrRequest *message,
ProtobufCAllocator *allocator);
/* Lorawan__DevAddrResponse methods */
void lorawan__dev_addr_response__init
(Lorawan__DevAddrResponse *message);
size_t lorawan__dev_addr_response__get_packed_size
(const Lorawan__DevAddrResponse *message);
size_t lorawan__dev_addr_response__pack
(const Lorawan__DevAddrResponse *message,
uint8_t *out);
size_t lorawan__dev_addr_response__pack_to_buffer
(const Lorawan__DevAddrResponse *message,
ProtobufCBuffer *buffer);
Lorawan__DevAddrResponse *
lorawan__dev_addr_response__unpack
(ProtobufCAllocator *allocator,
size_t len,
const uint8_t *data);
void lorawan__dev_addr_response__free_unpacked
(Lorawan__DevAddrResponse *message,
ProtobufCAllocator *allocator);
/* --- per-message closures --- */
typedef void (*Lorawan__PrefixesRequest_Closure)
(const Lorawan__PrefixesRequest *message,
void *closure_data);
typedef void (*Lorawan__PrefixesResponse__PrefixMapping_Closure)
(const Lorawan__PrefixesResponse__PrefixMapping *message,
void *closure_data);
typedef void (*Lorawan__PrefixesResponse_Closure)
(const Lorawan__PrefixesResponse *message,
void *closure_data);
typedef void (*Lorawan__DevAddrRequest_Closure)
(const Lorawan__DevAddrRequest *message,
void *closure_data);
typedef void (*Lorawan__DevAddrResponse_Closure)
(const Lorawan__DevAddrResponse *message,
void *closure_data);
/* --- services --- */
typedef struct _Lorawan__DevAddrManager_Service Lorawan__DevAddrManager_Service;
struct _Lorawan__DevAddrManager_Service
{
ProtobufCService base;
void (*get_prefixes)(Lorawan__DevAddrManager_Service *service,
const Lorawan__PrefixesRequest *input,
Lorawan__PrefixesResponse_Closure closure,
void *closure_data);
void (*get_dev_addr)(Lorawan__DevAddrManager_Service *service,
const Lorawan__DevAddrRequest *input,
Lorawan__DevAddrResponse_Closure closure,
void *closure_data);
};
typedef void (*Lorawan__DevAddrManager_ServiceDestroy)(Lorawan__DevAddrManager_Service *);
void lorawan__dev_addr_manager__init (Lorawan__DevAddrManager_Service *service,
Lorawan__DevAddrManager_ServiceDestroy destroy);
#define LORAWAN__DEV_ADDR_MANAGER__BASE_INIT \
{ &lorawan__dev_addr_manager__descriptor, protobuf_c_service_invoke_internal, NULL }
#define LORAWAN__DEV_ADDR_MANAGER__INIT(function_prefix__) \
{ LORAWAN__DEV_ADDR_MANAGER__BASE_INIT,\
function_prefix__ ## get_prefixes,\
function_prefix__ ## get_dev_addr }
void lorawan__dev_addr_manager__get_prefixes(ProtobufCService *service,
const Lorawan__PrefixesRequest *input,
Lorawan__PrefixesResponse_Closure closure,
void *closure_data);
void lorawan__dev_addr_manager__get_dev_addr(ProtobufCService *service,
const Lorawan__DevAddrRequest *input,
Lorawan__DevAddrResponse_Closure closure,
void *closure_data);
/* --- descriptors --- */
extern const ProtobufCMessageDescriptor lorawan__prefixes_request__descriptor;
extern const ProtobufCMessageDescriptor lorawan__prefixes_response__descriptor;
extern const ProtobufCMessageDescriptor lorawan__prefixes_response__prefix_mapping__descriptor;
extern const ProtobufCMessageDescriptor lorawan__dev_addr_request__descriptor;
extern const ProtobufCMessageDescriptor lorawan__dev_addr_response__descriptor;
extern const ProtobufCServiceDescriptor lorawan__dev_addr_manager__descriptor;
PROTOBUF_C__END_DECLS
#endif /* PROTOBUF_C_github_2ecom_2fTheThingsNetwork_2fapi_2fprotocol_2florawan_2fdevice_5faddress_2eproto__INCLUDED */
|
/*
*
*/
package net.community.chest.swing;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeMap;
import javax.swing.SwingConstants;
import net.community.chest.convert.NumberValueStringInstantiator;
import net.community.chest.dom.AbstractXmlValueStringInstantiator;
import net.community.chest.lang.StringUtil;
/**
* <P>Copyright 2008 as per GPLv2</P>
*
* @author <NAME>.
* @since Sep 24, 2008 11:03:53 AM
*/
public class SwingConstantsValueStringInstantiator
extends AbstractXmlValueStringInstantiator<Integer>
implements NumberValueStringInstantiator<Integer> {
/*
* @see net.community.chest.convert.NumberValueStringInstantiator#getPrimitiveValuesClass()
*/
@Override
public final Class<Integer> getPrimitiveValuesClass ()
{
return Integer.TYPE;
}
/*
* @see net.community.chest.reflect.ValueNumberInstantiator#getInstanceNumber(java.lang.Object)
*/
@Override
public Integer getInstanceNumber (Integer inst) throws Exception
{
return inst;
}
/*
* @see net.community.chest.reflect.ValueNumberInstantiator#newInstance(java.lang.Number)
*/
@Override
public Integer newInstance (Integer num) throws Exception
{
return num;
}
private static Map<String,Integer> _constsMap /* =null */;
/**
* @return A {@link Map} of all the static fields defined in
* {@link SwingConstants} class where key=field name (case
* <U>insensitive</U>), value=field {@link Integer} value
* @throws Exception If failed to explore the class
*/
public static final synchronized Map<String,Integer> getConstantsMap () throws Exception
{
if (null == _constsMap)
{
try
{
final Field[] fa=SwingConstants.class.getDeclaredFields();
for (final Field f : fa)
{
final String n=(null == f) ? null : f.getName();
if ((null == n) || (n.length() <= 0))
continue; // should not happen
final int mod=f.getModifiers();
if ((!Modifier.isPublic(mod)) || (!Modifier.isStatic(mod)))
continue;
if (!f.isAccessible()) // should not happen, but do it anyway...
f.setAccessible(true);
final Object v=f.get(null);
if (!(v instanceof Integer))
continue;
if (null == _constsMap)
_constsMap = new TreeMap<String,Integer>(String.CASE_INSENSITIVE_ORDER);
final Object prev=_constsMap.put(n, (Integer) v);
if (prev != null)
throw new IllegalStateException("Multiple values for field=" + n + ": new=" + v + "/old=" + prev);
}
}
catch(Exception e)
{
if (_constsMap != null)
_constsMap = null;
throw e;
}
}
return _constsMap;
}
/*
* @see net.community.chest.convert.ValueStringInstantiator#convertInstance(java.lang.Object)
*/
@Override
public String convertInstance (final Integer inst) throws Exception
{
if (null == inst)
return null;
// NOTE !!! only UNIQUE values will succeed
final Map<String,Integer> cm=getConstantsMap();
final Collection<? extends Map.Entry<String,Integer>> cml=
((null == cm) || (cm.size() <= 0)) ? null : cm.entrySet();
String ret=null;
if ((cml != null) && (cml.size() > 0))
{
for (final Map.Entry<String,Integer> ce : cml)
{
final Integer v=(null == ce) ? null : ce.getValue();
if (!inst.equals(v))
continue;
if (ret != null)
throw new IllegalStateException("convertInstance(" + inst + ") multiple matches: " + ret + "/" + ce.getKey());
if ((null == (ret=ce.getKey())) || (ret.length() <= 0)) // should not happen
throw new IllegalStateException("convertInstance(" + inst + ") no constant name");
}
}
if ((null == ret) || (ret.length() <= 0))
throw new NoSuchElementException("convertInstance(" + inst + ") no match found");
return ret;
}
/*
* @see net.community.chest.convert.ValueStringInstantiator#newInstance(java.lang.String)
*/
@Override
public Integer newInstance (final String v) throws Exception
{
final String s=StringUtil.getCleanStringValue(v);
if ((null == s) || (s.length() <= 0))
return null;
final Map<String,Integer> cm=getConstantsMap();
final Integer i=((null == cm) || (cm.size() <= 0)) ? null : cm.get(s);
if (null == v)
throw new NoSuchElementException("newInstance(" + s + ") unknown constant");
return i;
}
public SwingConstantsValueStringInstantiator ()
{
super(Integer.class);
}
public static final SwingConstantsValueStringInstantiator DEFAULT=new SwingConstantsValueStringInstantiator();
}
|
package test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import arc.Core;
import arc.files.Fi;
import arc.struct.Array;
import arc.struct.ArrayMap;
import arc.struct.ObjectMap;
import arc.util.reflect.ArrayReflection;
import arc.util.serialization.Json;
import arc.util.serialization.JsonReader;
import arc.util.serialization.JsonValue;
import arc.util.serialization.JsonWriter;
import mindustry.content.Items;
import mindustry.type.Category;
import mindustry.type.ItemStack;
import z.tools.serialize.JSON;
import z.tools.serialize.Parameter;
import z.utils.FinalCons;
public class JsonTest {
public JsonTest() {
init();
}
JSON json;
public void init () {
json = new JSON();
// json.fromJson(Test1.class, //
// "{byteArrayField:[-1\n,-2]}"
// );
// if (true) return;
Test1 test = new Test1();
test.booleanField = true;
test.byteField = 123;
test.charField = 'Z';
test.shortField = 12345;
test.intField = 123456;
test.longField = 123456789;
test.floatField = 123.456f;
test.doubleField = 1.23456d;
test.BooleanField = true;
test.ByteField = -12;
test.CharacterField = 'X';
test.ShortField = -12345;
test.IntegerField = -123456;
test.LongField = -123456789l;
test.FloatField = -123.3f;
test.DoubleField = -0.121231d;
test.stringField = "stringvalue";
test.byteArrayField = new byte[] {2, 1, 0, -1, -2};
test.map = new ObjectMap();
test.map.put("one", 1);
test.map.put("two", 2);
test.map.put("nine", 9);
test.stringArray = new Array();
test.stringArray.add("meow");
test.stringArray.add("moo");
test.objectArray = new Array();
test.objectArray.add("meow");
test.objectArray.add(new Test1());
test.someEnum = SomeEnum.b;
test.itemStack = new ItemStack(Items.timber, 10);
if (true) {
try {
Parameter parameter = new Parameter();
parameter.param = new Object[3];
parameter.param[0] = Category.crafting;
{
ItemStack itemStack[][] = new ItemStack[][]{
{new ItemStack(Items.lead, 10), new ItemStack(Items.lead, 5)},
// {new ItemStack(Items.copper, 10)},
// {new ItemStack(Items.copper, 10)},
// {new ItemStack(Items.copper, 10)},
// {new ItemStack(Items.copper, 10)},
// {new ItemStack(Items.copper, 10)},
};
// parameter.param[1] = new ItemStack(Items.copper, 10);
parameter.param[1] = itemStack;
System.out.println(itemStack.getClass() + " --");
}
parameter.param[2] = false;
String value = new Json().toJson(parameter);
Fi handle = Core.files.absolute("D:\\Develop\\workspace\\libgdx\\zones\\Public\\DiabloTown\\SanGuoTD\\desktop\\assets\\xml\\test2.json");
FinalCons.createFile(handle, value);
System.out.println(value);
} catch (Exception e) {
System.out.println(e.toString());
}
return;
}
if (true && false) {
String value2 = json.toJson(test.itemStack);
// FileHandle handle = Gdx.files.absolute("D:\\Develop\\workspace\\libgdx\\zones\\tools\\T_URLDownload\\Assets\\Test\\test.json");
//// FILE.createFile(handle, value);
System.out.println(value2);
System.out.println("---------------");
//
// Object obj = json.fromJson(Test1.class, value);
// Test1 t2 = (Test1) obj;
// System.out.println(t2.FloatField);
Test1 t3 = new Test1();
// t3.byteField = 111;
String vv = json.prettyPrint(t3);
try {
JsonValue value = new JsonReader().parse("{byteField:111}").child;
System.out.println(value.name() + "----" );
json.readFieldCustom(t3, value.name, "byte.class", new JsonReader().parse("{byteField:111}"));
json.readField(t3, value.name, value.name, new JsonReader().parse("{byteField:51}"));
// json.readField(t3, "", new JsonReader().parse("{byteField:111}"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(t3.byteField);
// json.readField(t3, "byteField", JsonValue);
if (int.class == Integer.class) {
System.out.println("------------------------");
}
try {
Field ff = Test1.class.getField("booleanField");
System.out.println(ff.getType() + " " + ff.getGenericType());
} catch ( Exception e) {
e.printStackTrace();
}
// System.out.println(obj.toString());
return;
}
roundTrip(test);
test.someEnum = null;
roundTrip(test);
test = new Test1();
roundTrip(test);
test.stringArray = new Array();
roundTrip(test);
test.stringArray.add("meow");
roundTrip(test);
test.stringArray.add("moo");
roundTrip(test);
TestMapGraph objectGraph = new TestMapGraph();
testObjectGraph(objectGraph, "exoticTypeName");
test = new Test1();
test.map = new ObjectMap();
roundTrip(test);
test.map.put("one", 1);
roundTrip(test);
test.map.put("two", 2);
test.map.put("nine", 9);
roundTrip(test);
test.map.put("\nst\nuff\n", 9);
test.map.put("\r\nst\r\nuff\r\n", 9);
roundTrip(test);
equals(json.toJson("meow"), "meow");
equals(json.toJson("meow "), "\"meow \"");
equals(json.toJson(" meow"), "\" meow\"");
equals(json.toJson(" meow "), "\" meow \"");
equals(json.toJson("\nmeow\n"), "\\nmeow\\n");
equals(json.toJson(Array.with(1, 2, 3), null, int.class), "[1,2,3]");
equals(json.toJson(Array.with("1", "2", "3"), null, String.class), "[1,2,3]");
equals(json.toJson(Array.with(" 1", "2 ", " 3 "), null, String.class), "[\" 1\",\"2 \",\" 3 \"]");
equals(json.toJson(Array.with("1", "", "3"), null, String.class), "[1,\"\",3]");
System.out.println();
System.out.println("Success!");
}
private String roundTrip (Object object) {
String text = json.toJson(object);
System.out.println(text);
test(text, object);
text = json.prettyPrint(object, 130);
test(text, object);
return text;
}
private void testObjectGraph (TestMapGraph object, String typeName) {
Json json = new Json();
json.setTypeName(typeName);
json.setUsePrototypes(false);
json.setIgnoreUnknownFields(true);
json.setOutputType(JsonWriter.OutputType.json);
String text = json.prettyPrint(object);
TestMapGraph object2 = json.fromJson(TestMapGraph.class, text);
if (object2.map.size() != object.map.size()) {
throw new RuntimeException("Too many items in deserialized json map.");
}
if (object2.objectMap.size != object.objectMap.size) {
throw new RuntimeException("Too many items in deserialized json object map.");
}
if (object2.arrayMap.size != object.arrayMap.size) {
throw new RuntimeException("Too many items in deserialized json map.");
}
}
private void test (String text, Object object) {
check(text, object);
text = text.replace("{", "/*moo*/{/*moo*/");
check(text, object);
text = text.replace("}", "/*moo*/}/*moo*/");
text = text.replace("[", "/*moo*/[/*moo*/");
text = text.replace("]", "/*moo*/]/*moo*/");
text = text.replace(":", "/*moo*/:/*moo*/");
text = text.replace(",", "/*moo*/,/*moo*/");
check(text, object);
text = text.replace("/*moo*/", " /*moo*/ ");
check(text, object);
text = text.replace("/*moo*/", "// moo\n");
check(text, object);
text = text.replace("\n", "\r\n");
check(text, object);
text = text.replace(",", "\n");
check(text, object);
text = text.replace("\n", "\r\n");
check(text, object);
text = text.replace("\r\n", "\r\n\r\n");
check(text, object);
}
private void check (String text, Object object) {
Object object2 = json.fromJson(object.getClass(), text);
equals(object, object2);
}
private void equals (Object a, Object b) {
if (!a.equals(b)) throw new RuntimeException("Fail!\n" + a + "\n!=\n" + b);
}
static public class Test1 {
// Primitives.
public boolean booleanField;
public byte byteField;
public char charField;
public short shortField;
public int intField;
public long longField;
public float floatField;
public double doubleField;
// Primitive wrappers.
public Boolean BooleanField;
public Byte ByteField;
public Character CharacterField;
public Short ShortField;
public Integer IntegerField;
public Long LongField;
public Float FloatField;
public Double DoubleField;
// Other.
public String stringField;
public byte[] byteArrayField;
public Object object;
public ObjectMap<String, Integer> map;
public Array<String> stringArray;
public Array objectArray;
public SomeEnum someEnum;
public ItemStack itemStack;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Test1 other = (Test1)obj;
if (BooleanField == null) {
if (other.BooleanField != null) return false;
} else if (!BooleanField.equals(other.BooleanField)) return false;
if (ByteField == null) {
if (other.ByteField != null) return false;
} else if (!ByteField.equals(other.ByteField)) return false;
if (CharacterField == null) {
if (other.CharacterField != null) return false;
} else if (!CharacterField.equals(other.CharacterField)) return false;
if (DoubleField == null) {
if (other.DoubleField != null) return false;
} else if (!DoubleField.equals(other.DoubleField)) return false;
if (FloatField == null) {
if (other.FloatField != null) return false;
} else if (!FloatField.equals(other.FloatField)) return false;
if (IntegerField == null) {
if (other.IntegerField != null) return false;
} else if (!IntegerField.equals(other.IntegerField)) return false;
if (LongField == null) {
if (other.LongField != null) return false;
} else if (!LongField.equals(other.LongField)) return false;
if (ShortField == null) {
if (other.ShortField != null) return false;
} else if (!ShortField.equals(other.ShortField)) return false;
if (stringField == null) {
if (other.stringField != null) return false;
} else if (!stringField.equals(other.stringField)) return false;
if (booleanField != other.booleanField) return false;
Object list1 = arrayToList(byteArrayField);
Object list2 = arrayToList(other.byteArrayField);
if (list1 != list2) {
if (list1 == null || list2 == null) return false;
if (!list1.equals(list2)) return false;
}
if (object != other.object) {
if (object == null || other.object == null) return false;
if (object != this && !object.equals(other.object)) return false;
}
if (map != other.map) {
if (map == null || other.map == null) return false;
if (!map.keys().toArray().equals(other.map.keys().toArray())) return false;
if (!map.values().toArray().equals(other.map.values().toArray())) return false;
}
if (stringArray != other.stringArray) {
if (stringArray == null || other.stringArray == null) return false;
if (!stringArray.equals(other.stringArray)) return false;
}
if (byteField != other.byteField) return false;
if (charField != other.charField) return false;
if (Double.doubleToLongBits(doubleField) != Double.doubleToLongBits(other.doubleField)) return false;
if (Float.floatToIntBits(floatField) != Float.floatToIntBits(other.floatField)) return false;
if (intField != other.intField) return false;
if (longField != other.longField) return false;
if (shortField != other.shortField) return false;
return true;
}
}
public static class TestMapGraph {
public Map<String, String> map = new HashMap<String, String>();
public ObjectMap<String, String> objectMap = new ObjectMap<String, String>();
public ArrayMap<String, String> arrayMap = new ArrayMap<String, String>();
public TestMapGraph () {
map.put("a", "b");
map.put("c", "d");
objectMap.put("a", "b");
objectMap.put("c", "d");
arrayMap.put("a", "b");
arrayMap.put("c", "d");
}
}
public enum SomeEnum {
a, b, c;
}
static Object arrayToList (Object array) {
if (array == null || !array.getClass().isArray()) return array;
ArrayList list = new ArrayList(ArrayReflection.getLength(array));
for (int i = 0, n = ArrayReflection.getLength(array); i < n; i++)
list.add(arrayToList(ArrayReflection.get(array, i)));
return list;
}
}
|
#!/usr/bin/env bash
# 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.
#
# Pulls and rebuilds the full CI image used for testing
#
set -euo pipefail
MY_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# shellcheck source=scripts/ci/_utils.sh
. "${MY_DIR}/_utils.sh"
basic_sanity_checks
script_start
cleanup_ci_image
cleanup_ci_slim_image
cleanup_checklicence_image
script_end
|
<reponame>Itschrismorgan/meanBlog<filename>routes/posts.js<gh_stars>0
/**
* Created by chris on 3/1/14.
*/
/* Posts routes */
var apiCtrl = require('../app_server/controllers/apiPosts.js');
var expressJwt = require('express-jwt');
var tokenSecret = require('../config/token');
module.exports = function(app){
app.get('/api/posts',apiCtrl.posts);
app.get('/api/posts/:id', apiCtrl.post);
app.post('/api/posts/:id', expressJwt({secret: tokenSecret.secret}),apiCtrl.updatePost);
}; |
<gh_stars>1-10
function now() {
return new Date().toISOString().split("T")[0];
}
function lastYear() {
var d = new Date();
d.setFullYear(d.getFullYear() - 1);
return d.toISOString().split("T")[0];
}
function hello(name) {
return "name:" + name;
}
|
#!/bin/bash
EXP_TAG=2021-02-05-hitchhiking
EXP_DIR=/mnt/home/lalejini/devo_ws/evolutionary-consequences-of-plasticity/experiments/${EXP_TAG}
BASE_DATA_DIR=/mnt/scratch/lalejini/data/avida-plasticity/${EXP_TAG}
REPLICATES=100
CONFIG_DIR=${EXP_DIR}/hpcc/config
JOB_DIR=${BASE_DATA_DIR}/jobs
# JOB_DIR=./jobs
PHASE_ONE_DIR=${BASE_DATA_DIR}/phase-1
PHASE_TWO_DIR=${BASE_DATA_DIR}/phase-2
python3 gen_sub_multi.py --phase_one_dir ${PHASE_ONE_DIR} --phase_two_dir ${PHASE_TWO_DIR} --config_dir ${CONFIG_DIR} --replicates ${REPLICATES} --job_dir ${JOB_DIR} |
<reponame>riversun/ajax-client
const Server = require('../test-util/TestServer.js');
const AjaxClient = require('../src/AjaxClient2.js').AjaxClient2;
let server;
const fetch = require('node-fetch');
window.fetch = fetch;
function getRandomPort() {
return 40000 + Math.floor(Math.random() * Math.floor(1000));
}
let serverPort = getRandomPort();
beforeAll(() => {
server = new Server(serverPort);
console.log(`Before all: start server on port:${serverPort}`);
});
afterAll(() => {
console.log("After all: close server.");
server.close();
});
describe('AjaxClient', () => {
describe('ajax()', () => {
test('Method "get" and receive "done"', (done) => {
const client = new AjaxClient();
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api`,
// contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data),
}).done((result) => {
try {
console.log(result)
expect(result.output).toContain('Hi,there! You say hello');
done();
} catch (error) {
done(error);
}
});
});
test('Method "post" and receive "done"', (done) => {
const client = new AjaxClient();
const data = {
message: "hello"
}
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/api`,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data),
}).done((result) => {
try {
expect(result.output).toContain('Hi,there! You say hello');
done();
} catch (error) {
done(error);
}
});
});
test('Method "jsonp" and receive "done"', (done) => {
const client = new AjaxClient();
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api`,
contentType: 'application/json',
dataType: 'jsonp',
data: JSON.stringify(data),
}).done((result) => {
try {
console.log("debug", result);
expect(result.output).toContain('Hi,there! You say hello');
done();
} catch (error) {
done(error);
}
});
});
test('Method "get" and receive "fail" of status:404', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/test_nothing`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
}).done((data, response) => {
}).fail((data, response, cause) => {
console.log("response", response);
expect(response.status).toBe(404);
expect(cause).toBe("server error,statusCode:404");
done();
});
});//test
test('Method "get" and receive "fail" of network error', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:12345`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
}).done((data, response) => {
}).fail((data, response, cause, err) => {
console.log("response", err);
expect(cause).toBe("network error");
done();
});
});//test
test('Method "get" text and receive "fail" of JSON format error.', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/text`,
//contentType: 'application/json',//content-type of sending data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
}).done((data, response) => {
}).fail((data, response, cause) => {
console.log("cause", cause);
expect(cause).toContain('invalid json response');
done();
});
});//test
test('"post"', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (data, response) => {
try {
expect(JSON.stringify(data)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
done();
} catch (error) {
done(error);
}
},
error: (data, response, cause, err) => {
},
timeout: (data, response, cause, err) => {
}
});
});//test
test('"post" and fail', async (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
if (false)
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/api-error`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (data, response) => {
try {
expect(JSON.stringify(data)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
done();
} catch (error) {
done(error);
}
},
error: (data, response) => {
console.log("dddd", data, response)
},
timeout: (e, xhr) => {
}
});
// first access = Receive cookies with the intention of credential
const result = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api-error`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/x-www-form-urlencoded',
data: data,
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: true,
},
});
console.log(result);
done();
});//test
test('"post with cookie"', async () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
// first access = Receive cookies with the intention of credential
await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api-auth`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: true,
},
});
// second access = make sure that the credential (cookie) is sent without being aware of it
const resultOf2ndAccess = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api-auth`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: true,
},
});
expect(resultOf2ndAccess.success).toBe(true);
// todo node-fetch doesn't support credentials:'include'
//expect(resultOf2ndAccess.data['req-cookies-copy']['test-name1']).toBe('test-value1');
// third access = withCredentials:false to ensure that no cookie is sent
const resultOf3rdAccess = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api-auth`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: false,
},
});
expect(resultOf3rdAccess.data['req-cookies-copy']).toStrictEqual({});
});//test
test('"post with application/x-www-form-urlencoded"', async () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
// first access = Receive cookies with the intention of credential
const result = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/form`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/x-www-form-urlencoded',
data: data,
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: true,
},
});
// Verify that the posted as "application/x-www-form-urlencoded" form data is interpreted on the server side
expect(result.data.output).toBe(`Hi,there! You say hello`);//
// second access = make sure that the credential (cookie) is sent without being aware of it
const resultOf2ndAccess = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/form`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/x-www-form-urlencoded',
data: data,
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: true,
},
});
expect(resultOf2ndAccess.success).toBe(true);
// todo node-fetch doesn't support credentials:'include'
// expect(resultOf2ndAccess.data['req-cookies-copy']['test-name2']).toBe('test-value2');
// third access = withCredentials:false to ensure that no cookie is sent
const resultOf3rdAccess = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/form`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/x-www-form-urlencoded',
data: data,
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
crossDomain: true,
xhrFields: {
withCredentials: false,
},
});
expect(resultOf3rdAccess.data['req-cookies-copy']).toStrictEqual({});
expect(resultOf3rdAccess.response.status).toBe(200);
});//test
test('"POST"', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'POST',
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(JSON.stringify(response)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
done();
},
error: (e, xhr) => {
},
timeout: (e, xhr) => {
}
});
});//test
test('"post in text with async/await"', async () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
const result = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
});
expect(result.success).toBe(true);
expect(JSON.stringify(result.data)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
});//test
test('"post object with async/await"', async () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
const result = await client.post({
type: 'post',
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: data,//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
});
expect(result.success).toBe(true);
expect(JSON.stringify(result.data)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
});//test
test('check dataType', (done) => {
const client = new AjaxClient();
expect(function() {
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'xml',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
},
error: (e, xhr) => {
},
timeout: (e, xhr) => {
}
});
}).toThrow('Please check dataType');
done();
});//test
test('"get"', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/test.html`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(response).toContain('Test HTML');
done();
},
error: (e, xhr) => {
console.log('Error occurred' + xhr.status);
},
timeout: (e, xhr) => {
console.error('Timeout occurred.' + e);
}
});
});//test
test('"GET"', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'GET',
url: `http://localhost:${serverPort}/test.html`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(response).toContain('Test HTML');
done();
},
error: (e, xhr) => {
console.log('Error occurred' + xhr.status);
},
timeout: (e, xhr) => {
console.error('Timeout occurred.' + e);
}
});
});//test
test('"get" with async/await', async () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
const result = await client.get({
url: `http://localhost:${serverPort}/test.html`,
contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
});
expect(result.success).toBe(true);
expect(result.data).toContain('Test HTML');
});//test
test('"get" with parameters', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api`,
//contentType: 'application/json',//content-type of sending data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
data: JSON.stringify(data),
success: (json, xhr) => {
try {
expect(json.output).toContain('Hi,there! You say hello');
done();
} catch (error) {
done(error);
}
},
error: (e, xhr) => {
throw Error('Error occurred.(error)' + e);
},
timeout: (e, xhr) => {
//throw Error('Error occurred.(timeout)' + e);
}
});
});//test
test('Status error 404', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/test_nothing`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
throw Error('404 Error should be occurred.');
},
error: (e, xhr) => {
expect(xhr.status).toBe(404);
done();
},
timeout: (e, xhr) => {
throw Error('404 Error should be occurred.');
}
});
});//test
test('General error', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: 'http://localhost:1111/test.html',
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
throw Error('404 Error should be occurred.');
},
error: (e, xhr) => {
done();
},
timeout: (e, xhr) => {
throw Error('404 Error should be occurred.');
}
});
});//test
test('post with jsonp to error', () => {
const client = new AjaxClient();
expect(function() {
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/test.html`,
contentType: 'application/json',//content-type of sending data
dataType: 'jsonp',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
},
});
}).toThrow("'POST' and 'jsonp' can not be specified together");
});//test
test('headers with jsonp to error', () => {
const client = new AjaxClient();
expect(function() {
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/test.html`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
//contentType: 'application/json',//content-type of sending data
dataType: 'jsonp',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
},
});
}).toThrow("Http headers cannot be sent when using jsonp");
});//test
test('jsonp', (done) => {
const client = new AjaxClient();
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api?message=hello2`,//Endpoint
//contentType: 'application/json',//content-type of sending data
dataType: 'jsonp',
success: (json, xhr) => {
try {
expect(JSON.stringify(json)).toBe(JSON.stringify({ output: 'Hi,there! You say hello2' }));
done();
} catch (error) {
done(error);
}
},
});
});//test
test('jsonp with no query params', (done) => {
const client = new AjaxClient();
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api`,//Endpoint
//contentType: 'application/json',//content-type of sending data
dataType: 'jsonp',
success: (json, xhr) => {
try {
expect(json.output).toContain('Hi,there! You say');
done();
} catch (error) {
done(error);
}
},
});
});//test
test('jsonp with error', (done) => {
const client = new AjaxClient();
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/api_nothing`,//Endpoint
//contentType: 'application/json',//content-type of sending data
dataType: 'jsonp',
success: (json, xhr) => {
throw Error('Error must be occurred');
},
error: (err) => {
done();
}
});
});//test
test.skip('timeout', (done) => {
// timeout is successfully implemented but node-fetch has error.
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.ajax({
type: 'get',
url: `http://localhost:${serverPort}/timeout`,
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 1000,//timeout milli-seconds
success: (response, xhr) => {
throw Error('Timeout not fired(success fired)');
},
error: (e, xhr) => {
throw Error('Timeout not fired(error fired');
},
timeout: (e, xhr) => {
done();
}
});
});//test
test('"option" to error', () => {
const client = new AjaxClient();
expect(function() {
client.ajax({
type: 'option',
url: `http://localhost:${serverPort}/test.html`,
contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
},
});
}).toThrow('option is not supported');
});//test
test('Illegal content-type to error', () => {
const client = new AjaxClient();
// do not thrown on fetch
// expect(function() {
// client.ajax({
// type: 'get',
// url: `http://localhost:${serverPort}/test.html`,
// contentType: 'application/json; charset = UTF8',
// dataType: 'text',
// });
// }).toThrow('Invalid content type');
});//test
// Content-Type is not needed for GET request
// test('No content-type to error', () => {
//
// const client = new AjaxClient();
//
// expect(function() {
// client.ajax({
// type: 'get',
// url: `http://localhost:${serverPort}/test.html`,
// dataType: 'text',
// });
// }).toThrow('Please specify contentType');
//
// });//test
test('forget url', () => {
const client = new AjaxClient();
expect(function() {
client.ajax({
type: 'get',
//contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
},
});
}).toThrow('Please specify url.');
});//test
});//describe
describe('postAsync()', () => {
test('default', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.postAsync({
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',//content-type of sending data
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(JSON.stringify(response)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
done();
},
error: (e, xhr) => {
},
timeout: (e, xhr) => {
}
});
});//test
test('No content-type to error while POST', () => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
expect(function() {
client.postAsync({
url: `http://localhost:${serverPort}/api`,
headers: {
'X-Original-Header1': 'header-value-1',//Additional Headers
'X-Original-Header2': 'header-value-2',
},
data: JSON.stringify(data),//text data
dataType: 'json',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(JSON.stringify(response)).toBe(JSON.stringify({ output: 'Hi,there! You say hello' }));
done();
},
error: (e, xhr) => {
},
timeout: (e, xhr) => {
}
});
}).toThrow('Please specify contentType');
});//test
});//describe
describe('getAsync()', () => {
test('default', (done) => {
const client = new AjaxClient();
//Data object to send
const data = {
message: "hello"
}
client.getAsync({
url: `http://localhost:${serverPort}/test.html`,
contentType: 'application/json',//content-type of sending data
dataType: 'text',//data type to parse when receiving response from server
timeoutMillis: 5000,//timeout milli-seconds
success: (response, xhr) => {
expect(response).toContain('Test HTML');
done();
},
error: (e, xhr) => {
console.log('Error occurred' + xhr.status);
},
timeout: (e, xhr) => {
console.error('Timeout occurred.' + e);
}
});
});
});
});
|
<gh_stars>0
module.exports = {
siteMetadata: {
title: `Emanuel Canova`,
description: `Where the code is rising up...`,
author: `@emanuelcanova`,
siteUrl: "https://emanuelcanova.com",
},
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-embedder`,
},
],
},
},
`gatsby-plugin-postcss`,
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
"gatsby-plugin-mdx",
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `specialContent`,
path: `${__dirname}/src/specialContent`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/blog`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`,
},
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: "UA-11406472-11",
},
},
],
}
|
import java.util.ArrayList;
/**
* Class to implement a model to predict the severity of COVID-19 symptoms in a patient.
*/
public class PredictCOVIDSymptoms {
public double predict(ArrayList<Double> data) {
// Implement a prediction model here.
return 0.0;
}
} |
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = input.nextInt();
System.out.println("Enter the second number: ");
int num2 = input.nextInt();
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
}
} |
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-N-IP/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-N-IP/1024+0+512-ST-1 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_within_trigrams_first_two_thirds_full --eval_function last_element_eval |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.