text
stringlengths 3
1.05M
|
|---|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "Pass.h"
/**
* This pass only makes sense when applied at the end of a redex optimization
* run. It does not work on its own when applied to a "random" apk.
* It relies on the fact that deleted classes/methods/fields are still
* around at the end of a run.
*/
class CheckBreadcrumbsPass : public Pass {
public:
CheckBreadcrumbsPass() : Pass("CheckBreadcrumbsPass") {}
void bind_config() override {
bind("fail", false, fail);
bind("fail_if_illegal_refs", false, fail_if_illegal_refs);
bind("reject_illegal_refs_root_store",
false,
reject_illegal_refs_root_store);
}
void run_pass(DexStoresVector&, ConfigFiles&, PassManager&) override;
private:
bool fail;
bool fail_if_illegal_refs;
bool reject_illegal_refs_root_store;
};
namespace {
using Fields = std::vector<const DexField*>;
using Methods = std::vector<const DexMethod*>;
using Instructions = std::vector<const IRInstruction*>;
using MethodInsns =
std::map<const DexMethod*, Instructions, dexmethods_comparator>;
} // namespace
class Breadcrumbs {
public:
explicit Breadcrumbs(const Scope& scope, DexStoresVector& stores, bool reject_illegal_refs_root_store);
void check_breadcrumbs();
void report_deleted_types(bool report_only, PassManager& mgr);
std::string get_methods_with_bad_refs();
void report_illegal_refs(bool fail_if_illegal_refs, PassManager& mgr);
bool has_illegal_access(const DexMethod* input_method);
private:
const Scope& m_scope;
std::unordered_set<const DexClass*> m_classes;
std::map<const DexType*, Fields, dextypes_comparator> m_bad_fields;
std::map<const DexType*, Methods, dextypes_comparator> m_bad_methods;
std::map<const DexType*, MethodInsns, dextypes_comparator> m_bad_type_insns;
std::map<const DexField*, MethodInsns, dexfields_comparator>
m_bad_field_insns;
std::map<const DexMethod*, MethodInsns, dexmethods_comparator>
m_bad_meth_insns;
std::map<const DexType*, Fields, dextypes_comparator> m_illegal_field;
std::map<const DexMethod*, Fields, dexmethods_comparator> m_bad_fields_refs;
MethodInsns m_illegal_type;
MethodInsns m_illegal_field_type;
MethodInsns m_illegal_field_cls;
MethodInsns m_illegal_method_call;
XStoreRefs m_xstores;
bool m_multiple_root_store_dexes;
bool m_reject_illegal_refs_root_store;
bool is_illegal_cross_store(const DexType* caller, const DexType* callee);
const DexType* check_type(const DexType* type);
const DexType* check_method(const DexMethodRef* method);
void bad_type(const DexType* type,
const DexMethod* method,
const IRInstruction* insn);
void check_fields();
void check_methods();
bool referenced_field_is_deleted(DexFieldRef* field);
bool referenced_method_is_deleted(DexMethodRef* method);
bool check_field_accessibility(const DexMethod* method,
const DexField* res_field);
bool check_method_accessibility(const DexMethod* method,
const DexMethod* res_called_method);
void check_type_opcode(const DexMethod* method, IRInstruction* insn);
void check_field_opcode(const DexMethod* method, IRInstruction* insn);
void check_method_opcode(const DexMethod* method, IRInstruction* insn);
void check_opcodes();
};
|
import os.path as op
import numpy as np
from ginipls.data.data_utils import load_data
from ginipls.__main__ import init_and_train_pls
from ginipls.models.ginipls import PLS, PLS_VARIANT
from ginipls.config import GLOBAL_LOGGER
logger = GLOBAL_LOGGER
def main():
X_train = [[2.0, 0.0, 7.0, 4, 5.2, 9.7], [3.0, 1.0, 5.0, 4, 1.0, .97], [0.0, 4.0, 5.0, 4, .1235, 2.58], [4.0, 0.0, 7.0, 4, 10, 4.78], [4.0, 1.0, 8.0, 4, 1, 5], [1.5, 1.3, 1.1, 4, 7, 6]]
y_train= [0, 0, 0, 1, 1, 1]
X_test = [[.8, 1.0, 3, 0.0, 7.0, 4], [1.3, 1.0, 5.0, 1.4, 1.7, 5], [4.0, 4, .1235, 1.2, 5.5, 3], [3.3, 0.0, 7.0, 1.0, 1.4, 6], [1.5, 0.0, 7.0, 1.3, 1.1, 0]]
y_test= [1, 0, 0, 1, 1]
from sklearn import datasets
from sklearn.model_selection import train_test_split
iris = datasets.load_iris()
#X_train, X_test, y_train, y_test = train_test_split(iris.data[50:], iris.target[50:], test_size=0.33, random_state=42) # classe{2,3}
data_path = 'data/processed'
trainfilename = op.join(data_path, 'doris0_CHI2_ATF-train.tsv')
testfilename = op.join(data_path, 'doris0_CHI2_ATF-test.tsv')
X_train, y_train, h, ids_train = load_data(data=trainfilename, output_col='category')
X_test, y_test, h, ids_test = load_data(data=testfilename, output_col='category')
pls_type = PLS_VARIANT.GINI
nu_min = 1
nu_max = 2
nu_step = 0.01
nu_range = [i*nu_step for i in range(int(nu_min/nu_step),int(nu_max/nu_step))]
n_components_min = 1
n_components_max = min(5,len(X_train[0])) # nb de caractéristiques
n_components_step = 1
n_components_range = range(n_components_min, n_components_max, n_components_step)
hyerparameters_selection_nfolds=10
clf = init_and_train_pls(X_train, y_train, pls_type, hyerparameters_selection_nfolds, nu_range, n_components_range, only_the_first_fold=False)
test_score = clf.score(X_test, y_test)
logger.info("test f1_score = %.3f" % (test_score))
if __name__ == "__main__":
main()
|
from .client import Client
from .server import Server
class Slient(Client, Server):
"""
Merges the methods of class:`.Client` & class:`.Server` to allow intercommunication
between two discord bots.
"""
def __init__(
self,
bot,
host="localhost",
base_port = 8654,
secret_key = None,
base_multicast = 20000,
instance = 0
):
self.client = Client(
port = base_port + instance,
multicast_port = base_multicast +1-instance,
host = host,
secret_key = secret_key)
self.server = Server(
bot = bot,
port = base_port+1-instance,
multicast_port = base_multicast + instance,
host = host,
secret_key = secret_key
)
for com in (self.server, self.client):
for method in dir(com):
if method.startswith('__') is False:
try:
setattr(self, method, getattr(com, method))
except:
...
|
/*
* Copyright 2018, University Corporation for Atmospheric Research
* See netcdf/COPYRIGHT file for copying and redistribution conditions.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef _WIN32
#include "XGetopt.h"
#endif
#include "zincludes.h"
#include "ncpathmgr.h"
#define DEBUG
#define DATANAME "data"
typedef enum Mapop {
MOP_NONE=0,
MOP_OBJDUMP=1,
MOP_CLEAR=2
} Mapop;
typedef enum OBJKIND {
OK_NONE=0,
OK_META=1,
OK_CHUNK=2
} OBJKIND;
static struct Mops {
Mapop mapop;
const char* opname;
} mapops[] = {
{MOP_NONE,"none"},
{MOP_OBJDUMP,"objdump"},
{MOP_CLEAR,"clear"},
{MOP_NONE,NULL}
};
static struct Type {
const char* typename;
nc_type nctype;
int typesize;
} types[] = {
{"ubyte",NC_UBYTE,1},
{"byte",NC_BYTE,1},
{"ushort",NC_USHORT,2},
{"short",NC_SHORT,2},
{"uint",NC_UINT,4},
{"int",NC_INT,4},
{"uint64",NC_UINT64,8},
{"int64",NC_INT64,8},
{"float",NC_FLOAT,4},
{"double",NC_DOUBLE,8},
{NULL,NC_NAT,0}
};
/* Command line options */
struct Dumpptions {
int debug;
Mapop mop;
char infile[4096];
NCZM_IMPL impl;
char* rootpath;
const struct Type* nctype;
} dumpoptions;
/* Forward */
static int objdump(void);
static NCZM_IMPL implfor(const char* path);
static void printcontent(size64_t len, const char* content, OBJKIND kind);
static int depthR(NCZMAP* map, char* key, NClist* stack);
static char* rootpathfor(const char* path);
static OBJKIND keykind(const char* key);
static void sortlist(NClist* l);
static const char* filenamefor(const char* f0);
#define NCCHECK(expr) nccheck((expr),__LINE__)
static void nccheck(int stat, int line)
{
if(stat) {
fprintf(stderr,"%d: %s\n",line,nc_strerror(stat));
fflush(stderr);
exit(1);
}
}
static void
zmapusage(void)
{
fprintf(stderr,"usage: zmapio [-t <type>][-d][-v][-x] <file>\n");
exit(1);
}
static Mapop
decodeop(const char* name)
{
struct Mops* p = mapops;
while(p->opname != NULL) {
if(strcasecmp(p->opname,name)==0) return p->mapop;
}
return MOP_NONE;
}
static const struct Type*
decodetype(const char* name)
{
struct Type* p = types;
for(;p->typename != NULL;p++) {
if(strcasecmp(p->typename,name)==0) return p;
}
return NULL;
}
int
main(int argc, char** argv)
{
int stat = NC_NOERR;
int c;
memset((void*)&dumpoptions,0,sizeof(dumpoptions));
while ((c = getopt(argc, argv, "dvx:t:")) != EOF) {
switch(c) {
case 'd':
dumpoptions.debug = 1;
break;
case 'v':
zmapusage();
goto done;
case 't':
dumpoptions.nctype = decodetype(optarg);
if(dumpoptions.nctype == NULL) zmapusage();
break;
case 'x':
dumpoptions.mop = decodeop(optarg);
if(dumpoptions.mop == MOP_NONE) zmapusage();
break;
case '?':
fprintf(stderr,"unknown option\n");
goto fail;
}
}
/* Default the kind */
if(dumpoptions.nctype == NULL) {
dumpoptions.nctype = &types[0];
fprintf(stderr,"Default type: %s\n",dumpoptions.nctype->typename);
}
/* get file argument */
argc -= optind;
argv += optind;
if (argc > 1) {
fprintf(stderr, "zmapio: only one input file argument permitted\n");
goto fail;
}
if (argc == 0) {
fprintf(stderr, "zmapio: no input file specified\n");
goto fail;
}
{
char* p = NCdeescape(argv[0]);
strcpy(dumpoptions.infile,filenamefor(p));
if(p) free(p);
}
if((dumpoptions.impl = implfor(dumpoptions.infile))== NCZM_UNDEF)
zmapusage();
if((dumpoptions.rootpath = rootpathfor(dumpoptions.infile))== NULL)
zmapusage();
switch (dumpoptions.mop) {
default:
fprintf(stderr,"Default action: objdump\n");
/* fall thru */
case MOP_OBJDUMP:
if((stat = objdump())) goto done;
break;
}
done:
/* Reclaim dumpoptions */
nullfree(dumpoptions.rootpath);
if(stat)
fprintf(stderr,"fail: %s\n",nc_strerror(stat));
return (stat ? 1 : 0);
fail:
stat = NC_EINVAL;
goto done;
}
static NCZM_IMPL
implfor(const char* path)
{
NCURI* uri = NULL;
const char* mode = NULL;
NClist* segments = nclistnew();
int i;
NCZM_IMPL impl = NCZM_UNDEF;
ncuriparse(path,&uri);
if(uri == NULL) goto done;
mode = ncurifragmentlookup(uri,"mode");
if(mode == NULL) goto done;
/* split on commas */
NCCHECK(nczm_split_delim(mode,',',segments));
for(i=0;i<nclistlength(segments);i++) {
const char* value = nclistget(segments,i);
if(strcmp(value,"nz4")==0) {impl = NCZM_NC4; goto done;}
if(strcmp(value,"nzf")==0) {impl = NCZM_FILE; goto done;}
if(strcmp(value,"s3")==0) {impl = NCZM_S3; goto done;}
}
done:
ncurifree(uri);
nclistfreeall(segments);
return impl;
}
static char*
rootpathfor(const char* path)
{
int stat = NC_NOERR;
NCURI* uri = NULL;
char* rootpath = NULL;
NClist* segments = nclistnew();
char* p = NULL;
ncuriparse(path,&uri);
if(uri == NULL) goto done;
switch (dumpoptions.impl) {
case NCZM_FILE:
case NCZM_NC4:
rootpath = strdup("/"); /*constant*/
break;
case NCZM_S3:
/* Split the path part */
if((stat = nczm_split(uri->path,segments))) goto done;
/* remove the bucket name */
p = (char*)nclistremove(segments,0);
nullfree(p); p = NULL;
/* Put it back together */
if((stat = nczm_join(segments,&rootpath))) goto done;
break;
default:
stat = NC_EINVAL;
goto done;
}
done:
nclistfreeall(segments); segments = NULL;
ncurifree(uri); uri = NULL;
if(stat)
{nullfree(rootpath); rootpath = NULL;}
return rootpath;
}
static int
objdump(void)
{
int stat = NC_NOERR;
NCZMAP* map = NULL;
NClist* matches = nclistnew();
NClist* stack = nclistnew();
char* obj = NULL;
char* content = NULL;
int depth;
if((stat=nczmap_open(dumpoptions.impl, dumpoptions.infile, NC_NOCLOBBER, 0, NULL, &map)))
goto done;
/* Depth first walk all the groups to get all keys */
obj = strdup("/");
if((stat = depthR(map,obj,stack))) goto done;
obj = NULL; /* its now in the stack */
if(dumpoptions.debug) {
int i;
fprintf(stderr,"stack:\n");
for(i=0;i<nclistlength(stack);i++)
fprintf(stderr,"[%d] %s\n",i,(char*)nclistget(stack,i));
}
for(depth=0;nclistlength(stack) > 0;depth++) {
size64_t len = 0;
OBJKIND kind = 0;
int hascontent = 0;
obj = nclistremove(stack,0); /* zero pos is always top of stack */
/* Now print info for this obj key */
switch (stat=nczmap_len(map,obj,&len)) {
case NC_NOERR: hascontent = 1; break;
case NC_EEMPTY: /* fall thru */ /* this is not a content bearing key */
case NC_EACCESS: hascontent = 0; len = 0; stat = NC_NOERR; break;
default: goto done;
}
if(!hascontent) goto next; /* ignore it */
if(len > 0) {
content = malloc(len+1);
if((stat=nczmap_read(map,obj,0,len,content))) goto done;
content[len] = '\0';
} else {
content = NULL;
}
if(hascontent) {
if(len > 0) {
assert(content != NULL);
kind = keykind(obj);
if(kind == OK_CHUNK) len /= dumpoptions.nctype->typesize;
printf("[%d] %s : (%llu)",depth,obj,len);
if(kind == OK_CHUNK) printf(" (%s)",dumpoptions.nctype->typename);
printf(" |");
printcontent(len,content,kind);
printf("|\n");
} else {
printf("[%d] %s : (%llu) ||\n",depth,obj,len);
}
} else {
printf("[%d] %s\n",depth,obj);
}
nullfree(content); content = NULL;
next:
nullfree(obj); obj = NULL;
}
done:
nullfree(obj);
nullfree(content);
nczmap_close(map,0);
nclistfreeall(matches);
nclistfreeall(stack);
return stat;
}
/* Depth first walk all the groups to get all keys */
static int
depthR(NCZMAP* map, char* key, NClist* stack)
{
int stat = NC_NOERR;
NClist* nextlevel = nclistnew();
nclistpush(stack,key);
if((stat=nczmap_search(map,key,nextlevel))) goto done;
/* Sort nextlevel */
sortlist(nextlevel);
/* Push new names onto the stack and recurse */
while(nclistlength(nextlevel) > 0) {
char* subkey = nclistremove(nextlevel,0);
if((stat = depthR(map,subkey,stack))) goto done;
}
done:
nclistfreeall(nextlevel);
return stat;
}
static char hex[16] = "0123456789abcdef";
static void
printcontent(size64_t len, const char* content, OBJKIND kind)
{
size64_t i;
unsigned int c0,c1;
for(i=0;i<len;i++) {
/* If kind is chunk, then len is # of values, not # of bytes */
switch(kind) {
case OK_CHUNK:
if(i > 0) printf(", ");
switch(dumpoptions.nctype->nctype) {
case NC_BYTE: printf("%d",((char*)content)[i]); break;
case NC_SHORT: printf("%d",((short*)content)[i]); break;
case NC_INT: printf("%d",((int*)content)[i]); break;
case NC_INT64: printf("%lld",((long long*)content)[i]); break;
case NC_UBYTE: printf("%u",((unsigned char*)content)[i]); break;
case NC_USHORT: printf("%u",((unsigned short*)content)[i]); break;
case NC_UINT: printf("%u",((unsigned int*)content)[i]); break;
case NC_UINT64: printf("%llu",((unsigned long long*)content)[i]); break;
case NC_FLOAT: printf("%f",((float*)content)[i]); break;
case NC_DOUBLE: printf("%lf",((double*)content)[i]); break;
default: abort();
}
break;
case OK_META:
printf("%c",content[i]);
break;
default:
c1 = (unsigned char)(content[i]);
c0 = c1 & 0xf;
c1 = (c1 >> 4);
c0 = hex[c0];
c1 = hex[c1];
printf("%c%c",(char)c1,(char)c0);
}
}
}
static char chunkchars[] = ".0123456789";
static OBJKIND
keykind(const char* key)
{
OBJKIND kind = OK_NONE;
char* suffix = NULL;
if(nczm_divide_at(key,-1,NULL,&suffix) == NC_NOERR) {
if(suffix) {
if(suffix[0] != '/')
kind = OK_NONE;
else if(suffix[1] == '.')
kind = OK_META;
else {
char* p = suffix+1;
for(;*p;p++) {
if(strchr(chunkchars,*p) == NULL) break;
}
kind = OK_CHUNK;
}
}
}
nullfree(suffix);
return kind;
}
/* bubble sort a list of strings */
static void
sortlist(NClist* l)
{
size_t i, switched;
if(nclistlength(l) <= 1) return;
do {
switched = 0;
for(i=0;i<nclistlength(l)-1;i++) {
char* ith = nclistget(l,i);
char* ith1 = nclistget(l,i+1);
if(strcmp(ith,ith1) > 0) {
nclistset(l,i,ith1);
nclistset(l,i+1,ith);
switched = 1;
}
}
} while(switched);
#if 0
for(i=0;i<nclistlength(l);i++)
fprintf(stderr,"sorted: [%d] %s\n",i,(const char*)nclistget(l,i));
#endif
}
static const char* urlexts[] = {"nzf", "nz4", NULL};
static const char*
filenamefor(const char* f0)
{
static char result[4096];
const char** extp;
char* p;
strcpy(result,f0); /* default */
if(nc__testurl(f0,NULL)) goto done;
/* Not a URL */
p = strrchr(f0,'.'); /* look at the extension, if any */
if(p == NULL) goto done; /* No extension */
p++;
for(extp=urlexts;*extp;extp++) {
if(strcmp(p,*extp)==0) break;
}
if(*extp == NULL) goto done; /* not found */
/* Assemble the url */
strcpy(result,"file://");
strcat(result,f0); /* core path */
strcat(result,"#mode=nczarr,");
strcat(result,*extp);
done:
return result;
}
|
/*
* FreeRTOS V202112.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/* Standard includes. */
#include <stdlib.h>
/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"
/* Application includes. */
#include "tcp.h"
/* Misc constants. */
#define tcpPOLL_DELAY ( ( TickType_t ) 12 / portTICK_PERIOD_MS )
#define tcpCONNECTION_DELAY ( ( TickType_t ) 8 / portTICK_PERIOD_MS )
/*-----------------------------------------------------------*/
/*
* This task initialises the hardware then processes one TCP connection at a
* time. When an HTTP client connects we just simply send a single page then
* disconnect - reset the socket data and wait for the next connection.
*/
void vHTTPServerTask( void *pvParameters )
{
/* Reset the network hardware. */
vTCPHardReset();
/* Loop, processing connections are they arrive. */
for( ;; )
{
/* Initialise the TCP interface.
The current minimal implementation does not check for buffer overflows
in the WIZnet hardware, so simply resets all the buffers for each
connection - and only processes one connection at a time. */
if( lTCPSoftReset() )
{
/* Create the socket that is going to accept incoming connections. */
if( lTCPCreateSocket() )
{
/* Wait for a connection. */
vTCPListen();
/* Process connections as they arrive. This function will only
return once the connection has been closed. */
lProcessConnection();
}
}
/* If we get here then the connection completed or failed. Wait a
while then try or start again. */
vTaskDelay( tcpCONNECTION_DELAY );
}
}
|
import React, { PureComponent } from 'react';
import Icon from '../Icon';
import { Popover, Badge, Avatar } from 'antd';
import { router } from 'dva';
import cx from 'classnames';
import './style/index.less';
import logoImg from 'assets/images/logo.svg';
import SearchBox from './SearchBox';
const { Link } = router;
/**
* 其本本局头部区域
*/
class NavBar extends PureComponent {
state = {
openSearchBox: false
};
static defaultProps = {
fixed: true,
theme: '' //'bg-dark',
};
toggleFullScreen() {
if (
!document.fullscreenElement &&
!document.mozFullScreenElement &&
!document.webkitFullscreenElement &&
!document.msFullscreenElement
) {
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(
Element.ALLOW_KEYBOARD_INPUT
);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
onCloseSearchBox = () => {
this.setState({
openSearchBox: false
});
};
onOpenSearchBox = () => {
this.setState({
openSearchBox: true
});
};
render() {
const { openSearchBox } = this.state;
const {
fixed,
theme,
onCollapseLeftSide,
collapsed,
onExpandTopBar,
toggleSidebarHeader,
user,
isMobile
} = this.props;
const classnames = cx('navbar', {
'navbar-fixed-top': !!fixed,
'navbar-sm': isMobile ? true : collapsed,
['bg-' + theme]: !!theme
});
return (
<header className={classnames}>
<div className="navbar-branding">
<Link className="navbar-brand" to="/">
<img src={logoImg} alt="logo" />
<b>活动管理</b>
</Link>
<span className="toggle_sidemenu_l" onClick={onCollapseLeftSide}>
<Icon type="lines" />
</span>
</div>
<ul className="nav navbar-nav navbar-left clearfix">
{collapsed || isMobile ? null : (
<li>
<a className="sidebar-menu-toggle" onClick={toggleSidebarHeader}>
<Icon type="ruby" />
</a>
</li>
)}
<li>
<a onClick={onExpandTopBar}>
<Icon type="wand" />
</a>
</li>
{isMobile ? (
<li className="mini-search" onClick={this.onOpenSearchBox}>
<a>
<Icon type="search" antd />
</a>
</li>
) : (
<li onClick={this.toggleFullScreen}>
<a className="request-fullscreen">
<Icon type="screen-full" />
</a>
</li>
)}
</ul>
{isMobile ? null : (
<form className="navbar-form navbar-search clearfix">
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="全文检索"
onClick={this.onOpenSearchBox}
/>
</div>
</form>
)}
<ul className="nav navbar-nav navbar-right clearfix">
<li className="dropdown">
<Popover
placement="bottomRight"
title={'通知'}
overlayClassName={cx('navbar-popup', { [theme]: !!theme })}
content={''}
trigger="click"
>
<a className="dropdown-toggle">
<Icon type="radio-tower" />
</a>
</Popover>
</li>
<li className="dropdown">
<Popover
placement="bottomRight"
title={`WELCOME ${user.name}`}
overlayClassName={cx('navbar-popup', { [theme]: !!theme })}
content={<UserDropDown />}
trigger="click"
>
<a className="dropdown-toggle">
<Badge dot>
<Avatar src={require('assets/images/avatar.jpg')}>
{user.userName}
</Avatar>
</Badge>
</a>
</Popover>
</li>
</ul>
<SearchBox visible={openSearchBox} onClose={this.onCloseSearchBox} />
</header>
);
}
}
const UserDropDown = props => (
<ul className="dropdown-menu list-group dropdown-persist">
<li className="list-group-item">
<a className="animated animated-short fadeInUp">
<Icon type="mail" /> 信息
<Badge count={5} className="label" />
</a>
</li>
<li className="list-group-item">
<a className="animated animated-short fadeInUp">
<Icon type="users" /> 好友
<Badge count={6} className="label" />
</a>
</li>
<li className="list-group-item">
<a className="animated animated-short fadeInUp">
<Icon type="gear" /> 帐户设置
</a>
</li>
<li className="list-group-item">
<a className="animated animated-short fadeInUp">
<Icon type="ring" /> 通知
</a>
</li>
<li className="list-group-item dropdown-footer">
<Link to="/sign/login">
<Icon type="poweroff" /> 退出
</Link>
</li>
</ul>
);
export default NavBar;
|
router = require("@system.router")
export default {
data: {
title: '热门推荐',
increased: true,
opacity: 0.1,
msgbox_style: {
'display': 'none'
},
msgbox_style1: {
'display': 'none'
},
messageTitle: "口袋故事",
messageSubtitle: "确定下此应用?",
json:[{
name:'口袋故事1',
icon:'image/kdgs.bin',
status:'0',
price:'2',
id:'123456',
},{
name:'国学诗词2',
icon:'image/gxsc.bin',
status:'0',
price:'2',
id:'123457',
},{
name:'生活百科3',
icon:'image/shbk.bin',
status:'1',
price:'',
id:'123458',
}],
list: [{
name: '',
icon: '',
status: '', //状态信息0:未购买并且应用是付费的 1:免费
price: '', //应用价格
id:'' //应用id
}, {
name: '',
icon: '',
status: '',
price: '',
id:''
}, {
name: '',
icon: '',
status: '',
price: '',
id:''
}, {
name: '',
icon: '',
status: '',
price: '',
id:''
}, {
name: '',
icon: '',
status: '',
price: '',
id:''
}],
isShow: [{
'display': 'show'
}, {
'display': 'none'
}, {
'display': 'none'
}, {
'display': 'none'
}, {
'display': 'none'
}],
},
onInit: function () {
for(var i=0;i<this.json.length;i++){
this.isShow[i].display='show'
this.json[i].name=this.list[i].name
this.json[i].icon=this.list[i].icon
this.json[i].status=this.list[i].status
this.json[i].price=this.list[i].price
this.json[i].id=this.list[i].id
}
// this.messageTitle=this.todolist.length
},
onReady: function () {
print("==========onReady==========")
},
onShow: function () {
print("==========onShow==========")
},
onHide: function () {
print("==========onHide==========")
},
onDestroy: function () {
print("==========onDestroy==========")
},
onclick: function () {
print("==========onInit==========")
print("=====onclick=====");
},
onlongpress: function () {
print("=====longpress=====");
},
onButtonPress: function () {
print("=====onButtonPress=====");
},
onButtonLongPress: function () {
print("=====onButtonLongPress=====");
},
onPageRedirect: function (obj, x, y) {
print("==========onclick==========")
print(obj.attributes.url)
router.push({
path: obj.attributes.url
})
},
onButtonRelease: function () {
print("=====onButtonRelease=====");
},
onButtonClick: function () {
print("=====onButtonClick=====");
print(this.$page)
show();
},
onEnterclick: function() {
this.hideMsgBox();
this.msgbox_style1['display'] = 'show';
},
onCancleclick: function() {
this.hideMsgBox();
},
onCancleclick1: function() {
this.msgbox_style1['display'] = 'none';
},
showMsgBox: function(obj) {
this.messageTitle=obj.attributes.title
this.msgbox_style['display'] = 'show'
// for(var i=0;i<this.todolist.length ){}
},
hideMsgBox: function() {
this.msgbox_style['display'] = 'none';
},
onReturn: function () {
print("=====onReturn=====");
router.push({
path: "evue-dock",
params: {
a: 1,
b: 2
}
})
}
}
|
// @flow
import { StyleSheet } from 'react-native';
import { viewportWidth, viewportHeight } from '../../Themes/';
export default StyleSheet.create({
container: {
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
width: viewportWidth(100),
height: viewportHeight(100),
},
scrollView: {
paddingHorizontal: 5,
width: viewportWidth(100),
},
infoContainer: {
flexDirection: 'column',
justifyContent: 'flex-start',
padding: 30,
width: viewportWidth(100),
},
infoTop: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'flex-start',
},
infoTopImage: {
width: viewportWidth(30),
height: viewportWidth(30),
borderRadius: viewportWidth(30) / 2,
},
infoTopLikeWrapper: {
height: viewportWidth(30),
marginLeft: 'auto',
// marginTop: 30,
marginRight: 30,
flexDirection: 'row',
alignItems: 'center',
},
infoTopLike: {
},
infoName: {
flexDirection: 'row',
marginTop: 15,
},
infoNameText: {
fontSize: 20,
},
infoDetail: {
flexDirection: 'row',
flexWrap: 'wrap',
marginTop: 10,
},
infoDetailItem: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
marginRight: 10,
marginBottom: 5,
},
infoDetailItemIcon: {
marginRight: 2,
},
});
|
#pragma once
#include "YarnSimNetHeter.h"
#include "Saver.h"
#include "Random.h"
#include "indicators/progress_bar.hpp"
#include "boost/format.hpp"
#include <cmath>
using namespace indicators;
void train_heter_full(std::string save_path, std::string data_path,
int epoch, int iter, int batch, int sample, int steps,
bool all_steps, bool random, bool wordy) {
// epoch: the number of training epoches
// iter:
// 1.if not random, the number of bacthes in each iteration
// (save in variable iteration) (see all training data)
// 2. if random, use the give iter as iteration.
// batch: the number of samples in each batch
// sample: the number of steps in each sample
// steps : the number of simulation steps in traing data
//torch::autograd::DetectAnomalyGuard detect_anomaly;
// file in which saves training result
H5File file{ save_path, H5F_ACC_TRUNC };
int samples{ steps / sample }; // the number of sample of training dataset
int iteration{ 0 }; // the number of training iteration
if (all_steps)
iteration = random ? iter : (samples / batch);
else
iteration = iter;
int train_steps{ epoch * iteration }; // the number of training steps (backprop steps)
RandInt SeleSample{ 0, samples - 1 }; // For Randomly Select Sample
auto SizePhy = cloth_property_loader_heter(data_path); // Read Cloth Size and Cloth Physical Properties
H5ClothSize size{ SizePhy.first };
H5PhysicalHeterYarn phy{ SizePhy.second };
std::vector<std::pair<int, int>> handles{}; // Handle vector
handles.push_back(std::make_pair(0, 0));
handles.push_back(std::make_pair(16, 0)); // Alter this handle when changing cloth size
Tensor h = torch::tensor({ 0.001 }, opts); // Simulation Time Step Size: sec
// Initialization Parameters
// Parameters for training
double init_rho1{ 0.00225 };
double init_rho2{ 0.00245 };
double init_Y1{ 335000.0 };
double init_Y2{ 145000.0 };
double init_B1{ 0.000125 };
double init_B2{ 0.0001 };
double init_S{ 600 };
double init_mu{0.7};
// Gt Parameters
//double init_rho1{ 0.002 };
//double init_rho2{ 0.0025 };
//double init_Y1{ 500000.0 };
//double init_Y2{ 170000.0 };
//double init_B1{ 0.00014 };
//double init_B2{ 0.00011 };
//double init_S{ 1000 };
//double init_mu{ 0.5 };
// Parameters' range
auto rho1_range = std::make_pair(0.003, 0.001);
auto rho2_range = std::make_pair(0.003, 0.001);
auto Y1_range = std::make_pair(800000.0, 0.0);
auto Y2_range = std::make_pair(300000.0, 0.0);
auto B1_range = std::make_pair(0.00018, 0.00005);
auto B2_range = std::make_pair(0.00018, 0.00005);
auto S_range = std::make_pair(1200.0, 0.0);
auto mu_range = std::make_pair(1.0, 0.0);
phy.rho1 = invert_constraint_para(init_rho1, rho1_range.first, rho1_range.second);
phy.rho2 = invert_constraint_para(init_rho2, rho2_range.first, rho2_range.second);
phy.Y1 = invert_constraint_para(init_Y1, Y1_range.first, Y1_range.second);
phy.Y2 = invert_constraint_para(init_Y2, Y2_range.first, Y2_range.second);
phy.B1 = invert_constraint_para(init_B1, B1_range.first, B1_range.second);
phy.B2 = invert_constraint_para(init_B2, B2_range.first, B2_range.second);
phy.S = invert_constraint_para(init_S, S_range.first, S_range.second);
phy.mu = invert_constraint_para(init_mu, mu_range.first, mu_range.second);
//phy.rho1 = init_rho1;
//phy.rho2 = init_rho2;
//phy.Y1 = init_Y1;
//phy.Y2 = init_Y2;
//phy.B1 = init_B1;
//phy.B2 = init_B2;
//phy.S = init_S;
//phy.mu = init_mu;
std::cout << "Epoch: " << std::to_string(epoch) << std::endl;
std::cout << "Iteration: " << std::to_string(iteration) << std::endl;
std::cout << "Batch Size: " << std::to_string(batch) << std::endl;
std::cout << "Sample Size: " << std::to_string(sample - 1) << std::endl;
std::cout << "Random Sampling: " << (random ? "True" : "False") << std::endl;
YarnSimNetHeter simnet(size, phy, handles, h, rho1_range, rho2_range, Y1_range, Y2_range, B1_range, B2_range, S_range, mu_range); // Construct Net
torch::optim::OptimizerParamGroup rho1({ simnet.named_parameters()["rho_1"] });
torch::optim::OptimizerParamGroup rho2({ simnet.named_parameters()["rho_2"] });
torch::optim::OptimizerParamGroup Y1({ simnet.named_parameters()["Y_1"] });
torch::optim::OptimizerParamGroup Y2({ simnet.named_parameters()["Y_2"] });
torch::optim::OptimizerParamGroup B1({ simnet.named_parameters()["B_1"] });
torch::optim::OptimizerParamGroup B2({ simnet.named_parameters()["B_2"] });
torch::optim::OptimizerParamGroup S({ simnet.named_parameters()["S"] });
torch::optim::OptimizerParamGroup mu({ simnet.named_parameters()["mu"] });
torch::optim::SGD cloth_opt({ rho1, rho2, Y1, Y2, B1, B2, S, mu}, torch::optim::SGDOptions(1e5));
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[0].options()).lr(0.1); // lr rho1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[1].options()).lr(1e-4); // lr rho2
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[2].options()).lr(12e16); // lr Y1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[3].options()).lr(7e16); // lr Y2
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[4].options()).lr(0.219); // lr B1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[5].options()).lr(0.145); // lr B2
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[6].options()).lr(19e10); // lr S
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[7].options()).lr(14e9); // lr mu
for (int epc = 0; epc < epoch; ++epc) {
std::cout << "Epoch: " << epc << std::endl;
for (int i = 0; i < iteration; ++i) {
// Update parameters each batch
std::cout << "Batch: " << i << std::endl;
int success_steps{ 0 }; // Success simulation steps
int curr_step{ epc * iteration + i }; // cuttent step in all steps
Tensor loss{ torch::zeros(1, opts) }; // Create loss
//Tensor loss_no_uv { torch::zeros(1, opts) }; // Loss function exclude uv coordinates for testing
simnet.reset_cloth();
cloth_opt.zero_grad();
for (int bch = 0; bch < batch; ++bch) {
std::cout << "Sample: " << std::to_string(bch + 1) << std::endl;
int sample_choice{ 0 };
if (random)
sample_choice = SeleSample(); // Generate a random number
else
sample_choice = i * batch + bch; // Sequential retrieve
ClothState clothStateSample = data_loader(data_path, sample_choice * sample, sample_choice * sample + sample, opts); // Load training batch
ClothState clothStateCurrt{
clothStateSample.LPos[0],
clothStateSample.LPosFix[0],
clothStateSample.LVel[0],
clothStateSample.EPos[0],
clothStateSample.EPosBar[0],
clothStateSample.EVel[0] }; // Cloth Initial State in this Batch. Later replaced by predicted cloth state
ProgressBar bar{
option::BarWidth{50},
option::Start{"["},
option::Fill{"="},
option::Lead{">"},
option::Remainder{" "},
option::End{"]"},
option::PostfixText{"Sample step 0"},
option::ForegroundColor{Color::white},
option::FontStyles{std::vector<FontStyle>{FontStyle::bold}} };
float bar_step = 100.0f / (sample - 1);
float bar_progress = 0.0f;
for (int smp = 0; smp < sample - 1; ++smp) {
std::string sample_step{ "Sample step: " + std::to_string(smp + 1) };
bool is_success{ false }; // Flag indicating if forward simulation success
bar_progress += bar_step;
bar.set_option(option::PostfixText{ sample_step });
bar.set_progress(bar_progress);
if (smp == 0 || all_steps)
clothStateCurrt = simnet.forward(clothStateCurrt, is_success); // Initial sample: set cloth state
else
clothStateCurrt = simnet.forward(is_success); // Later samples: directly moving on
if (!is_success) break; // Break out from the loop if NaN detected in simulating
++success_steps;
Tensor GT_LPos{ clothStateSample.LPos[smp + 1] }; // Ground Truth Lagrangian Position
Tensor GT_EPos{ clothStateSample.EPos[smp + 1] }; // Ground Truth Euler Position
Tensor Dis_L{ clothStateCurrt.LPos - GT_LPos }; // Distance Lagrangian Position
Tensor Dis_E{ clothStateCurrt.EPos - GT_EPos }; // Distance Euler Position
Tensor L2_Dis_L{ torch::bmm(Dis_L.transpose(2,1), Dis_L) }; // L2 Distance of nodes' Lagrangian Position
Tensor L2_Dis_E{ torch::bmm(Dis_E.transpose(2,1), Dis_E) }; // L2 Distance of nodes' Euler Position
Tensor PosLoss{ torch::mean(L2_Dis_L) + torch::mean(L2_Dis_E) }; // Mean of L2 Position distance at one step
loss = loss + PosLoss;
//loss_no_uv = loss_no_uv + PosLoss_no_uv;
}
}
loss = loss / ((success_steps - 1) > 0 ? (success_steps - 1) : 1); // Mean of loss of one sample (sample-1 losses)
//loss_no_uv = loss_no_uv / ((success_steps - 1) > 0 ? (success_steps - 1) : 1);
//std::cout << "Loss: " << loss.item<double>() << std::endl;
//std::cout << "Loss no uv: " << loss_no_uv.item<double>() << std::endl;
loss.backward(); // compute grad of register paremeters
if (wordy) {
std::cout << "\nrho1 grad" << simnet.rho1.grad() << std::endl;
std::cout << "rho2 grad" << simnet.rho2.grad() << std::endl;
std::cout << "Y1 grad" << simnet.Y1.grad() << std::endl;
std::cout << "Y2 grad" << simnet.Y2.grad() << std::endl;
std::cout << "B1 grad" << simnet.B1.grad() << std::endl;
std::cout << "B2 grad" << simnet.B2.grad() << std::endl;
std::cout << "S grad" << simnet.S.grad() << std::endl;
std::cout << "mu grad" << simnet.mu.grad() << std::endl;
}
bool valid_step{ true };
for (const auto& para : simnet.parameters())
if (torch::isnan(para.grad()).item<bool>() ||
torch::isinf(para.grad()).item<bool>()) {
valid_step = false;
break;
}
if (valid_step)
cloth_opt.step(); // Excute Optim
auto rho1_constraint = constraint_para(simnet.rho1, rho1_range.first, rho1_range.second);
auto rho2_constraint = constraint_para(simnet.rho2, rho2_range.first, rho2_range.second);
auto Y1_constraint = constraint_para(simnet.Y1, Y1_range.first, Y1_range.second);
auto Y2_constraint = constraint_para(simnet.Y2, Y2_range.first, Y2_range.second);
auto B1_constraint = constraint_para(simnet.B1, B1_range.first, B1_range.second);
auto B2_constraint = constraint_para(simnet.B2, B2_range.first, B2_range.second);
auto S_constraint = constraint_para(simnet.S, S_range.first, S_range.second);
auto mu_constraint = constraint_para(simnet.mu, mu_range.first, mu_range.second);
if (wordy) {
std::cout << "\nOptimized rho1: " << rho1_constraint.item<double>() << std::endl;
std::cout << "Optimized rho2: " << rho2_constraint.item<double>() << std::endl;
std::cout << "Optimized Y1: " << Y1_constraint.item<double>() << std::endl;
std::cout << "Optimized Y2: " << Y2_constraint.item<double>() << std::endl;
std::cout << "Optimized B1: " << B1_constraint.item<double>() << std::endl;
std::cout << "Optimized B2: " << B2_constraint.item<double>() << std::endl;
std::cout << "Optimized S: " << S_constraint.item<double>() << std::endl;
std::cout << "Optimized mu: " << mu_constraint.item<double>() << std::endl;
}
std::cout << "Loss: " << loss.item<double>() << std::endl;
std::map<std::string, Tensor> constrained_para;
constrained_para.insert({ "rho1", rho1_constraint });
constrained_para.insert({ "rho2", rho2_constraint });
constrained_para.insert({ "Y1", Y1_constraint });
constrained_para.insert({ "Y2", Y2_constraint });
constrained_para.insert({ "B1", B1_constraint });
constrained_para.insert({ "B2", B2_constraint });
constrained_para.insert({ "S", S_constraint });
constrained_para.insert({ "mu", mu_constraint });
SaveTrainProc(file, curr_step, train_steps, loss, constrained_para); // save loss and parameters
}
}
file.close();
}
void train_heter_few(std::string save_path, std::string data_path,
int epoch, int iter, int batch, int sample, int steps,
bool all_steps, bool random, bool wordy) {
// epoch: the number of training epoches
// iter:
// 1.if not random, the number of bacthes in each iteration
// (save in variable iteration) (see all training data)
// 2. if random, use the give iter as iteration.
// batch: the number of samples in each batch
// sample: the number of steps in each sample
// steps : the number of simulation steps in traing data
// file in which saves training result
H5File file{ save_path, H5F_ACC_TRUNC };
int samples{ steps / sample }; // the number of sample of training dataset
int iteration{ 0 }; // the number of training iteration
if (all_steps)
iteration = random ? iter : (samples / batch);
else
iteration = iter;
int train_steps{ epoch * iteration }; // the number of training steps (backprop steps)
RandInt SeleSample{ 0, samples - 1 }; // For Randomly Select Sample
auto SizePhy = cloth_property_loader_heter(data_path); // Read Cloth Size and Cloth Physical Properties
H5ClothSize size{ SizePhy.first };
H5PhysicalHeterYarn phy{ SizePhy.second };
std::vector<std::pair<int, int>> handles{}; // Handle vector
handles.push_back(std::make_pair(0, 0));
// *** Change Handle below when changing cloth size ***
// Cloth Size 5 x 5: std::make_pair(4, 0)
// Cloth Size 10 x 10: std::make_pair(9, 0)
// Cloth Size 17 x 17: std::make_pair(16, 0)
// Cloth Size 17 x 17: std::make_pair(24, 0)
handles.push_back(std::make_pair(4, 0));
Tensor h = torch::tensor({ 0.001 }, opts); // Simulation Time Step Size: sec
// Initialization Parameters
// Parameters for training
double init_rho1{ 0.00225 }; // 0.002
double init_rho2{ 0.00245 }; // 0.0025
double init_Y1{ 335000.0 }; // 500000
double init_Y2{ 145000.0 }; // 170000
double init_B1{ 0.000125 }; // 0.00014
double init_B2{ 0.0001 }; // 0.00011
// GTs
//double init_rho1{ phy.rho1 }; // 0.002
//double init_rho2{ phy.rho2 }; // 0.0025
//double init_Y1{ phy.Y1 }; // 500000
//double init_Y2{ phy.Y2 }; // 170000
//double init_B1{ phy.B1 }; // 0.00014
//double init_B2{ phy.B2 }; // 0.00011
auto rho1_range = std::make_pair(0.003, 0.001);
auto rho2_range = std::make_pair(0.003, 0.001);
auto Y1_range = std::make_pair(800000.0, 0.0);
auto Y2_range = std::make_pair(300000.0, 0.0);
auto B1_range = std::make_pair(0.00018, 0.00005);
auto B2_range = std::make_pair(0.00018, 0.00005);
phy.rho1 = invert_constraint_para(init_rho1, rho1_range.first, rho1_range.second);
phy.rho2 = invert_constraint_para(init_rho2, rho2_range.first, rho2_range.second);
phy.Y1 = invert_constraint_para(init_Y1, Y1_range.first, Y1_range.second);
phy.Y2 = invert_constraint_para(init_Y2, Y2_range.first, Y2_range.second);
phy.B1 = invert_constraint_para(init_B1, B1_range.first, B1_range.second);
phy.B2 = invert_constraint_para(init_B2, B2_range.first, B2_range.second);
std::cout << "Epoch: " << std::to_string(epoch) << std::endl;
std::cout << "Iteration: " << std::to_string(iteration) << std::endl;
std::cout << "Batch Size: " << std::to_string(batch) << std::endl;
std::cout << "Sample Size: " << std::to_string(sample - 1) << std::endl;
std::cout << "Random Sampling: " << (random ? "True" : "False") << std::endl;
YarnSimNetHeterFew simnet(size, phy, handles, h, rho1_range, rho2_range,
Y1_range, Y2_range, B1_range, B2_range); // Construct Net Train
torch::optim::OptimizerParamGroup rho1({ simnet.named_parameters()["rho_1"] });
torch::optim::OptimizerParamGroup rho2({ simnet.named_parameters()["rho_2"] });
torch::optim::OptimizerParamGroup Y1({ simnet.named_parameters()["Y_1"] });
torch::optim::OptimizerParamGroup Y2({ simnet.named_parameters()["Y_2"] });
torch::optim::OptimizerParamGroup B1({ simnet.named_parameters()["B_1"] });
torch::optim::OptimizerParamGroup B2({ simnet.named_parameters()["B_2"] });
torch::optim::SGD cloth_opt({ rho1, rho2, Y1, Y2, B1, B2 }, torch::optim::SGDOptions(1e5));
// ***Altering Parameters' learning rate here***
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[0].options()).lr(38e5); // lr rho1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[1].options()).lr(13e5); // lr rho2
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[2].options()).lr(11e6); // lr Y1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[3].options()).lr(18e6); // lr Y2
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[4].options()).lr(5e8); // lr B1
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[5].options()).lr(2e8); // lr B2
for (int epc = 0; epc < epoch; ++epc) {
std::cout << "Epoch: " << epc << std::endl;
for (int i = 0; i < iteration; ++i) {
// Update parameters each batch
std::cout << "Batch: " << i << std::endl;
int success_steps{ 0 }; // Success simulation steps
int curr_step{ epc * iteration + i }; // cuttent step in all steps
Tensor loss{ torch::zeros(1, opts) }; // Create loss
simnet.reset_cloth();
cloth_opt.zero_grad();
for (int bch = 0; bch < batch; ++bch) {
std::cout << "Sample: " << std::to_string(bch + 1) << std::endl;
int sample_choice{ 0 };
if (random)
sample_choice = SeleSample(); // Generate a random number
else
sample_choice = i * batch + bch; // Sequential retrieve
ClothState clothStateSample = data_loader(data_path, sample_choice * sample, sample_choice * sample + sample, opts); // Load training batch
ClothState clothStateCurrt{
clothStateSample.LPos[0],
clothStateSample.LPosFix[0],
clothStateSample.LVel[0],
clothStateSample.EPos[0],
clothStateSample.EPosBar[0],
clothStateSample.EVel[0] }; // Cloth Initial State in this Batch. Later replaced by predicted cloth state
ProgressBar bar{
option::BarWidth{50},
option::Start{"["},
option::Fill{"="},
option::Lead{">"},
option::Remainder{" "},
option::End{"]"},
option::PostfixText{"Sample step 0"},
option::ForegroundColor{Color::white},
option::FontStyles{std::vector<FontStyle>{FontStyle::bold}} };
float bar_step = 100.0f / (sample - 1);
float bar_progress = 0.0f;
for (int smp = 0; smp < sample - 1; ++smp) {
std::string sample_step{ "Sample step: " + std::to_string(smp + 1) };
bool is_success{ false }; // Flag indicating if forward simulation success
bar_progress += bar_step;
bar.set_option(option::PostfixText{ sample_step });
bar.set_progress(bar_progress);
if (smp == 0 || all_steps)
clothStateCurrt = simnet.forward(clothStateCurrt, is_success); // Initial sample: set cloth state
else
clothStateCurrt = simnet.forward(is_success); // Later samples: directly moving on
if (!is_success) break; // Break out from the loop if NaN detected in simulating
++success_steps;
Tensor GT_LPos{ clothStateSample.LPos[smp + 1] }; // Ground Truth Lagrangian Position
Tensor GT_EPos{ clothStateSample.EPos[smp + 1] }; // Ground Truth Euler Position
Tensor Dis_L{ clothStateCurrt.LPos - GT_LPos }; // Distance Lagrangian Position
Tensor Dis_E{ clothStateCurrt.EPos - GT_EPos }; // Distance Euler Position
Tensor L2_Dis_L{ torch::bmm(Dis_L.transpose(2,1), Dis_L) }; // L2 Distance of nodes' Lagrangian Position
Tensor L2_Dis_E{ torch::bmm(Dis_E.transpose(2,1), Dis_E) }; // L2 Distance of nodes' Euler Position
Tensor PosLoss{ torch::mean(L2_Dis_L) + torch::mean(L2_Dis_E) }; // Mean of L2 Position distance at one step
Tensor PosLoss_no_uv{ torch::mean(L2_Dis_L)}; // Mean of L2 Position distance at one step
loss = loss + PosLoss;
}
}
loss = loss / ((success_steps - 1) > 0 ? (success_steps - 1) : 1); // Mean of loss of one sample (sample-1 losses)
//loss_no_uv = loss_no_uv / ((success_steps - 1) > 0 ? (success_steps - 1) : 1);
//std::cout << "Loss: " << loss.item<double>() << std::endl;
//std::cout << "Loss no uv: " << loss_no_uv.item<double>() << std::endl;
loss.backward(); // compute grad of register paremeters
if (wordy) {
std::cout << "\nrho1 grad" << simnet.rho1.grad() << std::endl;
std::cout << "rho2 grad" << simnet.rho2.grad() << std::endl;
std::cout << "Y1 grad" << simnet.Y1.grad() << std::endl;
std::cout << "Y2 grad" << simnet.Y2.grad() << std::endl;
std::cout << "B1 grad" << simnet.B1.grad() << std::endl;
std::cout << "B2 grad" << simnet.B2.grad() << std::endl;
}
bool valid_step{ true };
for (const auto& para : simnet.parameters())
if (torch::isnan(para.grad()).item<bool>() ||
torch::isinf(para.grad()).item<bool>()) {
valid_step = false;
break;
}
if (valid_step)
cloth_opt.step(); // Excute Optim
auto rho1_constraint = constraint_para(simnet.rho1, rho1_range.first, rho1_range.second);
auto rho2_constraint = constraint_para(simnet.rho2, rho2_range.first, rho2_range.second);
auto Y1_constraint = constraint_para(simnet.Y1, Y1_range.first, Y1_range.second);
auto Y2_constraint = constraint_para(simnet.Y2, Y2_range.first, Y2_range.second);
auto B1_constraint = constraint_para(simnet.B1, B1_range.first, B1_range.second);
auto B2_constraint = constraint_para(simnet.B2, B2_range.first, B2_range.second);
if (wordy) {
std::cout << "\nOptimized rho1: " << rho1_constraint.item<double>() << std::endl;
std::cout << "Optimized rho2: " << rho2_constraint.item<double>() << std::endl;
std::cout << "Optimized Y1: " << Y1_constraint.item<double>() << std::endl;
std::cout << "Optimized Y2: " << Y2_constraint.item<double>() << std::endl;
std::cout << "Optimized B1: " << B1_constraint.item<double>() << std::endl;
std::cout << "Optimized B2: " << B2_constraint.item<double>() << std::endl;
}
std::cout << "Loss: " << loss.item<double>() << std::endl;
std::map<std::string, Tensor> constrained_para;
constrained_para.insert({ "rho1", rho1_constraint });
constrained_para.insert({ "rho2", rho2_constraint });
constrained_para.insert({ "Y1", Y1_constraint });
constrained_para.insert({ "Y2", Y2_constraint });
constrained_para.insert({ "B1", B1_constraint });
constrained_para.insert({ "B2", B2_constraint });
SaveTrainProc(file, curr_step, train_steps, loss, constrained_para); // save loss and parameters
}
}
file.close();
}
void train_heter_few_obj(std::string save_path, std::string data_path, std::string objs_path,
int epoch, int iter, int batch, int sample, int steps, bool all_steps, bool random, bool para) {
// epoch: the number of training epoches
// iter:
// 1.if not random, the number of bacthes in each iteration
// (save in variable iteration) (see all training data)
// 2. if random, use the give iter as iteration.
// batch: the number of samples in each batch
// sample: the number of steps in each sample
// steps : the number of simulation steps in traing data
//torch::autograd::DetectAnomalyGuard detect_anomaly;
// file in which saves training result
H5File file{ save_path, H5F_ACC_TRUNC };
int samples{ steps / sample }; // the number of sample of training dataset
int iteration{ 0 }; // the number of training iteration
if (all_steps)
iteration = random ? iter : (samples / batch);
else
iteration = iter;
int train_steps{ epoch * iteration }; // the number of training steps (backprop steps)
RandInt SeleSample{ 0, samples - 1 }; // For Randomly Select Sample
auto SizePhy = cloth_property_loader_heter(data_path); // Read Cloth Size and Cloth Physical Properties
H5ClothSize size{ SizePhy.first };
H5PhysicalHeterYarn phy{ SizePhy.second };
std::vector<std::pair<int, int>> handles{}; // Handle vector
handles.push_back(std::make_pair(0, 0));
handles.push_back(std::make_pair(16, 0));
Tensor h = torch::tensor({ 0.001 }, opts); // Simulation Time Step Size: sec
// Initialization Parameters
double init_rho1{ 0.00225 };
double init_rho2{ 0.00245 };
double init_Y1{ 335000.0 };
double init_Y2{ 170000.0 };
double init_B1{ 0.000125 };
double init_B2{ 0.0001 };
double init_S{ 1000 };
auto rho1_range = std::make_pair(0.003, 0.001);
auto rho2_range = std::make_pair(0.003, 0.001);
auto Y1_range = std::make_pair(800000.0, 0.0);
auto Y2_range = std::make_pair(300000.0, 0.0);
auto B1_range = std::make_pair(0.00018, 0.00005);
auto B2_range = std::make_pair(0.00018, 0.00005);
auto S_range = std::make_pair(5000, 0);
phy.rho1 = invert_constraint_para(init_rho1, rho1_range.first, rho1_range.second);
phy.rho2 = invert_constraint_para(init_rho2, rho2_range.first, rho2_range.second);
phy.Y1 = invert_constraint_para(init_Y1, Y1_range.first, Y1_range.second);
phy.Y2 = invert_constraint_para(init_Y2, Y2_range.first, Y2_range.second);
phy.B1 = invert_constraint_para(init_B1, B1_range.first, B1_range.second);
phy.B2 = invert_constraint_para(init_B2, B2_range.first, B2_range.second);
phy.S = invert_constraint_para(init_S, S_range.first, S_range.second);
std::cout << "Epoch: " << std::to_string(epoch) << std::endl;
std::cout << "Iteration: " << std::to_string(iteration) << std::endl;
std::cout << "Batch Size: " << std::to_string(batch) << std::endl;
std::cout << "Sample Size: " << std::to_string(sample - 1) << std::endl;
std::cout << "Random Sampling: " << (random ? "True" : "False") << std::endl;
std::cout << "Parallel: " << (para ? "True" : "False") << std::endl;
YarnSimNetHeterMid simnet(size, phy, handles, h, rho1_range, rho2_range,
Y1_range, Y2_range, B1_range, B2_range, S_range); // Construct Net Train
torch::optim::OptimizerParamGroup rho1({ simnet.named_parameters()["rho_1"] });
torch::optim::OptimizerParamGroup rho2({ simnet.named_parameters()["rho_2"] });
torch::optim::OptimizerParamGroup Y1({ simnet.named_parameters()["Y_1"] });
torch::optim::OptimizerParamGroup Y2({ simnet.named_parameters()["Y_2"] });
torch::optim::OptimizerParamGroup B1({ simnet.named_parameters()["B_1"] });
torch::optim::OptimizerParamGroup B2({ simnet.named_parameters()["B_2"] });
torch::optim::OptimizerParamGroup S({ simnet.named_parameters()["S"] });
torch::optim::SGD cloth_opt({ rho1, rho2, Y1, Y2, B1, B2, S }, torch::optim::SGDOptions(1e5));
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[0].options()).lr(4e6);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[1].options()).lr(6e7);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[2].options()).lr(1e7);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[3].options()).lr(40e8);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[4].options()).lr(6e9);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[5].options()).lr(8e8);
static_cast<torch::optim::SGDOptions&>(cloth_opt.param_groups()[6].options()).lr(3e7);
for (int epc = 0; epc < epoch; ++epc) {
std::cout << "Epoch: " << epc << std::endl;
for (int i = 0; i < iteration; ++i) {
// Update parameters each batch
std::cout << "Batch: " << i << std::endl;
int success_steps{ 0 }; // Success simulation steps
int curr_step{ epc * iteration + i }; // cuttent step in all steps
Tensor loss{ torch::zeros(1, opts) }; // Create loss
simnet.reset_cloth();
cloth_opt.zero_grad();
for (int bch = 0; bch < batch; ++bch) {
std::cout << "Sample: " << std::to_string(bch + 1) << std::endl;
int sample_choice{ 0 };
if (random)
sample_choice = SeleSample(); // Generate a random number
else
sample_choice = i * batch + bch; // Sequential retrieve
ClothState clothStateSample = data_loader(data_path, sample_choice * sample, sample_choice * sample + sample, opts); // Load training batch
ClothState clothStateCurrt{
clothStateSample.LPos[0],
clothStateSample.LPosFix[0],
clothStateSample.LVel[0],
clothStateSample.EPos[0],
clothStateSample.EPosBar[0],
clothStateSample.EVel[0] }; // Cloth Initial State in this Batch. Later replaced by predicted cloth state
ProgressBar bar{
option::BarWidth{50},
option::Start{"["},
option::Fill{"="},
option::Lead{">"},
option::Remainder{" "},
option::End{"]"},
option::PostfixText{"Sample step 0"},
option::ForegroundColor{Color::white},
option::FontStyles{std::vector<FontStyle>{FontStyle::bold}} };
float bar_step = 100.0f / (sample - 1);
float bar_progress = 0.0f;
for (int smp = 0; smp < sample - 1; ++smp) {
std::string sample_step{ "Sample step: " + std::to_string(smp + 1) };
std::string obj_name{ boost::str(boost::format("%|04|_00") % (smp+1)) };
std::string obj_full_path{objs_path + obj_name + ".obj" };
std::cout << obj_full_path << std::endl;
bool is_success{ false }; // Flag indicating if forward simulation success
bar_progress += bar_step;
bar.set_option(option::PostfixText{ sample_step });
bar.set_progress(bar_progress);
if (smp == 0 && all_steps)
clothStateCurrt = simnet.forward(clothStateCurrt, is_success); // Initial sample: set cloth state
else
clothStateCurrt = simnet.forward(is_success); // Later samples: directly moving on
if (!is_success) break; // Break out from the loop if NaN detected in simulating
++success_steps;
Tensor GT_LPos{ torch::zeros_like(clothStateCurrt.LPos) }; // Ground Truth Lagrangian Position
load_obj_train(obj_full_path, GT_LPos);
Tensor Dis_L{ clothStateCurrt.LPos - GT_LPos }; // Distance Lagrangian Position
Tensor L2_Dis_L{ torch::bmm(Dis_L.transpose(2,1), Dis_L) }; // L2 Distance of nodes' Lagrangian Position
Tensor PosLoss{ torch::mean(L2_Dis_L) }; // Mean of L2 Position distance at one step
loss = loss + PosLoss;
}
}
loss = loss / ((success_steps - 1) > 0 ? (success_steps - 1) : 1);
loss.backward(); // compute grad of register paremeters
std::cout << "\nrho1 grad" << simnet.rho1.grad() << std::endl;
std::cout << "rho2 grad" << simnet.rho2.grad() << std::endl;
std::cout << "Y1 grad" << simnet.Y1.grad() << std::endl;
std::cout << "Y2 grad" << simnet.Y2.grad() << std::endl;
std::cout << "B1 grad" << simnet.B1.grad() << std::endl;
std::cout << "B2 grad" << simnet.B2.grad() << std::endl;
std::cout << "S grad" << simnet.S.grad() << std::endl;
bool valid_step{ true };
for (const auto& para : simnet.parameters())
if (torch::isnan(para.grad()).item<bool>() ||
torch::isinf(para.grad()).item<bool>()) {
valid_step = false;
break;
}
if (valid_step)
cloth_opt.step(); // Excute Optim
auto rho1_constraint = constraint_para(simnet.rho1, rho1_range.first, rho1_range.second);
auto rho2_constraint = constraint_para(simnet.rho2, rho2_range.first, rho2_range.second);
auto Y1_constraint = constraint_para(simnet.Y1, Y1_range.first, Y1_range.second);
auto Y2_constraint = constraint_para(simnet.Y2, Y2_range.first, Y2_range.second);
auto B1_constraint = constraint_para(simnet.B1, B1_range.first, B1_range.second);
auto B2_constraint = constraint_para(simnet.B2, B2_range.first, B2_range.second);
auto S_constraint = constraint_para(simnet.S, S_range.first, S_range.second);
std::cout << "\nOptimized rho1: " << rho1_constraint.item<double>() << std::endl;
std::cout << "Optimized rho2: " << rho2_constraint.item<double>() << std::endl;
std::cout << "Optimized Y1: " << Y1_constraint.item<double>() << std::endl;
std::cout << "Optimized Y2: " << Y2_constraint.item<double>() << std::endl;
std::cout << "Optimized B1: " << B1_constraint.item<double>() << std::endl;
std::cout << "Optimized B2: " << B2_constraint.item<double>() << std::endl;
std::cout << "Optimized S: " << S_constraint.item<double>() << std::endl;
std::cout << "Loss: " << loss.item<double>() << std::endl;
std::map<std::string, Tensor> constrained_para;
constrained_para.insert({ "rho1", rho1_constraint });
constrained_para.insert({ "rho2", rho2_constraint });
constrained_para.insert({ "Y1", Y1_constraint });
constrained_para.insert({ "Y2", Y2_constraint });
constrained_para.insert({ "B1", B1_constraint });
constrained_para.insert({ "B2", B2_constraint });
constrained_para.insert({ "S", S_constraint });
SaveTrainProc(file, curr_step, train_steps, loss, constrained_para); // save loss and parameters
}
}
file.close();
}
|
import styles from './template.css';
import template from './template';
import AoflElement from '@aofl/web-components/aofl-element';
/**
* @summary IconTwotoneColorLensElement
* @class IconTwotoneColorLensElement
* @extends {AoflElement}
*/
class IconTwotoneColorLensElement extends AoflElement {
/**
* Creates an instance of IconTwotoneColorLensElement.
*/
constructor() {
super();
}
/**
* @readonly
*/
static get is() {
return 'icon-twotone-color-lens';
}
/**
*
* @return {Object}
*/
render() {
return super.render(template, [styles]);
}
}
window.customElements.define(IconTwotoneColorLensElement.is, IconTwotoneColorLensElement);
export default IconTwotoneColorLensElement;
|
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
# Update class names from the immediately prior version only
# to ensure that cycles are not possible
from apptools.persistence.updater import Updater
def cleanup_foo(self, state):
print('cleaning up Foo0')
state['firstname'] = state['prenom']
state['lastname'] = state['surnom']
del state['prenom']
del state['surnom']
'''for key in state:
print('%s state ---> %s' % (key, state[key]))
'''
self.__dict__.update(state)
def update_project(self, state):
print('updating to v1')
metadata = state['metadata']
metadata['version'] = 1
metadata['diesel'] = 'E300TD'
return state
class Update1(Updater):
def __init__(self):
self.refactorings = {
("__main__", "Foo0"): ("__main__", "Foo"),
}
self.setstates = {
("cplab.project", "Project"): update_project
}
|
import os
project_path = os.getenv("PROJECT_PATH")
data_path = os.path.join(project_path, "data")
output_path = os.path.join(project_path, "output")
model_cp_path = os.path.join(output_path, "model_checkpoint")
logger_path = os.path.join(output_path, "logs")
result_path = os.path.join(output_path, "result")
result_metadata_path = os.path.join(output_path, 'result_metadata')
artifacts_path = os.path.join(output_path, 'artifacts')
logger_repo = os.path.join(logger_path, "logger.log")
train_repo = os.path.join(data_path, "train.csv")
train_path = os.path.join(data_path, 'train')
test_path = os.path.join(data_path, 'test')
|
# CPU: 0.06 s
for _ in range(int(input())):
s, d = map(int, input().split())
# a + b = s => a = s - b
# a - b = d => a = b + d (assume a >= b)
# s - b = b + d
# b = (s - d) / 2
b = (s - d) / 2
a = s - b
if b >= 0 and b.is_integer():
print(int(a), int(b))
else:
print("impossible")
|
from django import forms
from django.core.exceptions import ValidationError
from app.training.models import Topic, Content
from app.widgets.ace import AceWidget
class TopicAdminForm(forms.ModelForm):
class Meta:
model = Topic
fields = '__all__'
widgets = {'course': forms.HiddenInput}
def clean(self):
slug = self.cleaned_data.get('slug')
course = self.cleaned_data.get('course')
if slug and course:
qst = Topic.objects.filter(course=course, slug=slug)
if self.instance:
qst = qst.exclude(id=self.instance.id)
if qst.exists():
self.add_error('slug', ValidationError('Значение не уникально в рамках курса'))
return self.cleaned_data
class ContentAdminForm(forms.ModelForm):
class Meta:
model = Content
fields = '__all__'
widgets = {
'input': AceWidget,
'content': AceWidget
}
class Media:
js = [
'js/ace-1.4.7/ace.js',
'admin/training/topic.js'
]
css = {
'all': ['admin/training/topic.css']
}
class ContentForm(forms.Form):
input = forms.CharField(label="Консольный ввод", required=False)
content = forms.CharField(label='')
output = forms.CharField(
label="Вывод", required=False,
widget=forms.Textarea(attrs={'readonly': True})
)
error = forms.CharField(
label="Ошибка", required=False,
widget=forms.Textarea(attrs={'readonly': True})
)
operation = forms.CharField(widget=forms.Select(choices='Operations.CHOICES'))
translator = forms.IntegerField(widget=forms.HiddenInput)
|
import os
import setuptools
here = os.path.abspath(os.path.dirname(__file__))
# Get __version__ variable
exec(open(os.path.join(here, 'pytorch_pfn_extras', '_version.py')).read())
setuptools.setup(
name='pytorch-pfn-extras',
version=__version__, # NOQA
description='Supplementary components to accelerate research and '
'development in PyTorch.',
author='Preferred Networks, Inc.',
license='MIT License',
install_requires=['numpy', 'torch'],
extras_require={
'test': ['pytest'],
'onnx': ['onnx'],
},
python_requires='>=3.6.0',
packages=setuptools.find_packages(exclude=['tests']),
)
|
import {
CREATE_ORDER_REQUEST,
CREATE_ORDER_SUCCESS,
CREATE_ORDER_FAIL,
MY_ORDERS_REQUEST,
MY_ORDERS_SUCCESS,
MY_ORDERS_FAIL,
ALL_ORDERS_REQUEST,
ALL_ORDERS_SUCCESS,
ALL_ORDERS_FAIL,
UPDATE_ORDER_REQUEST,
UPDATE_ORDER_SUCCESS,
UPDATE_ORDER_FAIL,
UPDATE_ORDER_RESET,
DELETE_ORDER_REQUEST,
DELETE_ORDER_SUCCESS,
DELETE_ORDER_FAIL,
DELETE_ORDER_RESET,
ORDER_DETAILS_REQUEST,
ORDER_DETAILS_SUCCESS,
ORDER_DETAILS_FAIL,
CLEAR_ERRORS,
} from "../constants/orderConstants";
/**
* @description reducer for creating new order
* @param {} object: state
* @param {} action
*/
export const newOrderReducer = (state = {}, action) => {
switch (action.type) {
case CREATE_ORDER_REQUEST:
return {
...state,
loading: true,
};
case CREATE_ORDER_SUCCESS:
return {
loading: false,
order: action.payload,
};
case CREATE_ORDER_FAIL:
return {
loading: false,
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
/**
* @description reducer to view my orders
* @param {[]}} state={orders
* @param {} action
*/
export const myOrdersReducer = (state = { orders: [] }, action) => {
switch (action.type) {
case MY_ORDERS_REQUEST:
return {
loading: true,
};
case MY_ORDERS_SUCCESS:
return {
loading: false,
orders: action.payload,
};
case MY_ORDERS_FAIL:
return {
loading: false,
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
/**
* @description all orders reducer
* @param {[]} state={orders: [] }
* @param {} action
*/
export const allOrdersReducer = (state = { orders: [] }, action) => {
switch (action.type) {
case ALL_ORDERS_REQUEST:
return {
loading: true,
};
case ALL_ORDERS_SUCCESS:
return {
loading: false,
orders: action.payload,
};
case ALL_ORDERS_FAIL:
return {
loading: false,
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
/**
* @description order update and delete reducer
* @param {} state={}
* @param {} action
*/
export const orderReducer = (state = {}, action) => {
switch (action.type) {
case UPDATE_ORDER_REQUEST:
case DELETE_ORDER_REQUEST:
return {
...state,
loading: true,
};
case UPDATE_ORDER_SUCCESS:
return {
...state,
loading: false,
isUpdated: action.payload,
};
case DELETE_ORDER_SUCCESS:
return {
...state,
loading: false,
isDeleted: action.payload,
};
case UPDATE_ORDER_FAIL:
case DELETE_ORDER_FAIL:
return {
...state,
loading: false,
error: action.payload,
};
case UPDATE_ORDER_RESET:
return {
...state,
isUpdated: false,
};
case DELETE_ORDER_RESET:
return {
...state,
isDeleted: false,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
/**
* @description reducer to view single order details
* @param {} state Object: order
* @param {} action
*/
export const orderDetailsReducer = (state = { order: {} }, action) => {
switch (action.type) {
case ORDER_DETAILS_REQUEST:
return {
loading: true,
};
case ORDER_DETAILS_SUCCESS:
return {
loading: false,
order: action.payload,
};
case ORDER_DETAILS_FAIL:
return {
loading: false,
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
|
import React from 'react';
import MapboxGL from '@react-native-mapbox/maps';
import {
View,
Image,
StyleSheet,
Dimensions,
Text,
ActivityIndicator,
} from 'react-native';
import BaseExamplePropTypes from './common/BaseExamplePropTypes';
import Page from './common/Page';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
snapshot: {
flex: 1,
},
});
class TakeSnapshot extends React.Component {
static propTypes = {
...BaseExamplePropTypes,
};
constructor(props) {
super(props);
this.state = {
snapshotURI: null,
};
}
componentDidMount() {
this.takeSnapshot();
}
async takeSnapshot() {
const {width, height} = Dimensions.get('window');
const uri = await MapboxGL.snapshotManager.takeSnap({
centerCoordinate: [-74.12641, 40.797968],
width,
height,
zoomLevel: 12,
pitch: 30,
heading: 20,
styleURL: MapboxGL.StyleURL.Dark,
writeToDisk: true, // creates a temp file
});
this.setState({snapshotURI: uri});
}
render() {
let childView = null;
if (!this.state.snapshotURI) {
childView = (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ActivityIndicator size="large" color="#0000ff" />
<Text>Generating Snapshot</Text>
</View>
);
} else {
childView = (
<View style={styles.container}>
<Image
source={{uri: this.state.snapshotURI}}
resizeMode="contain"
style={styles.snapshot}
/>
</View>
);
}
return <Page {...this.props}>{childView}</Page>;
}
}
export default TakeSnapshot;
|
from setuptools import find_packages, setup
__version__ = "1.5.1"
# Load README
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='chemprop',
author='Kyle Swanson, Kevin Yang, Wengong Jin, Lior Hirschfeld, Allison Tam',
author_email='chemprop@mit.edu',
description='Molecular Property Prediction with Message Passing Neural Networks',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/chemprop/chemprop',
download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz',
project_urls={
'Documentation': 'https://chemprop.readthedocs.io/en/latest/',
'Source': 'https://github.com/chemprop/chemprop',
'PyPi': 'https://pypi.org/project/chemprop/',
'Demo': 'http://chemprop.csail.mit.edu/',
},
license='MIT',
packages=find_packages(),
package_data={'chemprop': ['py.typed']},
entry_points={
'console_scripts': [
'chemprop_train=chemprop.train:chemprop_train',
'chemprop_predict=chemprop.train:chemprop_predict',
'chemprop_fingerprint=chemprop.train:chemprop_fingerprint',
'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt',
'chemprop_interpret=chemprop.interpret:chemprop_interpret',
'chemprop_web=chemprop.web.run:chemprop_web',
'sklearn_train=chemprop.sklearn_train:sklearn_train',
'sklearn_predict=chemprop.sklearn_predict:sklearn_predict',
]
},
install_requires=[
'flask>=1.1.2',
'hyperopt>=0.2.3',
'matplotlib>=3.1.3',
'numpy>=1.18.1',
'pandas>=1.0.3',
'pandas-flavor>=0.2.0',
'scikit-learn>=0.22.2.post1',
'scipy>=1.5.1',
'sphinx>=3.1.2',
'tensorboardX>=2.0',
'torch>=1.5.1',
'tqdm>=4.45.0',
'typed-argument-parser>=1.6.1'
],
extras_require={
'test': [
'pytest>=6.2.2',
'parameterized>=0.8.1'
]
},
python_requires='>=3.7',
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent'
],
keywords=[
'chemistry',
'machine learning',
'property prediction',
'message passing neural network',
'graph neural network'
]
)
|
# -*- coding: utf-8 -*-
"""
Form implementation generated from reading ui file 'ui1.ui'. This module defines all the PyQT classes for creating the
Graphical User Interface. This file was generated automatically and editing it is not recommended.
"""
#
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(977, 740)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
Form.setMinimumSize(QtCore.QSize(977, 740))
Form.setMaximumSize(QtCore.QSize(977, 740))
self.tabWidget = QtGui.QTabWidget(Form)
self.tabWidget.setEnabled(False)
self.tabWidget.setGeometry(QtCore.QRect(0, 30, 981, 711))
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.tabSpace = QtGui.QWidget()
self.tabSpace.setObjectName(_fromUtf8("tabSpace"))
self.verticalLayoutWidget = QtGui.QWidget(self.tabSpace)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(210, 30, 761, 541))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.layoutSpace = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.layoutSpace.setObjectName(_fromUtf8("layoutSpace"))
self.grpSpaceIlluminance = QtGui.QGroupBox(self.tabSpace)
self.grpSpaceIlluminance.setGeometry(QtCore.QRect(0, 30, 201, 231))
self.grpSpaceIlluminance.setToolTip(_fromUtf8(""))
self.grpSpaceIlluminance.setObjectName(_fromUtf8("grpSpaceIlluminance"))
self.groupSpaceNavigateIlluminance = QtGui.QGroupBox(self.grpSpaceIlluminance)
self.groupSpaceNavigateIlluminance.setGeometry(QtCore.QRect(0, 40, 201, 191))
self.groupSpaceNavigateIlluminance.setAutoFillBackground(False)
self.groupSpaceNavigateIlluminance.setStyleSheet(_fromUtf8(""))
self.groupSpaceNavigateIlluminance.setObjectName(_fromUtf8("groupSpaceNavigateIlluminance"))
self.cmbSpaceTimeIllum = QtGui.QComboBox(self.groupSpaceNavigateIlluminance)
self.cmbSpaceTimeIllum.setGeometry(QtCore.QRect(110, 30, 81, 21))
self.cmbSpaceTimeIllum.setObjectName(_fromUtf8("cmbSpaceTimeIllum"))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.cmbSpaceTimeIllum.addItem(_fromUtf8(""))
self.lblSpaceTime = QtGui.QLabel(self.groupSpaceNavigateIlluminance)
self.lblSpaceTime.setGeometry(QtCore.QRect(130, 0, 31, 41))
self.lblSpaceTime.setObjectName(_fromUtf8("lblSpaceTime"))
self.calSpaceDateTimeIllum = QtGui.QDateTimeEdit(self.groupSpaceNavigateIlluminance)
self.calSpaceDateTimeIllum.setGeometry(QtCore.QRect(10, 30, 81, 21))
self.calSpaceDateTimeIllum.setWrapping(True)
self.calSpaceDateTimeIllum.setAlignment(QtCore.Qt.AlignCenter)
self.calSpaceDateTimeIllum.setDate(QtCore.QDate(2015, 1, 1))
self.calSpaceDateTimeIllum.setTime(QtCore.QTime(0, 0, 0))
self.calSpaceDateTimeIllum.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(2015, 12, 31), QtCore.QTime(23, 59, 59)))
self.calSpaceDateTimeIllum.setMinimumDateTime(QtCore.QDateTime(QtCore.QDate(2015, 1, 1), QtCore.QTime(0, 0, 0)))
self.calSpaceDateTimeIllum.setMinimumDate(QtCore.QDate(2015, 1, 1))
self.calSpaceDateTimeIllum.setCalendarPopup(True)
self.calSpaceDateTimeIllum.setObjectName(_fromUtf8("calSpaceDateTimeIllum"))
self.lblSpaceDate = QtGui.QLabel(self.groupSpaceNavigateIlluminance)
self.lblSpaceDate.setGeometry(QtCore.QRect(40, 10, 31, 21))
self.lblSpaceDate.setObjectName(_fromUtf8("lblSpaceDate"))
self.grpSpaceIlluminanceNavigateDetailed = QtGui.QGroupBox(self.groupSpaceNavigateIlluminance)
self.grpSpaceIlluminanceNavigateDetailed.setGeometry(QtCore.QRect(0, 60, 201, 131))
self.grpSpaceIlluminanceNavigateDetailed.setTitle(_fromUtf8(""))
self.grpSpaceIlluminanceNavigateDetailed.setObjectName(_fromUtf8("grpSpaceIlluminanceNavigateDetailed"))
self.cmbSpaceTimeIntervalMin = QtGui.QComboBox(self.grpSpaceIlluminanceNavigateDetailed)
self.cmbSpaceTimeIntervalMin.setGeometry(QtCore.QRect(42, 40, 71, 20))
font = QtGui.QFont()
font.setPointSize(7)
self.cmbSpaceTimeIntervalMin.setFont(font)
self.cmbSpaceTimeIntervalMin.setObjectName(_fromUtf8("cmbSpaceTimeIntervalMin"))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMin.addItem(_fromUtf8(""))
self.lblSpaceTimeStep = QtGui.QLabel(self.grpSpaceIlluminanceNavigateDetailed)
self.lblSpaceTimeStep.setGeometry(QtCore.QRect(7, 100, 56, 20))
self.lblSpaceTimeStep.setObjectName(_fromUtf8("lblSpaceTimeStep"))
self.cmbSpaceIlluminanceStepType = QtGui.QComboBox(self.grpSpaceIlluminanceNavigateDetailed)
self.cmbSpaceIlluminanceStepType.setGeometry(QtCore.QRect(69, 100, 55, 20))
self.cmbSpaceIlluminanceStepType.setObjectName(_fromUtf8("cmbSpaceIlluminanceStepType"))
self.cmbSpaceIlluminanceStepType.addItem(_fromUtf8(""))
self.cmbSpaceIlluminanceStepType.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax = QtGui.QComboBox(self.grpSpaceIlluminanceNavigateDetailed)
self.cmbSpaceTimeIntervalMax.setGeometry(QtCore.QRect(119, 40, 71, 20))
font = QtGui.QFont()
font.setPointSize(7)
self.cmbSpaceTimeIntervalMax.setFont(font)
self.cmbSpaceTimeIntervalMax.setObjectName(_fromUtf8("cmbSpaceTimeIntervalMax"))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbSpaceTimeIntervalMax.addItem(_fromUtf8(""))
self.chkSpaceSkipDarkHours = QtGui.QCheckBox(self.grpSpaceIlluminanceNavigateDetailed)
self.chkSpaceSkipDarkHours.setGeometry(QtCore.QRect(10, 70, 181, 20))
self.chkSpaceSkipDarkHours.setObjectName(_fromUtf8("chkSpaceSkipDarkHours"))
self.lblSpaceDayInterval = QtGui.QLabel(self.grpSpaceIlluminanceNavigateDetailed)
self.lblSpaceDayInterval.setGeometry(QtCore.QRect(10, 40, 41, 20))
self.lblSpaceDayInterval.setObjectName(_fromUtf8("lblSpaceDayInterval"))
self.cmbSpaceIluminanceStepValue = QtGui.QComboBox(self.grpSpaceIlluminanceNavigateDetailed)
self.cmbSpaceIluminanceStepValue.setGeometry(QtCore.QRect(130, 100, 56, 20))
self.cmbSpaceIluminanceStepValue.setObjectName(_fromUtf8("cmbSpaceIluminanceStepValue"))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbSpaceIluminanceStepValue.addItem(_fromUtf8(""))
self.btnSpacePrevHour = QtGui.QPushButton(self.grpSpaceIlluminanceNavigateDetailed)
self.btnSpacePrevHour.setGeometry(QtCore.QRect(10, 10, 88, 20))
self.btnSpacePrevHour.setObjectName(_fromUtf8("btnSpacePrevHour"))
self.btnSpaceNextHour = QtGui.QPushButton(self.grpSpaceIlluminanceNavigateDetailed)
self.btnSpaceNextHour.setGeometry(QtCore.QRect(103, 10, 88, 20))
self.btnSpaceNextHour.setObjectName(_fromUtf8("btnSpaceNextHour"))
self.cmbSpaceSelectIlluminanceFile = QtGui.QComboBox(self.grpSpaceIlluminance)
self.cmbSpaceSelectIlluminanceFile.setGeometry(QtCore.QRect(10, 20, 181, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.cmbSpaceSelectIlluminanceFile.setFont(font)
self.cmbSpaceSelectIlluminanceFile.setObjectName(_fromUtf8("cmbSpaceSelectIlluminanceFile"))
self.cmbSpacePlotType = QtGui.QComboBox(self.tabSpace)
self.cmbSpacePlotType.setGeometry(QtCore.QRect(10, 2, 181, 21))
self.cmbSpacePlotType.setObjectName(_fromUtf8("cmbSpacePlotType"))
self.grpSpaceColorScheme = QtGui.QGroupBox(self.tabSpace)
self.grpSpaceColorScheme.setGeometry(QtCore.QRect(0, 570, 201, 111))
self.grpSpaceColorScheme.setTitle(_fromUtf8(""))
self.grpSpaceColorScheme.setObjectName(_fromUtf8("grpSpaceColorScheme"))
self.lblSpaceChartOpacity = QtGui.QLabel(self.grpSpaceColorScheme)
self.lblSpaceChartOpacity.setGeometry(QtCore.QRect(11, 50, 121, 16))
self.lblSpaceChartOpacity.setObjectName(_fromUtf8("lblSpaceChartOpacity"))
self.txtSpaceOpacityValue = QtGui.QLineEdit(self.grpSpaceColorScheme)
self.txtSpaceOpacityValue.setEnabled(False)
self.txtSpaceOpacityValue.setGeometry(QtCore.QRect(160, 60, 31, 20))
self.txtSpaceOpacityValue.setObjectName(_fromUtf8("txtSpaceOpacityValue"))
self.sliderSpaceOpacity = QtGui.QSlider(self.grpSpaceColorScheme)
self.sliderSpaceOpacity.setGeometry(QtCore.QRect(11, 60, 141, 20))
self.sliderSpaceOpacity.setMaximum(100)
self.sliderSpaceOpacity.setSliderPosition(100)
self.sliderSpaceOpacity.setOrientation(QtCore.Qt.Horizontal)
self.sliderSpaceOpacity.setObjectName(_fromUtf8("sliderSpaceOpacity"))
self.lblSpaceColorSchemeSelect = QtGui.QLabel(self.grpSpaceColorScheme)
self.lblSpaceColorSchemeSelect.setGeometry(QtCore.QRect(10, 0, 121, 16))
self.lblSpaceColorSchemeSelect.setObjectName(_fromUtf8("lblSpaceColorSchemeSelect"))
self.cmbSpaceColorScheme = QtGui.QComboBox(self.grpSpaceColorScheme)
self.cmbSpaceColorScheme.setGeometry(QtCore.QRect(10, 20, 111, 21))
font = QtGui.QFont()
font.setPointSize(7)
self.cmbSpaceColorScheme.setFont(font)
self.cmbSpaceColorScheme.setObjectName(_fromUtf8("cmbSpaceColorScheme"))
self.chkSpaceColorSchemeInvert = QtGui.QCheckBox(self.grpSpaceColorScheme)
self.chkSpaceColorSchemeInvert.setGeometry(QtCore.QRect(130, 0, 51, 31))
self.chkSpaceColorSchemeInvert.setObjectName(_fromUtf8("chkSpaceColorSchemeInvert"))
self.btnSpaceSetColorScheme = QtGui.QPushButton(self.grpSpaceColorScheme)
self.btnSpaceSetColorScheme.setGeometry(QtCore.QRect(10, 82, 181, 21))
self.btnSpaceSetColorScheme.setObjectName(_fromUtf8("btnSpaceSetColorScheme"))
self.chkSpaceColorSchemeInterpolate = QtGui.QCheckBox(self.grpSpaceColorScheme)
self.chkSpaceColorSchemeInterpolate.setGeometry(QtCore.QRect(130, 20, 71, 31))
self.chkSpaceColorSchemeInterpolate.setObjectName(_fromUtf8("chkSpaceColorSchemeInterpolate"))
self.txtSpaceMsgBox = QtGui.QTextBrowser(self.tabSpace)
self.txtSpaceMsgBox.setGeometry(QtCore.QRect(210, 590, 361, 91))
font = QtGui.QFont()
font.setPointSize(7)
self.txtSpaceMsgBox.setFont(font)
self.txtSpaceMsgBox.setStyleSheet(_fromUtf8(""))
self.txtSpaceMsgBox.setObjectName(_fromUtf8("txtSpaceMsgBox"))
self.txtSpaceStatusDisplay = QtGui.QLineEdit(self.tabSpace)
self.txtSpaceStatusDisplay.setEnabled(False)
self.txtSpaceStatusDisplay.setGeometry(QtCore.QRect(210, 2, 761, 21))
self.txtSpaceStatusDisplay.setObjectName(_fromUtf8("txtSpaceStatusDisplay"))
self.grpSpaceColorContourSettings = QtGui.QGroupBox(self.tabSpace)
self.grpSpaceColorContourSettings.setGeometry(QtCore.QRect(0, 260, 201, 311))
self.grpSpaceColorContourSettings.setTitle(_fromUtf8(""))
self.grpSpaceColorContourSettings.setObjectName(_fromUtf8("grpSpaceColorContourSettings"))
self.grpColoursIlluminance = QtGui.QGroupBox(self.grpSpaceColorContourSettings)
self.grpColoursIlluminance.setGeometry(QtCore.QRect(110, 50, 81, 261))
self.grpColoursIlluminance.setStyleSheet(_fromUtf8(""))
self.grpColoursIlluminance.setTitle(_fromUtf8(""))
self.grpColoursIlluminance.setObjectName(_fromUtf8("grpColoursIlluminance"))
self.btnSelectColorLowerMask = QtGui.QPushButton(self.grpColoursIlluminance)
self.btnSelectColorLowerMask.setGeometry(QtCore.QRect(0, 190, 81, 21))
self.btnSelectColorLowerMask.setObjectName(_fromUtf8("btnSelectColorLowerMask"))
self.lblSpaceColorMinLimit = QtGui.QLabel(self.grpColoursIlluminance)
self.lblSpaceColorMinLimit.setGeometry(QtCore.QRect(0, 70, 81, 20))
self.lblSpaceColorMinLimit.setAlignment(QtCore.Qt.AlignCenter)
self.lblSpaceColorMinLimit.setObjectName(_fromUtf8("lblSpaceColorMinLimit"))
self.txtSpaceColorsMin = QtGui.QLineEdit(self.grpColoursIlluminance)
self.txtSpaceColorsMin.setGeometry(QtCore.QRect(0, 90, 81, 20))
self.txtSpaceColorsMin.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.txtSpaceColorsMin.setInputMask(_fromUtf8(""))
self.txtSpaceColorsMin.setText(_fromUtf8(""))
self.txtSpaceColorsMin.setCursorPosition(0)
self.txtSpaceColorsMin.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceColorsMin.setObjectName(_fromUtf8("txtSpaceColorsMin"))
self.btnSelectColorUpperMask = QtGui.QPushButton(self.grpColoursIlluminance)
self.btnSelectColorUpperMask.setGeometry(QtCore.QRect(0, 130, 81, 21))
self.btnSelectColorUpperMask.setObjectName(_fromUtf8("btnSelectColorUpperMask"))
self.txtSpaceColorsMax = QtGui.QLineEdit(self.grpColoursIlluminance)
self.txtSpaceColorsMax.setGeometry(QtCore.QRect(0, 40, 81, 20))
self.txtSpaceColorsMax.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.txtSpaceColorsMax.setInputMask(_fromUtf8(""))
self.txtSpaceColorsMax.setText(_fromUtf8(""))
self.txtSpaceColorsMax.setCursorPosition(0)
self.txtSpaceColorsMax.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceColorsMax.setObjectName(_fromUtf8("txtSpaceColorsMax"))
self.lblSpaceColorMaxLimit = QtGui.QLabel(self.grpColoursIlluminance)
self.lblSpaceColorMaxLimit.setGeometry(QtCore.QRect(0, 20, 81, 20))
self.lblSpaceColorMaxLimit.setAlignment(QtCore.Qt.AlignCenter)
self.lblSpaceColorMaxLimit.setObjectName(_fromUtf8("lblSpaceColorMaxLimit"))
self.txtSpaceColorsUpperMask = QtGui.QLineEdit(self.grpColoursIlluminance)
self.txtSpaceColorsUpperMask.setEnabled(False)
self.txtSpaceColorsUpperMask.setGeometry(QtCore.QRect(0, 150, 81, 20))
self.txtSpaceColorsUpperMask.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.txtSpaceColorsUpperMask.setInputMask(_fromUtf8(""))
self.txtSpaceColorsUpperMask.setCursorPosition(0)
self.txtSpaceColorsUpperMask.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceColorsUpperMask.setObjectName(_fromUtf8("txtSpaceColorsUpperMask"))
self.txtSpaceColorsLowerMask = QtGui.QLineEdit(self.grpColoursIlluminance)
self.txtSpaceColorsLowerMask.setEnabled(False)
self.txtSpaceColorsLowerMask.setGeometry(QtCore.QRect(0, 210, 81, 20))
self.txtSpaceColorsLowerMask.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.txtSpaceColorsLowerMask.setInputMask(_fromUtf8(""))
self.txtSpaceColorsLowerMask.setCursorPosition(0)
self.txtSpaceColorsLowerMask.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceColorsLowerMask.setObjectName(_fromUtf8("txtSpaceColorsLowerMask"))
self.btnSpaceSetColors = QtGui.QPushButton(self.grpColoursIlluminance)
self.btnSpaceSetColors.setGeometry(QtCore.QRect(0, 240, 79, 19))
self.btnSpaceSetColors.setObjectName(_fromUtf8("btnSpaceSetColors"))
self.btnSpaceResetColors = QtGui.QPushButton(self.grpColoursIlluminance)
self.btnSpaceResetColors.setGeometry(QtCore.QRect(0, 1, 79, 18))
self.btnSpaceResetColors.setObjectName(_fromUtf8("btnSpaceResetColors"))
self.chkSpaceContours = QtGui.QCheckBox(self.grpSpaceColorContourSettings)
self.chkSpaceContours.setGeometry(QtCore.QRect(10, 0, 81, 20))
self.chkSpaceContours.setChecked(True)
self.chkSpaceContours.setObjectName(_fromUtf8("chkSpaceContours"))
self.grpContoursIlluminance = QtGui.QGroupBox(self.grpSpaceColorContourSettings)
self.grpContoursIlluminance.setGeometry(QtCore.QRect(10, 50, 81, 261))
self.grpContoursIlluminance.setTitle(_fromUtf8(""))
self.grpContoursIlluminance.setObjectName(_fromUtf8("grpContoursIlluminance"))
self.btnSpaceSetContours = QtGui.QPushButton(self.grpContoursIlluminance)
self.btnSpaceSetContours.setGeometry(QtCore.QRect(0, 240, 79, 19))
self.btnSpaceSetContours.setObjectName(_fromUtf8("btnSpaceSetContours"))
self.txtSpaceCountourValue6 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue6.setGeometry(QtCore.QRect(0, 166, 79, 18))
self.txtSpaceCountourValue6.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue6.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue6.setCursorPosition(0)
self.txtSpaceCountourValue6.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue6.setObjectName(_fromUtf8("txtSpaceCountourValue6"))
self.btnSpaceResetContours = QtGui.QPushButton(self.grpContoursIlluminance)
self.btnSpaceResetContours.setGeometry(QtCore.QRect(0, 1, 79, 18))
self.btnSpaceResetContours.setObjectName(_fromUtf8("btnSpaceResetContours"))
self.txtSpaceCountourValue7 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue7.setGeometry(QtCore.QRect(0, 190, 79, 17))
self.txtSpaceCountourValue7.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue7.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue7.setCursorPosition(0)
self.txtSpaceCountourValue7.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue7.setObjectName(_fromUtf8("txtSpaceCountourValue7"))
self.txtSpaceCountourValue5 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue5.setGeometry(QtCore.QRect(0, 143, 79, 17))
self.txtSpaceCountourValue5.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue5.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue5.setCursorPosition(0)
self.txtSpaceCountourValue5.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue5.setObjectName(_fromUtf8("txtSpaceCountourValue5"))
self.txtSpaceCountourValue4 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue4.setGeometry(QtCore.QRect(0, 119, 79, 18))
self.txtSpaceCountourValue4.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue4.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue4.setCursorPosition(0)
self.txtSpaceCountourValue4.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue4.setObjectName(_fromUtf8("txtSpaceCountourValue4"))
self.txtSpaceCountourValue1 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue1.setGeometry(QtCore.QRect(0, 49, 79, 17))
self.txtSpaceCountourValue1.setLayoutDirection(QtCore.Qt.LeftToRight)
self.txtSpaceCountourValue1.setAutoFillBackground(True)
self.txtSpaceCountourValue1.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue1.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue1.setCursorPosition(0)
self.txtSpaceCountourValue1.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue1.setObjectName(_fromUtf8("txtSpaceCountourValue1"))
self.txtSpaceCountourValue2 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue2.setGeometry(QtCore.QRect(0, 72, 79, 18))
self.txtSpaceCountourValue2.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue2.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue2.setObjectName(_fromUtf8("txtSpaceCountourValue2"))
self.txtSpaceCountourValue3 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue3.setGeometry(QtCore.QRect(0, 96, 79, 17))
self.txtSpaceCountourValue3.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue3.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue3.setCursorPosition(0)
self.txtSpaceCountourValue3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue3.setObjectName(_fromUtf8("txtSpaceCountourValue3"))
self.cmbSpaceContourQuantity = QtGui.QComboBox(self.grpContoursIlluminance)
self.cmbSpaceContourQuantity.setGeometry(QtCore.QRect(0, 25, 79, 18))
self.cmbSpaceContourQuantity.setLayoutDirection(QtCore.Qt.LeftToRight)
self.cmbSpaceContourQuantity.setObjectName(_fromUtf8("cmbSpaceContourQuantity"))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.cmbSpaceContourQuantity.addItem(_fromUtf8(""))
self.txtSpaceCountourValue8 = QtGui.QLineEdit(self.grpContoursIlluminance)
self.txtSpaceCountourValue8.setGeometry(QtCore.QRect(0, 214, 79, 17))
self.txtSpaceCountourValue8.setInputMethodHints(QtCore.Qt.ImhNone)
self.txtSpaceCountourValue8.setInputMask(_fromUtf8(""))
self.txtSpaceCountourValue8.setCursorPosition(0)
self.txtSpaceCountourValue8.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.txtSpaceCountourValue8.setObjectName(_fromUtf8("txtSpaceCountourValue8"))
self.btnSpaceSettingsColours = QtGui.QPushButton(self.grpSpaceColorContourSettings)
self.btnSpaceSettingsColours.setGeometry(QtCore.QRect(110, 20, 81, 21))
font = QtGui.QFont()
font.setPointSize(7)
self.btnSpaceSettingsColours.setFont(font)
self.btnSpaceSettingsColours.setObjectName(_fromUtf8("btnSpaceSettingsColours"))
self.btnSpaceSettingsContour = QtGui.QPushButton(self.grpSpaceColorContourSettings)
self.btnSpaceSettingsContour.setEnabled(False)
self.btnSpaceSettingsContour.setGeometry(QtCore.QRect(10, 20, 81, 21))
font = QtGui.QFont()
font.setPointSize(7)
self.btnSpaceSettingsContour.setFont(font)
self.btnSpaceSettingsContour.setObjectName(_fromUtf8("btnSpaceSettingsContour"))
self.chkSpaceColors = QtGui.QCheckBox(self.grpSpaceColorContourSettings)
self.chkSpaceColors.setGeometry(QtCore.QRect(110, 0, 81, 20))
self.chkSpaceColors.setChecked(True)
self.chkSpaceColors.setObjectName(_fromUtf8("chkSpaceColors"))
self.txtSpaceErrorBox = QtGui.QTextBrowser(self.tabSpace)
self.txtSpaceErrorBox.setGeometry(QtCore.QRect(600, 590, 371, 91))
self.txtSpaceErrorBox.setStyleSheet(_fromUtf8("background-color: rgb(255, 255, 255);\n"
"color: rgb(255, 0, 0);"))
self.txtSpaceErrorBox.setObjectName(_fromUtf8("txtSpaceErrorBox"))
self.lblSpaceProjectLog = QtGui.QLabel(self.tabSpace)
self.lblSpaceProjectLog.setGeometry(QtCore.QRect(210, 571, 81, 20))
self.lblSpaceProjectLog.setObjectName(_fromUtf8("lblSpaceProjectLog"))
self.lblSpaceErrorLog = QtGui.QLabel(self.tabSpace)
self.lblSpaceErrorLog.setGeometry(QtCore.QRect(600, 570, 101, 20))
self.lblSpaceErrorLog.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);\n"
"font: 75 8pt \"MS Shell Dlg 2\";"))
self.lblSpaceErrorLog.setObjectName(_fromUtf8("lblSpaceErrorLog"))
self.tabWidget.addTab(self.tabSpace, _fromUtf8(""))
self.tabTimeSeries = QtGui.QWidget()
self.tabTimeSeries.setObjectName(_fromUtf8("tabTimeSeries"))
self.grpTimeSeriesMain = QtGui.QGroupBox(self.tabTimeSeries)
self.grpTimeSeriesMain.setGeometry(QtCore.QRect(0, 0, 971, 691))
self.grpTimeSeriesMain.setTitle(_fromUtf8(""))
self.grpTimeSeriesMain.setObjectName(_fromUtf8("grpTimeSeriesMain"))
self.grpTimeSeriesColorScheme = QtGui.QGroupBox(self.grpTimeSeriesMain)
self.grpTimeSeriesColorScheme.setGeometry(QtCore.QRect(0, 570, 201, 111))
self.grpTimeSeriesColorScheme.setTitle(_fromUtf8(""))
self.grpTimeSeriesColorScheme.setObjectName(_fromUtf8("grpTimeSeriesColorScheme"))
self.lblTimeSeriesChartOpacity = QtGui.QLabel(self.grpTimeSeriesColorScheme)
self.lblTimeSeriesChartOpacity.setGeometry(QtCore.QRect(11, 50, 121, 16))
self.lblTimeSeriesChartOpacity.setObjectName(_fromUtf8("lblTimeSeriesChartOpacity"))
self.txtTimeSeriesOpacityValue = QtGui.QLineEdit(self.grpTimeSeriesColorScheme)
self.txtTimeSeriesOpacityValue.setEnabled(False)
self.txtTimeSeriesOpacityValue.setGeometry(QtCore.QRect(160, 60, 31, 20))
self.txtTimeSeriesOpacityValue.setObjectName(_fromUtf8("txtTimeSeriesOpacityValue"))
self.sliderTimeSeriesOpacity = QtGui.QSlider(self.grpTimeSeriesColorScheme)
self.sliderTimeSeriesOpacity.setGeometry(QtCore.QRect(11, 60, 141, 20))
self.sliderTimeSeriesOpacity.setMaximum(100)
self.sliderTimeSeriesOpacity.setSliderPosition(100)
self.sliderTimeSeriesOpacity.setOrientation(QtCore.Qt.Horizontal)
self.sliderTimeSeriesOpacity.setObjectName(_fromUtf8("sliderTimeSeriesOpacity"))
self.lblTimeSeriesColorSchemeSelect = QtGui.QLabel(self.grpTimeSeriesColorScheme)
self.lblTimeSeriesColorSchemeSelect.setGeometry(QtCore.QRect(10, 0, 121, 16))
self.lblTimeSeriesColorSchemeSelect.setObjectName(_fromUtf8("lblTimeSeriesColorSchemeSelect"))
self.cmbTimeSeriesColorScheme = QtGui.QComboBox(self.grpTimeSeriesColorScheme)
self.cmbTimeSeriesColorScheme.setGeometry(QtCore.QRect(10, 20, 121, 21))
self.cmbTimeSeriesColorScheme.setObjectName(_fromUtf8("cmbTimeSeriesColorScheme"))
self.chkTimeSeriesColorSchemeInvert = QtGui.QCheckBox(self.grpTimeSeriesColorScheme)
self.chkTimeSeriesColorSchemeInvert.setGeometry(QtCore.QRect(150, 15, 51, 31))
self.chkTimeSeriesColorSchemeInvert.setObjectName(_fromUtf8("chkTimeSeriesColorSchemeInvert"))
self.btnTimeSeriesSetColorScheme = QtGui.QPushButton(self.grpTimeSeriesColorScheme)
self.btnTimeSeriesSetColorScheme.setGeometry(QtCore.QRect(10, 82, 181, 21))
self.btnTimeSeriesSetColorScheme.setObjectName(_fromUtf8("btnTimeSeriesSetColorScheme"))
self.verticalLayoutWidget_2 = QtGui.QWidget(self.grpTimeSeriesMain)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(210, 0, 761, 681))
self.verticalLayoutWidget_2.setObjectName(_fromUtf8("verticalLayoutWidget_2"))
self.layoutTimeSeries = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)
self.layoutTimeSeries.setObjectName(_fromUtf8("layoutTimeSeries"))
self.grpTimeSeriesChart1 = QtGui.QGroupBox(self.grpTimeSeriesMain)
self.grpTimeSeriesChart1.setGeometry(QtCore.QRect(10, 20, 191, 111))
self.grpTimeSeriesChart1.setObjectName(_fromUtf8("grpTimeSeriesChart1"))
self.cmbTimeSeriesPlotType = QtGui.QComboBox(self.grpTimeSeriesChart1)
self.cmbTimeSeriesPlotType.setGeometry(QtCore.QRect(10, 20, 171, 21))
self.cmbTimeSeriesPlotType.setObjectName(_fromUtf8("cmbTimeSeriesPlotType"))
self.txtTimeSeriesChart1Min = QtGui.QLineEdit(self.grpTimeSeriesChart1)
self.txtTimeSeriesChart1Min.setGeometry(QtCore.QRect(130, 50, 51, 20))
self.txtTimeSeriesChart1Min.setObjectName(_fromUtf8("txtTimeSeriesChart1Min"))
self.txtTimeSeriesChart1Max = QtGui.QLineEdit(self.grpTimeSeriesChart1)
self.txtTimeSeriesChart1Max.setGeometry(QtCore.QRect(40, 50, 51, 20))
self.txtTimeSeriesChart1Max.setObjectName(_fromUtf8("txtTimeSeriesChart1Max"))
self.btnTimeSeriesChart1 = QtGui.QPushButton(self.grpTimeSeriesChart1)
self.btnTimeSeriesChart1.setGeometry(QtCore.QRect(10, 80, 171, 23))
self.btnTimeSeriesChart1.setObjectName(_fromUtf8("btnTimeSeriesChart1"))
self.lblTimeSeriesChart1Max = QtGui.QLabel(self.grpTimeSeriesChart1)
self.lblTimeSeriesChart1Max.setGeometry(QtCore.QRect(20, 50, 31, 20))
self.lblTimeSeriesChart1Max.setObjectName(_fromUtf8("lblTimeSeriesChart1Max"))
self.lblTimeSeriesChart1Min = QtGui.QLabel(self.grpTimeSeriesChart1)
self.lblTimeSeriesChart1Min.setGeometry(QtCore.QRect(110, 50, 31, 20))
self.lblTimeSeriesChart1Min.setObjectName(_fromUtf8("lblTimeSeriesChart1Min"))
self.grpTimeSeriesChart2 = QtGui.QGroupBox(self.grpTimeSeriesMain)
self.grpTimeSeriesChart2.setGeometry(QtCore.QRect(10, 150, 191, 111))
self.grpTimeSeriesChart2.setObjectName(_fromUtf8("grpTimeSeriesChart2"))
self.txtTimeSeriesChart2Max = QtGui.QLineEdit(self.grpTimeSeriesChart2)
self.txtTimeSeriesChart2Max.setGeometry(QtCore.QRect(40, 50, 51, 20))
self.txtTimeSeriesChart2Max.setObjectName(_fromUtf8("txtTimeSeriesChart2Max"))
self.txtTimeSeriesChart2Min = QtGui.QLineEdit(self.grpTimeSeriesChart2)
self.txtTimeSeriesChart2Min.setGeometry(QtCore.QRect(130, 50, 51, 20))
self.txtTimeSeriesChart2Min.setObjectName(_fromUtf8("txtTimeSeriesChart2Min"))
self.btnTimeSeriesChart2 = QtGui.QPushButton(self.grpTimeSeriesChart2)
self.btnTimeSeriesChart2.setGeometry(QtCore.QRect(10, 80, 171, 23))
self.btnTimeSeriesChart2.setObjectName(_fromUtf8("btnTimeSeriesChart2"))
self.cmbTimeSeriesPlotType2 = QtGui.QComboBox(self.grpTimeSeriesChart2)
self.cmbTimeSeriesPlotType2.setGeometry(QtCore.QRect(10, 20, 171, 21))
self.cmbTimeSeriesPlotType2.setObjectName(_fromUtf8("cmbTimeSeriesPlotType2"))
self.lblTimeSeriesChart2Max = QtGui.QLabel(self.grpTimeSeriesChart2)
self.lblTimeSeriesChart2Max.setGeometry(QtCore.QRect(20, 50, 31, 20))
self.lblTimeSeriesChart2Max.setObjectName(_fromUtf8("lblTimeSeriesChart2Max"))
self.lblTimeSeriesChart2Min = QtGui.QLabel(self.grpTimeSeriesChart2)
self.lblTimeSeriesChart2Min.setGeometry(QtCore.QRect(110, 50, 31, 20))
self.lblTimeSeriesChart2Min.setObjectName(_fromUtf8("lblTimeSeriesChart2Min"))
self.grpTimeSeriesChart3 = QtGui.QGroupBox(self.grpTimeSeriesMain)
self.grpTimeSeriesChart3.setGeometry(QtCore.QRect(10, 280, 191, 111))
self.grpTimeSeriesChart3.setObjectName(_fromUtf8("grpTimeSeriesChart3"))
self.btnTimeSeriesChart3 = QtGui.QPushButton(self.grpTimeSeriesChart3)
self.btnTimeSeriesChart3.setGeometry(QtCore.QRect(10, 80, 171, 23))
self.btnTimeSeriesChart3.setObjectName(_fromUtf8("btnTimeSeriesChart3"))
self.lblTimeSeriesChart3Min = QtGui.QLabel(self.grpTimeSeriesChart3)
self.lblTimeSeriesChart3Min.setGeometry(QtCore.QRect(110, 50, 31, 20))
self.lblTimeSeriesChart3Min.setObjectName(_fromUtf8("lblTimeSeriesChart3Min"))
self.txtTimeSeriesChart3Max = QtGui.QLineEdit(self.grpTimeSeriesChart3)
self.txtTimeSeriesChart3Max.setGeometry(QtCore.QRect(40, 50, 51, 20))
self.txtTimeSeriesChart3Max.setObjectName(_fromUtf8("txtTimeSeriesChart3Max"))
self.cmbTimeSeriesPlotType3 = QtGui.QComboBox(self.grpTimeSeriesChart3)
self.cmbTimeSeriesPlotType3.setGeometry(QtCore.QRect(10, 20, 171, 21))
self.cmbTimeSeriesPlotType3.setObjectName(_fromUtf8("cmbTimeSeriesPlotType3"))
self.lblTimeSeriesChart3Max = QtGui.QLabel(self.grpTimeSeriesChart3)
self.lblTimeSeriesChart3Max.setGeometry(QtCore.QRect(20, 50, 31, 20))
self.lblTimeSeriesChart3Max.setObjectName(_fromUtf8("lblTimeSeriesChart3Max"))
self.txtTimeSeriesChart3Min = QtGui.QLineEdit(self.grpTimeSeriesChart3)
self.txtTimeSeriesChart3Min.setGeometry(QtCore.QRect(130, 50, 51, 20))
self.txtTimeSeriesChart3Min.setObjectName(_fromUtf8("txtTimeSeriesChart3Min"))
self.grpTimeSeriesChart4 = QtGui.QGroupBox(self.grpTimeSeriesMain)
self.grpTimeSeriesChart4.setGeometry(QtCore.QRect(10, 410, 191, 111))
self.grpTimeSeriesChart4.setObjectName(_fromUtf8("grpTimeSeriesChart4"))
self.btnTimeSeriesChart4 = QtGui.QPushButton(self.grpTimeSeriesChart4)
self.btnTimeSeriesChart4.setGeometry(QtCore.QRect(10, 80, 171, 23))
self.btnTimeSeriesChart4.setObjectName(_fromUtf8("btnTimeSeriesChart4"))
self.lblTimeSeriesChart4Min = QtGui.QLabel(self.grpTimeSeriesChart4)
self.lblTimeSeriesChart4Min.setGeometry(QtCore.QRect(110, 50, 31, 20))
self.lblTimeSeriesChart4Min.setObjectName(_fromUtf8("lblTimeSeriesChart4Min"))
self.txtTimeSeriesChart4Min = QtGui.QLineEdit(self.grpTimeSeriesChart4)
self.txtTimeSeriesChart4Min.setGeometry(QtCore.QRect(130, 50, 51, 20))
self.txtTimeSeriesChart4Min.setObjectName(_fromUtf8("txtTimeSeriesChart4Min"))
self.cmbTimeSeriesPlotType4 = QtGui.QComboBox(self.grpTimeSeriesChart4)
self.cmbTimeSeriesPlotType4.setGeometry(QtCore.QRect(10, 20, 171, 21))
self.cmbTimeSeriesPlotType4.setObjectName(_fromUtf8("cmbTimeSeriesPlotType4"))
self.txtTimeSeriesChart4Max = QtGui.QLineEdit(self.grpTimeSeriesChart4)
self.txtTimeSeriesChart4Max.setGeometry(QtCore.QRect(40, 50, 51, 20))
self.txtTimeSeriesChart4Max.setObjectName(_fromUtf8("txtTimeSeriesChart4Max"))
self.lblTimeSeriesChart4Max = QtGui.QLabel(self.grpTimeSeriesChart4)
self.lblTimeSeriesChart4Max.setGeometry(QtCore.QRect(20, 50, 31, 20))
self.lblTimeSeriesChart4Max.setObjectName(_fromUtf8("lblTimeSeriesChart4Max"))
self.tabWidget.addTab(self.tabTimeSeries, _fromUtf8(""))
self.tabCombined = QtGui.QWidget()
self.tabCombined.setObjectName(_fromUtf8("tabCombined"))
self.verticalLayoutWidget_3 = QtGui.QWidget(self.tabCombined)
self.verticalLayoutWidget_3.setGeometry(QtCore.QRect(210, 30, 761, 651))
self.verticalLayoutWidget_3.setObjectName(_fromUtf8("verticalLayoutWidget_3"))
self.layoutCombined = QtGui.QVBoxLayout(self.verticalLayoutWidget_3)
self.layoutCombined.setObjectName(_fromUtf8("layoutCombined"))
self.txtCombinedStatusDisplay = QtGui.QLineEdit(self.tabCombined)
self.txtCombinedStatusDisplay.setEnabled(False)
self.txtCombinedStatusDisplay.setGeometry(QtCore.QRect(210, 3, 761, 20))
self.txtCombinedStatusDisplay.setObjectName(_fromUtf8("txtCombinedStatusDisplay"))
self.grpCombinedIlluminance = QtGui.QGroupBox(self.tabCombined)
self.grpCombinedIlluminance.setGeometry(QtCore.QRect(0, 30, 201, 231))
self.grpCombinedIlluminance.setObjectName(_fromUtf8("grpCombinedIlluminance"))
self.cmbCombinedSelectIlluminanceFile = QtGui.QComboBox(self.grpCombinedIlluminance)
self.cmbCombinedSelectIlluminanceFile.setGeometry(QtCore.QRect(10, 20, 181, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.cmbCombinedSelectIlluminanceFile.setFont(font)
self.cmbCombinedSelectIlluminanceFile.setObjectName(_fromUtf8("cmbCombinedSelectIlluminanceFile"))
self.groupCombinedNavigateIlluminance = QtGui.QGroupBox(self.grpCombinedIlluminance)
self.groupCombinedNavigateIlluminance.setGeometry(QtCore.QRect(0, 40, 201, 191))
self.groupCombinedNavigateIlluminance.setObjectName(_fromUtf8("groupCombinedNavigateIlluminance"))
self.grpCombinedIlluminanceNavigateDetailed = QtGui.QGroupBox(self.groupCombinedNavigateIlluminance)
self.grpCombinedIlluminanceNavigateDetailed.setGeometry(QtCore.QRect(0, 60, 201, 131))
self.grpCombinedIlluminanceNavigateDetailed.setTitle(_fromUtf8(""))
self.grpCombinedIlluminanceNavigateDetailed.setObjectName(_fromUtf8("grpCombinedIlluminanceNavigateDetailed"))
self.cmbCombinedlluminanceStepType = QtGui.QComboBox(self.grpCombinedIlluminanceNavigateDetailed)
self.cmbCombinedlluminanceStepType.setGeometry(QtCore.QRect(69, 100, 55, 20))
self.cmbCombinedlluminanceStepType.setObjectName(_fromUtf8("cmbCombinedlluminanceStepType"))
self.cmbCombinedlluminanceStepType.addItem(_fromUtf8(""))
self.cmbCombinedlluminanceStepType.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax = QtGui.QComboBox(self.grpCombinedIlluminanceNavigateDetailed)
self.cmbCombinedTimeIntervalMax.setGeometry(QtCore.QRect(119, 40, 71, 20))
font = QtGui.QFont()
font.setPointSize(7)
self.cmbCombinedTimeIntervalMax.setFont(font)
self.cmbCombinedTimeIntervalMax.setObjectName(_fromUtf8("cmbCombinedTimeIntervalMax"))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMax.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin = QtGui.QComboBox(self.grpCombinedIlluminanceNavigateDetailed)
self.cmbCombinedTimeIntervalMin.setGeometry(QtCore.QRect(42, 40, 71, 20))
font = QtGui.QFont()
font.setPointSize(7)
self.cmbCombinedTimeIntervalMin.setFont(font)
self.cmbCombinedTimeIntervalMin.setObjectName(_fromUtf8("cmbCombinedTimeIntervalMin"))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.cmbCombinedTimeIntervalMin.addItem(_fromUtf8(""))
self.chkCombinedSkipDarkHours = QtGui.QCheckBox(self.grpCombinedIlluminanceNavigateDetailed)
self.chkCombinedSkipDarkHours.setGeometry(QtCore.QRect(10, 70, 181, 20))
self.chkCombinedSkipDarkHours.setObjectName(_fromUtf8("chkCombinedSkipDarkHours"))
self.btnCombinedPrevHour = QtGui.QPushButton(self.grpCombinedIlluminanceNavigateDetailed)
self.btnCombinedPrevHour.setGeometry(QtCore.QRect(10, 10, 88, 20))
self.btnCombinedPrevHour.setObjectName(_fromUtf8("btnCombinedPrevHour"))
self.lblCombinedDayInterval = QtGui.QLabel(self.grpCombinedIlluminanceNavigateDetailed)
self.lblCombinedDayInterval.setGeometry(QtCore.QRect(10, 40, 41, 20))
self.lblCombinedDayInterval.setObjectName(_fromUtf8("lblCombinedDayInterval"))
self.btnCombinedNextHour = QtGui.QPushButton(self.grpCombinedIlluminanceNavigateDetailed)
self.btnCombinedNextHour.setGeometry(QtCore.QRect(103, 10, 88, 20))
self.btnCombinedNextHour.setObjectName(_fromUtf8("btnCombinedNextHour"))
self.cmbCombinedIluminanceStepValue = QtGui.QComboBox(self.grpCombinedIlluminanceNavigateDetailed)
self.cmbCombinedIluminanceStepValue.setGeometry(QtCore.QRect(130, 100, 56, 20))
self.cmbCombinedIluminanceStepValue.setObjectName(_fromUtf8("cmbCombinedIluminanceStepValue"))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.cmbCombinedIluminanceStepValue.addItem(_fromUtf8(""))
self.lblCombinedTimeStep = QtGui.QLabel(self.grpCombinedIlluminanceNavigateDetailed)
self.lblCombinedTimeStep.setGeometry(QtCore.QRect(7, 100, 56, 20))
self.lblCombinedTimeStep.setObjectName(_fromUtf8("lblCombinedTimeStep"))
self.lblCombinedDate = QtGui.QLabel(self.groupCombinedNavigateIlluminance)
self.lblCombinedDate.setGeometry(QtCore.QRect(40, 10, 31, 21))
self.lblCombinedDate.setObjectName(_fromUtf8("lblCombinedDate"))
self.lblCombinedTime = QtGui.QLabel(self.groupCombinedNavigateIlluminance)
self.lblCombinedTime.setGeometry(QtCore.QRect(130, 0, 31, 41))
self.lblCombinedTime.setObjectName(_fromUtf8("lblCombinedTime"))
self.calCombinedDateTimeIllum = QtGui.QDateTimeEdit(self.groupCombinedNavigateIlluminance)
self.calCombinedDateTimeIllum.setGeometry(QtCore.QRect(10, 30, 81, 21))
self.calCombinedDateTimeIllum.setWrapping(True)
self.calCombinedDateTimeIllum.setAlignment(QtCore.Qt.AlignCenter)
self.calCombinedDateTimeIllum.setDate(QtCore.QDate(2015, 1, 1))
self.calCombinedDateTimeIllum.setTime(QtCore.QTime(0, 0, 0))
self.calCombinedDateTimeIllum.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(2015, 12, 31), QtCore.QTime(23, 59, 59)))
self.calCombinedDateTimeIllum.setMinimumDateTime(QtCore.QDateTime(QtCore.QDate(2015, 1, 1), QtCore.QTime(0, 0, 0)))
self.calCombinedDateTimeIllum.setMinimumDate(QtCore.QDate(2015, 1, 1))
self.calCombinedDateTimeIllum.setCalendarPopup(True)
self.calCombinedDateTimeIllum.setObjectName(_fromUtf8("calCombinedDateTimeIllum"))
self.cmbCombinedTimeIllum = QtGui.QComboBox(self.groupCombinedNavigateIlluminance)
self.cmbCombinedTimeIllum.setGeometry(QtCore.QRect(110, 30, 81, 21))
self.cmbCombinedTimeIllum.setObjectName(_fromUtf8("cmbCombinedTimeIllum"))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.cmbCombinedTimeIllum.addItem(_fromUtf8(""))
self.tabWidget.addTab(self.tabCombined, _fromUtf8(""))
self.grpFileDialog = QtGui.QGroupBox(Form)
self.grpFileDialog.setEnabled(True)
self.grpFileDialog.setGeometry(QtCore.QRect(-10, -10, 981, 41))
self.grpFileDialog.setTitle(_fromUtf8(""))
self.grpFileDialog.setObjectName(_fromUtf8("grpFileDialog"))
self.btnOpenJson = QtGui.QPushButton(self.grpFileDialog)
self.btnOpenJson.setGeometry(QtCore.QRect(10, 10, 101, 23))
self.btnOpenJson.setObjectName(_fromUtf8("btnOpenJson"))
self.txtJsonPath = QtGui.QLineEdit(self.grpFileDialog)
self.txtJsonPath.setEnabled(False)
self.txtJsonPath.setGeometry(QtCore.QRect(120, 10, 511, 23))
self.txtJsonPath.setReadOnly(False)
self.txtJsonPath.setObjectName(_fromUtf8("txtJsonPath"))
self.cmbSpaceName = QtGui.QComboBox(self.grpFileDialog)
self.cmbSpaceName.setEnabled(False)
self.cmbSpaceName.setGeometry(QtCore.QRect(710, 10, 161, 23))
self.cmbSpaceName.setObjectName(_fromUtf8("cmbSpaceName"))
self.btnSelectSpaceName = QtGui.QPushButton(self.grpFileDialog)
self.btnSelectSpaceName.setEnabled(False)
self.btnSelectSpaceName.setGeometry(QtCore.QRect(890, 10, 91, 23))
self.btnSelectSpaceName.setObjectName(_fromUtf8("btnSelectSpaceName"))
self.lblSpaceName = QtGui.QLabel(self.grpFileDialog)
self.lblSpaceName.setGeometry(QtCore.QRect(660, 10, 46, 23))
self.lblSpaceName.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lblSpaceName.setObjectName(_fromUtf8("lblSpaceName"))
self.retranslateUi(Form)
self.tabWidget.setCurrentIndex(0)
self.cmbSpaceTimeIllum.setCurrentIndex(8)
self.cmbSpaceTimeIntervalMin.setCurrentIndex(8)
self.cmbSpaceTimeIntervalMax.setCurrentIndex(8)
self.cmbSpaceContourQuantity.setCurrentIndex(6)
self.cmbCombinedTimeIntervalMax.setCurrentIndex(8)
self.cmbCombinedTimeIntervalMin.setCurrentIndex(8)
self.cmbCombinedTimeIllum.setCurrentIndex(8)
QtCore.QMetaObject.connectSlotsByName(Form)
Form.setTabOrder(self.cmbSpacePlotType, self.cmbSpaceSelectIlluminanceFile)
Form.setTabOrder(self.cmbSpaceSelectIlluminanceFile, self.calSpaceDateTimeIllum)
Form.setTabOrder(self.calSpaceDateTimeIllum, self.cmbSpaceTimeIllum)
Form.setTabOrder(self.cmbSpaceTimeIllum, self.chkSpaceContours)
Form.setTabOrder(self.chkSpaceContours, self.btnSpaceSettingsContour)
Form.setTabOrder(self.btnSpaceSettingsContour, self.chkSpaceColors)
Form.setTabOrder(self.chkSpaceColors, self.btnSpaceSettingsColours)
Form.setTabOrder(self.btnSpaceSettingsColours, self.btnSpaceSetContours)
Form.setTabOrder(self.btnSpaceSetContours, self.btnSpaceResetColors)
Form.setTabOrder(self.btnSpaceResetColors, self.txtSpaceColorsMax)
Form.setTabOrder(self.txtSpaceColorsMax, self.txtSpaceColorsMin)
Form.setTabOrder(self.txtSpaceColorsMin, self.btnSelectColorUpperMask)
Form.setTabOrder(self.btnSelectColorUpperMask, self.txtSpaceColorsUpperMask)
Form.setTabOrder(self.txtSpaceColorsUpperMask, self.btnSelectColorLowerMask)
Form.setTabOrder(self.btnSelectColorLowerMask, self.txtSpaceColorsLowerMask)
Form.setTabOrder(self.txtSpaceColorsLowerMask, self.btnSpaceSetColors)
Form.setTabOrder(self.btnSpaceSetColors, self.cmbSpaceColorScheme)
Form.setTabOrder(self.cmbSpaceColorScheme, self.chkSpaceColorSchemeInvert)
Form.setTabOrder(self.chkSpaceColorSchemeInvert, self.sliderSpaceOpacity)
Form.setTabOrder(self.sliderSpaceOpacity, self.txtSpaceOpacityValue)
Form.setTabOrder(self.txtSpaceOpacityValue, self.btnSpaceSetColorScheme)
Form.setTabOrder(self.btnSpaceSetColorScheme, self.txtJsonPath)
Form.setTabOrder(self.txtJsonPath, self.cmbSpaceName)
Form.setTabOrder(self.cmbSpaceName, self.btnOpenJson)
Form.setTabOrder(self.btnOpenJson, self.tabWidget)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "STADICvis 1.3", None))
self.grpSpaceIlluminance.setTitle(_translate("Form", "Illuminance Settings", None))
self.groupSpaceNavigateIlluminance.setToolTip(_translate("Form", "The navigation settings can be used to view plots corresponding to different dates and hours.", None))
self.groupSpaceNavigateIlluminance.setTitle(_translate("Form", "Navigate", None))
self.cmbSpaceTimeIllum.setToolTip(_translate("Form", "Select a time for which the readStadicData is to be displayed.", None))
self.cmbSpaceTimeIllum.setItemText(0, _translate("Form", "1", None))
self.cmbSpaceTimeIllum.setItemText(1, _translate("Form", "2", None))
self.cmbSpaceTimeIllum.setItemText(2, _translate("Form", "3", None))
self.cmbSpaceTimeIllum.setItemText(3, _translate("Form", "4", None))
self.cmbSpaceTimeIllum.setItemText(4, _translate("Form", "5", None))
self.cmbSpaceTimeIllum.setItemText(5, _translate("Form", "6", None))
self.cmbSpaceTimeIllum.setItemText(6, _translate("Form", "7", None))
self.cmbSpaceTimeIllum.setItemText(7, _translate("Form", "8", None))
self.cmbSpaceTimeIllum.setItemText(8, _translate("Form", "9", None))
self.cmbSpaceTimeIllum.setItemText(9, _translate("Form", "10", None))
self.cmbSpaceTimeIllum.setItemText(10, _translate("Form", "11", None))
self.cmbSpaceTimeIllum.setItemText(11, _translate("Form", "12", None))
self.cmbSpaceTimeIllum.setItemText(12, _translate("Form", "13", None))
self.cmbSpaceTimeIllum.setItemText(13, _translate("Form", "14", None))
self.cmbSpaceTimeIllum.setItemText(14, _translate("Form", "15", None))
self.cmbSpaceTimeIllum.setItemText(15, _translate("Form", "16", None))
self.cmbSpaceTimeIllum.setItemText(16, _translate("Form", "17", None))
self.cmbSpaceTimeIllum.setItemText(17, _translate("Form", "18", None))
self.cmbSpaceTimeIllum.setItemText(18, _translate("Form", "19", None))
self.cmbSpaceTimeIllum.setItemText(19, _translate("Form", "20", None))
self.cmbSpaceTimeIllum.setItemText(20, _translate("Form", "21", None))
self.cmbSpaceTimeIllum.setItemText(21, _translate("Form", "22", None))
self.cmbSpaceTimeIllum.setItemText(22, _translate("Form", "23", None))
self.cmbSpaceTimeIllum.setItemText(23, _translate("Form", "24", None))
self.lblSpaceTime.setText(_translate("Form", "Time", None))
self.calSpaceDateTimeIllum.setToolTip(_translate("Form", "<html><head/><body><p>Select a date by clicking on the pop-up calendar. Please note that selecting a year has no bearing on the readStadicData being displayed.The year shown in the calendar was chosen based on the \'first_day\' option in the STADIC json file.</p></body></html>", None))
self.calSpaceDateTimeIllum.setDisplayFormat(_translate("Form", "MMMM/d", None))
self.lblSpaceDate.setText(_translate("Form", "Date", None))
self.cmbSpaceTimeIntervalMin.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.cmbSpaceTimeIntervalMin.setItemText(0, _translate("Form", "1", None))
self.cmbSpaceTimeIntervalMin.setItemText(1, _translate("Form", "2", None))
self.cmbSpaceTimeIntervalMin.setItemText(2, _translate("Form", "3", None))
self.cmbSpaceTimeIntervalMin.setItemText(3, _translate("Form", "4", None))
self.cmbSpaceTimeIntervalMin.setItemText(4, _translate("Form", "5", None))
self.cmbSpaceTimeIntervalMin.setItemText(5, _translate("Form", "6", None))
self.cmbSpaceTimeIntervalMin.setItemText(6, _translate("Form", "7", None))
self.cmbSpaceTimeIntervalMin.setItemText(7, _translate("Form", "8", None))
self.cmbSpaceTimeIntervalMin.setItemText(8, _translate("Form", "9", None))
self.cmbSpaceTimeIntervalMin.setItemText(9, _translate("Form", "10", None))
self.cmbSpaceTimeIntervalMin.setItemText(10, _translate("Form", "11", None))
self.cmbSpaceTimeIntervalMin.setItemText(11, _translate("Form", "12", None))
self.cmbSpaceTimeIntervalMin.setItemText(12, _translate("Form", "13", None))
self.cmbSpaceTimeIntervalMin.setItemText(13, _translate("Form", "14", None))
self.cmbSpaceTimeIntervalMin.setItemText(14, _translate("Form", "15", None))
self.cmbSpaceTimeIntervalMin.setItemText(15, _translate("Form", "16", None))
self.cmbSpaceTimeIntervalMin.setItemText(16, _translate("Form", "17", None))
self.cmbSpaceTimeIntervalMin.setItemText(17, _translate("Form", "18", None))
self.cmbSpaceTimeIntervalMin.setItemText(18, _translate("Form", "19", None))
self.cmbSpaceTimeIntervalMin.setItemText(19, _translate("Form", "20", None))
self.cmbSpaceTimeIntervalMin.setItemText(20, _translate("Form", "21", None))
self.cmbSpaceTimeIntervalMin.setItemText(21, _translate("Form", "22", None))
self.cmbSpaceTimeIntervalMin.setItemText(22, _translate("Form", "23", None))
self.cmbSpaceTimeIntervalMin.setItemText(23, _translate("Form", "24", None))
self.lblSpaceTimeStep.setToolTip(_translate("Form", "The Time Step settings can be used to specify a time step for navigating between different plots.", None))
self.lblSpaceTimeStep.setText(_translate("Form", "Time Step", None))
self.cmbSpaceIlluminanceStepType.setToolTip(_translate("Form", "Choose between an hour or day.", None))
self.cmbSpaceIlluminanceStepType.setItemText(0, _translate("Form", "Hour", None))
self.cmbSpaceIlluminanceStepType.setItemText(1, _translate("Form", "Day", None))
self.cmbSpaceTimeIntervalMax.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.cmbSpaceTimeIntervalMax.setItemText(0, _translate("Form", "1", None))
self.cmbSpaceTimeIntervalMax.setItemText(1, _translate("Form", "2", None))
self.cmbSpaceTimeIntervalMax.setItemText(2, _translate("Form", "3", None))
self.cmbSpaceTimeIntervalMax.setItemText(3, _translate("Form", "4", None))
self.cmbSpaceTimeIntervalMax.setItemText(4, _translate("Form", "5", None))
self.cmbSpaceTimeIntervalMax.setItemText(5, _translate("Form", "6", None))
self.cmbSpaceTimeIntervalMax.setItemText(6, _translate("Form", "7", None))
self.cmbSpaceTimeIntervalMax.setItemText(7, _translate("Form", "8", None))
self.cmbSpaceTimeIntervalMax.setItemText(8, _translate("Form", "9", None))
self.cmbSpaceTimeIntervalMax.setItemText(9, _translate("Form", "10", None))
self.cmbSpaceTimeIntervalMax.setItemText(10, _translate("Form", "11", None))
self.cmbSpaceTimeIntervalMax.setItemText(11, _translate("Form", "12", None))
self.cmbSpaceTimeIntervalMax.setItemText(12, _translate("Form", "13", None))
self.cmbSpaceTimeIntervalMax.setItemText(13, _translate("Form", "14", None))
self.cmbSpaceTimeIntervalMax.setItemText(14, _translate("Form", "15", None))
self.cmbSpaceTimeIntervalMax.setItemText(15, _translate("Form", "16", None))
self.cmbSpaceTimeIntervalMax.setItemText(16, _translate("Form", "17", None))
self.cmbSpaceTimeIntervalMax.setItemText(17, _translate("Form", "18", None))
self.cmbSpaceTimeIntervalMax.setItemText(18, _translate("Form", "19", None))
self.cmbSpaceTimeIntervalMax.setItemText(19, _translate("Form", "20", None))
self.cmbSpaceTimeIntervalMax.setItemText(20, _translate("Form", "21", None))
self.cmbSpaceTimeIntervalMax.setItemText(21, _translate("Form", "22", None))
self.cmbSpaceTimeIntervalMax.setItemText(22, _translate("Form", "23", None))
self.cmbSpaceTimeIntervalMax.setItemText(23, _translate("Form", "24", None))
self.chkSpaceSkipDarkHours.setToolTip(_translate("Form", "Check this to skip over hours for which illuminance at every grid point is zero.", None))
self.chkSpaceSkipDarkHours.setText(_translate("Form", "Skip dark hours", None))
self.lblSpaceDayInterval.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.lblSpaceDayInterval.setText(_translate("Form", "Intvl", None))
self.cmbSpaceIluminanceStepValue.setToolTip(_translate("Form", "Choose a multiplier for the timestep.", None))
self.cmbSpaceIluminanceStepValue.setItemText(0, _translate("Form", "1", None))
self.cmbSpaceIluminanceStepValue.setItemText(1, _translate("Form", "2", None))
self.cmbSpaceIluminanceStepValue.setItemText(2, _translate("Form", "3", None))
self.cmbSpaceIluminanceStepValue.setItemText(3, _translate("Form", "4", None))
self.cmbSpaceIluminanceStepValue.setItemText(4, _translate("Form", "5", None))
self.cmbSpaceIluminanceStepValue.setItemText(5, _translate("Form", "6", None))
self.cmbSpaceIluminanceStepValue.setItemText(6, _translate("Form", "7", None))
self.cmbSpaceIluminanceStepValue.setItemText(7, _translate("Form", "8", None))
self.cmbSpaceIluminanceStepValue.setItemText(8, _translate("Form", "9", None))
self.cmbSpaceIluminanceStepValue.setItemText(9, _translate("Form", "10", None))
self.cmbSpaceIluminanceStepValue.setItemText(10, _translate("Form", "11", None))
self.cmbSpaceIluminanceStepValue.setItemText(11, _translate("Form", "12", None))
self.cmbSpaceIluminanceStepValue.setItemText(12, _translate("Form", "13", None))
self.cmbSpaceIluminanceStepValue.setItemText(13, _translate("Form", "14", None))
self.cmbSpaceIluminanceStepValue.setItemText(14, _translate("Form", "15", None))
self.cmbSpaceIluminanceStepValue.setItemText(15, _translate("Form", "16", None))
self.cmbSpaceIluminanceStepValue.setItemText(16, _translate("Form", "17", None))
self.cmbSpaceIluminanceStepValue.setItemText(17, _translate("Form", "18", None))
self.cmbSpaceIluminanceStepValue.setItemText(18, _translate("Form", "19", None))
self.cmbSpaceIluminanceStepValue.setItemText(19, _translate("Form", "20", None))
self.cmbSpaceIluminanceStepValue.setItemText(20, _translate("Form", "21", None))
self.cmbSpaceIluminanceStepValue.setItemText(21, _translate("Form", "22", None))
self.cmbSpaceIluminanceStepValue.setItemText(22, _translate("Form", "23", None))
self.cmbSpaceIluminanceStepValue.setItemText(23, _translate("Form", "24", None))
self.btnSpacePrevHour.setToolTip(_translate("Form", "Click to plot the previous hour/day as per the options specified in the controls below.", None))
self.btnSpacePrevHour.setText(_translate("Form", "Previous", None))
self.btnSpaceNextHour.setToolTip(_translate("Form", "Click to plot the next hour/day as per the options specified in the controls below.", None))
self.btnSpaceNextHour.setText(_translate("Form", "Next", None))
self.cmbSpaceSelectIlluminanceFile.setToolTip(_translate("Form", "<html><head/><body><p>Select the annual illuminance readStadicData that is to be plotted. The readStadicData selected by default is from the final illuminance file.</p><p>If present, (WG) and (Set.) in the name indicate Window Group and Shade Setting respectively.</p></body></html>", None))
self.cmbSpacePlotType.setToolTip(_translate("Form", "Select the type of readStadicData that you wish to plot", None))
self.lblSpaceChartOpacity.setToolTip(_translate("Form", "Select an opacity for the colors in the chart by using the slider.", None))
self.lblSpaceChartOpacity.setText(_translate("Form", "Select Chart Opacity", None))
self.txtSpaceOpacityValue.setPlaceholderText(_translate("Form", "100", None))
self.sliderSpaceOpacity.setToolTip(_translate("Form", "Select an opacity for the colors in the chart by using the slider.", None))
self.lblSpaceColorSchemeSelect.setText(_translate("Form", "Color Scheme", None))
self.cmbSpaceColorScheme.setToolTip(_translate("Form", "Select a color scheme for the chart.", None))
self.chkSpaceColorSchemeInvert.setToolTip(_translate("Form", "Check this box to invert the selected color scheme.", None))
self.chkSpaceColorSchemeInvert.setText(_translate("Form", "Invert", None))
self.btnSpaceSetColorScheme.setToolTip(_translate("Form", "Click to confirm the Color Scheme and Opacity settings.", None))
self.btnSpaceSetColorScheme.setText(_translate("Form", "Confirm", None))
self.chkSpaceColorSchemeInterpolate.setToolTip(_translate("Form", "Check this box to show discrete color patches in the plot.", None))
self.chkSpaceColorSchemeInterpolate.setText(_translate("Form", "Discretize", None))
self.txtSpaceMsgBox.setToolTip(_translate("Form", "This text panel displays readStadicData pertaining to visualizations and file paths which might be helpful in troubleshooting errors.", None))
self.btnSelectColorLowerMask.setToolTip(_translate("Form", "This option can be used to assign a specifc color to grid points which are lesser than the value specified in the text box below.", None))
self.btnSelectColorLowerMask.setText(_translate("Form", "Lower Mask", None))
self.lblSpaceColorMinLimit.setToolTip(_translate("Form", "The minimum limit specifies the lowest value for the color grid.", None))
self.lblSpaceColorMinLimit.setText(_translate("Form", "Minimum Limit", None))
self.txtSpaceColorsMin.setToolTip(_translate("Form", "The minimum limit specifies the lowest value for the color grid.", None))
self.btnSelectColorUpperMask.setToolTip(_translate("Form", "This option can be used to assign a specifc color to grid points which are greater than the value specified in the text box below.", None))
self.btnSelectColorUpperMask.setText(_translate("Form", "Upper Mask", None))
self.txtSpaceColorsMax.setToolTip(_translate("Form", "The maximum limit specifies the highest value for the color grid.", None))
self.lblSpaceColorMaxLimit.setToolTip(_translate("Form", "The maximum limit specifies the highest value for the color grid.", None))
self.lblSpaceColorMaxLimit.setText(_translate("Form", "Maximum Limit", None))
self.txtSpaceColorsUpperMask.setToolTip(_translate("Form", "Enter a positive number. The value of the upper mask should be always higher than the lower mask.", None))
self.txtSpaceColorsLowerMask.setToolTip(_translate("Form", "Enter a positive number. The value of the upper mask should be always higher than the lower mask.", None))
self.btnSpaceSetColors.setToolTip(_translate("Form", "Click to confirm the color settings.", None))
self.btnSpaceSetColors.setText(_translate("Form", "Confirm", None))
self.btnSpaceResetColors.setToolTip(_translate("Form", "Click to reset the color settings to their default values.", None))
self.btnSpaceResetColors.setText(_translate("Form", "Reset", None))
self.chkSpaceContours.setToolTip(_translate("Form", "Click to toggle between contour display on the chart.", None))
self.chkSpaceContours.setText(_translate("Form", "Contours", None))
self.btnSpaceSetContours.setToolTip(_translate("Form", "Click to confirm the contour settings.", None))
self.btnSpaceSetContours.setText(_translate("Form", "Confirm", None))
self.txtSpaceCountourValue6.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.btnSpaceResetContours.setToolTip(_translate("Form", "Click to reset the contour settings to their default values.", None))
self.btnSpaceResetContours.setText(_translate("Form", "Reset", None))
self.txtSpaceCountourValue7.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.txtSpaceCountourValue5.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.txtSpaceCountourValue4.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.txtSpaceCountourValue1.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.txtSpaceCountourValue2.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.txtSpaceCountourValue3.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.cmbSpaceContourQuantity.setToolTip(_translate("Form", "Select the number of contour lines on the plot.", None))
self.cmbSpaceContourQuantity.setItemText(0, _translate("Form", "2", None))
self.cmbSpaceContourQuantity.setItemText(1, _translate("Form", "3", None))
self.cmbSpaceContourQuantity.setItemText(2, _translate("Form", "4", None))
self.cmbSpaceContourQuantity.setItemText(3, _translate("Form", "5", None))
self.cmbSpaceContourQuantity.setItemText(4, _translate("Form", "6", None))
self.cmbSpaceContourQuantity.setItemText(5, _translate("Form", "7", None))
self.cmbSpaceContourQuantity.setItemText(6, _translate("Form", "8", None))
self.txtSpaceCountourValue8.setToolTip(_translate("Form", "Enter a positive number to set a contour line.", None))
self.btnSpaceSettingsColours.setToolTip(_translate("Form", "Click to show further settings.", None))
self.btnSpaceSettingsColours.setText(_translate("Form", "Show Settings", None))
self.btnSpaceSettingsContour.setToolTip(_translate("Form", "Click to show further settings.", None))
self.btnSpaceSettingsContour.setText(_translate("Form", "Show Settings", None))
self.chkSpaceColors.setToolTip(_translate("Form", "Click to toggle between display of colored grids on the plot.", None))
self.chkSpaceColors.setText(_translate("Form", "Colors", None))
self.txtSpaceErrorBox.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;\"><br /></p></body></html>", None))
self.lblSpaceProjectLog.setText(_translate("Form", "Project Data Log", None))
self.lblSpaceErrorLog.setText(_translate("Form", "Errors and Warnings", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabSpace), _translate("Form", "Spatial Plots", None))
self.lblTimeSeriesChartOpacity.setToolTip(_translate("Form", "Select an opacity for the colors in the chart by using the slider.", None))
self.lblTimeSeriesChartOpacity.setText(_translate("Form", "Select Chart Opacity", None))
self.txtTimeSeriesOpacityValue.setPlaceholderText(_translate("Form", "100", None))
self.sliderTimeSeriesOpacity.setToolTip(_translate("Form", "Select an opacity for the colors in the chart by using the slider.", None))
self.lblTimeSeriesColorSchemeSelect.setText(_translate("Form", "Color Scheme", None))
self.cmbTimeSeriesColorScheme.setToolTip(_translate("Form", "Select a color scheme for the chart.", None))
self.chkTimeSeriesColorSchemeInvert.setToolTip(_translate("Form", "Check this box to invert the selected color scheme.", None))
self.chkTimeSeriesColorSchemeInvert.setText(_translate("Form", "Invert", None))
self.btnTimeSeriesSetColorScheme.setToolTip(_translate("Form", "Click to confirm the Color Scheme and Opacity settings.", None))
self.btnTimeSeriesSetColorScheme.setText(_translate("Form", "Confirm", None))
self.grpTimeSeriesChart1.setToolTip(_translate("Form", "The controls in this group are meant for selecting thermal plots", None))
self.grpTimeSeriesChart1.setTitle(_translate("Form", "Chart 1", None))
self.cmbTimeSeriesPlotType.setToolTip(_translate("Form", "Select the type of readStadicData that you wish to plot", None))
self.txtTimeSeriesChart1Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.txtTimeSeriesChart1Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.btnTimeSeriesChart1.setToolTip(_translate("Form", "Click to confirm the thermal plot details.", None))
self.btnTimeSeriesChart1.setText(_translate("Form", "Confirm", None))
self.lblTimeSeriesChart1Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.lblTimeSeriesChart1Max.setText(_translate("Form", "Max", None))
self.lblTimeSeriesChart1Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.lblTimeSeriesChart1Min.setText(_translate("Form", "Min", None))
self.grpTimeSeriesChart2.setTitle(_translate("Form", "Chart 2", None))
self.txtTimeSeriesChart2Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.txtTimeSeriesChart2Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.btnTimeSeriesChart2.setToolTip(_translate("Form", "Click to confirm the thermal plot details.", None))
self.btnTimeSeriesChart2.setText(_translate("Form", "Confirm", None))
self.cmbTimeSeriesPlotType2.setToolTip(_translate("Form", "Select the type of readStadicData that you wish to plot", None))
self.lblTimeSeriesChart2Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.lblTimeSeriesChart2Max.setText(_translate("Form", "Max", None))
self.lblTimeSeriesChart2Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.lblTimeSeriesChart2Min.setText(_translate("Form", "Min", None))
self.grpTimeSeriesChart3.setTitle(_translate("Form", "Chart 3", None))
self.btnTimeSeriesChart3.setToolTip(_translate("Form", "Click to confirm the thermal plot details.", None))
self.btnTimeSeriesChart3.setText(_translate("Form", "Confirm", None))
self.lblTimeSeriesChart3Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.lblTimeSeriesChart3Min.setText(_translate("Form", "Min", None))
self.txtTimeSeriesChart3Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.cmbTimeSeriesPlotType3.setToolTip(_translate("Form", "Select the type of readStadicData that you wish to plot", None))
self.lblTimeSeriesChart3Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.lblTimeSeriesChart3Max.setText(_translate("Form", "Max", None))
self.txtTimeSeriesChart3Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.grpTimeSeriesChart4.setTitle(_translate("Form", "Chart 4", None))
self.btnTimeSeriesChart4.setToolTip(_translate("Form", "Click to confirm the thermal plot details.", None))
self.btnTimeSeriesChart4.setText(_translate("Form", "Confirm", None))
self.lblTimeSeriesChart4Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.lblTimeSeriesChart4Min.setText(_translate("Form", "Min", None))
self.txtTimeSeriesChart4Min.setToolTip(_translate("Form", "Set the minimum value for the thermal plot.", None))
self.cmbTimeSeriesPlotType4.setToolTip(_translate("Form", "Select the type of readStadicData that you wish to plot", None))
self.txtTimeSeriesChart4Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.lblTimeSeriesChart4Max.setToolTip(_translate("Form", "Set the maximum value for the thermal plot", None))
self.lblTimeSeriesChart4Max.setText(_translate("Form", "Max", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabTimeSeries), _translate("Form", "Time Series Plots", None))
self.grpCombinedIlluminance.setTitle(_translate("Form", "Illuminance Settings", None))
self.cmbCombinedSelectIlluminanceFile.setToolTip(_translate("Form", "<html><head/><body><p>Select the annual illuminance readStadicData that is to be plotted. The readStadicData selected by default is from the final illuminance file.</p></body></html>", None))
self.groupCombinedNavigateIlluminance.setTitle(_translate("Form", "Navigate", None))
self.cmbCombinedlluminanceStepType.setToolTip(_translate("Form", "Choose between an hour or day.", None))
self.cmbCombinedlluminanceStepType.setItemText(0, _translate("Form", "Hour", None))
self.cmbCombinedlluminanceStepType.setItemText(1, _translate("Form", "Day", None))
self.cmbCombinedTimeIntervalMax.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.cmbCombinedTimeIntervalMax.setItemText(0, _translate("Form", "1", None))
self.cmbCombinedTimeIntervalMax.setItemText(1, _translate("Form", "2", None))
self.cmbCombinedTimeIntervalMax.setItemText(2, _translate("Form", "3", None))
self.cmbCombinedTimeIntervalMax.setItemText(3, _translate("Form", "4", None))
self.cmbCombinedTimeIntervalMax.setItemText(4, _translate("Form", "5", None))
self.cmbCombinedTimeIntervalMax.setItemText(5, _translate("Form", "6", None))
self.cmbCombinedTimeIntervalMax.setItemText(6, _translate("Form", "7", None))
self.cmbCombinedTimeIntervalMax.setItemText(7, _translate("Form", "8", None))
self.cmbCombinedTimeIntervalMax.setItemText(8, _translate("Form", "9", None))
self.cmbCombinedTimeIntervalMax.setItemText(9, _translate("Form", "10", None))
self.cmbCombinedTimeIntervalMax.setItemText(10, _translate("Form", "11", None))
self.cmbCombinedTimeIntervalMax.setItemText(11, _translate("Form", "12", None))
self.cmbCombinedTimeIntervalMax.setItemText(12, _translate("Form", "13", None))
self.cmbCombinedTimeIntervalMax.setItemText(13, _translate("Form", "14", None))
self.cmbCombinedTimeIntervalMax.setItemText(14, _translate("Form", "15", None))
self.cmbCombinedTimeIntervalMax.setItemText(15, _translate("Form", "16", None))
self.cmbCombinedTimeIntervalMax.setItemText(16, _translate("Form", "17", None))
self.cmbCombinedTimeIntervalMax.setItemText(17, _translate("Form", "18", None))
self.cmbCombinedTimeIntervalMax.setItemText(18, _translate("Form", "19", None))
self.cmbCombinedTimeIntervalMax.setItemText(19, _translate("Form", "20", None))
self.cmbCombinedTimeIntervalMax.setItemText(20, _translate("Form", "21", None))
self.cmbCombinedTimeIntervalMax.setItemText(21, _translate("Form", "22", None))
self.cmbCombinedTimeIntervalMax.setItemText(22, _translate("Form", "23", None))
self.cmbCombinedTimeIntervalMax.setItemText(23, _translate("Form", "24", None))
self.cmbCombinedTimeIntervalMin.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.cmbCombinedTimeIntervalMin.setItemText(0, _translate("Form", "1", None))
self.cmbCombinedTimeIntervalMin.setItemText(1, _translate("Form", "2", None))
self.cmbCombinedTimeIntervalMin.setItemText(2, _translate("Form", "3", None))
self.cmbCombinedTimeIntervalMin.setItemText(3, _translate("Form", "4", None))
self.cmbCombinedTimeIntervalMin.setItemText(4, _translate("Form", "5", None))
self.cmbCombinedTimeIntervalMin.setItemText(5, _translate("Form", "6", None))
self.cmbCombinedTimeIntervalMin.setItemText(6, _translate("Form", "7", None))
self.cmbCombinedTimeIntervalMin.setItemText(7, _translate("Form", "8", None))
self.cmbCombinedTimeIntervalMin.setItemText(8, _translate("Form", "9", None))
self.cmbCombinedTimeIntervalMin.setItemText(9, _translate("Form", "10", None))
self.cmbCombinedTimeIntervalMin.setItemText(10, _translate("Form", "11", None))
self.cmbCombinedTimeIntervalMin.setItemText(11, _translate("Form", "12", None))
self.cmbCombinedTimeIntervalMin.setItemText(12, _translate("Form", "13", None))
self.cmbCombinedTimeIntervalMin.setItemText(13, _translate("Form", "14", None))
self.cmbCombinedTimeIntervalMin.setItemText(14, _translate("Form", "15", None))
self.cmbCombinedTimeIntervalMin.setItemText(15, _translate("Form", "16", None))
self.cmbCombinedTimeIntervalMin.setItemText(16, _translate("Form", "17", None))
self.cmbCombinedTimeIntervalMin.setItemText(17, _translate("Form", "18", None))
self.cmbCombinedTimeIntervalMin.setItemText(18, _translate("Form", "19", None))
self.cmbCombinedTimeIntervalMin.setItemText(19, _translate("Form", "20", None))
self.cmbCombinedTimeIntervalMin.setItemText(20, _translate("Form", "21", None))
self.cmbCombinedTimeIntervalMin.setItemText(21, _translate("Form", "22", None))
self.cmbCombinedTimeIntervalMin.setItemText(22, _translate("Form", "23", None))
self.cmbCombinedTimeIntervalMin.setItemText(23, _translate("Form", "24", None))
self.chkCombinedSkipDarkHours.setToolTip(_translate("Form", "Check this to skip over hours for which illuminance at every grid point is zero.", None))
self.chkCombinedSkipDarkHours.setText(_translate("Form", "Skip dark hours", None))
self.btnCombinedPrevHour.setToolTip(_translate("Form", "Click to plot the previous hour/day as per the options specified in the controls below.", None))
self.btnCombinedPrevHour.setText(_translate("Form", "Previous", None))
self.lblCombinedDayInterval.setToolTip(_translate("Form", "The interval settings, both inclusive, can be used to specify the time intervals for which the readStadicData is to be shown.", None))
self.lblCombinedDayInterval.setText(_translate("Form", "Intvl", None))
self.btnCombinedNextHour.setToolTip(_translate("Form", "Click to plot the next hour/day as per the options specified in the controls below.", None))
self.btnCombinedNextHour.setText(_translate("Form", "Next", None))
self.cmbCombinedIluminanceStepValue.setToolTip(_translate("Form", "Choose a multiplier for the timestep.", None))
self.cmbCombinedIluminanceStepValue.setItemText(0, _translate("Form", "1", None))
self.cmbCombinedIluminanceStepValue.setItemText(1, _translate("Form", "2", None))
self.cmbCombinedIluminanceStepValue.setItemText(2, _translate("Form", "3", None))
self.cmbCombinedIluminanceStepValue.setItemText(3, _translate("Form", "4", None))
self.cmbCombinedIluminanceStepValue.setItemText(4, _translate("Form", "5", None))
self.cmbCombinedIluminanceStepValue.setItemText(5, _translate("Form", "6", None))
self.cmbCombinedIluminanceStepValue.setItemText(6, _translate("Form", "7", None))
self.cmbCombinedIluminanceStepValue.setItemText(7, _translate("Form", "8", None))
self.cmbCombinedIluminanceStepValue.setItemText(8, _translate("Form", "9", None))
self.cmbCombinedIluminanceStepValue.setItemText(9, _translate("Form", "10", None))
self.cmbCombinedIluminanceStepValue.setItemText(10, _translate("Form", "11", None))
self.cmbCombinedIluminanceStepValue.setItemText(11, _translate("Form", "12", None))
self.cmbCombinedIluminanceStepValue.setItemText(12, _translate("Form", "13", None))
self.cmbCombinedIluminanceStepValue.setItemText(13, _translate("Form", "14", None))
self.cmbCombinedIluminanceStepValue.setItemText(14, _translate("Form", "15", None))
self.cmbCombinedIluminanceStepValue.setItemText(15, _translate("Form", "16", None))
self.cmbCombinedIluminanceStepValue.setItemText(16, _translate("Form", "17", None))
self.cmbCombinedIluminanceStepValue.setItemText(17, _translate("Form", "18", None))
self.cmbCombinedIluminanceStepValue.setItemText(18, _translate("Form", "19", None))
self.cmbCombinedIluminanceStepValue.setItemText(19, _translate("Form", "20", None))
self.cmbCombinedIluminanceStepValue.setItemText(20, _translate("Form", "21", None))
self.cmbCombinedIluminanceStepValue.setItemText(21, _translate("Form", "22", None))
self.cmbCombinedIluminanceStepValue.setItemText(22, _translate("Form", "23", None))
self.cmbCombinedIluminanceStepValue.setItemText(23, _translate("Form", "24", None))
self.lblCombinedTimeStep.setToolTip(_translate("Form", "The Time Step settings can be used to specify a time step for navigating between different plots.", None))
self.lblCombinedTimeStep.setText(_translate("Form", "Time Step", None))
self.lblCombinedDate.setText(_translate("Form", "Date", None))
self.lblCombinedTime.setText(_translate("Form", "Time", None))
self.calCombinedDateTimeIllum.setToolTip(_translate("Form", "Select a date by clicking on the pop-up calendar. Please note that selecting a year has no bearing on the readStadicData being displayed.", None))
self.calCombinedDateTimeIllum.setDisplayFormat(_translate("Form", "MMMM/d", None))
self.cmbCombinedTimeIllum.setToolTip(_translate("Form", "Select a time for which the readStadicData is to be displayed.", None))
self.cmbCombinedTimeIllum.setItemText(0, _translate("Form", "1", None))
self.cmbCombinedTimeIllum.setItemText(1, _translate("Form", "2", None))
self.cmbCombinedTimeIllum.setItemText(2, _translate("Form", "3", None))
self.cmbCombinedTimeIllum.setItemText(3, _translate("Form", "4", None))
self.cmbCombinedTimeIllum.setItemText(4, _translate("Form", "5", None))
self.cmbCombinedTimeIllum.setItemText(5, _translate("Form", "6", None))
self.cmbCombinedTimeIllum.setItemText(6, _translate("Form", "7", None))
self.cmbCombinedTimeIllum.setItemText(7, _translate("Form", "8", None))
self.cmbCombinedTimeIllum.setItemText(8, _translate("Form", "9", None))
self.cmbCombinedTimeIllum.setItemText(9, _translate("Form", "10", None))
self.cmbCombinedTimeIllum.setItemText(10, _translate("Form", "11", None))
self.cmbCombinedTimeIllum.setItemText(11, _translate("Form", "12", None))
self.cmbCombinedTimeIllum.setItemText(12, _translate("Form", "13", None))
self.cmbCombinedTimeIllum.setItemText(13, _translate("Form", "14", None))
self.cmbCombinedTimeIllum.setItemText(14, _translate("Form", "15", None))
self.cmbCombinedTimeIllum.setItemText(15, _translate("Form", "16", None))
self.cmbCombinedTimeIllum.setItemText(16, _translate("Form", "17", None))
self.cmbCombinedTimeIllum.setItemText(17, _translate("Form", "18", None))
self.cmbCombinedTimeIllum.setItemText(18, _translate("Form", "19", None))
self.cmbCombinedTimeIllum.setItemText(19, _translate("Form", "20", None))
self.cmbCombinedTimeIllum.setItemText(20, _translate("Form", "21", None))
self.cmbCombinedTimeIllum.setItemText(21, _translate("Form", "22", None))
self.cmbCombinedTimeIllum.setItemText(22, _translate("Form", "23", None))
self.cmbCombinedTimeIllum.setItemText(23, _translate("Form", "24", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabCombined), _translate("Form", "Combined Plots", None))
self.btnOpenJson.setText(_translate("Form", "Open Json File", None))
self.btnSelectSpaceName.setText(_translate("Form", "Confirm", None))
self.lblSpaceName.setText(_translate("Form", "Space", None))
|
/** redux-logger with different defaults. */
const IS_BROWSER = typeof window === 'object'
const repeat = (str, times) => (new Array(times + 1)).join(str)
const pad = (num, maxLength) => repeat('0', maxLength - num.toString().length) + num
const formatTime = (time) => `@ ${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`
// Use the new performance api to get better precision if available
const timer = typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance : Date
/**
* parse the level option of createLogger
*
* @property {string | function | object} level - console[level]
* @property {object} action
* @property {array} payload
* @property {string} type
*/
function getLogLevel(level, action, payload, type) {
switch (typeof level) {
case 'object':
return typeof level[type] === 'function' ? level[type](...payload) : level[type]
case 'function':
return level(action)
default:
return level
}
}
/**
* Creates logger with followed options
*
* @namespace
* @property {object} options - options for logger
* @property {string | function | object} options.level - console[level]
* @property {boolean} options.duration - print duration of each action?
* @property {boolean} options.timestamp - print timestamp with each action?
* @property {object} options.colors - custom colors
* @property {object} options.logger - implementation of the `console` API
* @property {boolean} options.logErrors - should errors in action execution be caught, logged, and re-thrown?
* @property {boolean} options.collapsed - is group collapsed?
* @property {boolean} options.predicate - condition which resolves logger behavior
* @property {function} options.stateTransformer - transform state before print
* @property {function} options.actionTransformer - transform action before print
* @property {function} options.errorTransformer - transform error before print
*/
export default function createLogger( { level = IS_BROWSER ? 'info' : 'trace'
, logger = console
, logErrors = true
, collapsed = true
, predicate
, duration = false
, timestamp = true
, stateTransformer = state => state
, actionTransformer = actn => actn
, errorTransformer = error => error
, colors = { title: () => '#000000'
, prevState: () => '#9E9E9E'
, action: () => '#03A9F4'
, nextState: () => '#4CAF50'
, error: () => '#F20404'
}
} = {}) {
// exit if console undefined
if (typeof logger === 'undefined')
return () => next => action => next(action)
const logBuffer = []
function printBuffer() {
logBuffer.forEach((logEntry, key) => {
const { started, startedTime, action, prevState, error } = logEntry
let { took, nextState } = logEntry
const nextEntry = logBuffer[key + 1]
if (nextEntry) {
nextState = nextEntry.prevState
took = nextEntry.started - started
}
// message
const formattedAction = actionTransformer(action)
const isCollapsed = (typeof collapsed === 'function') ? collapsed(() => nextState, action) : collapsed
const formattedTime = formatTime(startedTime)
const titleCSS = colors.title ? `color: ${colors.title(formattedAction)};` : null
const title = `action ${timestamp ? formattedTime : ''} ${formattedAction.type} ${duration ? `(in ${took.toFixed(2)} ms)` : ''}`
// render
try {
if (isCollapsed) {
if (colors.title) logger.groupCollapsed(`%c ${title}`, titleCSS)
else logger.groupCollapsed(title)
} else {
if (colors.title) logger.group(`%c ${title}`, titleCSS)
else logger.group(title)
}
} catch (e) {
logger[level](title)
}
const prevStateLevel = getLogLevel(level, formattedAction, [prevState], 'prevState')
const actionLevel = getLogLevel(level, formattedAction, [formattedAction], 'action')
const errorLevel = getLogLevel(level, formattedAction, [error, prevState], 'error')
const nextStateLevel = getLogLevel(level, formattedAction, [nextState], 'nextState')
if (prevStateLevel) {
if (colors.prevState) logger[prevStateLevel]('%c prev state', `color: ${colors.prevState(prevState)}; font-weight: bold`, prevState)
else logger[prevStateLevel]('prev state', prevState)
}
if (actionLevel) {
if (colors.action) logger[actionLevel]('%c action', `color: ${colors.action(formattedAction)}; font-weight: bold`, formattedAction)
else logger[actionLevel]('action', formattedAction)
}
if (error && errorLevel) {
if (colors.error) logger[errorLevel]('%c error', `color: ${colors.error(error, prevState)}; font-weight: bold`, error)
else logger[errorLevel]('error', error)
}
if (nextStateLevel) {
if (colors.nextState) logger[nextStateLevel]('%c next state', `color: ${colors.nextState(nextState)}; font-weight: bold`, nextState)
else logger[nextStateLevel]('next state', nextState)
}
try {
logger.groupEnd()
} catch (e) {
logger[level]('—— log end ——')
}
})
logBuffer.length = 0
}
return ({ getState }) => (next) => (action) => {
// exit early if predicate function returns false
if (typeof predicate === 'function' && !predicate(getState, action))
return next(action)
const logEntry = {}
logBuffer.push(logEntry)
logEntry.started = timer.now()
logEntry.startedTime = new Date()
logEntry.prevState = stateTransformer(getState())
logEntry.action = action
let returnedValue
if (logErrors) {
try {
returnedValue = next(action)
} catch (e) {
logEntry.error = errorTransformer(e)
}
} else
returnedValue = next(action)
logEntry.took = timer.now() - logEntry.started
logEntry.nextState = stateTransformer(getState())
printBuffer()
if (logEntry.error) throw logEntry.error
return returnedValue
}
}
|
from dataclasses import dataclass
from typing import Optional
from ects.types.blockchain_format.sized_bytes import bytes32
from ects.util.ints import uint8, uint64
from ects.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class SubEpochSummary(Streamable):
prev_subepoch_summary_hash: bytes32
reward_chain_hash: bytes32 # hash of reward chain at end of last segment
num_blocks_overflow: uint8 # How many more blocks than 384*(N-1)
new_difficulty: Optional[uint64] # Only once per epoch (diff adjustment)
new_sub_slot_iters: Optional[uint64] # Only once per epoch (diff adjustment)
|
import BaseComponent from '../core/base-component.js'
class ButtonGroup extends BaseComponent {
static get EVENTS() {
return {
ANSWER: 'answer',
CORRECTION: 'correction',
}
}
constructor({
rootElement,
childsSelector,
childActiveClass,
answerCondition = (activeButton) => activeButton.type !== 'button',
}) {
super()
const buttons = rootElement?.querySelectorAll(childsSelector)
rootElement.addEventListener('click', (event) => {
const activeButton = event.target.closest(childsSelector)
if (!activeButton) {
return
}
for (const button of buttons) {
button.classList.toggle(childActiveClass, button === activeButton)
}
const isPositiveAnswer = answerCondition(activeButton)
const eventType = isPositiveAnswer ? ButtonGroup.EVENTS.ANSWER : ButtonGroup.EVENTS.CORRECTION
this.emit(eventType, activeButton.value)
})
}
}
class DetailedAnswer extends BaseComponent {
static get EVENTS() {
return {
ANSWER: 'answer',
}
}
static get TEXT_THRESHOLD() {
return 4
}
constructor({ rootElement }) {
super()
this.textarea = rootElement.querySelector('textarea')
this.button = rootElement.querySelector('button')
this.button.addEventListener('click', () => {
const text = this.textarea.value.trim()
if (text.length >= DetailedAnswer.TEXT_THRESHOLD) {
this.emit(DetailedAnswer.EVENTS.ANSWER, text)
}
})
;['keydown', 'keyup'].forEach((eventType) => {
this.textarea.addEventListener(eventType, (event) => {
event.stopPropagation()
})
})
}
focus() {
this.textarea.focus()
}
}
function init() {
const form = document.querySelector('.feedback-form')
if (!form) {
return
}
const voteDownButton = form.querySelector('.vote--down')
const voteUpButton = form.querySelector('.vote--up')
const reasonFieldset = form.querySelector('.feedback-form__fieldset--reason')
const textControl = form.querySelector('.feedback-form__text')
let isSending = false
function getToken() {
return fetch('/api.json')
.then((resp) => resp.json())
.then((access) => {
return access.token
})
}
function sendForm(formData) {
const body = JSON.stringify({
type: 'feedback',
data: JSON.stringify(formData),
author_id: 1,
})
const url = 'https://api.doka.guide/form'
return getToken()
.then((token) => {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: token,
},
body,
})
})
.then((response) => {
if (!response.ok) {
throw response
}
return response
})
}
const detailedAnswer = new DetailedAnswer({
rootElement: textControl,
})
detailedAnswer.on(DetailedAnswer.EVENTS.ANSWER, () => {
setTimeout(() => {
reasonFieldset.disabled = true
voteUpButton.disabled = true
})
})
const voteButtonGroup = new ButtonGroup({
rootElement: form.querySelector('.feedback-form__fieldset--vote'),
childsSelector: '.vote',
childActiveClass: 'vote--active',
})
voteButtonGroup.on(
ButtonGroup.EVENTS.ANSWER,
() => {
setTimeout(() => {
voteDownButton.disabled = true
reasonFieldset.disabled = true
})
},
{ once: true }
)
voteButtonGroup.on(ButtonGroup.EVENTS.CORRECTION, () => {
reasonFieldset.hidden = false
})
const reasonsButtonGroup = new ButtonGroup({
rootElement: reasonFieldset,
childsSelector: '.feedback-form__reason-button',
childActiveClass: 'button--active',
})
reasonsButtonGroup.on(
ButtonGroup.EVENTS.ANSWER,
() => {
setTimeout(() => {
reasonFieldset.disabled = true
voteUpButton.disabled = true
textControl.hidden = true
})
},
{ once: true }
)
reasonsButtonGroup.on(ButtonGroup.EVENTS.CORRECTION, () => {
textControl.hidden = false
detailedAnswer.focus()
})
form.addEventListener('submit', (event) => {
event.preventDefault()
if (isSending) {
return
}
const formData = new FormData(form)
const answer = formData.get('answer') || event.submitter?.value
if (!(answer && answer.length >= DetailedAnswer.TEXT_THRESHOLD)) {
return
}
isSending = true
sendForm({
answer,
article_id: window.location.pathname,
})
.then(() => {
form.dataset.state = 'success'
})
.catch((error) => {
form.dataset.state = 'error'
console.error(error)
})
.finally(() => {
isSending = false
})
})
}
try {
init()
} catch (error) {
console.error(error)
}
|
console.log('hello from main js');
var x,
calculate = function(number1, number2) {
return {
add: function() {
return number1 + number2;
},
subtract: function() {
return number1 - number2;
},
multiply: function() {
return number1 * number2;
},
divide: function() {
return number1 / number2;
},
factorial: function() {
var result = 1;
for (var i = 2; i <= number1; i++)
result = result * i;
return result;
}
}
};
// x = calculate(3, 4);
// console.log(x.add());
// console.log(x.subtract());
// console.log(x.multiply());
// console.log(x.divide());
// console.log(x.factorial());
|
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
// Mock数据服务
// const express = require('express')
// const app = express()
// const goodsData = require('../mock/goods.json')
// const apiRoutes = express.Router()
// app.use('/', apiRoutes)
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
// Mock数据服务
// before(app) {
// app.get('/goods', (req, res) => {
// res.json(goodsData)
// });
// }
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
|
import numpy as np
from numpy import testing
from skimage import data, color
from skimage.util import img_as_bool
from skimage.morphology import binary, grey, selem
lena = color.rgb2gray(data.lena())
bw_lena = lena > 100
def test_non_square_image():
strel = selem.square(3)
binary_res = binary.binary_erosion(bw_lena[:100, :200], strel)
grey_res = img_as_bool(grey.erosion(bw_lena[:100, :200], strel))
testing.assert_array_equal(binary_res, grey_res)
def test_binary_erosion():
strel = selem.square(3)
binary_res = binary.binary_erosion(bw_lena, strel)
grey_res = img_as_bool(grey.erosion(bw_lena, strel))
testing.assert_array_equal(binary_res, grey_res)
def test_binary_dilation():
strel = selem.square(3)
binary_res = binary.binary_dilation(bw_lena, strel)
grey_res = img_as_bool(grey.dilation(bw_lena, strel))
testing.assert_array_equal(binary_res, grey_res)
def test_binary_closing():
strel = selem.square(3)
binary_res = binary.binary_closing(bw_lena, strel)
grey_res = img_as_bool(grey.closing(bw_lena, strel))
testing.assert_array_equal(binary_res, grey_res)
def test_binary_opening():
strel = selem.square(3)
binary_res = binary.binary_opening(bw_lena, strel)
grey_res = img_as_bool(grey.opening(bw_lena, strel))
testing.assert_array_equal(binary_res, grey_res)
def test_selem_overflow():
strel = np.ones((17, 17), dtype=np.uint8)
img = np.zeros((20, 20))
img[2:19, 2:19] = 1
binary_res = binary.binary_erosion(img, strel)
grey_res = img_as_bool(grey.erosion(img, strel))
testing.assert_array_equal(binary_res, grey_res)
def test_out_argument():
for func in (binary.binary_erosion, binary.binary_dilation):
strel = np.ones((3, 3), dtype=np.uint8)
img = np.ones((10, 10))
out = np.zeros_like(img)
out_saved = out.copy()
func(img, strel, out=out)
testing.assert_(np.any(out != out_saved))
testing.assert_array_equal(out, func(img, strel))
if __name__ == '__main__':
testing.run_module_suite()
|
/* -------------------------------------------------------------------------
* i2c-algo-bit.c i2c driver algorithms for bit-shift adapters
* -------------------------------------------------------------------------
* Copyright (C) 1995-2000 Simon G. Vogl
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301 USA.
* ------------------------------------------------------------------------- */
/* With some changes from Frodo Looijaard <frodol@dds.nl>, Kyösti Mälkki
<kmalkki@cc.hut.fi> and Jean Delvare <jdelvare@suse.de> */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
/* ----- global defines ----------------------------------------------- */
#ifdef DEBUG
#define bit_dbg(level, dev, format, args...) \
do { \
if (i2c_debug >= level) \
dev_dbg(dev, format, ##args); \
} while (0)
#else
#define bit_dbg(level, dev, format, args...) \
do {} while (0)
#endif /* DEBUG */
/* ----- global variables --------------------------------------------- */
static int bit_test; /* see if the line-setting functions work */
module_param(bit_test, int, S_IRUGO);
MODULE_PARM_DESC(bit_test, "lines testing - 0 off; 1 report; 2 fail if stuck");
#ifdef DEBUG
static int i2c_debug = 1;
module_param(i2c_debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(i2c_debug,
"debug level - 0 off; 1 normal; 2 verbose; 3 very verbose");
#endif
/* --- setting states on the bus with the right timing: --------------- */
#define setsda(adap, val) adap->setsda(adap->data, val)
#define setscl(adap, val) adap->setscl(adap->data, val)
#define getsda(adap) adap->getsda(adap->data)
#define getscl(adap) adap->getscl(adap->data)
static inline void sdalo(struct i2c_algo_bit_data *adap)
{
setsda(adap, 0);
udelay((adap->udelay + 1) / 2);
}
static inline void sdahi(struct i2c_algo_bit_data *adap)
{
setsda(adap, 1);
udelay((adap->udelay + 1) / 2);
}
static inline void scllo(struct i2c_algo_bit_data *adap)
{
setscl(adap, 0);
udelay(adap->udelay / 2);
}
/*
* Raise scl line, and do checking for delays. This is necessary for slower
* devices.
*/
static int sclhi(struct i2c_algo_bit_data *adap)
{
unsigned long start;
setscl(adap, 1);
/* Not all adapters have scl sense line... */
if (!adap->getscl)
goto done;
start = jiffies;
while (!getscl(adap)) {
/* This hw knows how to read the clock line, so we wait
* until it actually gets high. This is safer as some
* chips may hold it low ("clock stretching") while they
* are processing data internally.
*/
if (time_after(jiffies, start + adap->timeout)) {
/* Test one last time, as we may have been preempted
* between last check and timeout test.
*/
if (getscl(adap))
break;
return -ETIMEDOUT;
}
cpu_relax();
}
#ifdef DEBUG
if (jiffies != start && i2c_debug >= 3)
pr_debug("i2c-algo-bit: needed %ld jiffies for SCL to go "
"high\n", jiffies - start);
#endif
done:
udelay(adap->udelay);
return 0;
}
/* --- other auxiliary functions -------------------------------------- */
static void i2c_start(struct i2c_algo_bit_data *adap)
{
/* assert: scl, sda are high */
setsda(adap, 0);
udelay(adap->udelay);
scllo(adap);
}
static void i2c_repstart(struct i2c_algo_bit_data *adap)
{
/* assert: scl is low */
sdahi(adap);
sclhi(adap);
setsda(adap, 0);
udelay(adap->udelay);
scllo(adap);
}
static void i2c_stop(struct i2c_algo_bit_data *adap)
{
/* assert: scl is low */
sdalo(adap);
sclhi(adap);
setsda(adap, 1);
udelay(adap->udelay);
}
/* send a byte without start cond., look for arbitration,
check ackn. from slave */
/* returns:
* 1 if the device acknowledged
* 0 if the device did not ack
* -ETIMEDOUT if an error occurred (while raising the scl line)
*/
static int i2c_outb(struct i2c_adapter *i2c_adap, unsigned char c)
{
int i;
int sb;
int ack;
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
/* assert: scl is low */
for (i = 7; i >= 0; i--) {
sb = (c >> i) & 1;
setsda(adap, sb);
udelay((adap->udelay + 1) / 2);
if (sclhi(adap) < 0) { /* timed out */
bit_dbg(1, &i2c_adap->dev, "i2c_outb: 0x%02x, "
"timeout at bit #%d\n", (int)c, i);
return -ETIMEDOUT;
}
/* FIXME do arbitration here:
* if (sb && !getsda(adap)) -> ouch! Get out of here.
*
* Report a unique code, so higher level code can retry
* the whole (combined) message and *NOT* issue STOP.
*/
scllo(adap);
}
sdahi(adap);
if (sclhi(adap) < 0) { /* timeout */
bit_dbg(1, &i2c_adap->dev, "i2c_outb: 0x%02x, "
"timeout at ack\n", (int)c);
return -ETIMEDOUT;
}
/* read ack: SDA should be pulled down by slave, or it may
* NAK (usually to report problems with the data we wrote).
*/
ack = !getsda(adap); /* ack: sda is pulled low -> success */
bit_dbg(2, &i2c_adap->dev, "i2c_outb: 0x%02x %s\n", (int)c,
ack ? "A" : "NA");
scllo(adap);
return ack;
/* assert: scl is low (sda undef) */
}
static int i2c_inb(struct i2c_adapter *i2c_adap)
{
/* read byte via i2c port, without start/stop sequence */
/* acknowledge is sent in i2c_read. */
int i;
unsigned char indata = 0;
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
/* assert: scl is low */
sdahi(adap);
for (i = 0; i < 8; i++) {
if (sclhi(adap) < 0) { /* timeout */
bit_dbg(1, &i2c_adap->dev, "i2c_inb: timeout at bit "
"#%d\n", 7 - i);
return -ETIMEDOUT;
}
indata *= 2;
if (getsda(adap))
indata |= 0x01;
setscl(adap, 0);
udelay(i == 7 ? adap->udelay / 2 : adap->udelay);
}
/* assert: scl is low */
return indata;
}
/*
* Sanity check for the adapter hardware - check the reaction of
* the bus lines only if it seems to be idle.
*/
static int test_bus(struct i2c_adapter *i2c_adap)
{
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
const char *name = i2c_adap->name;
int scl, sda, ret;
if (adap->pre_xfer) {
ret = adap->pre_xfer(i2c_adap);
if (ret < 0)
return -ENODEV;
}
if (adap->getscl == NULL)
pr_info("%s: Testing SDA only, SCL is not readable\n", name);
sda = getsda(adap);
scl = (adap->getscl == NULL) ? 1 : getscl(adap);
if (!scl || !sda) {
printk(KERN_WARNING
"%s: bus seems to be busy (scl=%d, sda=%d)\n",
name, scl, sda);
goto bailout;
}
sdalo(adap);
sda = getsda(adap);
scl = (adap->getscl == NULL) ? 1 : getscl(adap);
if (sda) {
printk(KERN_WARNING "%s: SDA stuck high!\n", name);
goto bailout;
}
if (!scl) {
printk(KERN_WARNING "%s: SCL unexpected low "
"while pulling SDA low!\n", name);
goto bailout;
}
sdahi(adap);
sda = getsda(adap);
scl = (adap->getscl == NULL) ? 1 : getscl(adap);
if (!sda) {
printk(KERN_WARNING "%s: SDA stuck low!\n", name);
goto bailout;
}
if (!scl) {
printk(KERN_WARNING "%s: SCL unexpected low "
"while pulling SDA high!\n", name);
goto bailout;
}
scllo(adap);
sda = getsda(adap);
scl = (adap->getscl == NULL) ? 0 : getscl(adap);
if (scl) {
printk(KERN_WARNING "%s: SCL stuck high!\n", name);
goto bailout;
}
if (!sda) {
printk(KERN_WARNING "%s: SDA unexpected low "
"while pulling SCL low!\n", name);
goto bailout;
}
sclhi(adap);
sda = getsda(adap);
scl = (adap->getscl == NULL) ? 1 : getscl(adap);
if (!scl) {
printk(KERN_WARNING "%s: SCL stuck low!\n", name);
goto bailout;
}
if (!sda) {
printk(KERN_WARNING "%s: SDA unexpected low "
"while pulling SCL high!\n", name);
goto bailout;
}
if (adap->post_xfer)
adap->post_xfer(i2c_adap);
pr_info("%s: Test OK\n", name);
return 0;
bailout:
sdahi(adap);
sclhi(adap);
if (adap->post_xfer)
adap->post_xfer(i2c_adap);
return -ENODEV;
}
/* ----- Utility functions
*/
/* try_address tries to contact a chip for a number of
* times before it gives up.
* return values:
* 1 chip answered
* 0 chip did not answer
* -x transmission error
*/
static int try_address(struct i2c_adapter *i2c_adap,
unsigned char addr, int retries)
{
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
int i, ret = 0;
for (i = 0; i <= retries; i++) {
ret = i2c_outb(i2c_adap, addr);
if (ret == 1 || i == retries)
break;
bit_dbg(3, &i2c_adap->dev, "emitting stop condition\n");
i2c_stop(adap);
udelay(adap->udelay);
yield();
bit_dbg(3, &i2c_adap->dev, "emitting start condition\n");
i2c_start(adap);
}
if (i && ret)
bit_dbg(1, &i2c_adap->dev, "Used %d tries to %s client at "
"0x%02x: %s\n", i + 1,
addr & 1 ? "read from" : "write to", addr >> 1,
ret == 1 ? "success" : "failed, timeout?");
return ret;
}
static int sendbytes(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
{
const unsigned char *temp = msg->buf;
int count = msg->len;
unsigned short nak_ok = msg->flags & I2C_M_IGNORE_NAK;
int retval;
int wrcount = 0;
while (count > 0) {
retval = i2c_outb(i2c_adap, *temp);
/* OK/ACK; or ignored NAK */
if ((retval > 0) || (nak_ok && (retval == 0))) {
count--;
temp++;
wrcount++;
/* A slave NAKing the master means the slave didn't like
* something about the data it saw. For example, maybe
* the SMBus PEC was wrong.
*/
} else if (retval == 0) {
dev_err(&i2c_adap->dev, "sendbytes: NAK bailout.\n");
return -EIO;
/* Timeout; or (someday) lost arbitration
*
* FIXME Lost ARB implies retrying the transaction from
* the first message, after the "winning" master issues
* its STOP. As a rule, upper layer code has no reason
* to know or care about this ... it is *NOT* an error.
*/
} else {
dev_err(&i2c_adap->dev, "sendbytes: error %d\n",
retval);
return retval;
}
}
return wrcount;
}
static int acknak(struct i2c_adapter *i2c_adap, int is_ack)
{
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
/* assert: sda is high */
if (is_ack) /* send ack */
setsda(adap, 0);
udelay((adap->udelay + 1) / 2);
if (sclhi(adap) < 0) { /* timeout */
dev_err(&i2c_adap->dev, "readbytes: ack/nak timeout\n");
return -ETIMEDOUT;
}
scllo(adap);
return 0;
}
static int readbytes(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
{
int inval;
int rdcount = 0; /* counts bytes read */
unsigned char *temp = msg->buf;
int count = msg->len;
const unsigned flags = msg->flags;
while (count > 0) {
inval = i2c_inb(i2c_adap);
if (inval >= 0) {
*temp = inval;
rdcount++;
} else { /* read timed out */
break;
}
temp++;
count--;
/* Some SMBus transactions require that we receive the
transaction length as the first read byte. */
if (rdcount == 1 && (flags & I2C_M_RECV_LEN)) {
if (inval <= 0 || inval > I2C_SMBUS_BLOCK_MAX) {
if (!(flags & I2C_M_NO_RD_ACK))
acknak(i2c_adap, 0);
dev_err(&i2c_adap->dev, "readbytes: invalid "
"block length (%d)\n", inval);
return -EPROTO;
}
/* The original count value accounts for the extra
bytes, that is, either 1 for a regular transaction,
or 2 for a PEC transaction. */
count += inval;
msg->len += inval;
}
bit_dbg(2, &i2c_adap->dev, "readbytes: 0x%02x %s\n",
inval,
(flags & I2C_M_NO_RD_ACK)
? "(no ack/nak)"
: (count ? "A" : "NA"));
if (!(flags & I2C_M_NO_RD_ACK)) {
inval = acknak(i2c_adap, count);
if (inval < 0)
return inval;
}
}
return rdcount;
}
/* doAddress initiates the transfer by generating the start condition (in
* try_address) and transmits the address in the necessary format to handle
* reads, writes as well as 10bit-addresses.
* returns:
* 0 everything went okay, the chip ack'ed, or IGNORE_NAK flag was set
* -x an error occurred (like: -ENXIO if the device did not answer, or
* -ETIMEDOUT, for example if the lines are stuck...)
*/
static int bit_doAddress(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
{
unsigned short flags = msg->flags;
unsigned short nak_ok = msg->flags & I2C_M_IGNORE_NAK;
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
unsigned char addr;
int ret, retries;
retries = nak_ok ? 0 : i2c_adap->retries;
if (flags & I2C_M_TEN) {
/* a ten bit address */
addr = 0xf0 | ((msg->addr >> 7) & 0x06);
bit_dbg(2, &i2c_adap->dev, "addr0: %d\n", addr);
/* try extended address code...*/
ret = try_address(i2c_adap, addr, retries);
if ((ret != 1) && !nak_ok) {
dev_err(&i2c_adap->dev,
"died at extended address code\n");
return -ENXIO;
}
/* the remaining 8 bit address */
ret = i2c_outb(i2c_adap, msg->addr & 0xff);
if ((ret != 1) && !nak_ok) {
/* the chip did not ack / xmission error occurred */
dev_err(&i2c_adap->dev, "died at 2nd address code\n");
return -ENXIO;
}
if (flags & I2C_M_RD) {
bit_dbg(3, &i2c_adap->dev, "emitting repeated "
"start condition\n");
i2c_repstart(adap);
/* okay, now switch into reading mode */
addr |= 0x01;
ret = try_address(i2c_adap, addr, retries);
if ((ret != 1) && !nak_ok) {
dev_err(&i2c_adap->dev,
"died at repeated address code\n");
return -EIO;
}
}
} else { /* normal 7bit address */
addr = msg->addr << 1;
if (flags & I2C_M_RD)
addr |= 1;
if (flags & I2C_M_REV_DIR_ADDR)
addr ^= 1;
ret = try_address(i2c_adap, addr, retries);
if ((ret != 1) && !nak_ok)
return -ENXIO;
}
return 0;
}
static int bit_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg msgs[], int num)
{
struct i2c_msg *pmsg;
struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
int i, ret;
unsigned short nak_ok;
if (adap->pre_xfer) {
ret = adap->pre_xfer(i2c_adap);
if (ret < 0)
return ret;
}
bit_dbg(3, &i2c_adap->dev, "emitting start condition\n");
i2c_start(adap);
for (i = 0; i < num; i++) {
pmsg = &msgs[i];
nak_ok = pmsg->flags & I2C_M_IGNORE_NAK;
if (!(pmsg->flags & I2C_M_NOSTART)) {
if (i) {
bit_dbg(3, &i2c_adap->dev, "emitting "
"repeated start condition\n");
i2c_repstart(adap);
}
ret = bit_doAddress(i2c_adap, pmsg);
if ((ret != 0) && !nak_ok) {
bit_dbg(1, &i2c_adap->dev, "NAK from "
"device addr 0x%02x msg #%d\n",
msgs[i].addr, i);
goto bailout;
}
}
if (pmsg->flags & I2C_M_RD) {
/* read bytes into buffer*/
ret = readbytes(i2c_adap, pmsg);
if (ret >= 1)
bit_dbg(2, &i2c_adap->dev, "read %d byte%s\n",
ret, ret == 1 ? "" : "s");
if (ret < pmsg->len) {
if (ret >= 0)
ret = -EIO;
goto bailout;
}
} else {
/* write bytes from buffer */
ret = sendbytes(i2c_adap, pmsg);
if (ret >= 1)
bit_dbg(2, &i2c_adap->dev, "wrote %d byte%s\n",
ret, ret == 1 ? "" : "s");
if (ret < pmsg->len) {
if (ret >= 0)
ret = -EIO;
goto bailout;
}
}
}
ret = i;
bailout:
bit_dbg(3, &i2c_adap->dev, "emitting stop condition\n");
i2c_stop(adap);
if (adap->post_xfer)
adap->post_xfer(i2c_adap);
return ret;
}
static u32 bit_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_NOSTART | I2C_FUNC_SMBUS_EMUL |
I2C_FUNC_SMBUS_READ_BLOCK_DATA |
I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
I2C_FUNC_10BIT_ADDR | I2C_FUNC_PROTOCOL_MANGLING;
}
/* -----exported algorithm data: ------------------------------------- */
const struct i2c_algorithm i2c_bit_algo = {
.master_xfer = bit_xfer,
.functionality = bit_func,
};
EXPORT_SYMBOL(i2c_bit_algo);
/*
* registering functions to load algorithms at runtime
*/
static int __i2c_bit_add_bus(struct i2c_adapter *adap,
int (*add_adapter)(struct i2c_adapter *))
{
struct i2c_algo_bit_data *bit_adap = adap->algo_data;
int ret;
if (bit_test) {
ret = test_bus(adap);
if (bit_test >= 2 && ret < 0)
return -ENODEV;
}
/* register new adapter to i2c module... */
adap->algo = &i2c_bit_algo;
adap->retries = 3;
ret = add_adapter(adap);
if (ret < 0)
return ret;
/* Complain if SCL can't be read */
if (bit_adap->getscl == NULL) {
dev_warn(&adap->dev, "Not I2C compliant: can't read SCL\n");
dev_warn(&adap->dev, "Bus may be unreliable\n");
}
return 0;
}
int i2c_bit_add_bus(struct i2c_adapter *adap)
{
return __i2c_bit_add_bus(adap, i2c_add_adapter);
}
EXPORT_SYMBOL(i2c_bit_add_bus);
int i2c_bit_add_numbered_bus(struct i2c_adapter *adap)
{
return __i2c_bit_add_bus(adap, i2c_add_numbered_adapter);
}
EXPORT_SYMBOL(i2c_bit_add_numbered_bus);
MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
MODULE_DESCRIPTION("I2C-Bus bit-banging algorithm");
MODULE_LICENSE("GPL");
|
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
<ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
</ack>
'''
def __init__(self, _id, _class, _type, to, participant = None):
super(OutgoingAckProtocolEntity, self).__init__(_id, _class)
self.setOutgoingData(_type, to, participant)
def setOutgoingData(self, _type, _to, _participant):
self._type = _type
self._to = _to
self._participant = _participant
def toProtocolTreeNode(self):
node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode()
if self._type:
node.setAttribute("type", self._type)
node.setAttribute("to", self._to)
if self._participant:
node.setAttribute("participant", self._participant)
return node
def __str__(self):
out = super(OutgoingAckProtocolEntity, self).__str__()
out += "Type: %s\n" % self._type
out += "To: %s\n" % self._to
if self._participant:
out += "Participant: %s\n" % self._participant
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = AckProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = OutgoingAckProtocolEntity
entity.setOutgoingData(
node.getAttributeValue("type"),
node.getAttributeValue("to"),
node.getAttributeValue("participant")
)
return entity
|
import datetime
import math
import time
from funcy.colls import walk_values, get_in
from funcy.seqs import take
from funcy import rpartial
from smokebase.exceptions import AccountDoesNotExistsException
from toolz import dissoc
from .amount import Amount
from .blockchain import Blockchain
from .converter import Converter
from .instance import shared_steemd_instance
from .utils import parse_time, json_expand
class Account(dict):
""" This class allows to easily access Account data
:param str account_name: Name of the account
:param Steemd steemd_instance: Steemd() instance to use when
accessing a RPC
"""
def __init__(self, account_name, steemd_instance=None):
self.steemd = steemd_instance or shared_steemd_instance()
self.name = account_name
# caches
self._converter = None
self.refresh()
def refresh(self):
account = self.steemd.get_account(self.name)
if not account:
raise AccountDoesNotExistsException
# load json_metadata
account = json_expand(account, 'json_metadata')
super(Account, self).__init__(account)
def __getitem__(self, key):
return super(Account, self).__getitem__(key)
def items(self):
return super(Account, self).items()
@property
def converter(self):
if not self._converter:
self._converter = Converter(self.steemd)
return self._converter
@property
def profile(self):
try:
return get_in(self, ['json_metadata', 'profile'], default={})
except TypeError:
pass
return {}
@property
def sp(self):
vests = Amount(self['vesting_shares']).amount
return round(self.converter.vests_to_sp(vests), 3)
@property
def balances(self):
return self.get_balances()
def get_balances(self):
available = {
'SMOKE': Amount(self['balance']).amount,
'VESTS': Amount(self['vesting_shares']).amount,
}
rewards = {
'SMOKE': Amount(self['reward_steem_balance']).amount,
'VESTS': Amount(self['reward_vesting_balance']).amount,
}
totals = {
'SMOKE':
sum([available['SMOKE'], savings['SMOKE'], rewards['SMOKE']]),
'VESTS':
sum([available['VESTS'], rewards['VESTS']]),
}
total = walk_values(rpartial(round, 3), totals)
return {
'available': available,
'rewards': rewards,
'total': total,
}
def voting_power(self):
return self['voting_power'] / 100
def get_followers(self):
return [
x['follower'] for x in self._get_followers(direction="follower")
]
def get_following(self):
return [
x['following'] for x in self._get_followers(direction="following")
]
def _get_followers(self, direction="follower", last_user=""):
if direction == "follower":
followers = self.steemd.get_followers(self.name, last_user, "blog",
100)
elif direction == "following":
followers = self.steemd.get_following(self.name, last_user, "blog",
100)
if len(followers) >= 100:
followers += self._get_followers(
direction=direction, last_user=followers[-1][direction])[1:]
return followers
def has_voted(self, post):
active_votes = {v["voter"]: v for v in getattr(post, "active_votes")}
return self.name in active_votes
def curation_stats(self):
trailing_24hr_t = time.time() - datetime.timedelta(
hours=24).total_seconds()
trailing_7d_t = time.time() - datetime.timedelta(
days=7).total_seconds()
reward_24h = 0.0
reward_7d = 0.0
for reward in take(
5000, self.history_reverse(filter_by="curation_reward")):
timestamp = parse_time(reward['timestamp']).timestamp()
if timestamp > trailing_7d_t:
reward_7d += Amount(reward['reward']).amount
if timestamp > trailing_24hr_t:
reward_24h += Amount(reward['reward']).amount
reward_7d = self.converter.vests_to_sp(reward_7d)
reward_24h = self.converter.vests_to_sp(reward_24h)
return {
"24hr": reward_24h,
"7d": reward_7d,
"avg": reward_7d / 7,
}
def virtual_op_count(self):
try:
last_item = self.steemd.get_account_history(self.name, -1, 0)[0][0]
except IndexError:
return 0
else:
return last_item
def get_account_votes(self):
return self.steemd.get_account_votes(self.name)
def get_withdraw_routes(self):
return self.steemd.get_withdraw_routes(self.name, 'all')
def get_conversion_requests(self):
return self.steemd.get_conversion_requests(self.name)
@staticmethod
def filter_by_date(items, start_time, end_time=None):
start_time = parse_time(start_time).timestamp()
if end_time:
end_time = parse_time(end_time).timestamp()
else:
end_time = time.time()
filtered_items = []
for item in items:
if 'time' in item:
item_time = item['time']
elif 'timestamp' in item:
item_time = item['timestamp']
timestamp = parse_time(item_time).timestamp()
if end_time > timestamp > start_time:
filtered_items.append(item)
return filtered_items
def export(self, load_extras=True):
""" This method returns a dictionary that is type-safe to store as
JSON or in a database.
:param bool load_extras: Fetch extra information related to the
account (this might take a while).
"""
extras = dict()
if load_extras:
followers = self.get_followers()
following = self.get_following()
extras = {
"followers": followers,
"followers_count": len(followers),
"following": following,
"following_count": len(following),
"curation_stats": self.curation_stats(),
"withdrawal_routes": self.get_withdraw_routes(),
"conversion_requests": self.get_conversion_requests(),
}
composedDict = self.copy()
composedDict.update(extras)
composedDict.update(
{
"profile": self.profile,
"sp": self.sp,
"rep": self.rep,
"balances": self.get_balances(),
}
)
return composedDict
def get_account_history(self,
index,
limit,
start=None,
stop=None,
order=-1,
filter_by=None,
raw_output=False):
""" A generator over steemd.get_account_history.
It offers serialization, filtering and fine grained iteration control.
Args:
index (int): start index for get_account_history
limit (int): How many items are we interested in.
start (int): (Optional) skip items until this index
stop (int): (Optional) stop iteration early at this index
order: (1, -1): 1 for chronological, -1 for reverse order
filter_by (str, list): filter out all but these operations
raw_output (bool): (Defaults to False). If True, return history in
steemd format (unchanged).
"""
history = self.steemd.get_account_history(self.name, index, limit)
for item in history[::order]:
index, event = item
# start and stop utilities for chronological generator
if start and index < start:
continue
if stop and index > stop:
return
op_type, op = event['op']
block_props = dissoc(event, 'op')
def construct_op(account_name):
# verbatim output from steemd
if raw_output:
return item
# index can change during reindexing in
# future hard-forks. Thus we cannot take it for granted.
immutable = op.copy()
immutable.update(block_props)
immutable.update({
'account': account_name,
'type': op_type,
})
_id = Blockchain.hash_op(immutable)
immutable.update({
'_id': _id,
'index': index,
})
return immutable
if filter_by is None:
yield construct_op(self.name)
else:
if type(filter_by) is list:
if op_type in filter_by:
yield construct_op(self.name)
if type(filter_by) is str:
if op_type == filter_by:
yield construct_op(self.name)
def history(self,
filter_by=None,
start=0,
batch_size=1000,
raw_output=False):
""" Stream account history in chronological order.
"""
max_index = self.virtual_op_count()
if not max_index:
return
start_index = start + batch_size
i = start_index
while i < max_index + batch_size:
for account_history in self.get_account_history(
index=i,
limit=batch_size,
start=i - batch_size,
stop=max_index,
order=1,
filter_by=filter_by,
raw_output=raw_output,
):
yield account_history
i += (batch_size + 1)
def history_reverse(self,
filter_by=None,
batch_size=1000,
raw_output=False):
""" Stream account history in reverse chronological order.
"""
start_index = self.virtual_op_count()
if not start_index:
return
i = start_index
while i > 0:
if i - batch_size < 0:
batch_size = i
for account_history in self.get_account_history(
index=i,
limit=batch_size,
order=-1,
filter_by=filter_by,
raw_output=raw_output,
):
yield account_history
i -= (batch_size + 1)
|
exports.min = function min(array) {
if (array === undefined || array.length === 0) return 0;
let min = array[0];
for (let i = 0; i < array.length; i += 1){
array[i] < min ? min = array[i] : min = min;
}
return min;
}
exports.max = function max (array) {
if (array === undefined || array.length === 0) return 0;
let max = array[0];
for (let i = 0; i < array.length; i += 1){
array[i] > max ? max = array[i] : max = max;
}
return max;
}
exports.avg = function avg (array) {
if (array === undefined || array.length === 0) return 0;
let avg = 0;
for (let i = 0; i < array.length; i += 1){
avg += array[i];
}
return avg / array.length;
}
|
// Generated by LispyScript v1.0.0
var display = function(value) {
return console.log(value);
};
var warn = function(value) {
return console.warn(value);
};
var newline = function() {
return console.log("");
};
var round = function(value) {
return parseInt(value,10);
};
var flip = function(fn) {
return function(a,b) {
return fn(b,a);
};
};
var f = function() {
return false;
};
var t = function() {
return true;
};
var list = function(...args) {
return [
...args
];
};
var cons = function(element,l) {
l.push(element);
return l;
};
var concat = function(a,b,acc) {
(a).forEach(function(element) {
return acc.push(element);
});
(b).forEach(function(element) {
return acc.push(element);
});
return acc;
};
var reverse = function(list) {
return list.reverse();
};
var car = function(list) {
return list[0];
};
var cdr = function(list) {
return list.slice(1);
};
var listen = function(name,fn) {
return document.addEventListener(name,function(e) {
return fn(e);
});
};
var $ = function(element) {
return document.querySelector(element);
};
var ctx = function(canvas) {
return canvas.getContext("2d");
};
var centerize = function(position,size) {
var x = car(position);
var y = car(cdr(position));
var w = car(size);
var h = car(cdr(size));
return list(round((x + (w / 2))),round((y + (h / 2))));
};
var write = function(text,position,ctx) {
ctx.font = "12px Verdana";
var padd = (12 / 3);
var x = (car(position) - padd);
var y = (car(cdr(position)) + padd);
return ctx.fillText(text,x,y);
};
var drawSprite = function(source,destination,image,ctx) {
[sx, sy, sw, sh] = source;
[dx, dy, dw, dh] = destination;
return ctx.drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh);
};
var rect = function(position,size,ctx) {
ctx.beginPath();
return ctx.rect(car(position),car(cdr(position)),car(size),car(cdr(size)));
};
var stroke = function(ctx) {
return ctx.stroke();
};
var background = function(color,ctx) {
ctx.fillStyle = color;
return ctx.fill();
};
var clr = function(w,h,ctx) {
return ctx.clearRect(0,0,w,h);
};
var tilify = function(x,y,xMax,yMax,xTile,yTile,ctx) {
rect(list(x,y),list(xTile,yTile),ctx);
stroke(ctx);
return ((x === xMax) ?
((y === yMax) ?
false :
tilify(0,(y + yTile),xMax,yMax,xTile,yTile,ctx)) :
tilify((x + xTile),y,xMax,yMax,xTile,yTile,ctx));
};
var select = function(position,size,ctx) {
rect(position,size,ctx);
return background("green",ctx);
};
var moveSelect = function(currentDirection,padd,selectionBlock) {
var direction = {
UP: "UP",
RIGHT: "RIGHT",
DOWN: "DOWN",
LEFT: "LEFT"
};
var x = car(selectionBlock);
var y = car(cdr(selectionBlock));
var xPadd = car(padd);
var yPadd = car(cdr(padd));
return ((currentDirection === direction.UP) ?
list(x,(y - yPadd)) :
((currentDirection === direction.RIGHT) ?
list((x + xPadd),y) :
((currentDirection === direction.DOWN) ?
list(x,(y + yPadd)) :
((currentDirection === direction.LEFT) ?
list((x - xPadd),y) :
undefined))));
};
var hasMaxArrow = function(arrows) {
return ((arrows === MAX_ARROW) ?
true :
false);
};
var domArrowCounter = function(arrowCounter) {
var el = $(".arrow-counter");
el.innerHTML = arrowCounter;
};
var domArrowMax = function(max) {
var el = $(".arrow-max");
el.innerHTML = max;
};
var renderInventory = function(arrowList,image,ctx) {
var arrowTileSet = {
UP: list(0,0,50,50),
RIGHT: list(50,0,50,50),
DOWN: list(100,0,50,50),
LEFT: list(150,0,50,50)
};
var slotsPosition = list(list(0,0,50,50),list(70,0,50,50),list(140,0,50,50),list(210,0,50,50));
clearInventoryCanvas();
return (arrowList).forEach(function(arrow,index) {
return drawSprite(arrowTileSet[arrow],slotsPosition[index],image,ctx);
});
};
var arrowSelect = function(currentDirection,image,sizeBlock,selectedBlock,inventory,board,inventoryCtx,ctx) {
return ((false === hasArrow(currentDirection,inventory)) ?
list(inventory,board) :
(function() {
var arrowTileSet = {
UP: list(0,0,50,50),
RIGHT: list(50,0,50,50),
DOWN: list(100,0,50,50),
LEFT: list(150,0,50,50)
};
var x = car(selectedBlock);
var y = car(cdr(selectedBlock));
[dw, dh] = sizeBlock;
transfer = toBoardArrow(currentDirection,inventory,board);
[inventory, board] = transfer;
ctx.clearRect(x,y,dw,dh);
boardArrowPosition = addArrowPosition(selectedBlock,boardArrowPosition,[]);
padd = 5;
center_size = list((car(block_size) - 5),(car(cdr(block_size)) - 5));
drawSprite(arrowTileSet[currentDirection],list(x,y,dw,dh),image,ctx);
(boardArrowPosition).forEach(function(position) {
center = centerize(position,center_size);
rect(center,list(5,5),ctx);
return background("blue",ctx);
});
renderInventory(inventory,image,inventoryCtx);
return list(inventory,board,countBoard(board,0));
})());
};
var domSelectMode = function(currentMode) {
var el = $(".select-mode");
el.innerHTML = currentMode;
};
var toggleMode = function(currentMode) {
var modes = list("navigation","arrow");
((currentMode === car(modes)) ?
domSelectMode(car(cdr(modes))) :
domSelectMode(car(modes)));
return ((currentMode === car(modes)) ?
car(cdr(modes)) :
((currentMode === car(cdr(modes))) ?
car(modes) :
undefined));
};
var hasArrow = function(currentArrow,arrowList) {
return ((typeof(car(arrowList)) === "undefined") ?
f() :
((currentArrow === car(arrowList)) ?
t() :
hasArrow(currentArrow,cdr(arrowList))));
};
var countBoard = function(arrowList,acc) {
return ((typeof(car(arrowList)) === "undefined") ?
acc :
((car(arrowList) !== "") ?
countBoard(cdr(arrowList),(acc + 1)) :
countBoard(cdr(arrowList),acc)));
};
var removeArrow = function(currentArrow,arrowList,acc,found) {
return ((true === found) ?
acc :
((car(arrowList) === currentArrow) ?
removeArrow(currentArrow,arrowList,concat(acc,cdr(arrowList),[]),true) :
((typeof(car(arrowList)) === "undefined") ?
removeArrow(currentArrow,arrowList,acc,true) :
removeArrow(currentArrow,cdr(arrowList),cons(car(arrowList),acc),false))));
};
var removeArrowPosition = function(currentPosition,arrowList,acc,found) {
[x, y] = car(arrowList);
return ((true === found) ?
acc :
(((x === car(currentPosition)) && (y === car(cdr(currentPosition)))) ?
removeArrowPosition(currentPosition,arrowList,concat(acc,cdr(arrowList),[]),true) :
((typeof(car(arrowList)) === "undefined") ?
removeArrowPosition(currentPosition,arrowList,acc,true) :
removeArrowPosition(currentPosition,cdr(arrowList),cons(car(arrowList),acc),false))));
};
var addArrow = function(currentArrow,arrowList,acc) {
((typeof(acc) === "undefined") ?
acc = [] :
undefined);
return ((car(arrowList) === "") ?
concat(acc,concat(list(currentArrow),cdr(arrowList),[]),[]) :
((typeof(car(arrowList)) === "undefined") ?
concat(list(currentArrow),cdr(reverse(acc)),[]) :
addArrow(currentArrow,cdr(arrowList),concat(list(car(arrowList)),acc,[]))));
};
var addArrowPosition = function(currentPosition,arrowList,acc) {
((typeof(acc) === "undefined") ?
acc = [] :
undefined);
var defaultPosition = list(-100,-100);
[x, y] = car(arrowList);
return (((x === car(defaultPosition)) && (y === car(cdr(defaultPosition)))) ?
concat(acc,concat(list(currentPosition),cdr(arrowList),[]),[]) :
((typeof(car(arrowList)) === "undefined") ?
concat(currentPosition,cdr(reverse(acc)),[]) :
addArrowPosition(currentPosition,cdr(arrowList),concat(list(car(arrowList)),acc,[]))));
};
var transferArrow = function(arrow,origin,dest) {
var from = removeArrow(arrow,origin,[],false);
var to = addArrow(arrow,dest,[]);
return list(from,to);
};
var isEmptyInventory = function(inventory) {
var ln = inventory.length;
var index = 0;
(inventory).forEach(function(item) {
return ((item === "") ?
index = (index + 1) :
undefined);
});
return ((index === ln) ?
t() :
f());
};
var isEmptyBoard = function(board) {
var ln = board.length;
var index = 0;
(board).forEach(function(item) {
return ((car(item) !== -100) ?
index = (index + 1) :
undefined);
});
return ((index === 0) ?
t() :
f());
};
var toBoardArrow = function(arrow,inventory,board) {
return (((true === isEmptyInventory(inventory)) || (false === hasArrow(arrow,inventory))) ?
board :
transferArrow(arrow,inventory,board));
};
var toInventoryArrow = function(arrow,inventory,board) {
return ((true === isEmptyInventory(inventory)) ?
f() :
transferArrow(arrow,board,inventory));
};
var fill = function(iteration,list) {
return list.fill(iteration);
};
var length = function(list) {
return list.length;
};
var keyboard = {
UP: 38,
RIGHT: 39,
DOWN: 40,
LEFT: 37,
SPACE: 32
};
var arrowTileSet = list({
UP: list(0,0,50,0)
},{
RIGHT: list(50,0,50,0)
},{
DOWN: list(100,0,50,0)
},{
LEFT: list(150,0,50,0)
});
var selectMode = "navigation";
domSelectMode(selectMode);
var tileInit = function() {
tileMap = new Image();
tileMap.src = "./dist/assets/tileset.png";
return tileMap;
};
var TILE_SIZE = list(25,15);
var WIN_WIDTH = 800;
var WIN_HEIGHT = 600;
var GAME_WIDTH = 270;
var GAME_HEIGHT = 130;
var GAME_BOX = list(GAME_WIDTH,GAME_HEIGHT);
var CANVAS_MAIN = $("canvas.main");
var CANVAS_GROUND = $("canvas.ground");
var CANVAS_SELECTION = $("canvas.selection");
var CANVAS_ARROW = $("canvas.arrow");
var CANVAS_INVENTORY = $("canvas.inventory");
var block_size = TILE_SIZE;
var main = ctx(CANVAS_MAIN);
var ground = ctx(CANVAS_GROUND);
var selection = ctx(CANVAS_SELECTION);
var arrow = ctx(CANVAS_ARROW);
var inventory = ctx(CANVAS_INVENTORY);
main.scale(1.0,1.0);
ground.scale(1.0,1.0);
selection.scale(1.0,1.0);
arrow.scale(1.0,1.0);
inventory.scale(1.0,1.0);
var spriteSheet = tileInit();
var clearMainCanvas = function() {
return clr(CANVAS_MAIN.width,CANVAS_MAIN.height,main);
};
var clearSelectionCanvas = function() {
return clr(CANVAS_SELECTION.width,CANVAS_SELECTION.height,selection);
};
var clearInventoryCanvas = function() {
return clr(CANVAS_INVENTORY.width,CANVAS_INVENTORY.height,inventory);
};
tilify(0,0,WIN_WIDTH,WIN_HEIGHT,car(TILE_SIZE),car(cdr(TILE_SIZE)),ground);
var block_selected = list(0,0);
var listenTo = function(e) {
e.preventDefault();
domArrowCounter(arrowCounter);
((e.keyCode === keyboard.SPACE) ?
selectMode = toggleMode(selectMode) :
undefined);
((selectMode === "navigation") ?
((e.keyCode === keyboard.UP) ?
clearSelectionCanvas(block_selected = moveSelect("UP",block_size,block_selected)) :
undefined)(((e.keyCode === keyboard.RIGHT) ?
clearSelectionCanvas(block_selected = moveSelect("RIGHT",block_size,block_selected)) :
undefined),((e.keyCode === keyboard.DOWN) ?
clearSelectionCanvas(block_selected = moveSelect("DOWN",block_size,block_selected)) :
undefined),((e.keyCode === keyboard.LEFT) ?
clearSelectionCanvas(block_selected = moveSelect("LEFT",block_size,block_selected)) :
undefined)) :
undefined);
((selectMode === "arrow") ?
((true === hasMaxArrow(arrowCounter)) ?
f() :
((e.keyCode === keyboard.UP) ?
[inventoryArrowList,
boardArrowList,
arrowCounter] = arrowSelect("UP",spriteSheet,block_size,block_selected,inventoryArrowList,boardArrowList,inventory,arrow) :
((e.keyCode === keyboard.RIGHT) ?
[inventoryArrowList,
boardArrowList,
arrowCounter] = arrowSelect("RIGHT",spriteSheet,block_size,block_selected,inventoryArrowList,boardArrowList,inventory,arrow) :
((e.keyCode === keyboard.DOWN) ?
[inventoryArrowList,
boardArrowList,
arrowCounter] = arrowSelect("DOWN",spriteSheet,block_size,block_selected,inventoryArrowList,boardArrowList,inventory,arrow) :
((e.keyCode === keyboard.LEFT) ?
[inventoryArrowList,
boardArrowList,
arrowCounter] = arrowSelect("LEFT",spriteSheet,block_size,block_selected,inventoryArrowList,boardArrowList,inventory,arrow) :
undefined))))()) :
undefined);
return false;
};
var arrowCounter = 0;
var levelArrowList = list("UP","DOWN","LEFT","LEFT");
var MAX_ARROW = levelArrowList.length;
var inventoryArrowList = levelArrowList;
var boardArrowList = list("","","","");
var boardArrowPosition = list(list(-100,-100),list(-100,-100),list(-100,-100),list(-100,-100));
domArrowCounter(arrowCounter);
domArrowMax(MAX_ARROW);
var mouse = list(0,120);
[x,y] = mouse;
var goUp = function(y,velocity) {
return (y - velocity);
};
var goLeft = function(x,velocity) {
return (x - velocity);
};
var goDown = function(y,velocity) {
return (y + velocity);
};
var goRight = function(x,velocity) {
return (x + velocity);
};
var isRightCorner = function(x) {
return (x >= GAME_WIDTH);
};
var isBottomCorner = function(y) {
return (y > GAME_HEIGHT);
};
var isTopCorner = function(y) {
return (y <= 0);
};
var isLeftCorner = function(x) {
return (x <= 0);
};
var checkCollideGame = function(position,gameBox) {
[x, y] = position;
[w, h] = gameBox;
return (((x <= 0) || (y <= 0)) || ((x > w) || (y > h)));
};
var collideTopGame = function(position,gameBox) {
[x, y] = position;
[w, h] = gameBox;
return (y <= 0);
};
var collideBottomGame = function(position,gameBox) {
[x, y] = position;
[w, h] = gameBox;
return (y > h);
};
var collideRightGame = function(position,gameBox) {
[x, y] = position;
[w, h] = gameBox;
return (x > w);
};
var collideLeftGame = function(position,gameBox) {
[x, y] = position;
[w, h] = gameBox;
return (x <= 0);
};
var redirectTop = function(position) {
[x, y] = position;
return ((true === ((false === isRightCorner(x)) || (false === isLeftCorner(x)))) ?
"LEFT" :
((true === isRightCorner(x)) ?
"LEFT" :
((true === isLeftCorner(x)) ?
"RIGHT" :
undefined)));
};
var redirectBottom = function(position) {
[x, y] = position;
return ((true === ((false === isRightCorner(x)) || (false === isLeftCorner(x)))) ?
"RIGHT" :
((true === isRightCorner(x)) ?
"LEFT" :
((true === isLeftCorner(x)) ?
"RIGHT" :
undefined)));
};
var redirectRight = function(position) {
[x, y] = position;
return ((true === isBottomCorner(y)) ?
"UP" :
((true === isTopCorner(y)) ?
"DOWN" :
((true === ((false === isBottomCorner(y)) || (false === isTopcorner(y)))) ?
"UP" :
undefined)));
};
var redirectLeft = function(position) {
[x, y] = position;
return ((true === isBottomCorner(y)) ?
"UP" :
((true === isTopCorner(y)) ?
"DOWN" :
((true === ((false === isBottomCorner(y)) || (false === isTopcorner(y)))) ?
"DOWN" :
undefined)));
};
var collideEntityArrows = function(ent,arrows) {
[x, y] = ent;
var i = -1;
(arrows).forEach(function(arrow,index) {
[aX, aY] = arrow;
return (((x === aX) && (y === aY)) ?
i = index :
undefined);
});
return i;
};
var resetSpeed = function() {
return 0;
};
var normalSpeed = function() {
return 5;
};
var lowSpeed = function() {
return 1;
};
var highSpeed = function() {
return 10;
};
var spawnEntity = function(spawnPosition,size,ctx) {
var spawnEntity = spawnPosition;
rect(spawnPosition,size,ctx);
background("red",ctx);
return spawnEntity;
};
var moveEntity = function(position,velocity,direction) {
var entity = position;
((direction === "UP") ?
entity = list(car(position),goUp(car(cdr(position)),car(cdr(velocity)))) :
((direction === "RIGHT") ?
entity = list(goRight(car(position),car(velocity)),car(cdr(position))) :
((direction === "DOWN") ?
entity = list(car(position),goDown(car(cdr(position)),car(cdr(velocity)))) :
((direction === "LEFT") ?
entity = list(goLeft(car(position),car(velocity)),car(cdr(position))) :
undefined))));
return entity;
};
var ent = spawnEntity(mouse,block_size,main);
var init = true;
var currentDirection = -1;
var update = function() {
return setInterval(function() {
clearMainCanvas();
((car(cdr(ent)) > GAME_HEIGHT) ?
clearInterval(update) :
((true === init) ?
ent = moveEntity(ent,list(normalSpeed(),normalSpeed()),"RIGHT") :
undefined));
((true === checkCollideGame(ent,GAME_BOX)) ?
(function() {
init = false;
((false === isEmptyBoard(boardArrowPosition)) ?
(function() {
indexBoard = collideEntityArrows(ent,boardArrowPosition);
return ((indexBoard !== -1) ?
currentDirection = indexBoard :
undefined);
})() :
undefined);
((true === collideBottomGame(ent,GAME_BOX)) ?
ent = moveEntity(ent,list(normalSpeed(),resetSpeed()),redirectBottom(ent)) :
undefined);
((true === collideLeftGame(ent,GAME_BOX)) ?
ent = moveEntity(ent,list(resetSpeed(),normalSpeed()),redirectLeft(ent)) :
undefined);
((true === collideTopGame(ent,GAME_BOX)) ?
ent = moveEntity(ent,list(normalSpeed(),resetSpeed()),redirectTop(ent)) :
undefined);
return ((true === collideRightGame(ent,GAME_BOX)) ?
ent = moveEntity(ent,list(resetSpeed(),normalSpeed()),redirectRight(ent)) :
undefined);
})() :
undefined);
((-1 !== currentDirection) ?
(function() {
ent = moveEntity(ent,list(normalSpeed(),resetSpeed()),boardArrowList[currentDirection]);
})() :
undefined);
((false === isEmptyBoard(boardArrowPosition)) ?
(function() {
indexBoard = collideEntityArrows(ent,boardArrowPosition);
return ((indexBoard !== -1) ?
currentDirection = indexBoard :
undefined);
})() :
undefined);
select(block_selected,block_size,selection);
rect(ent,block_size,main);
return background("red",main);
},100);
};
spriteSheet.onload = function() {
renderInventory(inventoryArrowList,spriteSheet,inventory);
listen("keyup",function(e) {
return listenTo(e);
});
return update();
};
|
# -*- coding: utf-8 -*-
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): Ville Heikkilä <ville.heikkila@tuni.fi>
"""Unit tests for the SimulationStateMessage class."""
import copy
import datetime
import json
import unittest
import tools.exceptions.messages
import tools.messages
from tools.datetime_tools import to_utc_datetime_object
from tools.tests.messages_common import (
MESSAGE_TYPE_ATTRIBUTE, TIMESTAMP_ATTRIBUTE, SIMULATION_ID_ATTRIBUTE, SOURCE_PROCESS_ID_ATTRIBUTE,
MESSAGE_ID_ATTRIBUTE, SIMULATION_STATE_ATTRIBUTE, NAME_ATTRIBUTE, DESCRIPTION_ATTRIBUTE,
DEFAULT_TYPE, DEFAULT_TIMESTAMP, DEFAULT_SIMULATION_ID, DEFAULT_SOURCE_PROCESS_ID, DEFAULT_MESSAGE_ID,
DEFAULT_SIMULATION_STATE, DEFAULT_NAME, DEFAULT_DESCRIPTION,
FULL_JSON, ALTERNATE_JSON
)
DEFAULT_TYPE = "SimState"
FULL_JSON = {**FULL_JSON, "Type": DEFAULT_TYPE}
ALTERNATE_JSON = {**ALTERNATE_JSON, "Type": DEFAULT_TYPE}
class SimulationStateMessage(unittest.TestCase):
"""Unit tests for the SimulationStateMessage class."""
def test_message_type(self):
"""Unit test for the SimulationStateMessage type."""
self.assertEqual(tools.messages.SimulationStateMessage.CLASS_MESSAGE_TYPE, "SimState")
self.assertEqual(tools.messages.SimulationStateMessage.MESSAGE_TYPE_CHECK, True)
def test_message_creation(self):
"""Unit test for creating instances of SimulationStateMessage class."""
# When message is created without a Timestamp attribute,
# the current time in millisecond precision is used as the default value.
utcnow1 = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
utcnow1 -= datetime.timedelta(microseconds=utcnow1.microsecond % 1000)
message_full = tools.messages.SimulationStateMessage(**FULL_JSON)
message_timestamp = to_utc_datetime_object(message_full.timestamp)
utcnow2 = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
utcnow1 -= datetime.timedelta(microseconds=utcnow2.microsecond % 1000)
self.assertGreaterEqual(message_timestamp, utcnow1)
self.assertLessEqual(message_timestamp, utcnow2)
self.assertEqual(message_full.message_type, DEFAULT_TYPE)
self.assertEqual(message_full.simulation_id, DEFAULT_SIMULATION_ID)
self.assertEqual(message_full.source_process_id, DEFAULT_SOURCE_PROCESS_ID)
self.assertEqual(message_full.message_id, DEFAULT_MESSAGE_ID)
self.assertEqual(message_full.simulation_state, DEFAULT_SIMULATION_STATE)
self.assertEqual(message_full.name, DEFAULT_NAME)
self.assertEqual(message_full.description, DEFAULT_DESCRIPTION)
# Test with explicitely set timestamp
message_timestamped = tools.messages.SimulationStateMessage(Timestamp=DEFAULT_TIMESTAMP, **FULL_JSON)
self.assertEqual(message_timestamped.timestamp, DEFAULT_TIMESTAMP)
self.assertEqual(message_timestamped.message_type, DEFAULT_TYPE)
self.assertEqual(message_timestamped.simulation_id, DEFAULT_SIMULATION_ID)
self.assertEqual(message_timestamped.source_process_id, DEFAULT_SOURCE_PROCESS_ID)
self.assertEqual(message_timestamped.message_id, DEFAULT_MESSAGE_ID)
self.assertEqual(message_timestamped.simulation_state, DEFAULT_SIMULATION_STATE)
self.assertEqual(message_timestamped.name, DEFAULT_NAME)
self.assertEqual(message_timestamped.description, DEFAULT_DESCRIPTION)
def test_message_json(self):
"""Unit test for testing that the json from a message has correct attributes."""
message_full_json = tools.messages.SimulationStateMessage(**FULL_JSON).json()
self.assertIn(MESSAGE_TYPE_ATTRIBUTE, message_full_json)
self.assertIn(SIMULATION_ID_ATTRIBUTE, message_full_json)
self.assertIn(SOURCE_PROCESS_ID_ATTRIBUTE, message_full_json)
self.assertIn(MESSAGE_ID_ATTRIBUTE, message_full_json)
self.assertIn(TIMESTAMP_ATTRIBUTE, message_full_json)
self.assertIn(SIMULATION_STATE_ATTRIBUTE, message_full_json)
self.assertIn(NAME_ATTRIBUTE, message_full_json)
self.assertIn(DESCRIPTION_ATTRIBUTE, message_full_json)
self.assertEqual(len(message_full_json), 8)
def test_message_bytes(self):
"""Unit test for testing that the bytes conversion works correctly."""
# Convert to bytes and back to Message instance
message_full = tools.messages.SimulationStateMessage(**FULL_JSON)
message_copy = tools.messages.SimulationStateMessage(**json.loads(message_full.bytes().decode("UTF-8")))
self.assertEqual(message_copy.timestamp, message_full.timestamp)
self.assertEqual(message_copy.message_type, message_full.message_type)
self.assertEqual(message_copy.simulation_id, message_full.simulation_id)
self.assertEqual(message_copy.source_process_id, message_full.source_process_id)
self.assertEqual(message_copy.message_id, message_full.message_id)
self.assertEqual(message_copy.simulation_state, message_full.simulation_state)
self.assertEqual(message_copy.name, message_full.name)
self.assertEqual(message_copy.description, message_full.description)
def test_message_equals(self):
"""Unit test for testing if the __eq__ comparison works correctly."""
message_full = tools.messages.SimulationStateMessage(Timestamp=DEFAULT_TIMESTAMP, **FULL_JSON)
message_copy = tools.messages.SimulationStateMessage(Timestamp=DEFAULT_TIMESTAMP, **FULL_JSON)
message_alternate = tools.messages.SimulationStateMessage.from_json(ALTERNATE_JSON)
self.assertEqual(message_copy, message_full)
self.assertNotEqual(message_copy, message_alternate)
attributes = [
"simulation_id",
"source_process_id",
"message_id",
"timestamp",
"simulation_state",
"name",
"description"
]
for attribute_name in attributes:
with self.subTest(attribute=attribute_name):
setattr(message_copy, attribute_name, getattr(message_alternate, attribute_name))
self.assertNotEqual(message_copy, message_full)
setattr(message_copy, attribute_name, getattr(message_full, attribute_name))
self.assertEqual(message_copy, message_full)
def test_invalid_values(self):
"""Unit tests for testing that invalid attribute values are recognized."""
message_full = tools.messages.SimulationStateMessage(**FULL_JSON)
message_full_json = message_full.json()
allowed_simulation_states = [
"running",
"stopped"
]
for simulation_state_str in allowed_simulation_states:
message_full.simulation_state = simulation_state_str
self.assertEqual(message_full.simulation_state, simulation_state_str)
optional_attributes = [
NAME_ATTRIBUTE,
DESCRIPTION_ATTRIBUTE
]
invalid_attribute_exceptions = {
MESSAGE_TYPE_ATTRIBUTE: tools.exceptions.messages.MessageTypeError,
SIMULATION_ID_ATTRIBUTE: tools.exceptions.messages.MessageDateError,
SOURCE_PROCESS_ID_ATTRIBUTE: tools.exceptions.messages.MessageSourceError,
MESSAGE_ID_ATTRIBUTE: tools.exceptions.messages.MessageIdError,
TIMESTAMP_ATTRIBUTE: tools.exceptions.messages.MessageDateError,
SIMULATION_STATE_ATTRIBUTE: tools.exceptions.messages.MessageStateValueError,
NAME_ATTRIBUTE: tools.exceptions.messages.MessageValueError,
DESCRIPTION_ATTRIBUTE: tools.exceptions.messages.MessageValueError
}
invalid_attribute_values = {
MESSAGE_TYPE_ATTRIBUTE: ["Test", 12, "", "Epoch"],
SIMULATION_ID_ATTRIBUTE: ["simulation-id", 12, "2020-07-31T24:11:11.123Z", ""],
SOURCE_PROCESS_ID_ATTRIBUTE: [12, ""],
MESSAGE_ID_ATTRIBUTE: [12, True, ""],
TIMESTAMP_ATTRIBUTE: ["timestamp", 12, "2020-07-31T24:11:11.123Z", ""],
SIMULATION_STATE_ATTRIBUTE: ["waiting", 12, ""],
NAME_ATTRIBUTE: [1, 15],
DESCRIPTION_ATTRIBUTE: [1, 15]
}
for invalid_attribute in invalid_attribute_exceptions:
if invalid_attribute != TIMESTAMP_ATTRIBUTE and invalid_attribute not in optional_attributes:
json_invalid_attribute = copy.deepcopy(message_full_json)
json_invalid_attribute.pop(invalid_attribute)
with self.subTest(attribute=invalid_attribute):
with self.assertRaises(invalid_attribute_exceptions[invalid_attribute]):
tools.messages.SimulationStateMessage(**json_invalid_attribute)
for invalid_value in invalid_attribute_values[invalid_attribute]:
json_invalid_attribute = copy.deepcopy(message_full_json)
json_invalid_attribute[invalid_attribute] = invalid_value
with self.subTest(attribute=invalid_attribute, value=invalid_value):
with self.assertRaises((ValueError, invalid_attribute_exceptions[invalid_attribute])):
tools.messages.SimulationStateMessage(**json_invalid_attribute)
if __name__ == '__main__':
unittest.main()
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import Markdown from 'markdown-it';
import { RendererStrings } from '../../../i18n';
const { markdown: strings } = RendererStrings;
const md = new Markdown();
export const markdown = () => ({
name: 'markdown',
displayName: strings.getDisplayName(),
help: strings.getHelpDescription(),
reuseDomNode: true,
render(domNode, config, handlers) {
const html = { __html: md.render(String(config.content)) };
const fontStyle = config.font ? config.font.spec : {};
/* eslint-disable react/no-danger */
ReactDOM.render(
<div
className="kbnMarkdown__body canvasMarkdown"
style={fontStyle}
dangerouslySetInnerHTML={html}
/>,
domNode,
() => handlers.done()
);
/* eslint-enable */
handlers.onDestroy(() => ReactDOM.unmountComponentAtNode(domNode));
},
});
|
import os
from coinbase.wallet.client import Client
from portfolio import Portfolio
API_KEY = os.environ.get("COINBASE_API_KEY")
API_SECRET = os.environ.get("COINBASE_API_SECRET")
Portfolio.init(API_KEY, API_SECRET)
portfolio = Portfolio()
|
import logging
import re
from streamlink.compat import urlparse
from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
from streamlink.utils.parse import parse_qsd
log = logging.getLogger(__name__)
class BrightcovePlayer:
URL_PLAYER = "https://players.brightcove.net/{account_id}/{player_id}/index.html?videoId={video_id}"
URL_API = "https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}"
def __init__(self, session, account_id, player_id="default_default"):
self.session = session
self.account_id = account_id
self.player_id = player_id
self.title = None
log.debug("Creating player for account {0} (player_id={1})".format(account_id, player_id))
def get_streams(self, video_id):
log.debug("Finding streams for video: {0}".format(video_id))
player_url = self.URL_PLAYER.format(
account_id=self.account_id,
player_id=self.player_id,
video_id=video_id
)
policy_key = self.session.http.get(
player_url,
params={"videoId": video_id},
schema=validate.Schema(
validate.transform(re.compile(r"""policyKey\s*:\s*(?P<q>['"])(?P<key>[\w-]+)(?P=q)""").search),
validate.any(None, validate.get("key"))
)
)
if not policy_key:
raise PluginError("Could not find Brightcove policy key")
log.debug("Found policy key: {0}".format(policy_key))
self.session.http.headers.update({"Referer": player_url})
sources, self.title = self.session.http.get(
self.URL_API.format(account_id=self.account_id, video_id=video_id),
headers={"Accept": "application/json;pk={0}".format(policy_key)},
schema=validate.Schema(
validate.parse_json(),
{
"sources": [{
"src": validate.url(),
validate.optional("type"): validate.text,
validate.optional("container"): validate.text,
validate.optional("height"): int,
validate.optional("avg_bitrate"): int,
}],
validate.optional("name"): validate.text,
},
validate.union_get("sources", "name")
)
)
for source in sources:
if source.get("type") in ("application/vnd.apple.mpegurl", "application/x-mpegURL"):
for s in HLSStream.parse_variant_playlist(self.session, source.get("src")).items():
yield s
elif source.get("container") == "MP4":
# determine quality name
if source.get("height"):
q = "{0}p".format(source.get('height'))
elif source.get("avg_bitrate"):
q = "{0}k".format(source.get('avg_bitrate') // 1000)
else:
q = "live"
yield q, HTTPStream(self.session, source.get("src"))
@pluginmatcher(re.compile(
r"https?://players\.brightcove\.net/(?P<account_id>[^/]+)/(?P<player_id>[^/]+)/index\.html"
))
class Brightcove(Plugin):
def _get_streams(self):
video_id = parse_qsd(urlparse(self.url).query).get("videoId")
player = BrightcovePlayer(self.session, self.match.group("account_id"), self.match.group("player_id"))
streams = dict(player.get_streams(video_id))
self.title = player.title
return streams
__plugin__ = Brightcove
|
import json
import numpy as np
from PIL import Image, ImageDraw
import os
def draw(I, boxes):
for box in boxes:
draw = ImageDraw.Draw(I)
# Draw bounding box in neon yellow
top, left, bottom, right = box[:4]
draw.rectangle([left, top, right, bottom], outline=(204, 255, 0))
del draw
return I
# set the path to the downloaded data:
data_path = './data'
# set a path for saving predictions:
preds_path = './predictions'
# set a path for saving visualizations:
vis_path = './visualizations'
# load splits:
split_path = './splits'
file_names_train = np.load(os.path.join(split_path, 'file_names_train.npy'))
file_names_test = np.load(os.path.join(split_path, 'file_names_test.npy'))
# get bounding boxes
with open(os.path.join(preds_path, 'preds_train.json')) as f:
bounding_boxes_train = json.load(f)
with open(os.path.join(preds_path, 'preds_test.json')) as f:
bounding_boxes_test = json.load(f)
for i in range(len(file_names_train)):
# read image using PIL:
I = Image.open(os.path.join(data_path, file_names_train[i]))
I = draw(I, bounding_boxes_train[file_names_train[i]])
I.save(os.path.join(vis_path, file_names_train[i]))
for i in range(len(file_names_test)):
# read image using PIL:
I = Image.open(os.path.join(data_path, file_names_test[i]))
I = draw(I, bounding_boxes_test[file_names_test[i]])
I.save(os.path.join(vis_path, file_names_test[i]))
|
'use strict';
var SynapsePay = require('../../lib/SynapsePay');
var _ = require('lodash');
// Make sure we are running in sandbox
SynapsePay.apiBase = SynapsePay.apiSandbox;
SynapsePay.clientId = "4528d2e0a2988064d8ac";
SynapsePay.clientSecret = "dcbf52b16040c94a35f345b7e2c285f936d673c9";
SynapsePay.User.login("3ac38d63db58466982fe6f871c48f1", "TestTest123$").then(function(client) {
// With a promise
client.deposits.micro({
amount1: "0.10",
amount2: "0.22",
bank_id: "2174",
}).then(function(deposits) {
_.each(deposits.data, function(deposit) {
console.log(deposit);
});
}).catch(function(err) {
console.log("Got an error in DepositEndpoint#micro.");
console.log(err);
});
// With a callback
client.deposits.micro({
amount1: "0.10",
amount2: "0.22",
bank_id: "2174",
}, function(deposits, err) {
if(err) {
console.log("Got an error in DepositEndpoint#micro.");
console.log(err);
} else {
_.each(deposits.data, function(deposit) {
console.log(deposit);
});
}
});
}).catch(function(e) {
console.log("Got an error when attempting to log in.");
console.log(e);
});
|
KISSY.add(KISSY.noop,{
requires:[
'./delegate',
'./delegate-advanced',
'./event',
'./fire',
'./focus',
'./group',
'./mouse'
]
});
|
const { events } = require('./data.json');
export default (req, res) => {
if (req.method === 'GET') {
res.status(200).json(events);
} else {
res.setHeader('Allow', ['GET']);
res.status(405).json({ message: `Method ${req.method} is not allowed` });
}
};
|
#%%
import sys
from typing import Any, List
import pandas as pd
sys.path.append('C:/Users/panos/Documents/Διπλωματική/code/fz')
from arfftocsv import function_labelize
# %%
def function_concat_df(dest: List[str], labels: List[str],
source: List[str])->pd.DataFrame:
"""
function that takes the dir of a number of csvs, adds column names
and binds the to one saving them also to
specified in source List each of them
"""
dataframe = pd.DataFrame(columns=labels)
for d, s in zip(dest, source):
df = function_labelize(dest=d, labels=labels, source = s)
dataframe = pd.concat([dataframe, df], axis=0, ignore_index=True)
dataframe.to_csv('data.txt', index=False)
return dataframe
# %%
|
// Helper functions for emitting HTML from Javascript
let valid = function (value) {
return (typeof (value) !== "undefined") && (value !== null);
};
let block = function (block, attributes, content) {
let result = "<" + block;
if (valid (attributes)) {
let attributeNames = Object.keys (attributes);
for (let attributeName of attributeNames) {
if (valid (attributes[attributeName])) {
result += " " + attributeName + "=\"" + attributes[attributeName] + "\"";
}
}
}
return result + (valid (content) ? (">" + content + "</" + block + ">") : ("/>"));
};
let div = function (cssClass, content) {
return block ("div", { "class": cssClass }, content);
};
Bedrock.Html = function () {
let $ = Object.create (null);
$.removeAllChildren = function (element) {
while (element.firstChild) {
element.removeChild (element.firstChild);
}
};
$.makeElement = function (tag, options) {
let element = document.createElement (tag);
let optionNames = Object.keys (options);
for (let optionName of optionNames) {
switch (optionName) {
case "class": {
element.classList.add (options.class);
break;
}
case "classes": {
for (let cssClass of options.classes) {
element.classList.add (cssClass);
}
break;
}
case "style": {
for (let style of Object.keys (options.style)) {
element.style[style] = options.style[style];
}
break;
}
default: {
element[optionName] = options[optionName];
break;
}
}
}
return element;
};
$.addElement = function (parent, tag, options, before) {
let element = $.makeElement(tag, options);
parent.insertBefore (element, (typeof before !== "undefined") ? before : null);
return element;
};
/**
* Utility function to tell if an element is in view in the scrolling region of a container
* @param element
* @param view
* @returns {boolean}
*/
$.elementIsInView = function (element, view) {
let viewTop = view.scrollTop;
let viewBottom = view.offsetHeight + viewTop;
let elementTop = element.offsetTop;
let elementBottom = elementTop + element.offsetHeight;
return ((elementBottom <= viewBottom) && (elementTop >= viewTop));
};
$.Builder = function () {
let _ = Object.create (Bedrock.Base);
_.init = function (parameters) {
this.parentBuilder = ("parentBuilder" in parameters) ? parameters.parentBuilder : null;
this.elementType = parameters.elementType;
this.elementParameters = parameters.elementParameters;
this.builders = [];
return this;
};
_.addBuilder = function (builder) {
this.builders.push (builder);
return this;
};
_.add = function (elementType, elementParameters) {
// if this method is called as a static, this is creating a new builder
return (this === _) ?
_.new ({ elementType: elementType, elementParameters: elementParameters }).build () :
this.addBuilder (_.new ( { parentBuilder: this, elementType: elementType, elementParameters: elementParameters }));
};
_.beginBuilder = function (builder) {
this.builders.push (builder);
return builder;
};
_.begin = function (elementType, elementParameters) {
// if this method is called as a static, this is creating a new builder
return (this === _) ?
_.new ({ elementType: elementType, elementParameters: elementParameters }) :
this.beginBuilder (_.new ({ parentBuilder: this, elementType: elementType, elementParameters: elementParameters }));
};
_.end = function () {
return (this.parentBuilder !== null) ? this.parentBuilder : this.build ();
};
_.build = function () {
// create my element
let element = $.makeElement (this.elementType, this.elementParameters);
// walk down the builders, building in turn
for (let builder of this.builders) {
element.appendChild(builder.build ())
}
return element;
};
return _;
} ();
return $;
} ();
|
from bs4 import BeautifulSoup
import requests
import csv
import sys
from urllib.error import HTTPError
sys.path.append("..")
import mytemp
import time
data={
'wid':'346171123114509',
'dateGroup':'9month'
}
header={
'Referer':'http://data.weibo.com/index/newindex?visit_type=trend&wid=346171123114509',
'User-Agent':'Android'
}
url='http://data.weibo.com/index/ajax/newindex/getchartdata'
req=requests.post(url,data,headers=header)
print(req.text)
|
from __future__ import division, print_function, unicode_literals
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "t 0.1, s, t 2, s, t 5.1, s, q"
tags = "point_to_world"
import cocos
from cocos.director import director
from cocos.sprite import Sprite
from cocos.actions import *
import pyglet
from pyglet.gl import *
class TestLayer(cocos.layer.Layer):
def __init__(self):
super( TestLayer, self ).__init__()
x,y = director.get_window_size()
sprite1 = Sprite('grossini.png')
self.add( sprite1 )
sprite1.position = 300,300
sprite2 = Sprite('grossini.png')
sprite1.add( sprite2 )
sprite2.position = -50,-50
sprite3 = Sprite('grossini.png')
sprite2.add( sprite3 )
sprite3.position = 150,150
sprite3.rotation = 0
sprite3.opacity = 128
self.sprite3 = sprite3
sprite1.do( ScaleBy(1.5, 10) )
sprite2.do( MoveBy((100,-150),5) )
sprite3.do( RotateBy(360,20) )
def draw( self ):
p = self.sprite3.point_to_world( (0,0) )
glPointSize(16)
glBegin(GL_POINTS)
glColor4f(1, 0, 0, 1)
glVertex3f(p.x, p.y, 0)
glEnd()
def main():
director.init()
test_layer = TestLayer ()
main_scene = cocos.scene.Scene (test_layer)
director.run (main_scene)
if __name__ == '__main__':
main()
|
"""Review learning information"""
from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class ReviewInfo(BaseModel):
number_of_reviews: int
neighborhood: str
@router.post('/review_info')
async def review_neighborhood(info: ReviewInfo):
result = "The number of review is: " + str(info.number_of_reviews) + " The neighborhood is: " + info.neighborhood
return {"Information on review and neighborhood ": result}
|
"""
Builds the tensorflow graph neural networks for the actor and critic
"""
import tensorflow as tf
from settings import Settings
def build_Q_network(state, trainable, reuse, scope):
"""
Defines a Q network that predicts the Q-value (expected future return)
from taking a certain action from a given state, and then following the policy
thereafter.
"""
with tf.variable_scope(scope):
# The state is effectively the "0th" layer
layer = state
##################################
##### Fully connected layers #####
##################################
for i, number_of_neurons in enumerate(Settings.Q_NETWORK_HIDDEN_LAYERS):
layer = tf.layers.dense(inputs = layer,
units = number_of_neurons,
trainable = trainable,
reuse = reuse,
activation = tf.nn.relu,
name = 'fully_connected_layer_' + str(i))
##############################################
##### Final Layer to get Action Q-values #####
##############################################
"""
The final layer does not go through an activation function, because we
don't need the output Q-value to be within a certain range
"""
q_values = tf.layers.dense(inputs = layer,
units = Settings.ACTION_SIZE,
trainable = trainable,
reuse = reuse,
activation = None,
name = 'output_layer')
return q_values
|
import React from 'react';
import SignUp from './SignUp';
import HorizontalForm from './HorizontalForm';
import FormElements from './FormElements';
const RegularForms = () => (
<div>
<div className="row">
<div className="col-md-6">
<SignUp onSubmit={values => alert('Enter values: ' + JSON.stringify(values, null, 2))} />
</div>
<div className="col-md-6">
<HorizontalForm onSubmit={values => alert('Enter values: ' + JSON.stringify(values, null, 2))} />
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormElements initialValues={{
radioGroup: 'male',
a: true,
checked: true,
disabledChecked: true,
radioOnOff: 'on',
radioDisabledOnOff: 'on'
}} />
</div>
</div>
</div>
);
export default RegularForms;
|
/*
* 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.
*/
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["complex-table"],{"333d":function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"pagination-container",class:{hidden:e.hidden}},[n("el-pagination",e._b({attrs:{background:e.background,"current-page":e.currentPage,"page-size":e.pageSize,layout:e.layout,"page-sizes":e.pageSizes,total:e.total},on:{"update:currentPage":function(t){e.currentPage=t},"update:current-page":function(t){e.currentPage=t},"update:pageSize":function(t){e.pageSize=t},"update:page-size":function(t){e.pageSize=t},"size-change":e.handleSizeChange,"current-change":e.handleCurrentChange}},"el-pagination",e.$attrs,!1))],1)},i=[],r=n("d225"),o=n("b0b4"),c=n("308d"),u=n("6bb5"),s=n("4e2b"),l=n("9ab4"),d=n("60a3"),p=function(e,t,n,a){return e/=a/2,e<1?n/2*e*e+t:(e--,-n/2*(e*(e-2)-1)+t)},f=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}}(),b=function(e){document.documentElement.scrollTop=e,document.body.parentNode.scrollTop=e,document.body.scrollTop=e},m=function(){return document.documentElement.scrollTop||document.body.parentNode.scrollTop||document.body.scrollTop},h=function(e,t,n){var a=m(),i=e-a,r=20,o=0;t="undefined"===typeof t?500:t;var c=function e(){o+=r;var c=p(o,a,i,t);b(c),o<t?f(e):n&&"function"===typeof n&&n()};c()},g=function(e){function t(){return Object(r["a"])(this,t),Object(c["a"])(this,Object(u["a"])(t).apply(this,arguments))}return Object(s["a"])(t,e),Object(o["a"])(t,[{key:"handleSizeChange",value:function(e){this.$emit("pagination",{page:this.currentPage,limit:e}),this.autoScroll&&h(0,800)}},{key:"handleCurrentChange",value:function(e){this.$emit("pagination",{page:e,limit:this.pageSize}),this.autoScroll&&h(0,800)}},{key:"currentPage",get:function(){return this.page},set:function(e){this.$emit("update:page",e)}},{key:"pageSize",get:function(){return this.limit},set:function(e){this.$emit("update:limit",e)}}]),t}(d["c"]);l["a"]([Object(d["b"])({required:!0})],g.prototype,"total",void 0),l["a"]([Object(d["b"])({default:1})],g.prototype,"page",void 0),l["a"]([Object(d["b"])({default:20})],g.prototype,"limit",void 0),l["a"]([Object(d["b"])({default:function(){return[10,20,30,50]}})],g.prototype,"pageSizes",void 0),l["a"]([Object(d["b"])({default:"total, sizes, prev, pager, next, jumper"})],g.prototype,"layout",void 0),l["a"]([Object(d["b"])({default:!0})],g.prototype,"background",void 0),l["a"]([Object(d["b"])({default:!0})],g.prototype,"autoScroll",void 0),l["a"]([Object(d["b"])({default:!1})],g.prototype,"hidden",void 0),g=l["a"]([Object(d["a"])({name:"Pagination"})],g);var v=g,y=v,j=(n("b056"),n("2877")),w=Object(j["a"])(y,a,i,!1,null,"01722ae9",null);t["a"]=w.exports},"4eba":function(e,t,n){"use strict";n.r(t);var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"app-container"},[n("div",{staticClass:"filter-container"},[n("el-button",{staticClass:"filter-item",staticStyle:{"margin-left":"10px"},attrs:{type:"primary",icon:"el-icon-edit"},on:{click:e.handleCreate}},[e._v("\n "+e._s(e.$t("table.add"))+"\n ")])],1),n("el-table",{directives:[{name:"loading",rawName:"v-loading",value:e.listLoading,expression:"listLoading"}],key:e.tableKey,staticStyle:{width:"100%"},attrs:{data:e.tableData,border:!1,fit:"","highlight-current-row":""},on:{"sort-change":e.sortChange}},[e._l(e.tableKeys,(function(e,t){return n("el-table-column",{key:t,attrs:{label:e.key,prop:e.key,width:e.width,"class-name":"left"===e.align?"":"status-col","header-align":"center"}})})),n("el-table-column",{attrs:{label:e.$t("table.actions"),align:"center",width:"230","class-name":"fixed-width"},scopedSlots:e._u([{key:"default",fn:function(t){var a=t.row;return[n("el-button",{attrs:{type:"primary",size:"mini"},on:{click:function(t){return e.handleToEdit(a)}}},[e._v("\n "+e._s(e.$t("table.edit"))+"\n ")]),"deleted"!==a.status?n("el-button",{attrs:{size:"mini",type:"danger"},on:{click:function(t){return e.handleRemove(a)}}},[e._v("\n "+e._s(e.$t("table.delete"))+"\n ")]):e._e()]}}])})],2)],1)},i=[],r=(n("7f7f"),n("768b")),o=(n("ac6a"),n("ffc1"),n("75fc")),c=(n("96cf"),n("3b8d")),u=n("d225"),s=n("b0b4"),l=n("308d"),d=n("6bb5"),p=n("4e2b"),f=n("9ab4"),b=n("60a3"),m=n("333d"),h=n("c738"),g=function(e){function t(){var e;return Object(u["a"])(this,t),e=Object(l["a"])(this,Object(d["a"])(t).apply(this,arguments)),e.tableKey=0,e.list=[],e.total=0,e.listLoading=!0,e.listQuery={page:1,limit:20,importance:void 0,title:void 0,type:void 0,sort:"+id"},e.tableData=[],e.tableKeys=[],e}return Object(p["a"])(t,e),Object(s["a"])(t,[{key:"created",value:function(){this.getList()}},{key:"getList",value:function(){var e=Object(c["a"])(regeneratorRuntime.mark((function e(){var t,n,a,i=this;return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return this.listLoading=!0,this.tableKeys=[{key:"username",width:300},{key:"description",width:300,align:"left"},{key:"plugins",width:400}],e.next=4,Object(h["b"])();case 4:t=e.sent,n=t.node.nodes,a=void 0===n?[]:n,a=Object(o["a"])(a).map((function(e){var t=[],n=e.value,a=n.username,i=n.desc;return Object.entries(n.plugins).map((function(e){var n=Object(r["a"])(e,2),a=n[0],i=n[1];t.push({name:a,key:i.key})})),{username:a,plugins:t.map((function(e){return e.name})).join(", "),pluginArr:t,description:i}})),this.tableData=a,this.total=a.length,setTimeout((function(){i.listLoading=!1}),500);case 11:case"end":return e.stop()}}),e,this)})));function t(){return e.apply(this,arguments)}return t}()},{key:"handleFilter",value:function(){this.listQuery.page=1,this.getList()}},{key:"handleRemove",value:function(e){var t=this;this.$confirm("Do you want to remove consumer ".concat(e.username,"?"),"Warning",{confirmButtonText:"Confirm",cancelButtonText:"Cancel",type:"warning"}).then(Object(c["a"])(regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){while(1)switch(n.prev=n.next){case 0:return n.next=2,Object(h["c"])(e.username);case 2:t.getList(),t.$message.success("Remove consumer ".concat(e.username," successfully!"));case 4:case"end":return n.stop()}}),n)}))))}},{key:"sortChange",value:function(e){var t=e.prop,n=e.order;"id"===t&&this.sortByID(n)}},{key:"sortByID",value:function(e){this.listQuery.sort="ascending"===e?"+id":"-id",this.handleFilter()}},{key:"handleCreate",value:function(){this.$router.push({name:"SchemaConsumersCreate"})}},{key:"handleToEdit",value:function(e){this.$router.push({name:"SchemaConsumersEdit",params:{username:e.username}})}}]),t}(b["c"]);g=f["a"]([Object(b["a"])({name:"ComplexTable",components:{Pagination:m["a"]}})],g);var v=g,y=v,j=(n("b878"),n("2877")),w=Object(j["a"])(y,a,i,!1,null,null,null);t["default"]=w.exports},"504c":function(e,t,n){var a=n("9e1e"),i=n("0d58"),r=n("6821"),o=n("52a7").f;e.exports=function(e){return function(t){var n,c=r(t),u=i(c),s=u.length,l=0,d=[];while(s>l)n=u[l++],a&&!o.call(c,n)||d.push(e?[n,c[n]]:c[n]);return d}}},"6b99":function(e,t,n){},b056:function(e,t,n){"use strict";var a=n("6b99"),i=n.n(a);i.a},b32d:function(e,t,n){"use strict";var a=n("bc3a"),i=n.n(a),r=n("5c96"),o=i.a.create({baseURL:"/apisix/admin/",timeout:5e3});o.interceptors.request.use((function(e){return e}),(function(e){Promise.reject(e)})),o.interceptors.response.use((function(e){return e.data}),(function(e){return Object(r["Message"])({message:e.response.data.error_msg||e.message,type:"error",duration:5e3}),Promise.reject(e)})),t["a"]=o},b878:function(e,t,n){"use strict";var a=n("cb5c"),i=n.n(a);i.a},c738:function(e,t,n){"use strict";n.d(t,"d",(function(){return i})),n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c}));var a=n("b32d"),i=function(e){return Object(a["a"])({url:"/consumers",method:"PUT",data:e})},r=function(){return Object(a["a"])({url:"/consumers",method:"GET"})},o=function(e){return Object(a["a"])({url:"/consumers/".concat(e),method:"GET"})},c=function(e){return Object(a["a"])({url:"/consumers/".concat(e),method:"DELETE"})}},cb5c:function(e,t,n){e.exports={menuBg:"#304156",menuText:"#bfcbd9",menuActiveText:"#409eff"}},ffc1:function(e,t,n){var a=n("5ca1"),i=n("504c")(!0);a(a.S,"Object",{entries:function(e){return i(e)}})}}]);
|
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Convert LXMERT checkpoint."""
import argparse
import torch
from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert
from transformers.utils import logging
logging.set_verbosity_info()
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path):
# Initialise PyTorch model
config = LxmertConfig.from_json_file(config_file)
print(f"Building PyTorch model from configuration: {config}")
model = LxmertForPreTraining(config)
# Load weights from tf checkpoint
load_tf_weights_in_lxmert(model, config, tf_checkpoint_path)
# Save pytorch-model
print(f"Save PyTorch model to {pytorch_dump_path}")
torch.save(model.state_dict(), pytorch_dump_path)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
args = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
|
import math
import os
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
BatchNorm2d = nn.BatchNorm2d
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
hidden_dim = round(inp * expand_ratio)
self.use_res_connect = self.stride == 1 and inp == oup
if expand_ratio == 1:
self.conv = nn.Sequential(
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
BatchNorm2d(oup),
)
else:
self.conv = nn.Sequential(
# pw
nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
BatchNorm2d(oup),
)
def forward(self, x):
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x)
class MobileNetV2(nn.Module):
def __init__(self, n_class=1000, input_size=224, width_mult=1.):
super(MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
interverted_residual_setting = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# building first layer
assert input_size % 32 == 0
input_channel = int(input_channel * width_mult)
self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel
self.features = [conv_bn(3, input_channel, 2)]
# building inverted residual blocks
for t, c, n, s in interverted_residual_setting:
output_channel = int(c * width_mult)
for i in range(n):
if i == 0:
self.features.append(block(input_channel, output_channel, s, expand_ratio=t))
else:
self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))
input_channel = output_channel
# building last several layers
self.features.append(conv_1x1_bn(input_channel, self.last_channel))
# make it nn.Sequential
self.features = nn.Sequential(*self.features)
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(self.last_channel, n_class),
)
self._initialize_weights()
def forward(self, x):
x = self.features(x)
x = x.mean(3).mean(2)
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
n = m.weight.size(1)
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
def load_url(url, model_dir='./model_data', map_location=None):
if not os.path.exists(model_dir):
os.makedirs(model_dir)
filename = url.split('/')[-1]
cached_file = os.path.join(model_dir, filename)
if os.path.exists(cached_file):
return torch.load(cached_file, map_location=map_location)
else:
return model_zoo.load_url(url,model_dir=model_dir)
def mobilenetv2(pretrained=False, **kwargs):
model = MobileNetV2(n_class=1000, **kwargs)
if pretrained:
model.load_state_dict(load_url('http://sceneparsing.csail.mit.edu/model/pretrained_resnet/mobilenet_v2.pth.tar'), strict=False)
return model
if __name__ == "__main__":
model = mobilenetv2()
for i, layer in enumerate(model.features):
print(i, layer)
|
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from rest_framework import status
from .serializers import PostSerializer
from .models import Post
class PostView(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
authentication_classes = (TokenAuthentication, )
permissions_classes = (IsAuthenticated, )
def destroy(self, request, *args, **kwargs):
try:
user = request.user
instance = self.get_object()
if user.is_anonymous or user.id != instance.user_id:
return Response({'message': 'you aren`t owner of this post'}, status=status.HTTP_403_FORBIDDEN)
self.perform_destroy(instance)
except:
return Response({'message': 'doesn`t exists'})
return Response(status=status.HTTP_204_NO_CONTENT)
|
# qubit number=3
# total number=47
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename=(kernel + '-oracle.png'))
return oracle
def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the Bernstein-Vazirani circuit
zero = np.binary_repr(0, n)
b = f(zero)
# initial n + 1 bits
input_qubit = QuantumRegister(n+1, "qc")
classicals = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classicals)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(input_qubit[n])
# circuit begin
prog.h(input_qubit[1]) # number=1
prog.rx(-0.09738937226128368,input_qubit[2]) # number=2
prog.h(input_qubit[1]) # number=33
prog.cz(input_qubit[2],input_qubit[1]) # number=34
prog.h(input_qubit[1]) # number=35
prog.h(input_qubit[1]) # number=3
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[n])
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [input_qubit[n]])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
return prog
def get_statevector(prog: QuantumCircuit) -> Any:
state_backend = Aer.get_backend('statevector_simulator')
statevec = execute(prog, state_backend).result()
quantum_state = statevec.get_statevector()
qubits = round(log2(len(quantum_state)))
quantum_state = {
"|" + np.binary_repr(i, qubits) + ">": quantum_state[i]
for i in range(2 ** qubits)
}
return quantum_state
def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:
# Q: which backend should we use?
# get state vector
quantum_state = get_statevector(prog)
# get simulate results
# provider = IBMQ.load_account()
# backend = provider.get_backend(backend_str)
# qobj = compile(prog, backend, shots)
# job = backend.run(qobj)
# job.result()
backend = Aer.get_backend(backend_str)
# transpile/schedule -> assemble -> backend.run
results = execute(prog, backend, shots=shots).result()
counts = results.get_counts()
a = Counter(counts).most_common(1)[0][0][::-1]
return {
"measurements": counts,
# "state": statevec,
"quantum_state": quantum_state,
"a": a,
"b": b
}
def bernstein_test_1(rep: str):
"""011 . x + 1"""
a = "011"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_2(rep: str):
"""000 . x + 0"""
a = "000"
b = "0"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_3(rep: str):
"""111 . x + 1"""
a = "111"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
if __name__ == "__main__":
n = 2
a = "11"
b = "1"
f = lambda rep: \
bitwise_xor(bitwise_dot(a, rep), b)
prog = build_circuit(n, f)
sample_shot =4000
writefile = open("../data/startQiskit_noisy258.csv", "w")
# prog.draw('mpl', filename=(kernel + '.png'))
backend = FakeYorktown()
circuit1 = transpile(prog, FakeYorktown())
circuit1.h(qubit=2)
circuit1.x(qubit=3)
circuit1.measure_all()
info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
|
import argparse
import os
import sys
import torch
# yapf: enable
# yapf: disable
sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) # isort:skip # noqa
import agilegan # isort:skip # noqa
from mmgen.apis import init_model, sample_uncoditional_model # isort:skip # noqa
def parse_args():
parser = argparse.ArgumentParser(description='Blend decoders\' weights of'
' EncoderDecoders')
parser.add_argument('modelA', help='EncoderDecoder config file path'
',which decoder is base generator')
parser.add_argument('modelB', help='EncoderDecoder config file path'
'which decoder is stylized generator')
parser.add_argument(
'--swap-layer', type=int, default=4, help='swap layer')
parser.add_argument(
'--device', type=str, default='cuda:0', help='CUDA device id')
parser.add_argument(
'--save-path',
type=str,
default='./work_dirs/pre-trained/agile_transfer_blended.pth',
help='path to save image transfer result')
args = parser.parse_args()
return args
def swap_weights(base_ckpt, swap_ckpt, start_index, end_index=8):
for i in range(start_index, end_index):
for layer in base_ckpt.keys():
if f'convs.{2*i}' in layer or \
f'convs.{2*i + 1}' in layer or f'to_rgbs.{i}' in layer:
base_ckpt[layer] = swap_ckpt[layer]
return base_ckpt
def main():
args = parse_args()
# init models
modelA = init_model(args.modelA, checkpoint=None, device=args.device)
modelB = init_model(args.modelB, checkpoint=None, device=args.device)
base_ckpt = modelA.decoder.state_dict()
swap_ckpt = modelB.decoder.state_dict()
start_index = args.swap_layer - 1
end_index = modelA.decoder.log_size - 2
modelA.decoder.load_state_dict(swap_weights(base_ckpt, swap_ckpt,
start_index, end_index))
torch.save(modelA.state_dict(), args.save_path)
torch.save(modelA.decoder.state_dict(), 'work_dirs/pre-trained/'
'swap_toonify.pth')
if __name__ == '__main__':
main()
|
const gulp = require('gulp');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const del = require('del');
/**
* Cleans the prpl-server build in the server directory.
*/
gulp.task('prpl-server:clean', () => {
return del('server/build');
});
/**
* Copies the prpl-server build to the server directory while renaming the
* node_modules directory so services like App Engine will upload it.
*/
gulp.task('prpl-server:build', () => {
const pattern = 'node_modules';
const replacement = 'node_assets';
return gulp
.src('build/**')
.pipe(
rename(path => {
path.basename = path.basename.replace(pattern, replacement);
path.dirname = path.dirname.replace(pattern, replacement);
})
)
.pipe(replace(pattern, replacement))
.pipe(gulp.dest('server/build'));
});
/**
* Copies the assets to the server directory
*/
gulp.task('prpl-server:assets', () => {
return gulp.src(['img/**', 'css/**', 'mdl/**', 'manifest.json'], { base: '.' }).pipe(gulp.dest('server/build'));
});
gulp.task('prpl-server', gulp.series('prpl-server:clean', 'prpl-server:build', 'prpl-server:assets'));
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Carousel from './Carousel'
import * as serviceWorker from './serviceWorker';
ReactDOM.render((
<Carousel width={400} height={400}>
<img
draggable="false"
src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540189515942&di=99667ef98b324aabf1d1965f99097748&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201601%2F26%2F20160126173726_wcxR5.jpeg"
style={{width: 400, height: 400}}
>
</img>
<img
draggable="false"
src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540189515942&di=ff8eceeafa9ff70e4acc12bdecf0f0b3&imgtype=0&src=http%3A%2F%2Fimage.jisuxz.com%2Fdesktop%2F1856%2Fjisuxz_Dilraba_01.jpg"
style={{width: 400, height: 400}}
>
</img>
</Carousel>
), document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
|
/**
* Configuration container
*/
class Configuration {
/**
* Create a new configuration
* @param {String} privateKey
* @param {String} publicKey
* @constructor
*/
constructor(privateKey, publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
}
}
module.exports = Configuration;
|
#!/usr/bin/env python3
"""Home Assistant setup script."""
from datetime import datetime as dt
from setuptools import find_packages, setup
import homeassistant.const as hass_const
PROJECT_NAME = "Home Assistant"
PROJECT_PACKAGE_NAME = "homeassistant"
PROJECT_LICENSE = "Apache License 2.0"
PROJECT_AUTHOR = "The Home Assistant Authors"
PROJECT_COPYRIGHT = f" 2013-{dt.now().year}, {PROJECT_AUTHOR}"
PROJECT_URL = "https://www.home-assistant.io/"
PROJECT_EMAIL = "hello@home-assistant.io"
PROJECT_GITHUB_USERNAME = "home-assistant"
PROJECT_GITHUB_REPOSITORY = "core"
PYPI_URL = f"https://pypi.python.org/pypi/{PROJECT_PACKAGE_NAME}"
GITHUB_PATH = f"{PROJECT_GITHUB_USERNAME}/{PROJECT_GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{hass_const.__version__}.zip"
PROJECT_URLS = {
"Bug Reports": f"{GITHUB_URL}/issues",
"Dev Docs": "https://developers.home-assistant.io/",
"Discord": "https://discordapp.com/invite/c5DvZ4e",
"Forum": "https://community.home-assistant.io/",
}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
REQUIRES = [
"aiohttp==3.6.2",
"astral==1.10.1",
"async_timeout==3.0.1",
"attrs==19.3.0",
"bcrypt==3.1.7",
"certifi>=2020.4.5.1",
"ciso8601==2.1.3",
"importlib-metadata==1.6.0;python_version<'3.8'",
"jinja2>=2.11.2",
"PyJWT==1.7.1",
# PyJWT has loose dependency. We want the latest one.
"cryptography==2.9.2",
"pip>=8.0.3",
"python-slugify==4.0.1",
"pytz>=2020.1",
"pyyaml==5.3.1",
"requests==2.24.0",
"ruamel.yaml==0.15.100",
"voluptuous==0.11.7",
"voluptuous-serialize==2.4.0",
"yarl==1.4.2",
]
MIN_PY_VERSION = ".".join(map(str, hass_const.REQUIRED_PYTHON_VER))
setup(
name=PROJECT_PACKAGE_NAME,
version=hass_const.__version__,
url=PROJECT_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
author=PROJECT_AUTHOR,
author_email=PROJECT_EMAIL,
packages=PACKAGES,
include_package_data=True,
zip_safe=False,
install_requires=REQUIRES,
python_requires=f">={MIN_PY_VERSION}",
test_suite="tests",
entry_points={"console_scripts": ["hass = homeassistant.__main__:main"]},
)
|
import tempfile
import os
from PIL import Image
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APITestCase
from django.urls import reverse
from core.models import Recipe, Tag, Ingredient
from recipe.serializer import RecipeSerializer, RecipeDetailSerializer
RECIPE_LIST_URL = reverse('recipe:recipe-list')
def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=(recipe_id, ))
def recipe_url_detail(_id):
return reverse('recipe:recipe-detail', args=(_id, ))
def sample_recipe(user, **params):
defaults = {
'title': 'Sample recipe',
'price': 5.00,
'time_minutes': 10
}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults)
def sample_tag(user, name='Sample Tag'):
return Tag.objects.create(user=user, name=name)
def sample_ingredient(user, name='Sample Ingredient'):
return Ingredient.objects.create(user=user, name=name)
class PublicRecipeAPITests(APITestCase):
def test_retrieve_recipe(self):
resp = self.client.get(RECIPE_LIST_URL)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateRecipeAPITests(APITestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
'foo@bar.gr',
'test123'
)
self.client.force_authenticate(self.user)
def test_retrieve_recipe(self):
sample_recipe(self.user)
sample_recipe(self.user)
recipes = Recipe.objects.order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
resp = self.client.get(RECIPE_LIST_URL)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.data, serializer.data)
def test_retrieve_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user(
'another@bar.gr',
'test123'
)
sample_recipe(self.user)
sample_recipe(user2)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(recipes, many=True)
resp = self.client.get(RECIPE_LIST_URL)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.data, serializer.data)
def test_view_recipe_detail(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
serializer = RecipeDetailSerializer(recipe)
detail_url = recipe_url_detail(recipe.id)
resp = self.client.get(detail_url)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.data, serializer.data)
def test_create_recipe(self):
payload = {
'title': 'Sample Recipe',
'price': 4.00,
'time_minutes': 5
}
resp = self.client.post(RECIPE_LIST_URL, payload)
recipe = Recipe.objects.get(id=resp.data['id'])
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
for key in payload.keys():
self.assertEqual(payload[key], getattr(recipe, key))
def test_create_recipe_with_tags(self):
tag1 = sample_tag(self.user, 'sample tag1')
tag2 = sample_tag(self.user, 'sample tag2')
payload = {
'title': 'Sample Recipe',
'price': 4.00,
'time_minutes': 5,
'tags': [tag1.id, tag2.id]
}
resp = self.client.post(RECIPE_LIST_URL, payload)
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=resp.data['id'])
tags = recipe.tags.all()
self.assertEqual(tags.count(), 2)
def test_create_recipe_with_ingredients(self):
ingredient1 = sample_ingredient(self.user, 'sample ingredient1')
ingredient2 = sample_ingredient(self.user, 'sample ingredient2')
payload = {
'title': 'Sample Recipe',
'price': 4.00,
'time_minutes': 5,
'ingredients': [ingredient1.id, ingredient2.id]
}
resp = self.client.post(RECIPE_LIST_URL, payload)
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=resp.data['id'])
ingredients = recipe.ingredients.all()
self.assertEqual(ingredients.count(), 2)
self.assertIn(ingredient1, ingredients)
self.assertIn(ingredient2, ingredients)
def test_partial_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tag = sample_tag(user=self.user, name='Curry')
payload = {
'title': 'Another Sample Url',
'tags': [new_tag.id]
}
url = recipe_url_detail(recipe.id)
self.client.patch(url, payload)
recipe.refresh_from_db()
self.assertEqual(recipe.title, payload['title'])
tags = recipe.tags.all()
self.assertEqual(len(tags), 1)
def test_update_recipe(self):
recipe = sample_recipe(user=self.user)
payload = {
'title': 'Another Sample Url',
'time_minutes': 5,
'price': 5
}
url = recipe_url_detail(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.assertEqual(recipe.title, payload['title'])
self.assertEqual(recipe.price, payload['price'])
self.assertEqual(recipe.time_minutes, payload['time_minutes'])
self.assertEqual(recipe.tags.count(), 0)
self.assertEqual(recipe.ingredients.count(), 0)
class RecipeImageUploadTests(APITestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
'user@boo.gr', 'testpass'
)
self.client.force_authenticate(self.user)
self.recipe = sample_recipe(user=self.user)
def tearDown(self):
self.recipe.image.delete()
def test_upload_image_to_recipe(self):
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10)) # black square
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
self.recipe.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertIn('image', res.data)
self.assertTrue(os.path.exists(self.recipe.image.path))
def test_upload_image_bad_request(self):
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_filter_recipes_by_tags(self):
recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Vegetarian')
recipe1.tags.add(tag1)
recipe2.tags.add(tag2)
recipe3 = sample_recipe(user=self.user, title='Fish and chips')
resp = self.client.get(
RECIPE_LIST_URL,
{'tags': f'{tag1.id},{tag2.id}'}
)
serializer1 = RecipeSerializer(recipe1)
serializer2 = RecipeSerializer(recipe2)
serializer3 = RecipeSerializer(recipe3)
self.assertIn(serializer1.data, resp.data)
self.assertIn(serializer2.data, resp.data)
self.assertNotIn(serializer3.data, resp.data)
def test_filter_by_ingredients(self):
recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
recipe3 = sample_recipe(user=self.user, title='Spaghetti with meat')
ingredient1 = Ingredient.objects.create(user=self.user, name='Tomato')
ingredient2 = Ingredient.objects.create(user=self.user, name='Bean')
recipe1.ingredients.add(ingredient1)
recipe2.ingredients.add(ingredient2)
resp = self.client.get(
RECIPE_LIST_URL,
{'ingredients': f'{ingredient1.id},{ingredient2.id}'}
)
serializer1 = RecipeSerializer(recipe1)
serializer2 = RecipeSerializer(recipe2)
serializer3 = RecipeSerializer(recipe3)
self.assertIn(serializer1.data, resp.data)
self.assertIn(serializer2.data, resp.data)
self.assertNotIn(serializer3.data, resp.data)
|
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// About GLSL version:
// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
// Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#else
// Otherwise imgui_impl_opengl3_loader.h will be used.
#endif
#endif
|
import store from '../store.js';
import AppConstants from '../constants/AppConstants';
const add = (type, content, duration = 3000) => {
const _id = Date.now();
const toast = { _id, type, content };
store.dispatch({
type : AppConstants.APP_TOAST_ADD,
toast,
});
setTimeout(() => {
store.dispatch({
type : AppConstants.APP_TOAST_REMOVE,
_id,
});
}, duration);
};
export default {
add,
};
|
/**
* Created by thomas on 2016-09-29 at 17:06.
*
* MIT Licensed
*/
var error = require("../error"),
send = require("../send");
module.exports = Contestant;
function Contestant(instance, ws, quiz_id, id) {
this.instance = instance;
this.model = instance.model;
this.ws = ws;
this.quiz_id = quiz_id;
this.id = id;
this.closed = false;
this.address = ws.upgradeReq.socket.remoteAddress;
}
Contestant.prototype.getInfo = function (callback) {
return this.model.getContestantInfo(this.id, callback);
};
Contestant.prototype.connect = function () {
this.instance.contestantConnect(this);
this.instance.debug("Contestant %s connected (%s)", this.id, this.address);
if (this.instance.started) {
send(this.ws, {
"type": "start",
"title": this.instance.title,
"contestant_id": this.id
});
if (this.instance.currentQuestion != null) {
var question = this.instance.currentQuestion;
send(this.ws, {
"type": "question",
"question_id": question.id,
"question": question.question,
"timeout": question.timeout,
"score": question.score
});
var self = this;
if (question.answerSent) {
this.sendAnswer(question, function (err) {
if (err && err.send) err.send(self.ws);
}, true);
}
}
}
};
Contestant.prototype.disconnect = function () {
this.closed = true;
if (this.instance.host)
this.instance.host.updatePlayers();
this.instance.debug("Contestant %s disconnected (%s)", this.id, this.address);
};
Contestant.prototype.submitResponse = function (msg, callback) {
var self = this;
if (!msg.question_id)
return callback(error("bad_request",
"Message must have a 'question_id' field.", msg));
if (!msg.response_type)
return callback(error("bad_request",
"Message must have a 'response_type' field.", msg));
if (!msg.response_data)
return callback(error("bad_request",
"Message must have a 'response_data' field.", msg));
var question = self.instance.currentQuestion;
if (question === null)
return callback(error("invalid_question",
"The quiz is not currently running any questions.", msg));
if (question.id !== msg.question_id)
return callback(error("invalid_question",
"The current question is not the one that the response was sent for.", msg));
if (question.timeout <= new Date().getTime())
return callback(error("invalid_question",
"The current question is no longer accepting entries."));
if (question.validResponses !== null &&
question.validResponses.indexOf(msg.response_data) === -1)
return callback(error("invalid_client",
"Response is not valid (for multiple choice question)."));
self.model.submitResponse(msg.question_id, self.id, msg.response_type, msg.response_data, function (err, response) {
if (err) return callback(error("server_error",
"An error occurred while submitting a response.", msg, err));
if (self.instance.host) {
self.instance.host.sendResponse(response);
self.instance.debug("Contestant %s submitted response %s", self.id, response.id);
send(self.ws, {
"question_id": msg.question_id,
"response_id": response.id
}, msg);
callback(null);
}
});
};
Contestant.prototype.sendAnswer = function (question, callback, noSideEffects) {
if (this.closed) return callback(null);
var self = this;
self.model.isCorrect(self.id, question.id, function (err, isCorrect, bonusPoints) {
if (err) return callback(error("server_error",
"An error occurred while checking your answer.", null, err));
var score_delta = question.score;
if (!isCorrect || noSideEffects) score_delta = 0;
if (!noSideEffects) score_delta += bonusPoints; // bonus for correct and incorrect
self.model.increaseScore(self.id, score_delta, function (err, score) {
if (err) return callback(error("server_error",
"An error occurred while changing your score.", null, err));
send(self.ws, {
"type": "answer",
"question_id": question.id,
"question": question.question,
"answer": question.answer,
"correct": isCorrect,
"score": score
});
return callback(null);
});
});
};
|
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/UIKit.framework/UIKit
*/
@interface UIFeedbackGenerator : NSObject {
long long _activationCount;
NSObject<OS_dispatch_source> * _autoDeactivateTimer;
long long _autoDeactivationCount;
_UIFeedbackGeneratorConfiguration * _configuration;
<UICoordinateSpace> * _coordinateSpace;
double _currentDelay;
NSSet * _engines;
long long _externalActivationCount;
bool _hasMutableFeedbackKeyPaths;
bool _muted;
NSMutableDictionary * _preparationTimers;
long long _styleActivationCount;
NSSet * _usedFeedbacks;
}
@property (nonatomic, readonly) NSString *_stats_key;
@property (nonatomic) long long activationCount;
@property (getter=_isAutoDeactivated, nonatomic, readonly) bool autoDeactivated;
@property (getter=_autoDeactivationTimeout, nonatomic, readonly) double autoDeactivationTimeout;
@property (getter=_configuration, setter=_setConfiguration:, nonatomic, retain) _UIFeedbackGeneratorConfiguration *configuration;
@property (nonatomic) <UICoordinateSpace> *coordinateSpace;
@property (getter=_effectiveCoordinateSpace, nonatomic, readonly) <UICoordinateSpace> *effectiveCoordinateSpace;
@property (getter=_isEnabled, nonatomic, readonly) bool enabled;
@property (nonatomic, readonly) NSSet *engines;
@property (nonatomic) long long externalActivationCount;
@property (getter=_hasMutableFeedbackKeyPaths, nonatomic, readonly) bool hasMutableFeedbackKeyPaths;
@property (getter=_isMuted, setter=_setMuted:, nonatomic) bool muted;
+ (Class)_configurationClass;
+ (void)_resetAutoDeactivateTimeout;
+ (void)_resetPreparationTimeouts;
+ (void)_setAutoDeactivateTimeout:(double)arg1;
+ (void)_setPreparationTimeout:(double)arg1 forStyle:(long long)arg2;
+ (void)_setRunningTests:(bool)arg1;
+ (id)behaviorWithConfiguration:(id)arg1 coordinateSpace:(id)arg2;
+ (id)behaviorWithCoordinateSpace:(id)arg1;
- (void).cxx_destruct;
- (void)__activateWithStyle:(long long)arg1 completionBlock:(id /* block */)arg2;
- (void)__deactivateWithStyle:(long long)arg1;
- (void)_activateWithStyle:(long long)arg1 completionBlock:(id /* block */)arg2;
- (void)_activated;
- (id)_activationCountStatistics;
- (id)_activationDurationStatistics;
- (id)_activationTimeOutCountStatistics;
- (void)_autoDeactivate;
- (double)_autoDeactivationTimeout;
- (void)_clientDidUpdateGeneratorWithSelector:(SEL)arg1;
- (id)_configuration;
- (void)_deactivateWithStyle:(long long)arg1;
- (void)_deactivated;
- (id)_effectiveCoordinateSpace;
- (void)_forceDeactivationForStyle:(long long)arg1;
- (bool)_hasMutableFeedbackKeyPaths;
- (bool)_isAutoDeactivated;
- (bool)_isEnabled;
- (bool)_isMuted;
- (id)_playCountStatistics;
- (void)_playFeedback:(id)arg1;
- (void)_playFeedback:(id)arg1 withMinimumIntervalPassed:(double)arg2 since:(double*)arg3 prefersRegularPace:(bool)arg4;
- (id)_preparationCountStatistics;
- (double)_preparationTimeoutForStyle:(long long)arg1;
- (id)_preparationTimerForStyle:(long long)arg1;
- (void)_prepare;
- (void)_prepareWithStyle:(long long)arg1;
- (void)_resetAutoDeactivationTimeout;
- (void)_setConfiguration:(id)arg1;
- (void)_setMuted:(bool)arg1;
- (void)_setPreparationTimer:(id)arg1 forStyle:(long long)arg2;
- (void)_setupAutoDeactivateTimer;
- (void)_setupEnginesIfNeeded;
- (id)_statsSuffix;
- (void)_stats_activationDidChangeTo:(bool)arg1;
- (void)_stats_activationTimedOut;
- (id)_stats_key;
- (void)_stats_playedFeedback;
- (void)_stats_prepared;
- (void)_stopAutoDeactivateTimer;
- (void)_stopPreparationForAllStyles;
- (void)_stopPreparationForStyle:(long long)arg1;
- (void)_updatePreparationTimer:(id)arg1 withTimeout:(double)arg2;
- (void)activateWithCompletionBlock:(id /* block */)arg1;
- (long long)activationCount;
- (id)coordinateSpace;
- (void)deactivate;
- (void)dealloc;
- (id)description;
- (id)engines;
- (long long)externalActivationCount;
- (id)init;
- (id)initWithConfiguration:(id)arg1;
- (id)initWithConfiguration:(id)arg1 coordinateSpace:(id)arg2;
- (bool)isActive;
- (void)performFeedbackWithDelay:(double)arg1 insideBlock:(id /* block */)arg2;
- (void)prepare;
- (void)prepareForFeedback;
- (void)setActivationCount:(long long)arg1;
- (void)setCoordinateSpace:(id)arg1;
- (void)setExternalActivationCount:(long long)arg1;
@end
|
/*************************************************************************
**
** GSC-18128-1, "Core Flight Executive Version 6.7"
**
** Copyright (c) 2006-2019 United States Government as represented by
** the Administrator of the National Aeronautics and Space Administration.
** All Rights Reserved.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** File: cfe_test_tbl.c
**
** Purpose:
** Create a file containing a CFE Test Table
**
*************************************************************************/
/*
* Includes
*/
#include "cfe_tbl_filedef.h"
#include "cfe_test_tbl.h"
/*
* The test table data should contain some identifiable numeric values,
* so any issues with paritial loading/byteswapping are morely likely
* to be detected.
*/
TBL_TEST_Table_t TestTable = {0xf007, 0xba11};
CFE_TBL_FILEDEF(TestTable, CFE_TEST_APP.TestTable, Table Test Table, cfe_test_tbl.tbl)
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { ParticlesContainer } from './ParticlesContainer';
const svgParams = {
fps_limit: 28,
particles: {
number: {
value: 200,
density: {
enable: false,
},
},
line_linked: {
color: '#3CA9D1',
enable: true,
distance: 30,
opacity: 0.4,
},
move: {
speed: 1,
},
opacity: {
anim: {
enable: true,
opacity_min: 0.05,
speed: 2,
sync: false,
},
value: 0.4,
},
},
polygon: {
enable: true,
scale: 0.5,
type: 'inline',
move: {
radius: 10,
},
url: '/svg/small-deer.2a0425af.svg',
inline: {
arrangement: 'equidistant',
},
draw: {
enable: true,
stroke: {
color: 'rgba(255, 255, 255, .2)',
},
},
},
retina_detect: false,
interactivity: {
events: {
onhover: {
enable: true,
mode: 'bubble',
},
},
modes: {
bubble: {
size: 6,
distance: 40,
},
},
},
};
const imgParams = {
particles: {
number: {
value: 10,
density: {
enable: true,
value_area: 100,
},
},
line_linked: {
enable: false,
},
move: {
speed: 1,
out_mode: 'out',
},
shape: {
type: ['images', 'circles'],
images: [
{
src: './cys/png/001-lock.png',
height: 100,
width: 100,
},
{
src: './cys/png/003-password.png',
height: 100,
width: 100,
},
],
},
color: {
value: '#CCC',
},
size: {
value: 30,
random: false,
anim: {
enable: true,
speed: 4,
size_min: 10,
sync: false,
},
},
},
retina_detect: false,
};
storiesOf('Particles Container', module)
.add('basic', () => <ParticlesContainer>Basic</ParticlesContainer>)
.add('svg', () => <ParticlesContainer params={svgParams}>SVG</ParticlesContainer>)
.add('image', () => <ParticlesContainer params={imgParams}>SVG</ParticlesContainer>);
|
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
},
DocCommentHighlightRules.getTagRule(),
{
defaultToken : "comment.doc",
caseInsensitive: true
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getTagRule = function(start) {
return {
token : "comment.doc.tag.storage.type",
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
};
}
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b";
var JavaScriptHighlightRules = function(options) {
var keywordMapper = this.createKeywordMapper({
"variable.language":
"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors
"Namespace|QName|XML|XMLList|" + // E4X
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors
"SyntaxError|TypeError|URIError|" +
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
"isNaN|parseFloat|parseInt|" +
"JSON|Math|" + // Other
"this|arguments|prototype|window|document" , // Pseudo
"keyword":
"const|yield|import|get|set|" +
"break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
"__parent__|__count__|escape|unescape|with|__proto__|" +
"class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
"storage.type":
"const|let|var|function",
"constant.language":
"null|Infinity|NaN|undefined",
"support.function":
"alert",
"constant.language.boolean": "true|false"
}, "identifier");
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-6][0-7]?|" + // oct
"37[0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
this.$rules = {
"no_regex" : [
{
token : "comment",
regex : "\\/\\/",
next : "line_comment"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : /\/\*/,
next : "comment"
}, {
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0[xX][0-9a-fA-F]+\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, {
token : [
"storage.type", "punctuation.operator", "support.function",
"punctuation.operator", "entity.name.function", "text","keyword.operator"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
"text", "paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "punctuation.operator",
"text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"text", "text", "storage.type", "text", "paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "start"
}, {
token : ["support.constant"],
regex : /that\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
}, {
token : keywordMapper,
regex : identifierRe
}, {
token : "punctuation.operator",
regex : /[.](?![.])/,
next : "property"
}, {
token : "keyword.operator",
regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/,
next : "start"
}, {
token : "punctuation.operator",
regex : /[?:,;.]/,
next : "start"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "start"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token: "comment",
regex: /^#!.*$/
}
],
property: [{
token : "text",
regex : "\\s+"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()",
next: "function_arguments"
}, {
token : "punctuation.operator",
regex : /[.](?![.])/
}, {
token : "support.function",
regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : "support.function.dom",
regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : "support.constant",
regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : "identifier",
regex : identifierRe
}, {
regex: "",
token: "empty",
next: "no_regex"
}
],
"start": [
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment_regex_allowed"
}, {
token : "comment",
regex : "\\/\\/",
next : "line_comment_regex_allowed"
}, {
token: "string.regexp",
regex: "\\/",
next: "regex"
}, {
token : "text",
regex : "\\s+|^$",
next : "start"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp",
regex: "/[sxngimy]*",
next: "no_regex"
}, {
token : "invalid",
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
}, {
token : "constant.language.escape",
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
}, {
token : "constant.language.delimiter",
regex: /\|/
}, {
token: "constant.language.escape",
regex: /\[\^?/,
next: "regex_character_class"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp"
}
],
"regex_character_class": [
{
token: "regexp.charclass.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "constant.language.escape",
regex: "]",
next: "regex"
}, {
token: "constant.language.escape",
regex: "-"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp.charachterclass"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe
}, {
token: "punctuation.operator",
regex: "[, ]+"
}, {
token: "punctuation.operator",
regex: "$"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"comment_regex_allowed" : [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "\\*\\/", next : "start"},
{defaultToken : "comment", caseInsensitive: true}
],
"comment" : [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "\\*\\/", next : "no_regex"},
{defaultToken : "comment", caseInsensitive: true}
],
"line_comment_regex_allowed" : [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "$|^", next : "start"},
{defaultToken : "comment", caseInsensitive: true}
],
"line_comment" : [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "$|^", next : "no_regex"},
{defaultToken : "comment", caseInsensitive: true}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qqstring"
}, {
token : "string",
regex : '"|$',
next : "no_regex"
}, {
defaultToken: "string"
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qstring"
}, {
token : "string",
regex : "'|$",
next : "no_regex"
}, {
defaultToken: "string"
}
]
};
if (!options || !options.noES6) {
this.$rules.no_regex.unshift({
regex: "[{}]", onMatch: function(val, state, stack) {
this.next = val == "{" ? this.nextState : "";
if (val == "{" && stack.length) {
stack.unshift("start", state);
return "paren";
}
if (val == "}" && stack.length) {
stack.shift();
this.next = stack.shift();
if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1)
return "paren.quasi.end";
}
return val == "{" ? "paren.lparen" : "paren.rparen";
},
nextState: "start"
}, {
token : "string.quasi.start",
regex : /`/,
push : [{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "paren.quasi.start",
regex : /\${/,
push : "start"
}, {
token : "string.quasi.end",
regex : /`/,
next : "pop"
}, {
defaultToken: "string.quasi"
}]
});
if (!options || !options.noJSX)
JSX.call(this);
}
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
this.normalizeRules();
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
function JSX() {
var tagRegex = identifierRe.replace("\\d", "\\d\\-");
var jsxTag = {
onMatch : function(val, state, stack) {
var offset = val.charAt(1) == "/" ? 2 : 1;
if (offset == 1) {
if (state != this.nextState)
stack.unshift(this.next, this.nextState, 0);
else
stack.unshift(this.next);
stack[2]++;
} else if (offset == 2) {
if (state == this.nextState) {
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.shift();
stack.shift();
}
}
}
return [{
type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml",
value: val.slice(0, offset)
}, {
type: "meta.tag.tag-name.xml",
value: val.substr(offset)
}];
},
regex : "</?" + tagRegex + "",
next: "jsxAttributes",
nextState: "jsx"
};
this.$rules.start.unshift(jsxTag);
var jsxJsRule = {
regex: "{",
token: "paren.quasi.start",
push: "start"
};
this.$rules.jsx = [
jsxJsRule,
jsxTag,
{include : "reference"},
{defaultToken: "string"}
];
this.$rules.jsxAttributes = [{
token : "meta.tag.punctuation.tag-close.xml",
regex : "/?>",
onMatch : function(value, currentState, stack) {
if (currentState == stack[0])
stack.shift();
if (value.length == 2) {
if (stack[0] == this.nextState)
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.splice(0, 2);
}
}
this.next = stack[0] || "start";
return [{type: this.token, value: value}];
},
nextState: "jsx"
},
jsxJsRule,
{
token : "entity.other.attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
token : "text.tag-whitespace.xml",
regex : "\\s+"
}, {
token : "string.attribute-value.xml",
regex : "'",
stateName : "jsx_attr_q",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
jsxJsRule,
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
stateName : "jsx_attr_qq",
push : [
jsxJsRule,
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
}];
this.$rules.reference = [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}];
}
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.index;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var getWrapped = function(selection, selected, opening, closing) {
var rowDiff = selection.end.row - selection.start.row;
return {
text: opening + selected + closing,
selection: [
0,
selection.start.column + 1,
rowDiff,
selection.end.column + (rowDiff ? 0 : 1)
]
};
};
var CstyleBehaviour = function() {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '{', '}');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '(', ')');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '[', ']');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
if (text == '"' || text == "'") {
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, quote, quote);
} else if (!selected) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var token = session.getTokenAt(cursor.row, cursor.column);
var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
if (leftChar == "\\" && token && /escape/.test(token.type))
return null;
var stringBefore = token && /string|escape/.test(token.type);
var stringAfter = !rightToken || /string|escape/.test(rightToken.type);
var pair;
if (rightChar == quote) {
pair = stringBefore !== stringAfter;
} else {
if (stringBefore && !stringAfter)
return null; // wrap string with different quote
if (stringBefore && stringAfter)
return null; // do not pair quotes inside strings
var wordRe = session.$mode.tokenRe;
wordRe.lastIndex = 0;
var isWordBefore = wordRe.test(leftChar);
wordRe.lastIndex = 0;
var isWordAfter = wordRe.test(leftChar);
if (isWordBefore || isWordAfter)
return null; // before or after alphanumeric
if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
return null; // there is rightChar and it isn't closing
pair = true;
}
return {
text: pair ? quote + quote : "",
selection: [1,1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = JavaScriptHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/javascript";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index";
var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters";
var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero";
var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow";
var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace";
var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
var CssHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"support.function": supportFunction,
"support.constant": supportConstant,
"support.type": supportType,
"support.constant.color": supportConstantColor,
"support.constant.fonts": supportConstantFonts
}, "text", true);
this.$rules = {
"start" : [{
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
push: "ruleset"
}, {
token: "string",
regex: "@.*?{",
push: "media"
}, {
token: "keyword",
regex: "#[a-z0-9-_]+"
}, {
token: "variable",
regex: "\\.[a-z0-9-_]+"
}, {
token: "string",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
caseInsensitive: true
}],
"media" : [{
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
push: "ruleset"
}, {
token: "string",
regex: "\\}",
next: "pop"
}, {
token: "keyword",
regex: "#[a-z0-9-_]+"
}, {
token: "variable",
regex: "\\.[a-z0-9-_]+"
}, {
token: "string",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
caseInsensitive: true
}],
"comment" : [{
token : "comment",
regex : "\\*\\/",
next : "pop"
}, {
defaultToken : "comment"
}],
"ruleset" : [
{
token : "paren.rparen",
regex : "\\}",
next: "pop"
}, {
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : ["constant.numeric", "keyword"],
regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
}, {
token : "constant.numeric",
regex : numRe
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
regex : pseudoElements
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
regex : pseudoClasses
}, {
token : ["support.function", "string", "support.function"],
regex : "(url\\()(.*)(\\))"
}, {
token : keywordMapper,
regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
}, {
caseInsensitive: true
}]
};
this.normalizeRules();
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
});
ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) {
"use strict";
var propertyMap = {
"background": {"#$0": 1},
"background-color": {"#$0": 1, "transparent": 1, "fixed": 1},
"background-image": {"url('/$0')": 1},
"background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1},
"background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2,},
"background-attachment": {"scroll": 1, "fixed": 1},
"background-size": {"cover": 1, "contain": 1},
"background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1},
"background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1},
"border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1},
"border-color": {"#$0": 1},
"border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2,},
"border-collapse": {"collapse": 1, "separate": 1},
"bottom": {"px": 1, "em": 1, "%": 1},
"clear": {"left": 1, "right": 1, "both": 1, "none": 1},
"color": {"#$0": 1, "rgb(#$00,0,0)": 1},
"cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1},
"display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1},
"empty-cells": {"show": 1, "hide": 1},
"float": {"left": 1, "right": 1, "none": 1},
"font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1},
"font-size": {"px": 1, "em": 1, "%": 1},
"font-weight": {"bold": 1, "normal": 1},
"font-style": {"italic": 1, "normal": 1},
"font-variant": {"normal": 1, "small-caps": 1},
"height": {"px": 1, "em": 1, "%": 1},
"left": {"px": 1, "em": 1, "%": 1},
"letter-spacing": {"normal": 1},
"line-height": {"normal": 1},
"list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1},
"margin": {"px": 1, "em": 1, "%": 1},
"margin-right": {"px": 1, "em": 1, "%": 1},
"margin-left": {"px": 1, "em": 1, "%": 1},
"margin-top": {"px": 1, "em": 1, "%": 1},
"margin-bottom": {"px": 1, "em": 1, "%": 1},
"max-height": {"px": 1, "em": 1, "%": 1},
"max-width": {"px": 1, "em": 1, "%": 1},
"min-height": {"px": 1, "em": 1, "%": 1},
"min-width": {"px": 1, "em": 1, "%": 1},
"overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1},
"overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1},
"overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1},
"padding": {"px": 1, "em": 1, "%": 1},
"padding-top": {"px": 1, "em": 1, "%": 1},
"padding-right": {"px": 1, "em": 1, "%": 1},
"padding-bottom": {"px": 1, "em": 1, "%": 1},
"padding-left": {"px": 1, "em": 1, "%": 1},
"page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1},
"page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1},
"position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1},
"right": {"px": 1, "em": 1, "%": 1},
"table-layout": {"fixed": 1, "auto": 1},
"text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1},
"text-align": {"left": 1, "right": 1, "center": 1, "justify": 1},
"text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1},
"top": {"px": 1, "em": 1, "%": 1},
"vertical-align": {"top": 1, "bottom": 1},
"visibility": {"hidden": 1, "visible": 1},
"white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1},
"width": {"px": 1, "em": 1, "%": 1},
"word-spacing": {"normal": 1},
"filter": {"alpha(opacity=$0100)": 1},
"text-shadow": {"$02px 2px 2px #777": 1},
"text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1},
"-moz-border-radius": 1,
"-moz-border-radius-topright": 1,
"-moz-border-radius-bottomright": 1,
"-moz-border-radius-topleft": 1,
"-moz-border-radius-bottomleft": 1,
"-webkit-border-radius": 1,
"-webkit-border-top-right-radius": 1,
"-webkit-border-top-left-radius": 1,
"-webkit-border-bottom-right-radius": 1,
"-webkit-border-bottom-left-radius": 1,
"-moz-box-shadow": 1,
"-webkit-box-shadow": 1,
"transform": {"rotate($00deg)": 1, "skew($00deg)": 1},
"-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1},
"-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 }
};
var CssCompletions = function() {
};
(function() {
this.completionsDefined = false;
this.defineCompletions = function() {
if (document) {
var style = document.createElement('c').style;
for (var i in style) {
if (typeof style[i] !== 'string')
continue;
var name = i.replace(/[A-Z]/g, function(x) {
return '-' + x.toLowerCase();
});
if (!propertyMap.hasOwnProperty(name))
propertyMap[name] = 1;
}
}
this.completionsDefined = true;
}
this.getCompletions = function(state, session, pos, prefix) {
if (!this.completionsDefined) {
this.defineCompletions();
}
var token = session.getTokenAt(pos.row, pos.column);
if (!token)
return [];
if (state==='ruleset'){
var line = session.getLine(pos.row).substr(0, pos.column);
if (/:[^;]+$/.test(line)) {
/([\w\-]+):[^:]*$/.test(line);
return this.getPropertyValueCompletions(state, session, pos, prefix);
} else {
return this.getPropertyCompletions(state, session, pos, prefix);
}
}
return [];
};
this.getPropertyCompletions = function(state, session, pos, prefix) {
var properties = Object.keys(propertyMap);
return properties.map(function(property){
return {
caption: property,
snippet: property + ': $0',
meta: "property",
score: Number.MAX_VALUE
};
});
};
this.getPropertyValueCompletions = function(state, session, pos, prefix) {
var line = session.getLine(pos.row).substr(0, pos.column);
var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1];
if (!property)
return [];
var values = [];
if (property in propertyMap && typeof propertyMap[property] === "object") {
values = Object.keys(propertyMap[property]);
}
return values.map(function(value){
return {
caption: value,
snippet: value,
meta: "property value",
score: Number.MAX_VALUE
};
});
};
}).call(CssCompletions.prototype);
exports.CssCompletions = CssCompletions;
});
ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var CssBehaviour = function () {
this.inherit(CstyleBehaviour);
this.add("colon", "insertion", function (state, action, editor, session, text) {
if (text === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ':') {
return {
text: '',
selection: [1, 1]
}
}
if (!line.substring(cursor.column).match(/^\s*;/)) {
return {
text: ':;',
selection: [1, 1]
}
}
}
}
});
this.add("colon", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar === ';') {
range.end.column ++;
return range;
}
}
}
});
this.add("semicolon", "insertion", function (state, action, editor, session, text) {
if (text === ';') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ';') {
return {
text: '',
selection: [1, 1]
}
}
}
});
}
oop.inherits(CssBehaviour, CstyleBehaviour);
exports.CssBehaviour = CssBehaviour;
});
ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CssCompletions = require("./css_completions").CssCompletions;
var CssBehaviour = require("./behaviour/css").CssBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = CssHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CssBehaviour();
this.$completer = new CssCompletions();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokens = this.getTokenizer().getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.getCompletions = function(state, session, pos, prefix) {
return this.$completer.getCompletions(state, session, pos, prefix);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/css";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function(normalize) {
var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*";
this.$rules = {
start : [
{token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"},
{
token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"],
regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true
},
{
token : ["punctuation.instruction.xml", "keyword.instruction.xml"],
regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction",
},
{token : "comment.xml", regex : "<\\!--", next : "comment"},
{
token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"],
regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true
},
{include : "tag"},
{token : "text.end-tag-open.xml", regex: "</"},
{token : "text.tag-open.xml", regex: "<"},
{include : "reference"},
{defaultToken : "text.xml"}
],
xml_decl : [{
token : "entity.other.attribute-name.decl-attribute-name.xml",
regex : "(?:" + tagRegex + ":)?" + tagRegex + ""
}, {
token : "keyword.operator.decl-attribute-equals.xml",
regex : "="
}, {
include: "whitespace"
}, {
include: "string"
}, {
token : "punctuation.xml-decl.xml",
regex : "\\?>",
next : "start"
}],
processing_instruction : [
{token : "punctuation.instruction.xml", regex : "\\?>", next : "start"},
{defaultToken : "instruction.xml"}
],
doctype : [
{include : "whitespace"},
{include : "string"},
{token : "xml-pe.doctype.xml", regex : ">", next : "start"},
{token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"},
{token : "punctuation.int-subset", regex : "\\[", push : "int_subset"}
],
int_subset : [{
token : "text.xml",
regex : "\\s+"
}, {
token: "punctuation.int-subset.xml",
regex: "]",
next: "pop"
}, {
token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"],
regex : "(<\\!)(" + tagRegex + ")",
push : [{
token : "text",
regex : "\\s+"
},
{
token : "punctuation.markup-decl.xml",
regex : ">",
next : "pop"
},
{include : "string"}]
}],
cdata : [
{token : "string.cdata.xml", regex : "\\]\\]>", next : "start"},
{token : "text.xml", regex : "\\s+"},
{token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"}
],
comment : [
{token : "comment.xml", regex : "-->", next : "start"},
{defaultToken : "comment.xml"}
],
reference : [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
attr_reference : [{
token : "constant.language.escape.reference.attribute-value.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
tag : [{
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"],
regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"}
]
}],
tag_whitespace : [
{token : "text.tag-whitespace.xml", regex : "\\s+"}
],
whitespace : [
{token : "text.whitespace.xml", regex : "\\s+"}
],
string: [{
token : "string.xml",
regex : "'",
push : [
{token : "string.xml", regex: "'", next: "pop"},
{defaultToken : "string.xml"}
]
}, {
token : "string.xml",
regex : '"',
push : [
{token : "string.xml", regex: '"', next: "pop"},
{defaultToken : "string.xml"}
]
}],
attributes: [{
token : "entity.other.attribute-name.xml",
regex : "(?:" + tagRegex + ":)?" + tagRegex + ""
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
include: "tag_whitespace"
}, {
include: "attribute_value"
}],
attribute_value: [{
token : "string.attribute-value.xml",
regex : "'",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}]
};
if (this.constructor === XmlHighlightRules)
this.normalizeRules();
};
(function() {
this.embedTagRules = function(HighlightRules, prefix, tag){
this.$rules.tag.unshift({
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(<)(" + tag + "(?=\\s|>|$))",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"}
]
});
this.$rules[tag + "-end"] = [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start",
onMatch : function(value, currentState, stack) {
stack.splice(0);
return this.token;
}}
]
this.embedRules(HighlightRules, prefix, [{
token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(</)(" + tag + "(?=\\s|>|$))",
next: tag + "-end"
}, {
token: "string.cdata.xml",
regex : "<\\!\\[CDATA\\["
}, {
token: "string.cdata.xml",
regex : "\\]\\]>"
}]);
};
}).call(TextHighlightRules.prototype);
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var tagMap = lang.createMap({
a : 'anchor',
button : 'form',
form : 'form',
img : 'image',
input : 'form',
label : 'form',
option : 'form',
script : 'script',
select : 'form',
textarea : 'form',
style : 'style',
table : 'table',
tbody : 'table',
td : 'table',
tfoot : 'table',
th : 'table',
tr : 'table'
});
var HtmlHighlightRules = function() {
XmlHighlightRules.call(this);
this.addRules({
attributes: [{
include : "tag_whitespace"
}, {
token : "entity.other.attribute-name.xml",
regex : "[-_a-zA-Z0-9:.]+"
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "=",
push : [{
include: "tag_whitespace"
}, {
token : "string.unquoted.attribute-value.html",
regex : "[^<>='\"`\\s]+",
next : "pop"
}, {
token : "empty",
regex : "",
next : "pop"
}]
}, {
include : "attribute_value"
}],
tag: [{
token : function(start, tag) {
var group = tagMap[tag];
return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml",
"meta.tag" + (group ? "." + group : "") + ".tag-name.xml"];
},
regex : "(</?)([-_a-zA-Z0-9:.]+)",
next: "tag_stuff"
}],
tag_stuff: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"}
],
});
this.embedTagRules(CssHighlightRules, "css-", "style");
this.embedTagRules(new JavaScriptHighlightRules({noJSX: true}).getRules(), "js-", "script");
if (this.constructor === HtmlHighlightRules)
this.normalizeRules();
};
oop.inherits(HtmlHighlightRules, XmlHighlightRules);
exports.HtmlHighlightRules = HtmlHighlightRules;
});
ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
var XmlBehaviour = function () {
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selected = session.doc.getTextRange(editor.getSelectionRange());
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
}
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) {
return {
text: "",
selection: [1, 1]
};
}
if (!token)
token = iterator.stepBackward();
if (!token)
return;
while (is(token, "tag-whitespace") || is(token, "whitespace")) {
token = iterator.stepBackward();
}
var rightSpace = !rightChar || rightChar.match(/\s/);
if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) {
return {
text: quote + quote,
selection: [1, 1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
this.add("autoclosing", "insertion", function (state, action, editor, session, text) {
if (text == '>') {
var position = editor.getCursorPosition();
var iterator = new TokenIterator(session, position.row, position.column);
var token = iterator.getCurrentToken() || iterator.stepBackward();
if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value")))
return;
if (is(token, "reference.attribute-value"))
return;
if (is(token, "attribute-value")) {
var firstChar = token.value.charAt(0);
if (firstChar == '"' || firstChar == "'") {
var lastChar = token.value.charAt(token.value.length - 1);
var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length;
if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar)
return;
}
}
while (!is(token, "tag-name")) {
token = iterator.stepBackward();
}
var tokenRow = iterator.getCurrentTokenRow();
var tokenColumn = iterator.getCurrentTokenColumn();
if (is(iterator.stepBackward(), "end-tag-open"))
return;
var element = token.value;
if (tokenRow == position.row)
element = element.substring(0, position.column - tokenColumn);
if (this.voidElements.hasOwnProperty(element.toLowerCase()))
return;
return {
text: ">" + "</" + element + ">",
selection: [1, 1]
};
}
});
this.add("autoindent", "insertion", function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.getLine(cursor.row);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.type.indexOf("tag-close") !== -1) {
if (token.value == "/>")
return;
while (token && token.type.indexOf("tag-name") === -1) {
token = iterator.stepBackward();
}
if (!token) {
return;
}
var tag = token.value;
var row = iterator.getCurrentTokenRow();
token = iterator.stepBackward();
if (!token || token.type.indexOf("end-tag") !== -1) {
return;
}
if (this.voidElements && !this.voidElements[tag]) {
var nextToken = session.getTokenAt(cursor.row, cursor.column+1);
var line = session.getLine(row);
var nextIndent = this.$getIndent(line);
var indent = nextIndent + session.getTabString();
if (nextToken && nextToken.value === "</") {
return {
text: "\n" + indent + "\n" + nextIndent,
selection: [1, indent.length, 1, indent.length]
};
} else {
return {
text: "\n" + indent
};
}
}
}
}
});
};
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(defaultMode, subModes) {
this.defaultMode = defaultMode;
this.subModes = subModes;
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.$getMode = function(state) {
if (typeof state != "string")
state = state[0];
for (var key in this.subModes) {
if (state.indexOf(key) === 0)
return this.subModes[key];
}
return null;
};
this.$tryMode = function(state, session, foldStyle, row) {
var mode = this.$getMode(state);
return (mode ? mode.getFoldWidget(session, foldStyle, row) : "");
};
this.getFoldWidget = function(session, foldStyle, row) {
return (
this.$tryMode(session.getState(row-1), session, foldStyle, row) ||
this.$tryMode(session.getState(row), session, foldStyle, row) ||
this.defaultMode.getFoldWidget(session, foldStyle, row)
);
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var mode = this.$getMode(session.getState(row-1));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.$getMode(session.getState(row));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.defaultMode;
return mode.getFoldWidgetRange(session, foldStyle, row);
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
this.optionalEndTags = oop.mixin({}, this.voidElements);
if (optionalEndTags)
oop.mixin(this.optionalEndTags, optionalEndTags);
};
oop.inherits(FoldMode, BaseFoldMode);
var Tag = function() {
this.tagName = "";
this.closing = false;
this.selfClosing = false;
this.start = {row: 0, column: 0};
this.end = {row: 0, column: 0};
};
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (!tag)
return "";
if (tag.closing || (!tag.tagName && tag.selfClosing))
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase()))
return "";
if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column))
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var tag = new Tag();
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (is(token, "tag-open")) {
tag.end.column = tag.start.column + token.value.length;
tag.closing = is(token, "end-tag-open");
token = tokens[++i];
if (!token)
return null;
tag.tagName = token.value;
tag.end.column += token.value.length;
for (i++; i < tokens.length; i++) {
token = tokens[i];
tag.end.column += token.value.length;
if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
break;
}
}
return tag;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
return tag;
}
tag.start.column += token.value.length;
}
return null;
};
this._findEndTagInLine = function(session, row, tagName, startColumn) {
var tokens = session.getTokens(row);
var column = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
column += token.value.length;
if (column < startColumn)
continue;
if (is(token, "end-tag-open")) {
token = tokens[i + 1];
if (token && token.value == tagName)
return true;
}
}
return false;
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
iterator.stepForward();
return tag;
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
iterator.stepBackward();
return tag;
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.optionalEndTags.hasOwnProperty(top.tagName)) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.start.column);
var start = {
row: row,
column: firstTag.start.column + firstTag.tagName.length + 2
};
if (firstTag.start.row == firstTag.end.row)
start.column = firstTag.end.column;
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag);
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.end.column);
var end = {
row: row,
column: firstTag.start.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
if (tag.start.row == tag.end.row && tag.start.column < tag.end.column)
tag.start.column = tag.end.column;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag);
}
}
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var MixedFoldMode = require("./mixed").FoldMode;
var XmlFoldMode = require("./xml").FoldMode;
var CStyleFoldMode = require("./cstyle").FoldMode;
var FoldMode = exports.FoldMode = function(voidElements, optionalTags) {
MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), {
"js-": new CStyleFoldMode(),
"css-": new CStyleFoldMode()
});
};
oop.inherits(FoldMode, MixedFoldMode);
});
ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) {
"use strict";
var TokenIterator = require("../token_iterator").TokenIterator;
var commonAttributes = [
"accesskey",
"class",
"contenteditable",
"contextmenu",
"dir",
"draggable",
"dropzone",
"hidden",
"id",
"inert",
"itemid",
"itemprop",
"itemref",
"itemscope",
"itemtype",
"lang",
"spellcheck",
"style",
"tabindex",
"title",
"translate"
];
var eventAttributes = [
"onabort",
"onblur",
"oncancel",
"oncanplay",
"oncanplaythrough",
"onchange",
"onclick",
"onclose",
"oncontextmenu",
"oncuechange",
"ondblclick",
"ondrag",
"ondragend",
"ondragenter",
"ondragleave",
"ondragover",
"ondragstart",
"ondrop",
"ondurationchange",
"onemptied",
"onended",
"onerror",
"onfocus",
"oninput",
"oninvalid",
"onkeydown",
"onkeypress",
"onkeyup",
"onload",
"onloadeddata",
"onloadedmetadata",
"onloadstart",
"onmousedown",
"onmousemove",
"onmouseout",
"onmouseover",
"onmouseup",
"onmousewheel",
"onpause",
"onplay",
"onplaying",
"onprogress",
"onratechange",
"onreset",
"onscroll",
"onseeked",
"onseeking",
"onselect",
"onshow",
"onstalled",
"onsubmit",
"onsuspend",
"ontimeupdate",
"onvolumechange",
"onwaiting"
];
var globalAttributes = commonAttributes.concat(eventAttributes);
var attributeMap = {
"html": {"manifest": 1},
"head": {},
"title": {},
"base": {"href": 1, "target": 1},
"link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1},
"meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1},
"style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1},
"script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1},
"noscript": {"href": 1},
"body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1},
"section": {},
"nav": {},
"article": {"pubdate": 1},
"aside": {},
"h1": {},
"h2": {},
"h3": {},
"h4": {},
"h5": {},
"h6": {},
"header": {},
"footer": {},
"address": {},
"main": {},
"p": {},
"hr": {},
"pre": {},
"blockquote": {"cite": 1},
"ol": {"start": 1, "reversed": 1},
"ul": {},
"li": {"value": 1},
"dl": {},
"dt": {},
"dd": {},
"figure": {},
"figcaption": {},
"div": {},
"a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1},
"em": {},
"strong": {},
"small": {},
"s": {},
"cite": {},
"q": {"cite": 1},
"dfn": {},
"abbr": {},
"data": {},
"time": {"datetime": 1},
"code": {},
"var": {},
"samp": {},
"kbd": {},
"sub": {},
"sup": {},
"i": {},
"b": {},
"u": {},
"mark": {},
"ruby": {},
"rt": {},
"rp": {},
"bdi": {},
"bdo": {},
"span": {},
"br": {},
"wbr": {},
"ins": {"cite": 1, "datetime": 1},
"del": {"cite": 1, "datetime": 1},
"img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1},
"iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}},
"embed": {"src": 1, "height": 1, "width": 1, "type": 1},
"object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1},
"param": {"name": 1, "value": 1},
"video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}},
"audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }},
"source": {"src": 1, "type": 1, "media": 1},
"track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1},
"canvas": {"width": 1, "height": 1},
"map": {"name": 1},
"area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1},
"svg": {},
"math": {},
"table": {"summary": 1},
"caption": {},
"colgroup": {"span": 1},
"col": {"span": 1},
"tbody": {},
"thead": {},
"tfoot": {},
"tr": {},
"td": {"headers": 1, "rowspan": 1, "colspan": 1},
"th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1},
"form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}},
"fieldset": {"disabled": 1, "form": 1, "name": 1},
"legend": {},
"label": {"form": 1, "for": 1},
"input": {
"type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1},
"accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1},
"button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}},
"select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}},
"datalist": {},
"optgroup": {"disabled": 1, "label": 1},
"option": {"disabled": 1, "selected": 1, "label": 1, "value": 1},
"textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}},
"keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1},
"output": {"for": 1, "form": 1, "name": 1},
"progress": {"value": 1, "max": 1},
"meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1},
"details": {"open": 1},
"summary": {},
"command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1},
"menu": {"type": 1, "label": 1},
"dialog": {"open": 1}
};
var elements = Object.keys(attributeMap);
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
function findTagName(session, pos) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
while (token && !is(token, "tag-name")){
token = iterator.stepBackward();
}
if (token)
return token.value;
}
function findAttributeName(session, pos) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
while (token && !is(token, "attribute-name")){
token = iterator.stepBackward();
}
if (token)
return token.value;
}
var HtmlCompletions = function() {
};
(function() {
this.getCompletions = function(state, session, pos, prefix) {
var token = session.getTokenAt(pos.row, pos.column);
if (!token)
return [];
if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open"))
return this.getTagCompletions(state, session, pos, prefix);
if (is(token, "tag-whitespace") || is(token, "attribute-name"))
return this.getAttributeCompletions(state, session, pos, prefix);
if (is(token, "attribute-value"))
return this.getAttributeValueCompletions(state, session, pos, prefix);
var line = session.getLine(pos.row).substr(0, pos.column);
if (/&[A-z]*$/i.test(line))
return this.getHTMLEntityCompletions(state, session, pos, prefix);
return [];
};
this.getTagCompletions = function(state, session, pos, prefix) {
return elements.map(function(element){
return {
value: element,
meta: "tag",
score: Number.MAX_VALUE
};
});
};
this.getAttributeCompletions = function(state, session, pos, prefix) {
var tagName = findTagName(session, pos);
if (!tagName)
return [];
var attributes = globalAttributes;
if (tagName in attributeMap) {
attributes = attributes.concat(Object.keys(attributeMap[tagName]));
}
return attributes.map(function(attribute){
return {
caption: attribute,
snippet: attribute + '="$0"',
meta: "attribute",
score: Number.MAX_VALUE
};
});
};
this.getAttributeValueCompletions = function(state, session, pos, prefix) {
var tagName = findTagName(session, pos);
var attributeName = findAttributeName(session, pos);
if (!tagName)
return [];
var values = [];
if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") {
values = Object.keys(attributeMap[tagName][attributeName]);
}
return values.map(function(value){
return {
caption: value,
snippet: value,
meta: "attribute value",
score: Number.MAX_VALUE
};
});
};
this.getHTMLEntityCompletions = function(state, session, pos, prefix) {
var values = ['Á', 'á', 'Â', 'â', '´', 'Æ', 'æ', 'À', 'à', 'ℵ', 'Α', 'α', '&', '∧', '∠', 'Å', 'å', '≈', 'Ã', 'ã', 'Ä', 'ä', '„', 'Β', 'β', '¦', '•', '∩', 'Ç', 'ç', '¸', '¢', 'Χ', 'χ', 'ˆ', '♣', '≅', '©', '↵', '∪', '¤', '‡', '†', '⇓', '↓', '°', 'Δ', 'δ', '♦', '÷', 'É', 'é', 'Ê', 'ê', 'È', 'è', '∅', ' ', ' ', 'Ε', 'ε', '≡', 'Η', 'η', 'Ð', 'ð', 'Ë', 'ë', '€', '∃', 'ƒ', '∀', '½', '¼', '¾', '⁄', 'Γ', 'γ', '≥', '>', '⇔', '↔', '♥', '…', 'Í', 'í', 'Î', 'î', '¡', 'Ì', 'ì', 'ℑ', '∞', '∫', 'Ι', 'ι', '¿', '∈', 'Ï', 'ï', 'Κ', 'κ', 'Λ', 'λ', '⟨', '«', '⇐', '←', '⌈', '“', '≤', '⌊', '∗', '◊', '‎', '‹', '‘', '<', '¯', '—', 'µ', '·', '−', 'Μ', 'μ', '∇', ' ', '–', '≠', '∋', '¬', '∉', '⊄', 'Ñ', 'ñ', 'Ν', 'ν', 'Ó', 'ó', 'Ô', 'ô', 'Œ', 'œ', 'Ò', 'ò', '‾', 'Ω', 'ω', 'Ο', 'ο', '⊕', '∨', 'ª', 'º', 'Ø', 'ø', 'Õ', 'õ', '⊗', 'Ö', 'ö', '¶', '∂', '‰', '⊥', 'Φ', 'φ', 'Π', 'π', 'ϖ', '±', '£', '″', '′', '∏', '∝', 'Ψ', 'ψ', '"', '√', '⟩', '»', '⇒', '→', '⌉', '”', 'ℜ', '®', '⌋', 'Ρ', 'ρ', '‏', '›', '’', '‚', 'Š', 'š', '⋅', '§', '­', 'Σ', 'σ', 'ς', '∼', '♠', '⊂', '⊆', '∑', '⊃', '¹', '²', '³', '⊇', 'ß', 'Τ', 'τ', '∴', 'Θ', 'θ', 'ϑ', ' ', 'Þ', 'þ', '˜', '×', '™', 'Ú', 'ú', '⇑', '↑', 'Û', 'û', 'Ù', 'ù', '¨', 'ϒ', 'Υ', 'υ', 'Ü', 'ü', '℘', 'Ξ', 'ξ', 'Ý', 'ý', '¥', 'Ÿ', 'ÿ', 'Ζ', 'ζ', '‍', '‌'];
return values.map(function(value){
return {
caption: value,
snippet: value.substr(1),
meta: "html entity",
score: Number.MAX_VALUE
};
});
};
}).call(HtmlCompletions.prototype);
exports.HtmlCompletions = HtmlCompletions;
});
ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var CssMode = require("./css").Mode;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var HtmlFoldMode = require("./folding/html").FoldMode;
var HtmlCompletions = require("./html_completions").HtmlCompletions;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"];
var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"];
var Mode = function(options) {
this.fragmentContext = options && options.fragmentContext;
this.HighlightRules = HtmlHighlightRules;
this.$behaviour = new XmlBehaviour();
this.$completer = new HtmlCompletions();
this.createModeDelegates({
"js-": JavaScriptMode,
"css-": CssMode
});
this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags));
};
oop.inherits(Mode, TextMode);
(function() {
this.blockComment = {start: "<!--", end: "-->"};
this.voidElements = lang.arrayToMap(voidElements);
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.getCompletions = function(state, session, pos, prefix) {
return this.$completer.getCompletions(state, session, pos, prefix);
};
this.createWorker = function(session) {
if (this.constructor != Mode)
return;
var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker");
worker.attachToDocument(session.getDocument());
if (this.fragmentContext)
worker.call("setOptions", [{context: this.fragmentContext}]);
worker.on("error", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/html";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/smarty_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var SmartyHighlightRules = function() {
HtmlHighlightRules.call(this);
var smartyRules = { start:
[ { include: '#comments' },
{ include: '#blocks' } ],
'#blocks':
[ { token: 'punctuation.section.embedded.begin.smarty',
regex: '\\{%?',
push:
[ { token: 'punctuation.section.embedded.end.smarty',
regex: '%?\\}',
next: 'pop' },
{ include: '#strings' },
{ include: '#variables' },
{ include: '#lang' },
{ defaultToken: 'source.smarty' } ] } ],
'#comments':
[ { token:
[ 'punctuation.definition.comment.smarty',
'comment.block.smarty' ],
regex: '(\\{%?)(\\*)',
push:
[ { token: 'comment.block.smarty', regex: '\\*%?\\}', next: 'pop' },
{ defaultToken: 'comment.block.smarty' } ] } ],
'#lang':
[ { token: 'keyword.operator.smarty',
regex: '(?:!=|!|<=|>=|<|>|===|==|%|&&|\\|\\|)|\\b(?:and|or|eq|neq|ne|gte|gt|ge|lte|lt|le|not|mod)\\b' },
{ token: 'constant.language.smarty',
regex: '\\b(?:TRUE|FALSE|true|false)\\b' },
{ token: 'keyword.control.smarty',
regex: '\\b(?:if|else|elseif|foreach|foreachelse|section|switch|case|break|default)\\b' },
{ token: 'variable.parameter.smarty', regex: '\\b[a-zA-Z]+=' },
{ token: 'support.function.built-in.smarty',
regex: '\\b(?:capture|config_load|counter|cycle|debug|eval|fetch|include_php|include|insert|literal|math|strip|rdelim|ldelim|assign|constant|block|html_[a-z_]*)\\b' },
{ token: 'support.function.variable-modifier.smarty',
regex: '\\|(?:capitalize|cat|count_characters|count_paragraphs|count_sentences|count_words|date_format|default|escape|indent|lower|nl2br|regex_replace|replace|spacify|string_format|strip_tags|strip|truncate|upper|wordwrap)' } ],
'#strings':
[ { token: 'punctuation.definition.string.begin.smarty',
regex: '\'',
push:
[ { token: 'punctuation.definition.string.end.smarty',
regex: '\'',
next: 'pop' },
{ token: 'constant.character.escape.smarty', regex: '\\\\.' },
{ defaultToken: 'string.quoted.single.smarty' } ] },
{ token: 'punctuation.definition.string.begin.smarty',
regex: '"',
push:
[ { token: 'punctuation.definition.string.end.smarty',
regex: '"',
next: 'pop' },
{ token: 'constant.character.escape.smarty', regex: '\\\\.' },
{ defaultToken: 'string.quoted.double.smarty' } ] } ],
'#variables':
[ { token:
[ 'punctuation.definition.variable.smarty',
'variable.other.global.smarty' ],
regex: '\\b(\\$)(Smarty\\.)' },
{ token:
[ 'punctuation.definition.variable.smarty',
'variable.other.smarty' ],
regex: '(\\$)([a-zA-Z_][a-zA-Z0-9_]*)\\b' },
{ token: [ 'keyword.operator.smarty', 'variable.other.property.smarty' ],
regex: '(->)([a-zA-Z_][a-zA-Z0-9_]*)\\b' },
{ token:
[ 'keyword.operator.smarty',
'meta.function-call.object.smarty',
'punctuation.definition.variable.smarty',
'variable.other.smarty',
'punctuation.definition.variable.smarty' ],
regex: '(->)([a-zA-Z_][a-zA-Z0-9_]*)(\\()(.*?)(\\))' } ] }
var smartyStart = smartyRules.start;
for (var rule in this.$rules) {
this.$rules[rule].unshift.apply(this.$rules[rule], smartyStart);
}
Object.keys(smartyRules).forEach(function(x) {
if (!this.$rules[x])
this.$rules[x] = smartyRules[x];
}, this);
this.normalizeRules();
};
SmartyHighlightRules.metaData = { fileTypes: [ 'tpl' ],
foldingStartMarker: '\\{%?',
foldingStopMarker: '%?\\}',
name: 'Smarty',
scopeName: 'text.html.smarty' }
oop.inherits(SmartyHighlightRules, HtmlHighlightRules);
exports.SmartyHighlightRules = SmartyHighlightRules;
});
ace.define("ace/mode/smarty",["require","exports","module","ace/lib/oop","ace/mode/html","ace/mode/smarty_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var HtmlMode = require("./html").Mode;
var SmartyHighlightRules = require("./smarty_highlight_rules").SmartyHighlightRules;
var Mode = function() {
HtmlMode.call(this);
this.HighlightRules = SmartyHighlightRules;
};
oop.inherits(Mode, HtmlMode);
(function() {
this.$id = "ace/mode/smarty";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
int8_t x3 = 1;
int8_t x4 = 25;
uint32_t x13 = UINT32_MAX;
int64_t x21 = INT64_MAX;
uint32_t x26 = 19U;
uint16_t x29 = UINT16_MAX;
static int64_t x37 = -658966LL;
int8_t x48 = -17;
int8_t x61 = -1;
static int64_t x62 = INT64_MIN;
volatile int8_t x65 = -1;
static int64_t x68 = 3034707651073974LL;
volatile int32_t t17 = 273283;
static volatile int64_t x76 = 161925831952LL;
int64_t x77 = INT64_MIN;
int32_t x79 = 95531;
volatile uint16_t x84 = 28440U;
int32_t x86 = INT32_MAX;
int64_t x87 = INT64_MIN;
int64_t x88 = INT64_MAX;
int8_t x90 = -1;
uint64_t x95 = UINT64_MAX;
static volatile int32_t x103 = INT32_MIN;
int8_t x104 = INT8_MIN;
static volatile int32_t t25 = 58384035;
static int64_t x109 = -13LL;
volatile int8_t x116 = INT8_MIN;
int8_t x119 = INT8_MIN;
int8_t x121 = 1;
uint8_t x128 = 8U;
volatile uint64_t x129 = 0LLU;
int8_t x130 = INT8_MIN;
uint64_t x136 = 501437916LLU;
volatile int32_t t34 = -30588;
uint64_t x146 = 13089595741456001LLU;
int8_t x151 = INT8_MAX;
static volatile uint16_t x152 = UINT16_MAX;
static volatile uint16_t x162 = UINT16_MAX;
static int16_t x165 = INT16_MIN;
volatile int32_t x176 = INT32_MAX;
int16_t x184 = INT16_MAX;
static volatile int32_t t45 = -3118;
int32_t x193 = INT32_MAX;
int8_t x196 = -1;
int32_t t49 = -124;
volatile int32_t t50 = 366279;
uint8_t x207 = 0U;
int32_t t51 = 10;
uint16_t x209 = 22U;
int8_t x213 = -34;
volatile int32_t x215 = 1;
uint64_t x216 = 117950696735LLU;
static uint8_t x220 = 17U;
volatile uint8_t x225 = 3U;
static int8_t x231 = INT8_MAX;
static int32_t t57 = 462869;
volatile int64_t x236 = 47427721477LL;
uint16_t x237 = 6513U;
int16_t x239 = -116;
uint64_t x241 = 64905557108LLU;
static int8_t x245 = -1;
volatile int32_t t62 = -4;
volatile uint64_t x254 = UINT64_MAX;
int32_t t63 = 0;
static uint16_t x268 = 3U;
static int32_t t67 = -625;
static uint8_t x289 = UINT8_MAX;
static uint8_t x294 = 1U;
int32_t t73 = 123;
int32_t x297 = INT32_MIN;
uint16_t x305 = 11U;
int16_t x313 = INT16_MIN;
int64_t x314 = INT64_MIN;
int32_t t79 = 158212447;
int32_t t80 = 0;
static uint64_t x331 = 19094675767934038LLU;
static int8_t x334 = -11;
int32_t t86 = 12155;
uint8_t x352 = UINT8_MAX;
uint8_t x353 = UINT8_MAX;
int64_t x373 = -37400266LL;
int64_t x379 = INT64_MIN;
uint64_t x380 = 513368375LLU;
static volatile int32_t x381 = INT32_MIN;
uint32_t x385 = UINT32_MAX;
int32_t x390 = -3;
int32_t t97 = 4089;
uint8_t x400 = 52U;
volatile int32_t x404 = INT32_MIN;
int8_t x406 = INT8_MAX;
uint32_t x409 = 354375157U;
uint32_t x436 = 219461934U;
uint16_t x439 = 6U;
int64_t x453 = 40637991440756680LL;
int64_t x454 = -1LL;
uint8_t x458 = 31U;
int32_t x459 = INT32_MAX;
static int32_t t114 = -25569;
uint32_t x461 = 12U;
uint8_t x472 = 3U;
int64_t x478 = 31432LL;
volatile int32_t t119 = 944776;
int8_t x482 = -1;
static int8_t x483 = INT8_MIN;
int8_t x484 = INT8_MAX;
static uint32_t x488 = 0U;
static int32_t t121 = -3462;
static int32_t x490 = INT32_MAX;
static volatile int32_t x493 = INT32_MIN;
int8_t x497 = INT8_MAX;
uint64_t x502 = 211706432276304329LLU;
uint8_t x504 = UINT8_MAX;
int16_t x505 = -1;
int16_t x510 = INT16_MIN;
uint16_t x511 = 4061U;
uint64_t x512 = 3226903309321597LLU;
volatile int16_t x515 = 49;
volatile int32_t t129 = 19;
int32_t t130 = -30;
uint16_t x525 = UINT16_MAX;
uint16_t x528 = 5U;
static volatile int32_t t131 = 49;
uint64_t x535 = 97LLU;
int16_t x539 = INT16_MIN;
volatile int16_t x541 = -1;
volatile uint64_t x542 = 5LLU;
uint8_t x547 = 89U;
int32_t t136 = 885;
static int32_t t137 = 0;
int64_t x553 = 24749254LL;
int8_t x554 = -3;
static int32_t t138 = 51103;
int64_t x559 = -41557812LL;
int64_t x568 = -1LL;
int16_t x572 = INT16_MIN;
int32_t t144 = 14;
int32_t x583 = -1;
static int16_t x588 = 0;
int32_t x596 = -1;
int64_t x597 = INT64_MIN;
int16_t x598 = -3212;
static int8_t x600 = INT8_MAX;
int32_t t149 = 31427;
int64_t x605 = -10397631106406LL;
static int64_t x613 = -269520071770543059LL;
uint32_t x614 = 61693032U;
uint32_t x615 = UINT32_MAX;
volatile int32_t x627 = -1;
uint64_t x630 = 311071176LLU;
volatile int32_t t160 = -235819;
volatile uint32_t x645 = 175U;
volatile int32_t t161 = -194633103;
static volatile int64_t x651 = INT64_MIN;
volatile int32_t t163 = -18556764;
volatile int16_t x658 = 3006;
int64_t x662 = -1LL;
static int8_t x666 = INT8_MIN;
int32_t t167 = 14;
int16_t x673 = INT16_MIN;
int16_t x680 = INT16_MIN;
uint64_t x693 = 550448161182758LLU;
volatile int64_t x695 = INT64_MIN;
static volatile int32_t t173 = -41725609;
int32_t t174 = 5;
int32_t t175 = -592788;
int32_t t176 = 786;
volatile int64_t x711 = INT64_MAX;
int8_t x714 = 62;
int32_t x721 = INT32_MIN;
uint16_t x723 = 6362U;
volatile int64_t x724 = -1LL;
int32_t t182 = -50846;
volatile uint8_t x739 = 39U;
int8_t x742 = INT8_MAX;
int32_t t187 = -770;
int16_t x761 = INT16_MIN;
int64_t x769 = 44362343685568LL;
int8_t x771 = 0;
int32_t x775 = INT32_MIN;
int8_t x781 = -30;
uint32_t x789 = UINT32_MAX;
int32_t t197 = 147776541;
volatile uint16_t x796 = 20U;
volatile int32_t t198 = 18;
void f0(void) {
static int8_t x1 = INT8_MAX;
int32_t x2 = INT32_MAX;
int32_t t0 = 25953;
t0 = ((x1^(x2>x3))==x4);
if (t0 != 0) { NG(); } else { ; }
}
void f1(void) {
volatile int8_t x5 = -1;
int32_t x6 = 3451;
volatile uint64_t x7 = UINT64_MAX;
uint32_t x8 = 884377798U;
volatile int32_t t1 = -6280539;
t1 = ((x5^(x6>x7))==x8);
if (t1 != 0) { NG(); } else { ; }
}
void f2(void) {
uint16_t x9 = 10U;
uint8_t x10 = UINT8_MAX;
static int32_t x11 = INT32_MAX;
volatile int64_t x12 = -1258LL;
static volatile int32_t t2 = -107275318;
t2 = ((x9^(x10>x11))==x12);
if (t2 != 0) { NG(); } else { ; }
}
void f3(void) {
volatile int16_t x14 = INT16_MAX;
int16_t x15 = INT16_MIN;
int64_t x16 = 18127LL;
int32_t t3 = 28605;
t3 = ((x13^(x14>x15))==x16);
if (t3 != 0) { NG(); } else { ; }
}
void f4(void) {
uint16_t x17 = UINT16_MAX;
volatile int8_t x18 = -5;
int8_t x19 = -21;
static int8_t x20 = -1;
volatile int32_t t4 = -46921;
t4 = ((x17^(x18>x19))==x20);
if (t4 != 0) { NG(); } else { ; }
}
void f5(void) {
uint16_t x22 = 84U;
static uint32_t x23 = UINT32_MAX;
volatile uint64_t x24 = 2931631LLU;
volatile int32_t t5 = 462;
t5 = ((x21^(x22>x23))==x24);
if (t5 != 0) { NG(); } else { ; }
}
void f6(void) {
volatile int16_t x25 = INT16_MIN;
int8_t x27 = INT8_MIN;
uint64_t x28 = UINT64_MAX;
int32_t t6 = -984;
t6 = ((x25^(x26>x27))==x28);
if (t6 != 0) { NG(); } else { ; }
}
void f7(void) {
static int16_t x30 = -1;
int64_t x31 = -1LL;
int16_t x32 = -1;
volatile int32_t t7 = -1046590156;
t7 = ((x29^(x30>x31))==x32);
if (t7 != 0) { NG(); } else { ; }
}
void f8(void) {
uint64_t x33 = 285LLU;
int32_t x34 = -5627363;
static int16_t x35 = INT16_MIN;
uint8_t x36 = UINT8_MAX;
int32_t t8 = 114748;
t8 = ((x33^(x34>x35))==x36);
if (t8 != 0) { NG(); } else { ; }
}
void f9(void) {
int64_t x38 = -71810466408716233LL;
static int32_t x39 = INT32_MIN;
volatile uint16_t x40 = 140U;
int32_t t9 = -117447;
t9 = ((x37^(x38>x39))==x40);
if (t9 != 0) { NG(); } else { ; }
}
void f10(void) {
static int64_t x41 = -3755586528129LL;
int64_t x42 = INT64_MIN;
volatile uint16_t x43 = 1U;
volatile uint64_t x44 = 2468073684770371942LLU;
static volatile int32_t t10 = -186;
t10 = ((x41^(x42>x43))==x44);
if (t10 != 0) { NG(); } else { ; }
}
void f11(void) {
uint16_t x45 = 34U;
int16_t x46 = INT16_MIN;
uint16_t x47 = 37U;
static int32_t t11 = 199;
t11 = ((x45^(x46>x47))==x48);
if (t11 != 0) { NG(); } else { ; }
}
void f12(void) {
uint32_t x49 = 15073762U;
int8_t x50 = -1;
volatile int16_t x51 = -3463;
volatile int16_t x52 = INT16_MIN;
volatile int32_t t12 = 17707;
t12 = ((x49^(x50>x51))==x52);
if (t12 != 0) { NG(); } else { ; }
}
void f13(void) {
volatile int8_t x53 = 3;
volatile int16_t x54 = INT16_MAX;
uint32_t x55 = UINT32_MAX;
uint64_t x56 = UINT64_MAX;
volatile int32_t t13 = -1167521;
t13 = ((x53^(x54>x55))==x56);
if (t13 != 0) { NG(); } else { ; }
}
void f14(void) {
uint8_t x57 = 41U;
uint64_t x58 = UINT64_MAX;
static uint32_t x59 = 66883337U;
uint32_t x60 = 7U;
volatile int32_t t14 = 2510702;
t14 = ((x57^(x58>x59))==x60);
if (t14 != 0) { NG(); } else { ; }
}
void f15(void) {
uint32_t x63 = 61573553U;
volatile uint32_t x64 = 23U;
volatile int32_t t15 = 347138;
t15 = ((x61^(x62>x63))==x64);
if (t15 != 0) { NG(); } else { ; }
}
void f16(void) {
uint16_t x66 = 9607U;
int8_t x67 = INT8_MAX;
volatile int32_t t16 = -5206301;
t16 = ((x65^(x66>x67))==x68);
if (t16 != 0) { NG(); } else { ; }
}
void f17(void) {
int32_t x69 = INT32_MIN;
static uint64_t x70 = 2LLU;
volatile int16_t x71 = INT16_MIN;
static int8_t x72 = INT8_MIN;
t17 = ((x69^(x70>x71))==x72);
if (t17 != 0) { NG(); } else { ; }
}
void f18(void) {
int64_t x73 = -147528628312318966LL;
int16_t x74 = 1645;
int16_t x75 = -1343;
int32_t t18 = -7;
t18 = ((x73^(x74>x75))==x76);
if (t18 != 0) { NG(); } else { ; }
}
void f19(void) {
int8_t x78 = INT8_MIN;
uint16_t x80 = UINT16_MAX;
volatile int32_t t19 = -56789385;
t19 = ((x77^(x78>x79))==x80);
if (t19 != 0) { NG(); } else { ; }
}
void f20(void) {
int64_t x81 = 8342436687078LL;
int64_t x82 = -1LL;
uint8_t x83 = 35U;
volatile int32_t t20 = 1;
t20 = ((x81^(x82>x83))==x84);
if (t20 != 0) { NG(); } else { ; }
}
void f21(void) {
int64_t x85 = INT64_MIN;
static int32_t t21 = 25;
t21 = ((x85^(x86>x87))==x88);
if (t21 != 0) { NG(); } else { ; }
}
void f22(void) {
uint16_t x89 = 609U;
volatile int32_t x91 = -1;
int16_t x92 = -8;
volatile int32_t t22 = -323;
t22 = ((x89^(x90>x91))==x92);
if (t22 != 0) { NG(); } else { ; }
}
void f23(void) {
static uint16_t x93 = UINT16_MAX;
uint8_t x94 = UINT8_MAX;
volatile uint8_t x96 = UINT8_MAX;
volatile int32_t t23 = -237060;
t23 = ((x93^(x94>x95))==x96);
if (t23 != 0) { NG(); } else { ; }
}
void f24(void) {
volatile int16_t x97 = INT16_MAX;
volatile int8_t x98 = -1;
uint8_t x99 = 1U;
volatile int32_t x100 = INT32_MIN;
static volatile int32_t t24 = 87408;
t24 = ((x97^(x98>x99))==x100);
if (t24 != 0) { NG(); } else { ; }
}
void f25(void) {
uint8_t x101 = 0U;
int8_t x102 = INT8_MAX;
t25 = ((x101^(x102>x103))==x104);
if (t25 != 0) { NG(); } else { ; }
}
void f26(void) {
uint32_t x105 = 422944988U;
volatile int8_t x106 = INT8_MIN;
int16_t x107 = INT16_MAX;
int64_t x108 = 6498452244922LL;
volatile int32_t t26 = -752;
t26 = ((x105^(x106>x107))==x108);
if (t26 != 0) { NG(); } else { ; }
}
void f27(void) {
int32_t x110 = INT32_MAX;
int16_t x111 = INT16_MAX;
volatile uint32_t x112 = 2452859U;
volatile int32_t t27 = -128;
t27 = ((x109^(x110>x111))==x112);
if (t27 != 0) { NG(); } else { ; }
}
void f28(void) {
uint8_t x113 = UINT8_MAX;
volatile int64_t x114 = 126294663025LL;
static uint64_t x115 = 35241LLU;
static volatile int32_t t28 = -1;
t28 = ((x113^(x114>x115))==x116);
if (t28 != 0) { NG(); } else { ; }
}
void f29(void) {
int8_t x117 = -1;
int16_t x118 = -1;
int8_t x120 = -18;
int32_t t29 = 30639521;
t29 = ((x117^(x118>x119))==x120);
if (t29 != 0) { NG(); } else { ; }
}
void f30(void) {
int8_t x122 = 2;
int16_t x123 = -1;
int8_t x124 = -1;
static int32_t t30 = -2610820;
t30 = ((x121^(x122>x123))==x124);
if (t30 != 0) { NG(); } else { ; }
}
void f31(void) {
volatile int16_t x125 = 3;
static int64_t x126 = INT64_MIN;
static int32_t x127 = INT32_MAX;
int32_t t31 = 1;
t31 = ((x125^(x126>x127))==x128);
if (t31 != 0) { NG(); } else { ; }
}
void f32(void) {
int64_t x131 = INT64_MIN;
static int16_t x132 = INT16_MIN;
volatile int32_t t32 = 11561;
t32 = ((x129^(x130>x131))==x132);
if (t32 != 0) { NG(); } else { ; }
}
void f33(void) {
int32_t x133 = INT32_MAX;
static int16_t x134 = INT16_MAX;
volatile int64_t x135 = -6302LL;
static volatile int32_t t33 = -3554;
t33 = ((x133^(x134>x135))==x136);
if (t33 != 0) { NG(); } else { ; }
}
void f34(void) {
int16_t x137 = INT16_MIN;
uint16_t x138 = 2520U;
int8_t x139 = -1;
volatile int8_t x140 = 12;
t34 = ((x137^(x138>x139))==x140);
if (t34 != 0) { NG(); } else { ; }
}
void f35(void) {
static int8_t x141 = INT8_MIN;
static volatile uint32_t x142 = 103U;
uint32_t x143 = UINT32_MAX;
uint16_t x144 = UINT16_MAX;
int32_t t35 = -2184;
t35 = ((x141^(x142>x143))==x144);
if (t35 != 0) { NG(); } else { ; }
}
void f36(void) {
static volatile int16_t x145 = INT16_MIN;
uint8_t x147 = 24U;
uint64_t x148 = 302630950043LLU;
volatile int32_t t36 = 93722;
t36 = ((x145^(x146>x147))==x148);
if (t36 != 0) { NG(); } else { ; }
}
void f37(void) {
uint32_t x149 = UINT32_MAX;
int16_t x150 = INT16_MIN;
int32_t t37 = 610489146;
t37 = ((x149^(x150>x151))==x152);
if (t37 != 0) { NG(); } else { ; }
}
void f38(void) {
int16_t x153 = -6301;
int32_t x154 = INT32_MAX;
volatile int8_t x155 = 1;
static int8_t x156 = -1;
volatile int32_t t38 = -132297;
t38 = ((x153^(x154>x155))==x156);
if (t38 != 0) { NG(); } else { ; }
}
void f39(void) {
uint16_t x157 = 0U;
uint8_t x158 = 109U;
int8_t x159 = INT8_MAX;
int8_t x160 = -1;
volatile int32_t t39 = 136;
t39 = ((x157^(x158>x159))==x160);
if (t39 != 0) { NG(); } else { ; }
}
void f40(void) {
uint8_t x161 = 1U;
uint16_t x163 = 14U;
int16_t x164 = -1;
int32_t t40 = 11874;
t40 = ((x161^(x162>x163))==x164);
if (t40 != 0) { NG(); } else { ; }
}
void f41(void) {
volatile uint64_t x166 = UINT64_MAX;
uint8_t x167 = UINT8_MAX;
static int32_t x168 = INT32_MIN;
static volatile int32_t t41 = -266988450;
t41 = ((x165^(x166>x167))==x168);
if (t41 != 0) { NG(); } else { ; }
}
void f42(void) {
volatile int8_t x169 = INT8_MIN;
uint64_t x170 = 24894701843849LLU;
int8_t x171 = 28;
uint8_t x172 = 3U;
static int32_t t42 = -34341318;
t42 = ((x169^(x170>x171))==x172);
if (t42 != 0) { NG(); } else { ; }
}
void f43(void) {
uint32_t x173 = 157U;
volatile int8_t x174 = -6;
uint16_t x175 = UINT16_MAX;
volatile int32_t t43 = -93122819;
t43 = ((x173^(x174>x175))==x176);
if (t43 != 0) { NG(); } else { ; }
}
void f44(void) {
volatile int8_t x177 = INT8_MIN;
static int16_t x178 = INT16_MAX;
int16_t x179 = INT16_MAX;
static int32_t x180 = -1;
volatile int32_t t44 = -28646703;
t44 = ((x177^(x178>x179))==x180);
if (t44 != 0) { NG(); } else { ; }
}
void f45(void) {
int32_t x181 = INT32_MIN;
uint64_t x182 = 3714889042732479LLU;
volatile int32_t x183 = INT32_MIN;
t45 = ((x181^(x182>x183))==x184);
if (t45 != 0) { NG(); } else { ; }
}
void f46(void) {
int32_t x185 = 12365040;
volatile int16_t x186 = 4477;
int8_t x187 = INT8_MIN;
int64_t x188 = -77LL;
volatile int32_t t46 = 5;
t46 = ((x185^(x186>x187))==x188);
if (t46 != 0) { NG(); } else { ; }
}
void f47(void) {
int16_t x189 = 2;
uint32_t x190 = UINT32_MAX;
uint8_t x191 = 0U;
int8_t x192 = INT8_MAX;
volatile int32_t t47 = -586564;
t47 = ((x189^(x190>x191))==x192);
if (t47 != 0) { NG(); } else { ; }
}
void f48(void) {
int32_t x194 = 1;
int8_t x195 = INT8_MIN;
static int32_t t48 = -2026384;
t48 = ((x193^(x194>x195))==x196);
if (t48 != 0) { NG(); } else { ; }
}
void f49(void) {
volatile uint32_t x197 = UINT32_MAX;
int8_t x198 = -1;
uint32_t x199 = UINT32_MAX;
int8_t x200 = -1;
t49 = ((x197^(x198>x199))==x200);
if (t49 != 1) { NG(); } else { ; }
}
void f50(void) {
int32_t x201 = INT32_MIN;
uint16_t x202 = 1200U;
int8_t x203 = -1;
int16_t x204 = 26;
t50 = ((x201^(x202>x203))==x204);
if (t50 != 0) { NG(); } else { ; }
}
void f51(void) {
uint8_t x205 = 55U;
int64_t x206 = INT64_MAX;
uint32_t x208 = UINT32_MAX;
t51 = ((x205^(x206>x207))==x208);
if (t51 != 0) { NG(); } else { ; }
}
void f52(void) {
int32_t x210 = INT32_MIN;
int8_t x211 = -22;
int64_t x212 = 6287271823968665LL;
int32_t t52 = 1;
t52 = ((x209^(x210>x211))==x212);
if (t52 != 0) { NG(); } else { ; }
}
void f53(void) {
int32_t x214 = -349352;
volatile int32_t t53 = 100446380;
t53 = ((x213^(x214>x215))==x216);
if (t53 != 0) { NG(); } else { ; }
}
void f54(void) {
int64_t x217 = 77914715395LL;
uint32_t x218 = 769702315U;
int64_t x219 = 3988478547159039040LL;
volatile int32_t t54 = -1;
t54 = ((x217^(x218>x219))==x220);
if (t54 != 0) { NG(); } else { ; }
}
void f55(void) {
int16_t x221 = 1;
int8_t x222 = 43;
int64_t x223 = INT64_MAX;
volatile uint8_t x224 = UINT8_MAX;
int32_t t55 = 6;
t55 = ((x221^(x222>x223))==x224);
if (t55 != 0) { NG(); } else { ; }
}
void f56(void) {
uint8_t x226 = 11U;
volatile int8_t x227 = -1;
int16_t x228 = INT16_MIN;
int32_t t56 = -708602375;
t56 = ((x225^(x226>x227))==x228);
if (t56 != 0) { NG(); } else { ; }
}
void f57(void) {
uint8_t x229 = 10U;
uint32_t x230 = UINT32_MAX;
static uint16_t x232 = 4619U;
t57 = ((x229^(x230>x231))==x232);
if (t57 != 0) { NG(); } else { ; }
}
void f58(void) {
static int32_t x233 = INT32_MIN;
static int8_t x234 = INT8_MIN;
int8_t x235 = INT8_MIN;
volatile int32_t t58 = -1850;
t58 = ((x233^(x234>x235))==x236);
if (t58 != 0) { NG(); } else { ; }
}
void f59(void) {
int16_t x238 = 9;
uint8_t x240 = UINT8_MAX;
volatile int32_t t59 = 5306;
t59 = ((x237^(x238>x239))==x240);
if (t59 != 0) { NG(); } else { ; }
}
void f60(void) {
uint16_t x242 = 1171U;
int8_t x243 = 31;
int8_t x244 = INT8_MIN;
volatile int32_t t60 = -2303936;
t60 = ((x241^(x242>x243))==x244);
if (t60 != 0) { NG(); } else { ; }
}
void f61(void) {
int8_t x246 = INT8_MAX;
int8_t x247 = INT8_MIN;
volatile uint32_t x248 = 15067403U;
static volatile int32_t t61 = 1;
t61 = ((x245^(x246>x247))==x248);
if (t61 != 0) { NG(); } else { ; }
}
void f62(void) {
int8_t x249 = INT8_MAX;
uint8_t x250 = 6U;
uint64_t x251 = 26707166179538085LLU;
int16_t x252 = -1;
t62 = ((x249^(x250>x251))==x252);
if (t62 != 0) { NG(); } else { ; }
}
void f63(void) {
int64_t x253 = INT64_MIN;
int8_t x255 = INT8_MIN;
int64_t x256 = INT64_MIN;
t63 = ((x253^(x254>x255))==x256);
if (t63 != 0) { NG(); } else { ; }
}
void f64(void) {
static int16_t x257 = 22;
int64_t x258 = INT64_MAX;
uint16_t x259 = 430U;
uint32_t x260 = UINT32_MAX;
volatile int32_t t64 = 3481;
t64 = ((x257^(x258>x259))==x260);
if (t64 != 0) { NG(); } else { ; }
}
void f65(void) {
static int8_t x261 = 19;
volatile int32_t x262 = -65758584;
uint32_t x263 = 989497374U;
static uint16_t x264 = 12339U;
static int32_t t65 = 163;
t65 = ((x261^(x262>x263))==x264);
if (t65 != 0) { NG(); } else { ; }
}
void f66(void) {
int8_t x265 = INT8_MIN;
int64_t x266 = -271724081808523221LL;
uint16_t x267 = 2U;
volatile int32_t t66 = 90;
t66 = ((x265^(x266>x267))==x268);
if (t66 != 0) { NG(); } else { ; }
}
void f67(void) {
static int64_t x269 = INT64_MIN;
int32_t x270 = -1;
int16_t x271 = 1;
int8_t x272 = INT8_MAX;
t67 = ((x269^(x270>x271))==x272);
if (t67 != 0) { NG(); } else { ; }
}
void f68(void) {
volatile uint8_t x273 = 35U;
static int16_t x274 = -3956;
uint64_t x275 = UINT64_MAX;
volatile int16_t x276 = INT16_MAX;
int32_t t68 = 735171;
t68 = ((x273^(x274>x275))==x276);
if (t68 != 0) { NG(); } else { ; }
}
void f69(void) {
uint16_t x277 = 3U;
int8_t x278 = 1;
uint64_t x279 = UINT64_MAX;
uint64_t x280 = UINT64_MAX;
static volatile int32_t t69 = 8;
t69 = ((x277^(x278>x279))==x280);
if (t69 != 0) { NG(); } else { ; }
}
void f70(void) {
static uint32_t x281 = 623753203U;
int64_t x282 = -1LL;
int64_t x283 = -1LL;
int16_t x284 = INT16_MAX;
static volatile int32_t t70 = 15541917;
t70 = ((x281^(x282>x283))==x284);
if (t70 != 0) { NG(); } else { ; }
}
void f71(void) {
int16_t x285 = INT16_MAX;
static volatile uint32_t x286 = UINT32_MAX;
uint32_t x287 = 5034660U;
int8_t x288 = -1;
int32_t t71 = -3210;
t71 = ((x285^(x286>x287))==x288);
if (t71 != 0) { NG(); } else { ; }
}
void f72(void) {
static volatile int64_t x290 = INT64_MAX;
static volatile int8_t x291 = INT8_MIN;
int8_t x292 = -1;
volatile int32_t t72 = 720076178;
t72 = ((x289^(x290>x291))==x292);
if (t72 != 0) { NG(); } else { ; }
}
void f73(void) {
int32_t x293 = INT32_MIN;
int16_t x295 = INT16_MIN;
int64_t x296 = -1601641317LL;
t73 = ((x293^(x294>x295))==x296);
if (t73 != 0) { NG(); } else { ; }
}
void f74(void) {
volatile int16_t x298 = -4409;
volatile uint32_t x299 = UINT32_MAX;
uint8_t x300 = 7U;
int32_t t74 = -844271282;
t74 = ((x297^(x298>x299))==x300);
if (t74 != 0) { NG(); } else { ; }
}
void f75(void) {
int32_t x301 = 0;
static volatile uint32_t x302 = UINT32_MAX;
volatile int16_t x303 = 184;
volatile uint8_t x304 = 2U;
int32_t t75 = -3;
t75 = ((x301^(x302>x303))==x304);
if (t75 != 0) { NG(); } else { ; }
}
void f76(void) {
uint8_t x306 = UINT8_MAX;
static uint64_t x307 = 1523LLU;
uint16_t x308 = 15333U;
static volatile int32_t t76 = -483060;
t76 = ((x305^(x306>x307))==x308);
if (t76 != 0) { NG(); } else { ; }
}
void f77(void) {
int8_t x309 = INT8_MIN;
int16_t x310 = INT16_MIN;
static int32_t x311 = INT32_MIN;
uint64_t x312 = 21143782035146508LLU;
volatile int32_t t77 = 634;
t77 = ((x309^(x310>x311))==x312);
if (t77 != 0) { NG(); } else { ; }
}
void f78(void) {
volatile uint16_t x315 = 22U;
uint64_t x316 = 250668325LLU;
int32_t t78 = 115417446;
t78 = ((x313^(x314>x315))==x316);
if (t78 != 0) { NG(); } else { ; }
}
void f79(void) {
uint16_t x317 = 10U;
uint32_t x318 = 1067622443U;
static volatile uint32_t x319 = 19U;
static int32_t x320 = -15014;
t79 = ((x317^(x318>x319))==x320);
if (t79 != 0) { NG(); } else { ; }
}
void f80(void) {
int32_t x321 = INT32_MIN;
volatile int8_t x322 = INT8_MAX;
static uint8_t x323 = UINT8_MAX;
volatile int16_t x324 = -1;
t80 = ((x321^(x322>x323))==x324);
if (t80 != 0) { NG(); } else { ; }
}
void f81(void) {
static int16_t x325 = -1;
static volatile int16_t x326 = INT16_MAX;
int32_t x327 = INT32_MAX;
volatile int16_t x328 = -3;
int32_t t81 = 28184130;
t81 = ((x325^(x326>x327))==x328);
if (t81 != 0) { NG(); } else { ; }
}
void f82(void) {
volatile int64_t x329 = 13476272549LL;
int64_t x330 = 1LL;
int32_t x332 = -1;
static volatile int32_t t82 = -362;
t82 = ((x329^(x330>x331))==x332);
if (t82 != 0) { NG(); } else { ; }
}
void f83(void) {
static int8_t x333 = -1;
uint64_t x335 = UINT64_MAX;
int64_t x336 = INT64_MIN;
int32_t t83 = 891459;
t83 = ((x333^(x334>x335))==x336);
if (t83 != 0) { NG(); } else { ; }
}
void f84(void) {
int64_t x337 = INT64_MAX;
int32_t x338 = INT32_MIN;
int64_t x339 = INT64_MAX;
static int16_t x340 = INT16_MIN;
int32_t t84 = -6879191;
t84 = ((x337^(x338>x339))==x340);
if (t84 != 0) { NG(); } else { ; }
}
void f85(void) {
int64_t x341 = 1LL;
int32_t x342 = INT32_MIN;
int64_t x343 = INT64_MIN;
volatile int32_t x344 = -402064;
int32_t t85 = -33862;
t85 = ((x341^(x342>x343))==x344);
if (t85 != 0) { NG(); } else { ; }
}
void f86(void) {
volatile uint8_t x345 = 35U;
int32_t x346 = INT32_MIN;
volatile uint32_t x347 = UINT32_MAX;
int64_t x348 = INT64_MIN;
t86 = ((x345^(x346>x347))==x348);
if (t86 != 0) { NG(); } else { ; }
}
void f87(void) {
int16_t x349 = -1;
int8_t x350 = -1;
uint16_t x351 = 18U;
volatile int32_t t87 = 86913;
t87 = ((x349^(x350>x351))==x352);
if (t87 != 0) { NG(); } else { ; }
}
void f88(void) {
int64_t x354 = 3640LL;
int32_t x355 = -380603677;
int16_t x356 = -1;
int32_t t88 = -467103;
t88 = ((x353^(x354>x355))==x356);
if (t88 != 0) { NG(); } else { ; }
}
void f89(void) {
static int8_t x357 = -11;
static volatile int32_t x358 = -1;
static volatile uint64_t x359 = 39873004LLU;
static uint64_t x360 = 396158866050LLU;
volatile int32_t t89 = -20119;
t89 = ((x357^(x358>x359))==x360);
if (t89 != 0) { NG(); } else { ; }
}
void f90(void) {
uint32_t x361 = UINT32_MAX;
static volatile int64_t x362 = 26178LL;
uint8_t x363 = UINT8_MAX;
int64_t x364 = INT64_MIN;
int32_t t90 = 3001653;
t90 = ((x361^(x362>x363))==x364);
if (t90 != 0) { NG(); } else { ; }
}
void f91(void) {
static int64_t x365 = -1LL;
static uint16_t x366 = 57U;
uint8_t x367 = 1U;
int32_t x368 = INT32_MIN;
int32_t t91 = -2932;
t91 = ((x365^(x366>x367))==x368);
if (t91 != 0) { NG(); } else { ; }
}
void f92(void) {
int8_t x369 = INT8_MIN;
volatile uint8_t x370 = 55U;
volatile int8_t x371 = -8;
int64_t x372 = INT64_MIN;
static int32_t t92 = -53363956;
t92 = ((x369^(x370>x371))==x372);
if (t92 != 0) { NG(); } else { ; }
}
void f93(void) {
int16_t x374 = -26;
uint32_t x375 = 20482642U;
static volatile int16_t x376 = INT16_MAX;
volatile int32_t t93 = 181037938;
t93 = ((x373^(x374>x375))==x376);
if (t93 != 0) { NG(); } else { ; }
}
void f94(void) {
int32_t x377 = -222203;
int64_t x378 = INT64_MIN;
int32_t t94 = -42;
t94 = ((x377^(x378>x379))==x380);
if (t94 != 0) { NG(); } else { ; }
}
void f95(void) {
int32_t x382 = INT32_MIN;
int32_t x383 = -1;
int8_t x384 = -1;
volatile int32_t t95 = 14;
t95 = ((x381^(x382>x383))==x384);
if (t95 != 0) { NG(); } else { ; }
}
void f96(void) {
int32_t x386 = INT32_MIN;
static int16_t x387 = 2;
uint64_t x388 = 26184430LLU;
int32_t t96 = 0;
t96 = ((x385^(x386>x387))==x388);
if (t96 != 0) { NG(); } else { ; }
}
void f97(void) {
int16_t x389 = INT16_MIN;
volatile uint32_t x391 = 59U;
volatile int64_t x392 = INT64_MIN;
t97 = ((x389^(x390>x391))==x392);
if (t97 != 0) { NG(); } else { ; }
}
void f98(void) {
static int64_t x393 = 1498087LL;
int16_t x394 = INT16_MIN;
int16_t x395 = -1;
int8_t x396 = -3;
int32_t t98 = -532876126;
t98 = ((x393^(x394>x395))==x396);
if (t98 != 0) { NG(); } else { ; }
}
void f99(void) {
static int8_t x397 = INT8_MIN;
int32_t x398 = -819812;
int16_t x399 = INT16_MIN;
volatile int32_t t99 = 1807451;
t99 = ((x397^(x398>x399))==x400);
if (t99 != 0) { NG(); } else { ; }
}
void f100(void) {
volatile uint64_t x401 = 1650419325LLU;
volatile int16_t x402 = -1;
static uint64_t x403 = UINT64_MAX;
volatile int32_t t100 = -1317;
t100 = ((x401^(x402>x403))==x404);
if (t100 != 0) { NG(); } else { ; }
}
void f101(void) {
volatile uint8_t x405 = 8U;
uint64_t x407 = 2343817806720140LLU;
volatile int8_t x408 = 1;
int32_t t101 = 1349;
t101 = ((x405^(x406>x407))==x408);
if (t101 != 0) { NG(); } else { ; }
}
void f102(void) {
static int32_t x410 = -7;
int32_t x411 = INT32_MAX;
int64_t x412 = INT64_MIN;
int32_t t102 = 13222;
t102 = ((x409^(x410>x411))==x412);
if (t102 != 0) { NG(); } else { ; }
}
void f103(void) {
uint32_t x413 = 1349579831U;
int32_t x414 = INT32_MIN;
volatile int16_t x415 = -197;
static int8_t x416 = INT8_MIN;
int32_t t103 = -642776659;
t103 = ((x413^(x414>x415))==x416);
if (t103 != 0) { NG(); } else { ; }
}
void f104(void) {
int32_t x417 = INT32_MAX;
int32_t x418 = -1;
uint64_t x419 = 249060LLU;
int64_t x420 = INT64_MAX;
volatile int32_t t104 = -43;
t104 = ((x417^(x418>x419))==x420);
if (t104 != 0) { NG(); } else { ; }
}
void f105(void) {
volatile int16_t x421 = INT16_MIN;
uint32_t x422 = 0U;
int32_t x423 = INT32_MIN;
static volatile int32_t x424 = INT32_MAX;
static volatile int32_t t105 = 30;
t105 = ((x421^(x422>x423))==x424);
if (t105 != 0) { NG(); } else { ; }
}
void f106(void) {
int8_t x425 = INT8_MIN;
uint32_t x426 = 541303U;
uint32_t x427 = 92801416U;
static int16_t x428 = INT16_MAX;
static int32_t t106 = 53970263;
t106 = ((x425^(x426>x427))==x428);
if (t106 != 0) { NG(); } else { ; }
}
void f107(void) {
volatile uint32_t x429 = 8533355U;
int8_t x430 = 6;
uint16_t x431 = 282U;
uint32_t x432 = UINT32_MAX;
volatile int32_t t107 = 23915;
t107 = ((x429^(x430>x431))==x432);
if (t107 != 0) { NG(); } else { ; }
}
void f108(void) {
volatile int32_t x433 = INT32_MAX;
int16_t x434 = 8375;
int32_t x435 = INT32_MIN;
static volatile int32_t t108 = -6;
t108 = ((x433^(x434>x435))==x436);
if (t108 != 0) { NG(); } else { ; }
}
void f109(void) {
int8_t x437 = 0;
static int16_t x438 = INT16_MIN;
int16_t x440 = -1;
volatile int32_t t109 = 1394;
t109 = ((x437^(x438>x439))==x440);
if (t109 != 0) { NG(); } else { ; }
}
void f110(void) {
int32_t x441 = INT32_MIN;
uint8_t x442 = 1U;
int8_t x443 = INT8_MIN;
int8_t x444 = INT8_MIN;
int32_t t110 = 1;
t110 = ((x441^(x442>x443))==x444);
if (t110 != 0) { NG(); } else { ; }
}
void f111(void) {
int16_t x445 = INT16_MAX;
int64_t x446 = 157513385415787904LL;
static int16_t x447 = 119;
int32_t x448 = 217457;
volatile int32_t t111 = 13954;
t111 = ((x445^(x446>x447))==x448);
if (t111 != 0) { NG(); } else { ; }
}
void f112(void) {
int16_t x449 = INT16_MIN;
uint32_t x450 = UINT32_MAX;
volatile int64_t x451 = -105LL;
int64_t x452 = INT64_MIN;
int32_t t112 = 5580802;
t112 = ((x449^(x450>x451))==x452);
if (t112 != 0) { NG(); } else { ; }
}
void f113(void) {
uint64_t x455 = 259968921LLU;
int8_t x456 = -1;
int32_t t113 = -50047799;
t113 = ((x453^(x454>x455))==x456);
if (t113 != 0) { NG(); } else { ; }
}
void f114(void) {
volatile int8_t x457 = -1;
int64_t x460 = INT64_MAX;
t114 = ((x457^(x458>x459))==x460);
if (t114 != 0) { NG(); } else { ; }
}
void f115(void) {
static int64_t x462 = 0LL;
int16_t x463 = -13;
int64_t x464 = INT64_MIN;
volatile int32_t t115 = 91034499;
t115 = ((x461^(x462>x463))==x464);
if (t115 != 0) { NG(); } else { ; }
}
void f116(void) {
int64_t x465 = INT64_MAX;
int16_t x466 = INT16_MIN;
static int64_t x467 = INT64_MIN;
int16_t x468 = -1;
volatile int32_t t116 = 147;
t116 = ((x465^(x466>x467))==x468);
if (t116 != 0) { NG(); } else { ; }
}
void f117(void) {
uint8_t x469 = 0U;
int16_t x470 = -11;
static int64_t x471 = INT64_MAX;
int32_t t117 = -120906;
t117 = ((x469^(x470>x471))==x472);
if (t117 != 0) { NG(); } else { ; }
}
void f118(void) {
int32_t x473 = -1;
int8_t x474 = INT8_MAX;
uint64_t x475 = 669894208LLU;
int32_t x476 = INT32_MIN;
static int32_t t118 = 297784;
t118 = ((x473^(x474>x475))==x476);
if (t118 != 0) { NG(); } else { ; }
}
void f119(void) {
int64_t x477 = INT64_MIN;
uint32_t x479 = UINT32_MAX;
static volatile int32_t x480 = INT32_MIN;
t119 = ((x477^(x478>x479))==x480);
if (t119 != 0) { NG(); } else { ; }
}
void f120(void) {
uint8_t x481 = UINT8_MAX;
int32_t t120 = 1112876;
t120 = ((x481^(x482>x483))==x484);
if (t120 != 0) { NG(); } else { ; }
}
void f121(void) {
volatile int8_t x485 = INT8_MIN;
int16_t x486 = -57;
static int32_t x487 = INT32_MAX;
t121 = ((x485^(x486>x487))==x488);
if (t121 != 0) { NG(); } else { ; }
}
void f122(void) {
uint16_t x489 = 7569U;
static int32_t x491 = 103531426;
static int16_t x492 = -450;
int32_t t122 = -12792853;
t122 = ((x489^(x490>x491))==x492);
if (t122 != 0) { NG(); } else { ; }
}
void f123(void) {
int8_t x494 = INT8_MIN;
static int64_t x495 = -234565243086454LL;
int64_t x496 = INT64_MIN;
volatile int32_t t123 = 4798273;
t123 = ((x493^(x494>x495))==x496);
if (t123 != 0) { NG(); } else { ; }
}
void f124(void) {
int64_t x498 = INT64_MIN;
volatile uint8_t x499 = 112U;
int16_t x500 = -1;
int32_t t124 = -304764;
t124 = ((x497^(x498>x499))==x500);
if (t124 != 0) { NG(); } else { ; }
}
void f125(void) {
int16_t x501 = -1;
int8_t x503 = INT8_MIN;
int32_t t125 = 1;
t125 = ((x501^(x502>x503))==x504);
if (t125 != 0) { NG(); } else { ; }
}
void f126(void) {
static uint8_t x506 = 34U;
int64_t x507 = 0LL;
int8_t x508 = 52;
volatile int32_t t126 = -542554102;
t126 = ((x505^(x506>x507))==x508);
if (t126 != 0) { NG(); } else { ; }
}
void f127(void) {
uint16_t x509 = 335U;
int32_t t127 = -193073;
t127 = ((x509^(x510>x511))==x512);
if (t127 != 0) { NG(); } else { ; }
}
void f128(void) {
volatile int8_t x513 = -50;
volatile int16_t x514 = INT16_MIN;
int16_t x516 = -1;
volatile int32_t t128 = -4393;
t128 = ((x513^(x514>x515))==x516);
if (t128 != 0) { NG(); } else { ; }
}
void f129(void) {
static uint16_t x517 = UINT16_MAX;
volatile uint64_t x518 = 61842273887873LLU;
uint32_t x519 = 41294U;
uint64_t x520 = 2482076767809914683LLU;
t129 = ((x517^(x518>x519))==x520);
if (t129 != 0) { NG(); } else { ; }
}
void f130(void) {
int16_t x521 = -1;
int16_t x522 = -215;
uint64_t x523 = 1LLU;
int16_t x524 = INT16_MIN;
t130 = ((x521^(x522>x523))==x524);
if (t130 != 0) { NG(); } else { ; }
}
void f131(void) {
static int32_t x526 = -1;
volatile int8_t x527 = INT8_MIN;
t131 = ((x525^(x526>x527))==x528);
if (t131 != 0) { NG(); } else { ; }
}
void f132(void) {
int16_t x529 = -1;
uint16_t x530 = 19U;
static uint8_t x531 = 1U;
static uint32_t x532 = UINT32_MAX;
volatile int32_t t132 = -246819;
t132 = ((x529^(x530>x531))==x532);
if (t132 != 0) { NG(); } else { ; }
}
void f133(void) {
uint16_t x533 = 2771U;
static int64_t x534 = -1LL;
int32_t x536 = 1;
int32_t t133 = 7758;
t133 = ((x533^(x534>x535))==x536);
if (t133 != 0) { NG(); } else { ; }
}
void f134(void) {
uint32_t x537 = UINT32_MAX;
int16_t x538 = 0;
uint32_t x540 = UINT32_MAX;
int32_t t134 = -3701885;
t134 = ((x537^(x538>x539))==x540);
if (t134 != 0) { NG(); } else { ; }
}
void f135(void) {
static volatile int64_t x543 = INT64_MIN;
int8_t x544 = -6;
int32_t t135 = 1362026;
t135 = ((x541^(x542>x543))==x544);
if (t135 != 0) { NG(); } else { ; }
}
void f136(void) {
uint8_t x545 = 1U;
uint64_t x546 = UINT64_MAX;
static int64_t x548 = INT64_MIN;
t136 = ((x545^(x546>x547))==x548);
if (t136 != 0) { NG(); } else { ; }
}
void f137(void) {
static uint32_t x549 = 334U;
static int32_t x550 = -1;
volatile int16_t x551 = 1;
int8_t x552 = INT8_MIN;
t137 = ((x549^(x550>x551))==x552);
if (t137 != 0) { NG(); } else { ; }
}
void f138(void) {
static int8_t x555 = -10;
uint64_t x556 = 3671488198145LLU;
t138 = ((x553^(x554>x555))==x556);
if (t138 != 0) { NG(); } else { ; }
}
void f139(void) {
uint8_t x557 = 0U;
uint32_t x558 = UINT32_MAX;
int16_t x560 = 1;
int32_t t139 = -197;
t139 = ((x557^(x558>x559))==x560);
if (t139 != 1) { NG(); } else { ; }
}
void f140(void) {
int8_t x561 = -4;
int8_t x562 = 0;
static int64_t x563 = INT64_MAX;
static int8_t x564 = INT8_MIN;
volatile int32_t t140 = -59965;
t140 = ((x561^(x562>x563))==x564);
if (t140 != 0) { NG(); } else { ; }
}
void f141(void) {
uint32_t x565 = 9U;
int16_t x566 = -1;
static volatile int8_t x567 = -1;
int32_t t141 = -10043057;
t141 = ((x565^(x566>x567))==x568);
if (t141 != 0) { NG(); } else { ; }
}
void f142(void) {
uint16_t x569 = UINT16_MAX;
uint32_t x570 = UINT32_MAX;
int16_t x571 = -584;
volatile int32_t t142 = 5281743;
t142 = ((x569^(x570>x571))==x572);
if (t142 != 0) { NG(); } else { ; }
}
void f143(void) {
int32_t x573 = INT32_MIN;
int16_t x574 = -1;
uint32_t x575 = 87U;
volatile int64_t x576 = INT64_MAX;
volatile int32_t t143 = -6508665;
t143 = ((x573^(x574>x575))==x576);
if (t143 != 0) { NG(); } else { ; }
}
void f144(void) {
uint64_t x577 = 1541956LLU;
int64_t x578 = INT64_MIN;
int8_t x579 = INT8_MAX;
uint8_t x580 = 97U;
t144 = ((x577^(x578>x579))==x580);
if (t144 != 0) { NG(); } else { ; }
}
void f145(void) {
int32_t x581 = INT32_MIN;
volatile int32_t x582 = INT32_MIN;
static int64_t x584 = INT64_MIN;
int32_t t145 = 2044;
t145 = ((x581^(x582>x583))==x584);
if (t145 != 0) { NG(); } else { ; }
}
void f146(void) {
int16_t x585 = INT16_MIN;
int64_t x586 = 4903LL;
uint16_t x587 = UINT16_MAX;
int32_t t146 = -1048535;
t146 = ((x585^(x586>x587))==x588);
if (t146 != 0) { NG(); } else { ; }
}
void f147(void) {
static uint32_t x589 = 2447999U;
static int64_t x590 = -1LL;
uint16_t x591 = UINT16_MAX;
uint16_t x592 = UINT16_MAX;
volatile int32_t t147 = 112138;
t147 = ((x589^(x590>x591))==x592);
if (t147 != 0) { NG(); } else { ; }
}
void f148(void) {
static int32_t x593 = -48544;
static int8_t x594 = INT8_MIN;
volatile int32_t x595 = -1;
volatile int32_t t148 = -122926836;
t148 = ((x593^(x594>x595))==x596);
if (t148 != 0) { NG(); } else { ; }
}
void f149(void) {
static int8_t x599 = -1;
t149 = ((x597^(x598>x599))==x600);
if (t149 != 0) { NG(); } else { ; }
}
void f150(void) {
uint16_t x601 = 11U;
volatile uint16_t x602 = 59U;
int8_t x603 = -1;
volatile uint8_t x604 = 94U;
int32_t t150 = 375;
t150 = ((x601^(x602>x603))==x604);
if (t150 != 0) { NG(); } else { ; }
}
void f151(void) {
static uint64_t x606 = 2817897350LLU;
int16_t x607 = -1;
static uint64_t x608 = UINT64_MAX;
static int32_t t151 = 3170966;
t151 = ((x605^(x606>x607))==x608);
if (t151 != 0) { NG(); } else { ; }
}
void f152(void) {
volatile uint32_t x609 = 11U;
static int64_t x610 = -1LL;
int16_t x611 = -1;
int16_t x612 = 3840;
volatile int32_t t152 = 0;
t152 = ((x609^(x610>x611))==x612);
if (t152 != 0) { NG(); } else { ; }
}
void f153(void) {
int16_t x616 = -1;
volatile int32_t t153 = 1;
t153 = ((x613^(x614>x615))==x616);
if (t153 != 0) { NG(); } else { ; }
}
void f154(void) {
uint8_t x617 = 13U;
static volatile int32_t x618 = INT32_MIN;
uint64_t x619 = UINT64_MAX;
int32_t x620 = -1;
int32_t t154 = 1744;
t154 = ((x617^(x618>x619))==x620);
if (t154 != 0) { NG(); } else { ; }
}
void f155(void) {
static uint64_t x621 = 63076LLU;
uint16_t x622 = UINT16_MAX;
int64_t x623 = -1LL;
volatile int16_t x624 = INT16_MIN;
volatile int32_t t155 = -21740206;
t155 = ((x621^(x622>x623))==x624);
if (t155 != 0) { NG(); } else { ; }
}
void f156(void) {
int32_t x625 = -22100;
int8_t x626 = INT8_MIN;
int16_t x628 = -996;
int32_t t156 = 443294480;
t156 = ((x625^(x626>x627))==x628);
if (t156 != 0) { NG(); } else { ; }
}
void f157(void) {
uint16_t x629 = 4U;
int32_t x631 = 78612008;
int64_t x632 = -1LL;
int32_t t157 = -2311573;
t157 = ((x629^(x630>x631))==x632);
if (t157 != 0) { NG(); } else { ; }
}
void f158(void) {
uint16_t x633 = UINT16_MAX;
static int16_t x634 = -2;
int32_t x635 = INT32_MIN;
int32_t x636 = 21612307;
volatile int32_t t158 = 388171171;
t158 = ((x633^(x634>x635))==x636);
if (t158 != 0) { NG(); } else { ; }
}
void f159(void) {
volatile uint64_t x637 = UINT64_MAX;
uint16_t x638 = 24099U;
int8_t x639 = -1;
uint64_t x640 = 125589136114LLU;
volatile int32_t t159 = -21299771;
t159 = ((x637^(x638>x639))==x640);
if (t159 != 0) { NG(); } else { ; }
}
void f160(void) {
int8_t x641 = INT8_MIN;
int8_t x642 = 0;
int16_t x643 = -70;
volatile int64_t x644 = INT64_MIN;
t160 = ((x641^(x642>x643))==x644);
if (t160 != 0) { NG(); } else { ; }
}
void f161(void) {
volatile uint64_t x646 = UINT64_MAX;
int64_t x647 = -11415LL;
uint32_t x648 = 1905U;
t161 = ((x645^(x646>x647))==x648);
if (t161 != 0) { NG(); } else { ; }
}
void f162(void) {
volatile int8_t x649 = -1;
static int8_t x650 = -1;
int32_t x652 = 28418;
volatile int32_t t162 = -174927;
t162 = ((x649^(x650>x651))==x652);
if (t162 != 0) { NG(); } else { ; }
}
void f163(void) {
int16_t x653 = INT16_MIN;
int64_t x654 = INT64_MAX;
int16_t x655 = 10422;
volatile int16_t x656 = -5195;
t163 = ((x653^(x654>x655))==x656);
if (t163 != 0) { NG(); } else { ; }
}
void f164(void) {
uint64_t x657 = 798807LLU;
int8_t x659 = INT8_MAX;
int8_t x660 = INT8_MAX;
volatile int32_t t164 = -1208;
t164 = ((x657^(x658>x659))==x660);
if (t164 != 0) { NG(); } else { ; }
}
void f165(void) {
uint16_t x661 = UINT16_MAX;
int32_t x663 = -1;
uint8_t x664 = 0U;
int32_t t165 = 214;
t165 = ((x661^(x662>x663))==x664);
if (t165 != 0) { NG(); } else { ; }
}
void f166(void) {
volatile int64_t x665 = INT64_MIN;
int8_t x667 = -1;
static int64_t x668 = -132127482LL;
int32_t t166 = -45762031;
t166 = ((x665^(x666>x667))==x668);
if (t166 != 0) { NG(); } else { ; }
}
void f167(void) {
static volatile uint64_t x669 = 264LLU;
volatile int64_t x670 = -6LL;
int8_t x671 = -1;
volatile uint8_t x672 = 28U;
t167 = ((x669^(x670>x671))==x672);
if (t167 != 0) { NG(); } else { ; }
}
void f168(void) {
uint32_t x674 = 39077429U;
uint16_t x675 = UINT16_MAX;
uint64_t x676 = 19979601865803LLU;
int32_t t168 = 640915;
t168 = ((x673^(x674>x675))==x676);
if (t168 != 0) { NG(); } else { ; }
}
void f169(void) {
int64_t x677 = -493042842895475769LL;
uint64_t x678 = 84659LLU;
int8_t x679 = INT8_MIN;
int32_t t169 = -1;
t169 = ((x677^(x678>x679))==x680);
if (t169 != 0) { NG(); } else { ; }
}
void f170(void) {
uint16_t x681 = 408U;
uint32_t x682 = 477U;
int16_t x683 = 4;
int8_t x684 = INT8_MIN;
volatile int32_t t170 = 11;
t170 = ((x681^(x682>x683))==x684);
if (t170 != 0) { NG(); } else { ; }
}
void f171(void) {
static int32_t x685 = INT32_MIN;
volatile uint8_t x686 = 38U;
int8_t x687 = INT8_MIN;
uint64_t x688 = UINT64_MAX;
volatile int32_t t171 = -2911;
t171 = ((x685^(x686>x687))==x688);
if (t171 != 0) { NG(); } else { ; }
}
void f172(void) {
static int64_t x689 = 83664628607054089LL;
int32_t x690 = 11777149;
int32_t x691 = INT32_MIN;
uint32_t x692 = 66205U;
volatile int32_t t172 = 313332666;
t172 = ((x689^(x690>x691))==x692);
if (t172 != 0) { NG(); } else { ; }
}
void f173(void) {
int8_t x694 = -1;
static int8_t x696 = INT8_MIN;
t173 = ((x693^(x694>x695))==x696);
if (t173 != 0) { NG(); } else { ; }
}
void f174(void) {
static uint32_t x697 = 228U;
volatile int64_t x698 = 1107480053650384074LL;
static volatile int16_t x699 = INT16_MAX;
uint16_t x700 = 818U;
t174 = ((x697^(x698>x699))==x700);
if (t174 != 0) { NG(); } else { ; }
}
void f175(void) {
int32_t x701 = INT32_MAX;
static uint16_t x702 = 13U;
int16_t x703 = INT16_MAX;
volatile int16_t x704 = 5419;
t175 = ((x701^(x702>x703))==x704);
if (t175 != 0) { NG(); } else { ; }
}
void f176(void) {
int8_t x705 = 0;
volatile uint64_t x706 = UINT64_MAX;
uint64_t x707 = 28318488124LLU;
int32_t x708 = 70911;
t176 = ((x705^(x706>x707))==x708);
if (t176 != 0) { NG(); } else { ; }
}
void f177(void) {
uint8_t x709 = 7U;
int16_t x710 = -1;
static uint8_t x712 = 0U;
volatile int32_t t177 = -127656504;
t177 = ((x709^(x710>x711))==x712);
if (t177 != 0) { NG(); } else { ; }
}
void f178(void) {
uint32_t x713 = UINT32_MAX;
int8_t x715 = 7;
uint8_t x716 = UINT8_MAX;
volatile int32_t t178 = -1;
t178 = ((x713^(x714>x715))==x716);
if (t178 != 0) { NG(); } else { ; }
}
void f179(void) {
volatile int8_t x717 = -1;
int16_t x718 = INT16_MIN;
int8_t x719 = INT8_MIN;
int64_t x720 = 323563097LL;
volatile int32_t t179 = 1;
t179 = ((x717^(x718>x719))==x720);
if (t179 != 0) { NG(); } else { ; }
}
void f180(void) {
uint64_t x722 = UINT64_MAX;
int32_t t180 = 4007;
t180 = ((x721^(x722>x723))==x724);
if (t180 != 0) { NG(); } else { ; }
}
void f181(void) {
volatile int16_t x725 = -1;
uint16_t x726 = 12017U;
uint8_t x727 = 13U;
static int16_t x728 = -755;
int32_t t181 = 55115264;
t181 = ((x725^(x726>x727))==x728);
if (t181 != 0) { NG(); } else { ; }
}
void f182(void) {
volatile uint32_t x729 = UINT32_MAX;
uint16_t x730 = 78U;
volatile uint32_t x731 = UINT32_MAX;
volatile int32_t x732 = INT32_MIN;
t182 = ((x729^(x730>x731))==x732);
if (t182 != 0) { NG(); } else { ; }
}
void f183(void) {
int64_t x733 = -82693778218203LL;
int32_t x734 = INT32_MIN;
int8_t x735 = INT8_MAX;
uint16_t x736 = 1U;
volatile int32_t t183 = -1;
t183 = ((x733^(x734>x735))==x736);
if (t183 != 0) { NG(); } else { ; }
}
void f184(void) {
static int32_t x737 = INT32_MIN;
uint64_t x738 = UINT64_MAX;
uint64_t x740 = 817521639603LLU;
volatile int32_t t184 = -30;
t184 = ((x737^(x738>x739))==x740);
if (t184 != 0) { NG(); } else { ; }
}
void f185(void) {
uint8_t x741 = 42U;
uint16_t x743 = 1U;
static uint16_t x744 = 32257U;
volatile int32_t t185 = 195;
t185 = ((x741^(x742>x743))==x744);
if (t185 != 0) { NG(); } else { ; }
}
void f186(void) {
int32_t x745 = -1;
int64_t x746 = INT64_MIN;
int32_t x747 = -203485792;
volatile uint8_t x748 = 0U;
volatile int32_t t186 = 530289518;
t186 = ((x745^(x746>x747))==x748);
if (t186 != 0) { NG(); } else { ; }
}
void f187(void) {
uint64_t x749 = UINT64_MAX;
int16_t x750 = INT16_MIN;
uint32_t x751 = 0U;
static int16_t x752 = INT16_MIN;
t187 = ((x749^(x750>x751))==x752);
if (t187 != 0) { NG(); } else { ; }
}
void f188(void) {
int16_t x753 = -1;
uint32_t x754 = UINT32_MAX;
int16_t x755 = 14391;
int8_t x756 = INT8_MAX;
volatile int32_t t188 = 247311;
t188 = ((x753^(x754>x755))==x756);
if (t188 != 0) { NG(); } else { ; }
}
void f189(void) {
int8_t x757 = INT8_MIN;
uint16_t x758 = 45U;
uint32_t x759 = 20U;
uint64_t x760 = UINT64_MAX;
volatile int32_t t189 = 0;
t189 = ((x757^(x758>x759))==x760);
if (t189 != 0) { NG(); } else { ; }
}
void f190(void) {
int32_t x762 = INT32_MAX;
uint32_t x763 = UINT32_MAX;
int16_t x764 = -1;
static volatile int32_t t190 = 164;
t190 = ((x761^(x762>x763))==x764);
if (t190 != 0) { NG(); } else { ; }
}
void f191(void) {
uint32_t x765 = 6U;
int16_t x766 = INT16_MIN;
int16_t x767 = INT16_MIN;
uint16_t x768 = UINT16_MAX;
volatile int32_t t191 = -765460;
t191 = ((x765^(x766>x767))==x768);
if (t191 != 0) { NG(); } else { ; }
}
void f192(void) {
static int8_t x770 = INT8_MIN;
int32_t x772 = -1;
int32_t t192 = 249344627;
t192 = ((x769^(x770>x771))==x772);
if (t192 != 0) { NG(); } else { ; }
}
void f193(void) {
int8_t x773 = INT8_MAX;
int64_t x774 = INT64_MAX;
static int16_t x776 = 4379;
volatile int32_t t193 = 740375815;
t193 = ((x773^(x774>x775))==x776);
if (t193 != 0) { NG(); } else { ; }
}
void f194(void) {
static uint8_t x777 = UINT8_MAX;
uint64_t x778 = UINT64_MAX;
int8_t x779 = INT8_MIN;
int64_t x780 = INT64_MIN;
int32_t t194 = 138169;
t194 = ((x777^(x778>x779))==x780);
if (t194 != 0) { NG(); } else { ; }
}
void f195(void) {
static uint16_t x782 = UINT16_MAX;
static int32_t x783 = -1045240605;
int8_t x784 = INT8_MAX;
int32_t t195 = 120634;
t195 = ((x781^(x782>x783))==x784);
if (t195 != 0) { NG(); } else { ; }
}
void f196(void) {
int64_t x785 = INT64_MAX;
volatile int16_t x786 = INT16_MIN;
int8_t x787 = INT8_MIN;
int8_t x788 = 1;
volatile int32_t t196 = -8418189;
t196 = ((x785^(x786>x787))==x788);
if (t196 != 0) { NG(); } else { ; }
}
void f197(void) {
int64_t x790 = -33002875623768465LL;
uint64_t x791 = UINT64_MAX;
int64_t x792 = INT64_MIN;
t197 = ((x789^(x790>x791))==x792);
if (t197 != 0) { NG(); } else { ; }
}
void f198(void) {
static int8_t x793 = 0;
static uint64_t x794 = 154251LLU;
int16_t x795 = INT16_MIN;
t198 = ((x793^(x794>x795))==x796);
if (t198 != 0) { NG(); } else { ; }
}
void f199(void) {
volatile int16_t x797 = -3269;
int32_t x798 = INT32_MIN;
static uint16_t x799 = UINT16_MAX;
volatile uint8_t x800 = 1U;
static volatile int32_t t199 = -113986;
t199 = ((x797^(x798>x799))==x800);
if (t199 != 0) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
|
"""DNS Authenticator for Domain-Offensive."""
import logging
import requests
import zope.interface
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
logger = logging.getLogger(__name__)
ACCOUNT_URL = 'https://www.do.de/account/letsencrypt/'
API_URL = 'https://www.do.de/api/letsencrypt'
@zope.interface.implementer(interfaces.IAuthenticator)
@zope.interface.provider(interfaces.IPluginFactory)
class Authenticator(dns_common.DNSAuthenticator):
"""DNS Authenticator for Domain-Offensive
This Authenticator uses the Domain-Offensive API to fulfill a dns-01 challenge.
"""
description = ('Obtain certificates using a DNS TXT record (if you are using Domain-Offensive for '
'DNS).')
def __init__(self, *args, **kwargs):
super(Authenticator, self).__init__(*args, **kwargs)
self.credentials = None
@classmethod
def add_parser_arguments(cls, add): # pylint: disable=arguments-differ
super(Authenticator, cls).add_parser_arguments(add)
add('credentials', help='Domain-Offensive credentials INI file.')
def more_info(self): # pylint: disable=missing-docstring,no-self-use
return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \
'the Domain-Offensive API.'
def _setup_credentials(self):
self.credentials = self._configure_credentials(
'credentials',
'Domain-Offensive credentials INI file',
{
'api-token': 'API token for Domain-Offensive account, obtained from {0}'.format(ACCOUNT_URL)
}
)
def _perform(self, domain, validation_name, validation):
self._get_do_client().add_txt_record(domain, validation_name, validation)
def _cleanup(self, domain, validation_name, validation):
self._get_do_client().del_txt_record(domain, validation_name, validation)
def _get_do_client(self):
return _DomainOffensiveClient(self.credentials.conf('api-token'))
class _DomainOffensiveClient(object):
"""
Encapsulates all communication with the Domain-Offensive API.
"""
def __init__(self, api_token):
self.api_token = api_token
def add_txt_record(self, domain, record_name, record_content):
"""
Add a TXT record using the supplied information.
:param str domain: The domain to use to look up the managed zone.
:param str record_name: The record name (typically beginning with '_acme-challenge.').
:param str record_content: The record content (typically the challenge validation).
:param int record_ttl: The record TTL (number of seconds that the record may be cached).
:raises certbot.errors.PluginError: if an error occurs communicating with the API
"""
params = {'token': self.api_token,
'domain': record_name,
'value': record_content}
try:
r = requests.get(API_URL, params=params)
r.raise_for_status()
result = r.json()
if 'success' not in result or result['success'] != True:
logger.error('Encountered error adding TXT record: not successful')
raise errors.PluginError('Error adding TXT record: not successful')
except requests.exceptions.RequestException as e:
logger.error('Encountered error adding TXT record: %s', e, exc_info=True)
raise errors.PluginError('Error adding TXT record: {0}'.format(e))
def del_txt_record(self, domain, record_name, record_content):
"""
Delete a TXT record using the supplied information.
Note that both the record's name and content are used to ensure that similar records
created concurrently (e.g., due to concurrent invocations of this plugin) are not deleted.
Failures are logged, but not raised.
:param str domain: The domain to use to look up the managed zone.
:param str record_name: The record name (typically beginning with '_acme-challenge.').
:param str record_content: The record content (typically the challenge validation).
"""
params = {'token': self.api_token,
'domain': record_name,
'action': 'delete'}
try:
r = requests.get(API_URL, params=params)
r.raise_for_status()
result = r.json()
if 'success' not in result or result['success'] != True:
logger.error('Encountered error deleting TXT record: not successful')
except requests.exceptions.RequestException as e:
logger.error('Encountered error deleting TXT record: %s', e, exc_info=True)
|
import DataService from '../DataService';
import fetchAction from './fetch';
export const BUILDS_REQUEST = 'BUILDS_REQUEST';
export const BUILDS_SUCCESS = 'BUILDS_SUCCESS';
export const BUILDS_FAILURE = 'BUILDS_FAILURE';
export const fetchBuilds = fetchAction([BUILDS_REQUEST, BUILDS_SUCCESS, BUILDS_FAILURE], DataService.builds);
export const BUILD_TRIGGER_REQUEST = 'BUILD_TRIGGER_REQUEST';
export const BUILD_TRIGGER_SUCCESS = 'BUILD_TRIGGER_SUCCESS';
export const BUILD_TRIGGER_FAILURE = 'BUILD_TRIGGER_FAILURE';
export const triggerBuild = name =>
fetchAction([BUILD_TRIGGER_REQUEST, BUILD_TRIGGER_SUCCESS, BUILD_TRIGGER_FAILURE], async () =>
DataService.triggerBuild(name)
)();
export const BUILD_DOWNLOAD_REQUEST = 'BUILD_DOWNLOAD_REQUEST';
export const BUILD_DOWNLOAD_SUCCESS = 'BUILD_DOWNLOAD_SUCCESS';
export const BUILD_DOWNLOAD_FAILURE = 'BUILD_DOWNLOAD_FAILURE';
export const generateDownloadURL = name =>
fetchAction([BUILD_DOWNLOAD_REQUEST, BUILD_DOWNLOAD_SUCCESS, BUILD_DOWNLOAD_FAILURE], async () =>
DataService.generateDownloadURL(name)
)();
|
#pragma once
#include "skse/Utilities.h"
#include "skse/PapyrusVM.h"
class VMState;
class VMValue;
class VMClassRegistry;
struct StaticFunctionTag;
class EffectSetting;
class VMArgList
{
public:
VMArgList();
~VMArgList();
MEMBER_FN_PREFIX(VMArgList);
DEFINE_MEMBER_FN(GetOffset, UInt32, 0x00C3A620, VMState * state);
DEFINE_MEMBER_FN(Get, VMValue *, 0x00C3AC40, VMState * state, UInt32 idx, UInt32 offset);
};
template <typename T>
class VMArray
{
public:
VMValue::ArrayData * arr;
UInt32 Length() const { return arr ? arr->len : 0; }
void Get(T * dst, const UInt32 idx) { UnpackValue(dst, arr->GetData()+idx); }
void Set(T * src, const UInt32 idx)
{
VMClassRegistry * registry = (*g_skyrimVM)->GetClassRegistry();
PackValue(arr->GetData()+idx, src, registry);
}
};
template <typename T>
void PackValue(VMValue * dst, T * src, VMClassRegistry * registry);
template <typename T>
void UnpackValue(T * dst, VMValue * src);
template <typename T>
UInt32 GetTypeID(VMClassRegistry * registry);
template <> void PackValue <void>(VMValue * dst, void * src, VMClassRegistry * registry);
template <> void PackValue <UInt32>(VMValue * dst, UInt32 * src, VMClassRegistry * registry);
template <> void PackValue <SInt32>(VMValue * dst, SInt32 * src, VMClassRegistry * registry);
template <> void PackValue <float>(VMValue * dst, float * src, VMClassRegistry * registry);
template <> void PackValue <bool>(VMValue * dst, bool * src, VMClassRegistry * registry);
template <> void PackValue <BSFixedString>(VMValue * dst, BSFixedString * src, VMClassRegistry * registry);
void PackHandle(VMValue * dst, void * src, UInt32 typeID, VMClassRegistry * registry);
template <typename T>
void PackValue(VMValue * dst, T ** src, VMClassRegistry * registry)
{
typedef remove_pointer <T>::type BaseType;
PackHandle(dst, *src, BaseType::kTypeID, registry);
}
template <> void UnpackValue <float>(float * dst, VMValue * src);
template <> void UnpackValue <UInt32>(UInt32 * dst, VMValue * src);
template <> void UnpackValue <SInt32>(SInt32 * dst, VMValue * src);
template <> void UnpackValue <bool>(bool * dst, VMValue * src);
template <> void UnpackValue <BSFixedString>(BSFixedString * dst, VMValue * src);
template <> void UnpackValue <VMArray<float>>(VMArray<float> * dst, VMValue * src);
template <> void UnpackValue <VMArray<UInt32>>(VMArray<UInt32> * dst, VMValue * src);
template <> void UnpackValue <VMArray<SInt32>>(VMArray<SInt32> * dst, VMValue * src);
template <> void UnpackValue <VMArray<bool>>(VMArray<bool> * dst, VMValue * src);
template <> void UnpackValue <VMArray<BSFixedString>>(VMArray<BSFixedString> * dst, VMValue * src);
void * UnpackHandle(VMValue * src, UInt32 typeID);
template <typename T>
void UnpackValue(T ** dst, VMValue * src)
{
*dst = (T *)UnpackHandle(src, T::kTypeID);
}
template <typename T>
void UnpackArray(VMArray<T> * dst, VMValue * src, const UInt32 type)
{
VMValue::ArrayData * arrData;
if (src->type != type || (arrData = src->data.arr, !arrData))
{
dst->arr = NULL;
return;
}
dst->arr = arrData;
}
UInt32 GetTypeIDFromFormTypeID(UInt32 formTypeID, VMClassRegistry * registry);
template <> UInt32 GetTypeID <void>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <UInt32>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <SInt32>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <int>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <float>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <bool>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <BSFixedString>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<UInt32>>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<SInt32>>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<int>>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<float>>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<bool>>(VMClassRegistry * registry);
template <> UInt32 GetTypeID <VMArray<BSFixedString>>(VMClassRegistry * registry);
template<typename T>
struct IsArrayType
{
enum { value = 0 };
typedef T TypedArg;
};
template<typename T>
struct IsArrayType<VMArray<T*>>
{
enum { value = 1 };
typedef T TypedArg;
};
template <typename T>
UInt32 GetTypeID <T *>(VMClassRegistry * registry)
{
UInt32 result;
typedef remove_pointer <IsArrayType<T>::TypedArg>::type BaseType;
if(!IsArrayType<T>::value) {
result = GetTypeIDFromFormTypeID(BaseType::kTypeID, registry);
} else { // Arrays are ClassInfo ptr + 1
result = GetTypeIDFromFormTypeID(BaseType::kTypeID, registry) | VMValue::kType_Identifier;
}
return result;
}
template <class T>
struct IsStaticType
{
enum { value = 0 };
};
template <>
struct IsStaticType <StaticFunctionTag>
{
enum { value = 1 };
};
#ifdef _NATIVEDUMP
template <typename T>
const char * GetArgumentTypeName(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <void>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <UInt32>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <SInt32>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <int>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <float>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <bool>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <BSFixedString>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<UInt32>>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<SInt32>>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<int>>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<float>>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<bool>>(VMClassRegistry * registry);
template <> const char * GetArgumentTypeName <VMArray<BSFixedString>>(VMClassRegistry * registry);
const char * GetTypeNameFromFormTypeID(UInt32 formTypeID, VMClassRegistry * registry);
template <typename T>
const char * GetArgumentTypeName <T *>(VMClassRegistry * registry)
{
typedef remove_pointer <T>::type BaseType;
return GetTypeNameFromFormTypeID(BaseType::kTypeID, registry);
}
#endif
|
/*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
* Licensed under commercial Jaspersoft Subscription License Agreement
*/
/**
* @version: $Id: designer.contextmenu.js 6613 2014-07-18 09:12:59Z kklein $
*/
/*
* used to show dynamic menu based on context
* @param event
* @param updateContextActionModel optional method which
* will be called to have ability to change context action model
*/
define(function(require) {
var adhocDesigner = require("adhoc/designer"),
designerLabelActions = require("adhoc/designer.label.actions"),
designerFieldActions = require("adhoc/designer.field.actions"),
designerTreeActions = require("adhoc/designer.tree.actions"),
designerReportActions = require("adhoc/designer.report.actions"),
designerAjax = require("adhoc/designer.ajax"),
designerHelpers= require("adhoc/designer.helpers"),
designerInit = require("adhoc/designer.init"),
designerObservers = require("adhoc/designer.observers"),
designerSelection = require("adhoc/designer.selection"),
designwerObsolete = require("adhoc/designer.obsolete");
adhocDesigner.showDynamicMenu = function(event, contextLevel, coordinates, updateContextActionModel){
//in case we are dealing with multi-select get last item
var position = selObjects.length;
if (position > 0) {
var selected = selObjects[position - 1];
if(selected && selected.menuLevel) selected.menuLevel = contextLevel;
}
actionModel.showDynamicMenu(contextLevel, event, null, coordinates, localContext.state.actionmodel, updateContextActionModel);
};
adhocDesigner.contextMenuHandler = function(event) {
var matched = null;
var node = event.memo.node;
var evt = event.memo.targetEvent;
localContext.contextMenuHandler && localContext.contextMenuHandler(evt);
};
return adhocDesigner;
});
|
import re
# put your regex in the variable template
template = r"Scaramouch."
string = input()
match = re.match(template, string)
if match:
print("Match")
else:
print("No match")
|
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from source.infrastructure.settings import application_settings
from source.infrastructure.sqlalchemy import metadata
from source.infrastructure import tables
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option('sqlalchemy.url', str(application_settings.postgres_url))
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
IGNORE_TABLES = ['profiles', 'profiles_migrations']
def include_object(object, name, type_, reflected, compare_to):
"""
Should you include this table or not?
"""
if type_ == 'table' and (name in IGNORE_TABLES or object.info.get("skip_autogenerate", False)):
return False
elif type_ == "column" and object.info.get("skip_autogenerate", False):
return False
return True
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
version_table='users_migrations',
include_object=include_object
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata,
version_table='users_migrations',
include_object=include_object
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
import classnames from 'classnames';
import React, {Component} from 'react';
import {Link, withRouter} from 'react-router-dom';
import DataList from 'react/components/data_list';
import {SortDir, ColumnMeta, ListType} from '../types';
export default class SharedDesignList extends Component {
constructor(props, context) {
super(props, context);
this.onSort = this.onSort.bind(this);
this.onNext = this.onNext.bind(this);
this.onBack = this.onBack.bind(this);
this.onJumpTo = this.onJumpTo.bind(this);
this.onSearch = this.onSearch.bind(this);
this.onRefresh = this.onRefresh.bind(this);
this.onFilter = this.onFilter.bind(this);
this.onClearFilter = this.onClearFilter.bind(this);
this.onChangeItemNum = this.onChangeItemNum.bind(this);
this.onImport = this.onImport.bind(this);
this.renderHeader = this.renderHeader.bind(this);
this.renderItems = this.renderItems.bind(this);
}
onSort(e, idx) {
e.preventDefault();
const {handleSort} = this.props;
handleSort(idx);
}
onRefresh(e) {
e.preventDefault();
const {list} = this.props;
const {handleRefresh} = this.props;
handleRefresh(list.currListType);
}
onNext(e) {
e.preventDefault();
const {handleNext} = this.props;
handleNext();
}
onBack(e) {
e.preventDefault();
const {handleBack} = this.props;
handleBack();
}
onJumpTo(e, page) {
e.preventDefault();
const {handleJumpTo} = this.props;
handleJumpTo(page);
}
onSearch(keywords) {
const {handleSearch} = this.props;
handleSearch(keywords);
}
onFilter(e, key) {
e.preventDefault();
const {handleFilter} = this.props;
handleFilter(key, e.target.value);
}
onClearFilter(e) {
e.preventDefault();
const {handleClearFilter} = this.props;
handleClearFilter();
}
onChangeItemNum(itemNum) {
const {handleChangeItemNum} = this.props;
handleChangeItemNum(itemNum);
}
onImport(e, id) {
e.preventDefault();
const {handleImport} = this.props;
handleImport(id);
}
renderHeader() {
const {currListType, sortCol, sortDir} = this.props.list;
const {onSort} = this.props;
let headerMeta = [
{name: 'Name', className: 'col-name'},
{name: 'Tags', className: 'col-tags'},
{name: currListType == ListType.PUBLIC ? 'Contributed By' : 'Shared By', className: 'col-shared-by'},
{name: '', className: 'col-control'},
];
let headers = headerMeta.map((m, i) => {
let props;
if(ColumnMeta[currListType][i].sortable) {
props = {
key: i,
className: classnames({
[m.className]: true,
'sort': sortCol != i,
'sort-asc': sortCol == i && sortDir == SortDir.ASC,
'sort-desc': sortCol == i && sortDir == SortDir.DESC,
}),
onClick: e => this.onSort(e, i),
}
} else {
props = {
key: i,
className: classnames({
[m.className]: true,
}),
};
}
return <th {...props}>{m.name}</th>;
});
return <thead><tr>{headers}</tr></thead>;
}
renderItems() {
const {itemNum} = this.props.list;
let pagedData = JSON.parse(JSON.stringify(this.props.list.pagedData));
let isEmpty = pagedData.length == 0;
if(itemNum > pagedData.length) {
[...Array(itemNum - pagedData.length)].forEach((_, i) => {
pagedData.push({
id: 'dummy'+i,
fullname: ' ',
tags: [],
owner: ' ',
permission: null,
});
});
}
return (
<tbody>{
isEmpty ?
<tr className="empty"><td colSpan="6">No pattern found</td></tr> :
pagedData.map(i => {
let isDummy = i.id.toString().startsWith('dummy');
let trCls = classnames({
'dummy': isDummy,
});
let permission = i.permission;
let Name = withRouter(({history}) => (
<span>
<a href={(permission && permission.edit) ? `#/pattern/edit/${i.id}` : `#/pattern/preview/${i.id}`} title={i.fullname}>
{i.fullname}
</a>
</span>
));
let Control = withRouter(({history}) => (
<div className="btn-toolbar pull-right">
<button type="button" className="btn btn-default btn-xs" title="Preview" onClick={() => {history.push(`/pattern/preview/${i.id}`)}}>
<i className="fa fa-eye"></i>
</button>
{
permission && permission.import ?
<button type="button" className="btn btn-default btn-xs" title="Save to My Patterns" onClick={e => this.onImport(e, i.id)}>
<i className="fa fa-save"></i>
</button> :
null
}
{
permission && permission.edit ?
<button type="button" className="btn btn-default btn-xs" title="Edit" onClick={() => {history.push(`/pattern/edit/${i.id}`)}}>
<i className="fa fa-pencil"></i>
</button> :
null
}
</div>
));
return (
<tr key={i.id} className={trCls}>
<td className="text col-name">{!isDummy ? <Name/> : <span>{i.fullname}</span>}</td>
<td className="text col-tags">{i.tags.map((t, j) => <span key={`${i}-${j}`} className="label label-primary">{t}</span>)}</td>
<td className="text col-shared-by">{i.owner}</td>
<td className="col-control">
{!isDummy ?
<div className="dropdown pull-right">
<button className="btn btn-default btn-xs dropdown-toggle" type="button" title="Menu" id="extraDropDown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
<i className="fa fa-ellipsis-v"></i>
</button>
<ul className="dropdown-menu dropdown-menu-right" aria-labelledby="extraDropDown">
<li><Link to={`/pattern/preview/${i.id}`}><i className="fa fa-eye"></i> Preview</Link></li>
{
permission && permission.import ?
<li><a href="#" onClick={e => this.onImport(e, i.id)}><i className="fa fa-save"></i> Save to My Patterns</a></li> :
null
}
{
permission && permission.edit ?
<li><Link to={`/pattern/edit/${i.id}`}><i className="fa fa-pencil"></i> Edit</Link></li> :
null
}
</ul>
</div> :
null}
{!isDummy ? <Control/> : null}
</td>
</tr>
);
})
}</tbody>
);
}
render() {
const {filterOpts, filterKey, filterVal, searchVal, total, itemNum, page} = this.props.list;
const props = {
tableClassName: {'table-sm': true},
header: this.renderHeader(),
filterOpts,
filterKey,
filterVal,
searchVal,
itemNum,
total,
page,
onNext: this.onNext,
onBack: this.onBack,
onJumpTo: this.onJumpTo,
onSearch: this.onSearch,
onRefresh: this.onRefresh,
onFilter: this.onFilter,
onClearFilter: this.onClearFilter,
onChangeItemNum: this.onChangeItemNum,
}
return (
<div>
<DataList {...props}>
{this.renderItems()}
</DataList>
</div>
);
}
}
|
import * as React from 'react';
import IconButton from '@material-ui/core/IconButton';
import Badge from '@material-ui/core/Badge';
import MailIcon from '@material-ui/icons/Mail';
function notificationsLabel(count) {
if (count === 0) {
return 'no notifications';
}
if (count > 99) {
return 'more than 99 notifications';
}
return `${count} notifications`;
}
export default function AccessibleBadges() {
return (
<IconButton aria-label={notificationsLabel(100)}>
<Badge badgeContent={100} color="secondary">
<MailIcon />
</Badge>
</IconButton>
);
}
|
# -*- coding: utf-8 -*-
'''
Created on 29.11.2012
@author: 802300
'''
import datetime
from colors import *
from vis_calendar import *
class FDDEinzugNeu(BaiscCalendarModel):
tight = False
def beginn_vorlauf(self,due,vorlauf,bank,target):
einreichung_target = target.relative_workday(due,offset=-vorlauf)
return einreichung_target
def flag_custom(self):
for month in range(1,13):
self.flag_month(month)
def flag_month(self,month):
bank,target,hessen = self.calendars
flag = self._flag
print '%04d-%02d' % (self.year,month)
h16 = hessen.workday16(self.year, month)
flag(h16,'cycle_fdd')
if h16.month != month:
raise AssertionError
cycle_tb = bank.next_workday(h16)
if self.tight:
submission = cycle_tb
flag(h16,'cycle_tb')
flag(cycle_tb,'cycle_tb_con')
else:
submission = bank.next_workday(cycle_tb)
flag(cycle_tb,'cycle_tb')
flag(submission,'submission')
start_vorlauf = target.next_workday(submission)
dy,dm = inc_month(self.year,month)
due = target.next_workday2(datetime.date(dy,dm,1))
flag(due,'due')
flag(due,'due_main')
for d in (1,2,5):
vorlauf = self.beginn_vorlauf(due, d, bank, target)
if vorlauf < start_vorlauf:
vorlauf = start_vorlauf
actual_due = target.earliest_due_date(start_vorlauf,d)
print u'Fälligkeit kann mit D-%d nicht eingehalten werden' % d
print u' %s statt %s' % (actual_due,due)
flag(actual_due,'due_later')
else:
actual_due = due
flag(actual_due,'d%d' % d)
flag(actual_due,'due')
flag(vorlauf,'vorlauf')
flag(vorlauf,'v%d' % d)
#c_cycle = (75,172,198)
#c_cycle_light = (139,202,218)
#c_due = (192,0,0)
#c_due_later = (255,86,30)
#c_sub = (255,192,0)
cflags = {'cycle_fdd':FlagViz(c_cycle_alt, tc_white),
'cycle_tb':FlagViz(c_cycle, tc_white, prio=1),
'cycle_tb_con':FlagViz(c_cycle, tc_white, prio=2),
'submission_pre':FlagViz(c_cycle_dark, tc_white,prio=3),
'submission':FlagViz(c_cycle_dark, tc_white,prio=4),
'vorlauf':FlagViz(c_sub_alt, tc_black,prio=5),
'due_main':FlagViz(c_due, tc_white),
'due_later':FlagViz(c_due_later, tc_white),
}
class FDDVisualizer(Visualizer):
def custom_decoration(self, day, rect, viz):
print day
drop = self.vc.drop
def draw_dots(dproperty,dviz=None,targets=None):
if dviz is None:
dviz = viz
#dproperty = 's'
if targets is None:
targets = ['origin','base_center','base_right']
dots = ['5','2','1']
for dot_text in dots:
if not getattr(day,dproperty+dot_text):
continue
dot = drop('dot')
dot.text = dot_text
dot.color = dviz.txt_color
dot.txt_color = dviz.color
dot.attach_to('anchor', rect, targets.pop())
if day.due:
draw_dots('d')
if day.vorlauf:
draw_dots('v',self.color_flags['vorlauf'])
if (not day.workday) and day.target_workday:
corner = drop('corner')
corner.attach_to('anchor', rect, 'corner')
corner.color = tc_black
def main():
#import vis_calendar
#vis_calendar.VISIO_VISIBLE = True
render_cal(FDDVisualizer, FDDEinzugNeu,
#2013, 2015, m0=12, m1=1,
start='01.12.2013',end='31.07.2014',
color_flags=cflags, style='wrapped',
style_params=dict(alignment='independent'))
if __name__ == '__main__':
main()
|
import os
import sys
import json
import argparse
from collections import abc
import time
from collections import defaultdict
from easydict import EasyDict
from tqdm import tqdm
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, PretrainedConfig
from utils.logger import LOGGER, TB_LOGGER, RunningMeter, add_log_to_file
from utils.save import ModelSaver, save_training_meta
from utils.parser import load_parser, parse_with_config
from utils.misc import NoOp, set_dropout, set_random_seed, set_cuda, wrap_model
from optim import get_lr_sched
from optim.misc import build_optimizer
from data.image_data import MultiStepNavImageData
from data.image_tasks import (
MlmImageDataset,
mlm_image_collate,
SapImageDataset,
sap_image_collate,
SarImageDataset,
sar_image_collate,
SprelImageDataset,
sprel_image_collate,
MrcImageDataset,
mrc_image_collate,
ItmImageDataset,
itm_image_collate,
)
from data.image_loader import MetaLoader, PrefetchLoader, build_dataloader
from model.image_pretrain import MultiStepNavImagePreTraining
def create_dataloaders(data_cfg, nav_db, tok, is_train, device, opts):
dataloaders = {}
for k, task_name in enumerate(data_cfg.tasks):
if task_name == "mlm":
task_dataset = MlmImageDataset(nav_db, tok)
task_collate_fn = mlm_image_collate
elif task_name == "sap":
task_dataset = SapImageDataset(
nav_db,
tok,
opts.ob_random_kill_v if is_train else 0,
opts.ob_random_kill_a if is_train else 0,
)
task_collate_fn = sap_image_collate
elif task_name == "sar":
task_dataset = SarImageDataset(
nav_db,
tok,
opts.ob_random_kill_v if is_train else 0,
opts.ob_random_kill_a if is_train else 0,
)
task_collate_fn = sar_image_collate
elif task_name == "sprel":
task_dataset = SprelImageDataset(
nav_db,
tok,
opts.ob_random_kill_v if is_train else 0,
opts.ob_random_kill_a if is_train else 0,
)
task_collate_fn = sprel_image_collate
elif task_name == "mrc":
task_dataset = MrcImageDataset(nav_db, tok, opts.mrc_mask_prob)
task_collate_fn = mrc_image_collate
elif task_name == "itm":
task_dataset = ItmImageDataset(nav_db, tok)
task_collate_fn = itm_image_collate
else:
raise ValueError(f"Undefined task {task_name}")
LOGGER.info(f"{task_name}: {len(task_dataset)} samples loaded")
task_loader, pre_epoch = build_dataloader(
task_name, task_dataset, task_collate_fn, is_train, opts
)
if is_train:
ratio = data_cfg.mix_ratio[k]
dataloaders[task_name] = (task_loader, ratio, pre_epoch)
else:
dataloaders[task_name] = PrefetchLoader(task_loader, device)
return dataloaders
def main(opts):
default_gpu, n_gpu, device = set_cuda(opts)
LOGGER.info(f"16-bits training: {opts.fp16}")
seed = opts.seed
if opts.local_rank != -1 != -1:
seed += opts.local_rank != -1
set_random_seed(seed)
if default_gpu:
save_training_meta(opts)
TB_LOGGER.create(os.path.join(opts.output_dir, "logs"))
pbar = tqdm(total=opts.num_train_steps)
model_saver = ModelSaver(os.path.join(opts.output_dir, "ckpts"))
add_log_to_file(os.path.join(opts.output_dir, "logs", "log.txt"))
else:
LOGGER.disabled = True
pbar = NoOp()
model_saver = NoOp()
# Model config
model_config = PretrainedConfig.from_json_file(opts.model_config)
model_config.pretrain_tasks = []
for train_dataset_config in opts.train_datasets.values():
model_config.pretrain_tasks.extend(train_dataset_config["tasks"])
model_config.pretrain_tasks = set(model_config.pretrain_tasks)
# Prepare model
checkpoint = {}
if opts.checkpoint:
if not isinstance(opts.checkpoint, abc.Sequence):
opts.checkpoint = [checkpoint]
for ckpt in opts.checkpoint:
checkpoint.update(torch.load(ckpt))
model = MultiStepNavImagePreTraining.from_pretrained(
pretrained_model_name_or_path=None, config=model_config, state_dict=checkpoint
)
model.train()
set_dropout(model, opts.dropout)
model = wrap_model(model, device, opts.local_rank)
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
# load r2r training set
r2r_cfg = EasyDict(opts.train_datasets["R2R"])
img_db_file = r2r_cfg.img_db_file
train_nav_db = MultiStepNavImageData(
r2r_cfg.train_traj_files,
img_db_file,
r2r_cfg.img_ft_file,
r2r_cfg.scanvp_cands_file,
r2r_cfg.connectivity_dir,
image_prob_size=model_config.image_prob_size,
image_feat_size=model_config.image_feat_size,
angle_feat_size=model_config.angle_feat_size,
max_txt_len=opts.max_txt_len,
in_memory=True,
is_training=True,
)
val_nav_db = MultiStepNavImageData(
r2r_cfg.val_seen_traj_files,
img_db_file,
r2r_cfg.img_ft_file,
r2r_cfg.scanvp_cands_file,
r2r_cfg.connectivity_dir,
image_prob_size=model_config.image_prob_size,
image_feat_size=model_config.image_feat_size,
angle_feat_size=model_config.angle_feat_size,
max_txt_len=opts.max_txt_len,
in_memory=True,
is_training=False,
)
val2_nav_db = MultiStepNavImageData(
r2r_cfg.val_unseen_traj_files,
img_db_file,
r2r_cfg.img_ft_file,
r2r_cfg.scanvp_cands_file,
r2r_cfg.connectivity_dir,
image_prob_size=model_config.image_prob_size,
image_feat_size=model_config.image_feat_size,
angle_feat_size=model_config.angle_feat_size,
max_txt_len=opts.max_txt_len,
in_memory=True,
is_training=False,
)
# Build data loaders
train_dataloaders = create_dataloaders(
r2r_cfg, train_nav_db, tokenizer, True, device, opts
)
val_dataloaders = create_dataloaders(
r2r_cfg, val_nav_db, tokenizer, False, device, opts
)
val2_dataloaders = create_dataloaders(
r2r_cfg, val2_nav_db, tokenizer, False, device, opts
)
meta_loader = MetaLoader(
train_dataloaders,
accum_steps=opts.gradient_accumulation_steps,
distributed=opts.local_rank != -1,
device=device,
)
meta_loader = PrefetchLoader(meta_loader, device)
# Prepare optimizer
optimizer = build_optimizer(model, opts)
task2scaler = {t: i for i, t in enumerate(train_dataloaders.keys())}
if opts.fp16:
model, optimizer = amp.initialize(
model,
optimizer,
num_losses=len(task2scaler),
enabled=opts.fp16,
opt_level="O2",
)
global_step = 0
LOGGER.info(f"***** Running training with {n_gpu} GPUs *****")
LOGGER.info(" Batch size = %d", opts.train_batch_size)
LOGGER.info(" Accumulate steps = %d", opts.gradient_accumulation_steps)
LOGGER.info(" Num steps = %d", opts.num_train_steps)
# to compute training statistics
task2loss = {
task: RunningMeter(f"loss/{task}") for task in train_dataloaders.keys()
}
n_examples = defaultdict(int)
n_in_units = defaultdict(int)
n_loss_units = defaultdict(int)
grad_norm = 0
start_time = time.time()
# quick hack for amp delay_unscale bug
optimizer.zero_grad()
optimizer.step()
for step, (name, batch) in enumerate(meta_loader):
# forward pass
batch_size = batch["txt_ids"].size(0)
n_examples[name] += batch_size
n_in_units[name] += (batch["txt_masks"] == 1).sum().item()
task = name.split("_")[0]
# print(name, task)
# for k, v in batch.items():
# print(k, v.size(), v[0])
# continue
# FIXME there is a weird bug happening "sometimes"
if name == "itm" and batch_size < 2:
if default_gpu:
print(step)
for k, v in batch.items():
print(k, v.size(), v[0])
continue
# END
loss = model(batch, task=task, compute_loss=True)
n_loss_units[name] += loss.size(0)
loss = loss.mean() # loss is not normalized in model
# backward pass
if opts.gradient_accumulation_steps > 1: # average loss
loss = loss / opts.gradient_accumulation_steps
delay_unscale = (step + 1) % opts.gradient_accumulation_steps != 0
if opts.fp16:
with amp.scale_loss(
loss, optimizer, delay_unscale=delay_unscale, loss_id=task2scaler[name]
) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
if not delay_unscale:
# gather gradients from every processes
# do this before unscaling to make sure every process uses
# the same gradient scale
grads = [
p.grad.data
for p in model.parameters()
if p.requires_grad and p.grad is not None
]
# all_reduce_and_rescale_tensors(grads, float(1))
task2loss[name](loss.item())
# optimizer update and logging
if (step + 1) % opts.gradient_accumulation_steps == 0:
global_step += 1
# learning rate scheduling
lr_this_step = get_lr_sched(global_step, opts)
for param_group in optimizer.param_groups:
param_group["lr"] = lr_this_step
TB_LOGGER.add_scalar("lr", lr_this_step, global_step)
# log loss
# NOTE: not gathered across GPUs for efficiency
TB_LOGGER.log_scalar_dict(
{ll.name: ll.val for ll in task2loss.values() if ll.val is not None}
)
TB_LOGGER.step()
# update model params
if opts.grad_norm != -1:
if opts.fp16:
grad_norm = torch.nn.utils.clip_grad_norm_(
amp.master_params(optimizer), opts.grad_norm
)
else:
grad_norm = torch.nn.utils.clip_grad_norm_(
model.parameters(), opts.grad_norm
)
TB_LOGGER.add_scalar("grad_norm", grad_norm, global_step)
optimizer.step()
optimizer.zero_grad()
pbar.update(1)
if global_step % opts.log_steps == 0:
# monitor training throughput
LOGGER.info(f"==============Step {global_step}===============")
for t in train_dataloaders.keys():
# assert all(tt == t for tt in all_gather_list(t))
# tot_ex = sum(all_gather_list(n_examples[t]))
# ex_per_sec = int(tot_ex / (time()-start))
# tot_in = sum(all_gather_list(n_in_units[t]))
# in_per_sec = int(tot_in / (time()-start))
# tot_l = sum(all_gather_list(n_loss_units[t]))
# l_per_sec = int(tot_l / (time()-start))
tot_ex = n_examples[t]
ex_per_sec = int(tot_ex / (time.time() - start_time))
tot_in = n_in_units[t]
in_per_sec = int(tot_in / (time.time() - start_time))
tot_l = n_loss_units[t]
l_per_sec = int(tot_l / (time.time() - start_time))
LOGGER.info(
f"{t}: {tot_ex} examples trained at " f"{ex_per_sec} ex/s"
)
TB_LOGGER.add_scalar(f"perf/{t}_ex_per_s", ex_per_sec, global_step)
TB_LOGGER.add_scalar(f"perf/{t}_in_per_s", in_per_sec, global_step)
TB_LOGGER.add_scalar(f"perf/{t}_loss_per_s", l_per_sec, global_step)
LOGGER.info("===============================================")
if global_step % opts.valid_steps == 0:
LOGGER.info(f"------Step {global_step}: start validation seen------")
validate(model, val_dataloaders, setname="_seen")
LOGGER.info(f"------Step {global_step}: start validation unseen------")
validate(model, val2_dataloaders, setname="_unseen")
model_saver.save(model, global_step)
if global_step >= opts.num_train_steps:
break
if global_step % opts.valid_steps != 0:
LOGGER.info(f"------Step {global_step}: start validation seen------")
validate(model, val_dataloaders, setname="_seen")
LOGGER.info(f"------Step {global_step}: start validation unseen------")
validate(model, val2_dataloaders, setname="_unseen")
model_saver.save(model, global_step)
def validate(model, val_dataloaders, setname=""):
model.eval()
for task, loader in val_dataloaders.items():
LOGGER.info(f"validate val{setname} on {task} task")
if task.startswith("mlm"):
val_log = validate_mlm(model, loader)
elif task.startswith("sap"):
val_log = validate_sap(model, loader)
elif task.startswith("sar"):
val_log = validate_sar(model, loader)
elif task.startswith("sprel"):
val_log = validate_sprel(model, loader)
elif task.startswith("mrc"):
val_log = validate_mrc(model, loader)
elif task.startswith("itm"):
# val_log = validate_itm(model, loader)
continue
else:
raise ValueError(f"Undefined task {task}")
val_log = {f"val{setname}_{task}_{k}": v for k, v in val_log.items()}
TB_LOGGER.log_scalar_dict(
{f"valid{setname}_{task}/{k}": v for k, v in val_log.items()}
)
model.train()
@torch.no_grad()
def validate_mlm(model, val_loader):
LOGGER.info("start running MLM validation...")
val_loss = 0
n_correct = 0
n_word = 0
st = time.time()
for i, batch in enumerate(val_loader):
scores = model(batch, task="mlm", compute_loss=False)
labels = batch["txt_labels"]
labels = labels[labels != -1]
loss = F.cross_entropy(scores, labels, reduction="sum")
val_loss += loss.item()
n_correct += (scores.max(dim=-1)[1] == labels).sum().item()
n_word += labels.numel()
# val_loss = sum(all_gather_list(val_loss))
# n_correct = sum(all_gather_list(n_correct))
# n_word = sum(all_gather_list(n_word))
tot_time = time.time() - st
val_loss /= n_word
acc = n_correct / n_word
val_log = {"loss": val_loss, "acc": acc, "tok_per_s": n_word / tot_time}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, " f"acc: {acc*100:.2f}"
)
return val_log
@torch.no_grad()
def validate_sap(model, val_loader):
LOGGER.info("start running SAP validation...")
val_loss = 0
n_correct = 0
n_word = 0
st = time.time()
for i, batch in enumerate(val_loader):
scores = model(batch, task="sap", compute_loss=False)
labels = batch["ob_action_viewindex"]
loss = F.cross_entropy(scores, labels, reduction="sum")
val_loss += loss.item()
n_correct += (scores.max(dim=-1)[1] == labels).sum().item()
n_word += labels.numel()
# val_loss = sum(all_gather_list(val_loss))
# n_correct = sum(all_gather_list(n_correct))
# n_word = sum(all_gather_list(n_word))
tot_time = time.time() - st
val_loss /= n_word
acc = n_correct / n_word
val_log = {"loss": val_loss, "acc": acc, "tok_per_s": n_word / tot_time}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, " f"acc: {acc*100:.2f}"
)
return val_log
@torch.no_grad()
def validate_sar(model, val_loader):
LOGGER.info("start running SAR validation...")
val_heading_loss, val_elevation_loss, val_progress_loss = 0, 0, 0
n_data = 0
st = time.time()
for i, batch in enumerate(val_loader):
scores = model(batch, task="sar", compute_loss=False)
val_heading_loss += F.mse_loss(
scores[:, 0], batch["ob_action_angles"][:, 0], reduction="sum"
).item()
val_elevation_loss += F.mse_loss(
scores[:, 1], batch["ob_action_angles"][:, 1], reduction="sum"
).item()
val_progress_loss += F.mse_loss(
scores[:, 2], batch["ob_progress"], reduction="sum"
).item()
n_data += scores.size(0)
# val_loss = sum(all_gather_list(val_loss))
# n_correct = sum(all_gather_list(n_correct))
# n_word = sum(all_gather_list(n_word))
tot_time = time.time() - st
val_heading_loss /= n_data
val_elevation_loss /= n_data
val_progress_loss /= n_data
val_log = {
"heading_loss": val_heading_loss,
"elevation_loss": val_elevation_loss,
"progress_loss": val_progress_loss,
"tok_per_s": n_data / tot_time,
}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, "
f"heading_loss: {val_heading_loss:.4f}, "
f"elevation_loss: {val_elevation_loss:.4f}, "
f"progress_loss: {val_progress_loss:.4f}"
)
return val_log
@torch.no_grad()
def validate_sprel(model, val_loader):
LOGGER.info("start running SPREL validation...")
val_heading_loss, val_elevation_loss = 0, 0
n_data = 0
st = time.time()
for i, batch in enumerate(val_loader):
scores = model(batch, task="sprel", compute_loss=False)
val_heading_loss += F.mse_loss(
scores[:, 0], batch["sp_targets"][:, 0], reduction="sum"
).item()
val_elevation_loss += F.mse_loss(
scores[:, 1], batch["sp_targets"][:, 1], reduction="sum"
).item()
n_data += scores.size(0)
# val_loss = sum(all_gather_list(val_loss))
# n_correct = sum(all_gather_list(n_correct))
# n_word = sum(all_gather_list(n_word))
tot_time = time.time() - st
val_heading_loss /= n_data
val_elevation_loss /= n_data
val_log = {
"heading_loss": val_heading_loss,
"elevation_loss": val_elevation_loss,
"tok_per_s": n_data / tot_time,
}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, "
f"heading_loss: {val_heading_loss:.4f}, "
f"elevation_loss: {val_elevation_loss:.4f}"
)
return val_log
def compute_accuracy_for_soft_targets(out, labels):
outputs = out.max(dim=-1)[1]
labels = labels.max(dim=-1)[1] # argmax
n_correct = (outputs == labels).sum().item()
return n_correct
@torch.no_grad()
def validate_mrc(model, val_loader):
LOGGER.info("start running MRC validation...")
val_loss = 0
n_feat = 0
st = time.time()
tot_score = 0
for i, batch in enumerate(val_loader):
prediction_soft_label, img_target_probs = model(
batch, task="mrc", compute_loss=False
)
prediction_soft_label = F.log_softmax(prediction_soft_label, dim=-1)
loss = F.kl_div(prediction_soft_label, img_target_probs, reduction="sum")
tot_score += compute_accuracy_for_soft_targets(
prediction_soft_label, img_target_probs
)
val_loss += loss.item()
n_feat += batch["hist_mrc_masks"].sum().item()
tot_time = time.time() - st
val_loss /= n_feat
val_acc = tot_score / n_feat
val_log = {"loss": val_loss, "acc": val_acc, "feat_per_s": n_feat / tot_time}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, " f"score: {val_acc*100:.2f}"
)
return val_log
@torch.no_grad()
def validate_itm(model, val_loader):
LOGGER.info("start running ITM validation...")
val_loss = 0
n_correct = 0
n_word = 0
st = time.time()
for i, batch in enumerate(val_loader):
scores, labels = model(batch, task="itm", compute_loss=False)
loss = F.cross_entropy(scores, labels, reduction="sum")
val_loss += loss.item()
n_correct += (scores.max(dim=-1)[1] == labels).sum().item()
n_word += labels.numel()
# val_loss = sum(all_gather_list(val_loss))
# n_correct = sum(all_gather_list(n_correct))
# n_word = sum(all_gather_list(n_word))
tot_time = time.time() - st
val_loss /= n_word
acc = n_correct / n_word
val_log = {"loss": val_loss, "acc": acc, "tok_per_s": n_word / tot_time}
LOGGER.info(
f"validation finished in {int(tot_time)} seconds, " f"acc: {acc*100:.2f}"
)
return val_log
def build_args():
parser = load_parser()
# We could add specific arguments here
opts = parse_with_config(parser)
if os.path.exists(opts.output_dir) and os.listdir(opts.output_dir):
LOGGER.warning(
"Output directory ({}) already exists and is not empty.".format(
opts.output_dir
)
)
return opts
if __name__ == "__main__":
opts = build_args()
main(opts)
|
import React from "react";
// reactstrap components
import {
Button,
Card,
CardHeader,
CardBody,
FormGroup,
Form,
Input,
InputGroupAddon,
InputGroupText,
InputGroup,
Row,
Col
} from "reactstrap";
class Login extends React.Component {
render() {
return (
<>
<Row style={{display: "flex", justifyContent: "center", marginTop: "3%"}}>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardHeader className="bg-transparent pb-5">
<div className="text-muted text-center mt-2 mb-3">
<small>Sign in with</small>
</div>
<div className="btn-wrapper text-center">
<Button
className="btn-neutral btn-icon"
color="default"
href="#pablo"
onClick={e => e.preventDefault()}
>
<span className="btn-inner--icon">
<img
alt="..."
src={require("../../assets/img/icons/common/github.svg")}
/>
</span>
<span className="btn-inner--text">Github</span>
</Button>
<Button
className="btn-neutral btn-icon"
color="default"
href="#pablo"
onClick={e => e.preventDefault()}
>
<span className="btn-inner--icon">
<img
alt="..."
src={require("../../assets/img/icons/common/google.svg")}
/>
</span>
<span className="btn-inner--text">Google</span>
</Button>
</div>
</CardHeader>
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Or sign in with credentials</small>
</div>
<Form role="form">
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83" />
</InputGroupText>
</InputGroupAddon>
<Input placeholder="Email" type="email" autoComplete="new-email"/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open" />
</InputGroupText>
</InputGroupAddon>
<Input placeholder="Password" type="password" autoComplete="new-password"/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="button" href="/admin">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={e => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={e => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</Row>
</>
);
}
}
export default Login;
|
from __future__ import unicode_literals
import mock
import transaction as db_transaction
from freezegun import freeze_time
from sqlalchemy.exc import IntegrityError
from billy.models import tables
from billy.tests.functional.helper import ViewTestCase
@freeze_time('2013-08-16')
class TestDBSession(ViewTestCase):
def setUp(self):
super(TestDBSession, self).setUp()
with db_transaction.manager:
self.company = self.company_model.create(
processor_key='MOCK_PROCESSOR_KEY',
)
self.api_key = str(self.company.api_key)
@mock.patch('billy.models.customer.CustomerModel.create')
def test_db_session_is_removed(self, create_method):
self.testapp.app.registry.settings['db_session_cleanup'] = True
def raise_sql_error(*args, **kwargs):
with db_transaction.manager:
# this will raise SQL error
customer = tables.Customer()
self.testapp.session.add(customer)
self.testapp.session.flush()
create_method.side_effect = raise_sql_error
with self.assertRaises(IntegrityError):
self.testapp.post(
'/v1/customers',
extra_environ=dict(REMOTE_USER=self.api_key),
)
# if the session is not closed and remove correctly after a request is
# processed, the previous SQL error will leave in session, and once
# we touch db session below again, it will failed and complain we
# didn't rollback to session
self.testapp.get(
'/v1/customers',
extra_environ=dict(REMOTE_USER=self.api_key),
)
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:50:16 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/AccessibilityBundles/AXSpeechImplementation.bundle/AXSpeechImplementation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@interface AXSpeechPublicInterface : NSObject
@end
|
import requests
import threading
import time
import traceback
import re
import queue
from cmg.event import Event
from study_tool.russian.types import Aspect
from study_tool.russian.types import Case
from study_tool.russian.types import Gender
from study_tool.russian.types import Person
from study_tool.russian.types import Plurality
from study_tool.russian.types import Tense
from study_tool.russian.types import Participle
from study_tool.russian.types import WordType
from study_tool.russian.word import AccentedText
from study_tool.russian.word import Word
from study_tool.russian.word import WordSourceEnum
from study_tool.russian.noun import Noun
from study_tool.russian.verb import Verb
from study_tool.russian.adjective import Adjective
from study_tool.config import Config
class Cooljugator404Exception(Exception):
pass
class Cooljugator:
# Characters in examples that are wrong
russian_char_fixes = {"€": "я",
"¬": "в"}
URL_BASE_VERB = "https://cooljugator.com/ru/"
URL_BASE_NOUN = "https://cooljugator.com/run/"
URL_BASE_ADJECTIVE = "https://cooljugator.com/rua/"
# WordType to class
__WORD_TYPE_TYPES = {
WordType.Verb: Verb,
WordType.Noun: Noun,
WordType.Adjective: Adjective,
}
def __init__(self):
self.__404_words = set()
self.__error_words = set()
self.__lock = threading.Lock()
self.BeautifulSoup = None
def setup_imports(self):
"""Import the required python modules."""
with self.__lock:
from bs4 import BeautifulSoup
self.BeautifulSoup = BeautifulSoup
def download_word_info(self, word_type: WordType, name) -> Word:
"""
Downloads info for a Word. Returns None on error.
"""
key = (word_type, AccentedText(name).text.lower())
with self.__lock:
if key in self.__404_words:
return None
if key in self.__error_words:
return None
result = None
if word_type in self.__WORD_TYPE_TYPES:
Config.logger.info("Downloading {} info for: {} "
.format(key[0].name, key[1]))
try:
if word_type == WordType.Adjective:
result = self.download_adjective_info(name)
elif word_type == WordType.Noun:
result = self.download_noun_info(name)
elif word_type == WordType.Verb:
result = self.download_verb_info(name)
else:
raise Exception(word_type)
except Cooljugator404Exception:
pass
except Exception:
Config.logger.error("Error downloading {} data for: {}"
.format(key[0].name, key[1]))
with self.__lock:
self.__error_words.add(key)
traceback.print_exc()
if result:
result.set_complete(True)
result.set_source(WordSourceEnum.Cooljugator)
with self.__lock:
if key in self.__error_words:
self.__error_words.remove(key)
return result
def download_noun_info(self, dictionary_form) -> Noun:
"""
Download noun conjugation info.
"""
dictionary_form = AccentedText(dictionary_form)
key = (WordType.Noun, dictionary_form.text.lower())
url = self.URL_BASE_NOUN + key[1]
soup = self.__request_html(url, key=key)
root = soup.body
noun = Noun()
noun.name = dictionary_form
# Get singular forms
noun.declension[(Plurality.Singular, Case.Nominative)] = self.__get_conjugation(root, ["nom_S_no_accent", "nom_no_accent"])
noun.declension[(Plurality.Singular, Case.Genetive)] = self.__get_conjugation(root, ["gen_S_no_accent", "gen_no_accent"])
noun.declension[(Plurality.Singular, Case.Dative)] = self.__get_conjugation(root, ["dat_S_no_accent", "dat_no_accent"])
noun.declension[(Plurality.Singular, Case.Instrumental)] = self.__get_conjugation(root, ["instr_S_no_accent", "instr_no_accent"])
noun.declension[(Plurality.Singular, Case.Prepositional)] = self.__get_conjugation(root, ["prep_S_no_accent", "prep_no_accent"])
try:
noun.declension[(Plurality.Singular, Case.Accusative)] = self.__get_conjugation(root, ["acc_S_no_accent", "acc_no_accent"])
except:
# Sometimes it doesn't list accusative for animate nouns, so assume genetive
noun.declension[(Plurality.Singular, Case.Accusative)] = AccentedText(
noun.declension[(Plurality.Singular, Case.Genetive)])
# Get plural forms if present
try:
noun.declension[(Plurality.Plural, Case.Nominative)] = self.__get_conjugation(root, "nom_P")
noun.declension[(Plurality.Plural, Case.Genetive)] = self.__get_conjugation(root, "gen_P")
noun.declension[(Plurality.Plural, Case.Dative)] = self.__get_conjugation(root, "dat_P")
noun.declension[(Plurality.Plural, Case.Instrumental)] = self.__get_conjugation(root, "instr_P")
noun.declension[(Plurality.Plural, Case.Prepositional)] = self.__get_conjugation(root, "prep_P")
try:
noun.declension[(Plurality.Plural, Case.Accusative)] = self.__get_conjugation(root, "acc_P")
except:
# Sometimes it doesn't list accusative for animate nouns, so assume genetive
noun.declension[(Plurality.Plural, Case.Accusative)] = AccentedText(
noun.declension[(Plurality.Plural, Case.Genetive)])
except:
pass
gender = noun.classify_gender()
if gender is not None:
noun.gender = gender
noun.indeclinable = False
else:
noun.gender = None
noun.indeclinable = True
return noun
def download_adjective_info(self, dictionary_form) -> Adjective:
"""
Download adjective conjugation info.
"""
dictionary_form = AccentedText(dictionary_form)
key = (WordType.Adjective, dictionary_form.text.lower())
url = self.URL_BASE_ADJECTIVE+ key[1]
soup = self.__request_html(url, key=key)
root = soup.body
adj = Adjective()
adj.name = dictionary_form
for gender, letter in ((Gender.Masculine, "M"),
(Gender.Femanine, "F"),
(Gender.Neuter, "N"),
(None, "P")):
adj.declension[(gender, Case.Nominative)] = self.__get_conjugation(root, "nom_" + letter)
adj.declension[(gender, Case.Accusative)] = self.__get_conjugation(root, "acc_anim_" + letter)
adj.declension[(gender, Case.Genetive)] = self.__get_conjugation(root, "gen_" + letter)
adj.declension[(gender, Case.Dative)] = self.__get_conjugation(root, "dat_" + letter)
adj.declension[(gender, Case.Instrumental)] = self.__get_conjugation(root, "instr_" + letter)
adj.declension[(gender, Case.Prepositional)] = self.__get_conjugation(root, "prep_" + letter)
try:
adj.short_form[gender] = self.__get_conjugation(root, "short_" + letter)
except:
adj.short_form[gender] = AccentedText("-")
return adj
def download_verb_info(self, infinitive) -> Verb:
"""
Download verb conjugation info.
"""
infinitive = AccentedText(infinitive)
key = (WordType.Verb, infinitive.text.lower())
url = self.URL_BASE_VERB + key[1]
soup = self.__request_html(url, key=key)
root = soup.body.find("div", attrs={"id": "conjugation-data"})
top = root.find_all("div")[2]
verb = Verb()
verb.infinitive = infinitive
verb.name = infinitive
# Get the verb aspect
non_past_tense = root.find("div", attrs={"class": "conjugation-cell conjugation-cell-four tense-title"}).text.lower()
if "future" in non_past_tense:
verb.aspect = Aspect.Perfective
tense = "future"
elif "present" in non_past_tense:
verb.aspect = Aspect.Imperfective
tense = "present"
else:
raise Execption(non_past_tense)
# Parse the translation from the title
title = root.find_all("h1")[0].text
regex = re.compile(r".*?\[.*?\]\s+\((?P<translation>.*?)\).*")
match = regex.search(title)
verb.translation = AccentedText(match.group("translation"))
# Parse the other meanings and aspect counterparts
info = top.find("div", attrs={"id": "usage-info"}).text
regex = re.compile(r"\s*(?P<info>.*?)\s*This verb.s .* counterparts?:\s*(?P<counterparts>.*)\.?\s*")
match = regex.search(info)
other_meanings = match.group("info")
verb.info = AccentedText(other_meanings)
counterparts = match.group("counterparts")
verb.counterparts = [AccentedText(c.strip()) for c in counterparts.split(",") if bool(c.strip())]
# Get conjugation info
for index, (plurality, person) in enumerate(
[(Plurality.Singular, Person.First),
(Plurality.Singular, Person.Second),
(Plurality.Singular, Person.Third),
(Plurality.Plural, Person.First),
(Plurality.Plural, Person.Second),
(Plurality.Plural, Person.Third)]):
verb.non_past[(plurality, person)] = self.__get_conjugation(
root, [tense + str(index + 1), tense[0] + str(index + 1)], required=True)
verb.past[(Plurality.Singular, Gender.Masculine)] = self.__get_conjugation(root, "past_singM", required=True)
verb.past[(Plurality.Singular, Gender.Femanine)] = self.__get_conjugation(root, "past_singF", required=True)
verb.past[(Plurality.Singular, Gender.Neuter)] = self.__get_conjugation(root, "past_singN", required=True)
verb.past[(Plurality.Plural, None)] = self.__get_conjugation(root, "past_plur", required=True)
verb.imperative[Plurality.Singular] = self.__get_conjugation(root, "imperative2")
verb.imperative[Plurality.Plural] = self.__get_conjugation(root, "imperative5")
for participle in Participle:
for tense in (Tense.Past, Tense.Present):
key = "{}_{}_participle".format(tense.name.lower(), participle.name.lower())
conjugation = self.__get_conjugation(root, key)
verb.set_participle(participle=participle, tense=tense, text=conjugation)
# Parse the examples
#verb.examples = []
#example_table = soup.body.find("table", attrs={"id":
#"example-sentences"})
#for row in example_table.find("tbody").find_all("tr"):
# columns = row.find_all("td")
# russian = columns[0].text
# english = columns[1].text
# for a, b in russian_char_fixes.items():
# russian = russian.replace(a, b)
# verb.examples.append((russian, english))
return verb
def serialize(self) -> dict:
"""Serialize cooljugator data."""
# Serialize list of words with download errors
with self.__lock:
word_404_data = {}
for word_type, name in sorted(self.__404_words):
if word_type.name not in word_404_data:
word_404_data[word_type.name] = []
word_404_data[word_type.name].append(name)
word_error_data = {}
for word_type, name in sorted(self.__error_words):
if word_type.name not in word_error_data:
word_error_data[word_type.name] = []
word_error_data[word_type.name].append(name)
data = {"error_words": word_error_data,
"404_words": word_404_data}
return data
def deserialize(self, data: dict):
"""Deserialize cooljugator data."""
with self.__lock:
self.__404_words = set()
self.__error_words = set()
if "404_words" in data:
for word_type_name, word_list in data["404_words"].items():
word_type = getattr(WordType, word_type_name)
for name in word_list:
key = (word_type, name)
self.__404_words.add(key)
if "error_words" in data:
for word_type_name, word_list in data["error_words"].items():
word_type = getattr(WordType, word_type_name)
for name in word_list:
key = (word_type, name)
self.__error_words.add(key)
def __get_conjugation(self, root, name, required=False):
"""
Returns the conjugation text with the given element ID in
the html document.
"""
if not isinstance(name, list):
name = [name]
name.append(name[0] + "_no_accent")
for n in name:
element = root.find("div", attrs={"id": n})
if element is not None:
break
if element is None:
raise Exception("Cannot find element from ids: " + repr(name))
if "data-stressed" in element.attrs:
return AccentedText(element["data-stressed"])
elif "data-default" in element.attrs:
return AccentedText(element["data-default"])
elif required:
raise Exception(element.attrs)
return AccentedText("")
def __request_html(self, url: str, key: tuple):
"""
Downloads an html page.
"""
self.setup_imports()
response = requests.get(url)
soup = self.BeautifulSoup(response.text, features="lxml")
# Check if this is a 404 error
for h1 in soup.body.find_all("h1"):
if "page not found" in h1.text.lower():
with self.__lock:
self.__404_words.add(key)
Config.logger.warning("404 Page not found: " + url)
raise Cooljugator404Exception("404 Page not found: " + url)
return soup
class CooljugatorThread:
def __init__(self, cooljugator: Cooljugator):
self.__cooljugator = cooljugator
self.__queue = queue.Queue()
self.__thread = threading.Thread(target=self.__run)
self.__running = True
self.__status = None
def start(self):
self.__thread.start()
def stop(self):
self.__running = False
self.__thread.join()
def get_status(self) -> tuple:
return self.__status
def download_word_info(self, word_type: WordType, name, callback) -> Word:
self.__queue.put((word_type, name, callback))
def __run(self):
self.__running = True
while self.__running:
try:
while self.__running:
word_type, name, callback = self.__queue.get_nowait()
self.__status = (word_type, name)
result = self.__cooljugator.download_word_info(
word_type=word_type, name=name)
self.__status = None
if callback:
event = Event(object)
event.connect(callback)
event.emit(result)
except queue.Empty:
pass
time.sleep(0.1)
|
from flask import Blueprint, request, render_template, redirect, flash, abort
from flask_login import login_manager, login_required, logout_user, LoginManager, login_user, current_user
from wtforms import Form, StringField, PasswordField, validators
from wtforms.validators import ValidationError
from .models import db, User
from werkzeug.security import check_password_hash, generate_password_hash
# initialize login manager
login_manager = LoginManager()
# initialize Blueprint
bp = Blueprint('auth', __name__)
# Custom validator to check unique username
def unique_username(form, field):
if User.query.filter_by(username=form.username.data).first():
raise ValidationError('This username has been reistered.')
# Custom validator to check unique email
def unique_email(form, field):
if User.query.filter_by(email=form.email.data).first():
raise ValidationError('This email address has been registered.')
class RegistrationForm(Form):
username = StringField('Username', [
validators.DataRequired(),
validators.Length(min=4, max=25),
unique_username
])
email = StringField('Email Address', [
validators.Length(min=6, max=35),
validators.Email(),
unique_email
])
password = PasswordField('Password', [
validators.Length(min=4, max=25),
validators.DataRequired(),
validators.EqualTo('confirmation', message='Passwords must match.')
])
confirmation = PasswordField('Repeat Password')
class LoginForm(Form):
username = StringField('Username', [
validators.DataRequired(),
validators.Length(min=4, max=25),
])
password = PasswordField('Password', [
validators.DataRequired(),
])
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
@bp.route('/join', methods=['GET', 'POST'])
def register():
# Redirect if a logged user try to accesss
if current_user.is_authenticated:
return redirect('/dashboard')
"""Register user"""
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
new_user = User(username=form.username.data, email=form.email.data,
hash=generate_password_hash(form.password.data))
# Add new user to the database
db.session.add(new_user)
db.session.commit()
login_user(new_user)
flash('Thanks for your registration.')
return redirect('/dashboard')
return render_template('register.html', form=form)
@bp.route('/login', methods=['GET', 'POST'])
def login():
# Redirect if a logged user try to accesss
if current_user.is_authenticated:
return redirect('/dashboard')
"""Login user"""
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
# Query database for username
logged_user = User.query.filter_by(
username=form.username.data).first()
if not logged_user:
flash("Username is not existed.")
return render_template('login.html', form=form)
# print(logged_user.username)
# Ensure username exists and password is correct
if not check_password_hash(logged_user.hash, form.password.data):
flash("Incorrect Password.")
return render_template('login.html', form=form)
# Remember which user has logged in
login_user(logged_user)
# flash("Logged in successfully.")
# next = request.args.get('next')
# # is_safe_url should check if the url is safe for redirects.
# # See http://flask.pocoo.org/snippets/62/ for an example.
# if not is_safe_url(next):
# return abort(400)
# Redirect user to home page
return redirect('/dashboard')
return render_template('login.html', form=form)
@bp.route('/logout')
@login_required
def logout():
logout_user()
return redirect('/login')
|
"""walletproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.authtoken')),
path('users/' , include('users.urls')),
path('wallet/' , include('wallet_app.urls')),
]
|
#Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
#Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
#
#THE BSD LICENSE
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions
#are met:
#
#1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
#IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from index import *
from io.dataset import load, save
try:
from io.hdf5_dataset import load_range
except:
pass
|
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tracker.urls')),
]
|
import BaseComponent from '../base/Base';
import NestedComponent from '../nested/NestedComponent';
import _ from 'lodash';
import { uniqueKey } from '../../utils/utils';
export default class DataMapComponent extends NestedComponent {
static schema(...extend) {
return BaseComponent.schema({
label: 'Data Map',
key: 'dataMap',
type: 'datamap',
clearOnHide: true,
addAnother: 'Add Another',
disableAddingRemovingRows: false,
keyBeforeValue: true,
valueComponent: {
type: 'textfield',
key: 'value',
label: 'Value',
defaultValue: 'Value',
input: true
},
input: true,
validate: {
maxLength: 0,
minLength: 0
}
}, ...extend);
}
static get builderInfo() {
return {
title: 'Data Map',
icon: 'fa fa-th-list',
group: 'data',
documentation: 'http://help.form.io/userguide/#datamap',
weight: 25,
schema: DataMapComponent.schema()
};
}
get schema() {
const schema = super.schema;
schema.valueComponent = this.components[this.components.length - 1].schema;
return _.omit(schema, 'components');
}
constructor(component, options, data) {
super(component, options, data);
this.type = 'datamap';
this.rows = {};
}
get defaultSchema() {
return DataMapComponent.schema();
}
get emptyValue() {
return {};
}
hasAddButton() {
const maxLength = _.get(this.component, 'validate.maxLength');
return !this.component.disableAddingRemovingRows &&
!this.shouldDisable &&
!this.options.builder &&
!this.options.preview &&
(!maxLength || (Object.keys(this.dataValue).length < maxLength));
}
hasRemoveButtons() {
return !this.component.disableAddingRemovingRows &&
!this.shouldDisable &&
!this.options.builder &&
(Object.keys(this.dataValue).length > _.get(this.component, 'validate.minLength', 0));
}
hasChanged(before, after) {
return !_.isEqual(before, after);
}
get componentComponents() {
return [this.component.valueComponent];
}
build(state) {
if (this.options.builder) {
return super.build(state, true);
}
this.createElement();
this.createLabel(this.element);
let tableClass = 'table datagrid-table table-bordered form-group formio-data-map ';
_.each(['striped', 'bordered', 'hover', 'condensed'], (prop) => {
if (this.component[prop]) {
tableClass += `table-${prop} `;
}
});
this.tableElement = this.ce('table', {
class: tableClass
});
this.buildRows(state);
this.element.appendChild(this.tableElement);
this.createDescription(this.element);
this.attachLogic();
}
addKeyButton() {
if (!this.hasAddButton()) {
return null;
}
const addButton = this.ce('button', {
class: 'btn btn-primary formio-button-add-row'
});
this.addEventListener(addButton, 'click', (event) => {
event.preventDefault();
this.addRow();
});
addButton.appendChild(this.ce('i', {
class: this.iconClass('plus')
}));
addButton.appendChild(this.text(' '));
addButton.appendChild(this.text(this.component.addAnother || 'Add Another'));
return addButton;
}
removeKeyButton(key) {
const removeButton = this.ce('button', {
type: 'button',
class: 'btn btn-default btn-secondary formio-button-remove-row'
});
this.addEventListener(removeButton, 'click', (event) => {
event.preventDefault();
this.removeRow(key);
});
removeButton.appendChild(this.ce('i', {
class: this.iconClass('remove-circle')
}));
return removeButton;
}
// Build the header.
createHeader() {
const valueHeader = this.ce('th', {
'class': 'col-9 col-sm-8'
}, this.text(this.component.valueComponent.label));
if (this.component.valueComponent.tooltip) {
this.createTooltip(valueHeader, {
tooltip: this.t(this.component.valueComponent.tooltip)
});
}
const keyHeader = this.ce('th', {
'class': 'col-2 col-sm-3'
}, this.text(this.component.keyLabel || 'Key'));
this.createTooltip(keyHeader, {
tooltip: this.t('Enter the map "key" for this value.')
});
return this.ce('thead', null, this.ce('tr', {
class: 'd-flex'
},
[
this.component.keyBeforeValue ? keyHeader : valueHeader,
this.component.keyBeforeValue ? valueHeader : keyHeader,
this.hasRemoveButtons() ? this.ce('th', { 'class': 'col-1 col-sm-1' }, null) : null,
]
));
}
buildRows(state) {
// Do not builder rows when in builder mode.
if (this.options.builder) {
return;
}
// Destroy all value components before they are recreated.
this.destroyComponents();
_.each(this.rows, row => row.value.destroy());
this.rows = {};
this.empty(this.tableElement);
const tableRows = [];
_.each(this.dataValue, (value, key) => tableRows.push(this.buildRow(value, key, state)));
this.tableElement.appendChild(this.createHeader());
this.tableElement.appendChild(this.ce('tbody', null, tableRows));
this.tableElement.appendChild(this.ce('tfoot', null,
this.ce('tr', null,
this.ce('td', { colspan: this.hasRemoveButtons() ? 3 : 2 },
this.addKeyButton()
)
)
));
}
createValueComponent(state) {
const container = this.ce('td', {
class: 'col-9 col-sm-8'
});
const schema = this.component.valueComponent;
schema.hideLabel = true;
const value = this.addComponent(schema, container, {}, null, null, state);
value.on('change', () => this.updateValue(), true);
return { value, container };
}
buildRow(value, key, state) {
if (!this.rows[key]) {
this.rows[key] = this.createValueComponent(state);
}
const row = this.rows[key];
let lastColumn = null;
if (this.hasRemoveButtons()) {
row.remove = this.removeKeyButton(key);
lastColumn = this.ce('td', { class: 'col-1 col-sm-1' }, row.remove);
}
row.element = this.ce('tr', {
class: 'd-flex',
id: `${this.component.id}-row-${key}`
});
// Create our key input.
row.keyInput = this.ce('input', {
type: 'text',
class: 'form-control',
id: `${this.component.id}-value-${key}`,
value: key
});
this.addInput(row.keyInput);
if (this.component.keyBeforeValue) {
row.element.appendChild(this.ce('td', { class: 'col-2 col-sm-3' }, row.keyInput));
row.element.appendChild(row.container);
}
else {
row.element.appendChild(row.container);
row.element.appendChild(this.ce('td', null, row.keyInput));
}
row.element.appendChild(lastColumn);
// Set the value on the value component.
row.value.setValue(value);
return row.element;
}
addRow() {
const component = this.createValueComponent();
const key = uniqueKey(this.dataValue, _.camelCase(component.value.defaultValue) || 'key');
this.rows[key] = component;
this.dataValue[key] = component.value.defaultValue;
this.buildRows();
this.triggerChange();
}
removeRow(key) {
const value = this.dataValue;
delete value[key];
this.dataValue = value;
this.buildRows();
this.triggerChange();
}
updateValue(flags, value) {
return BaseComponent.prototype.updateValue.call(this, flags, value);
}
setValue(value) {
const changed = this.hasChanged(value, this.dataValue);
this.dataValue = value;
if (changed) {
this.buildRows();
}
return changed;
}
/**
* Get the value of this component.
*
* @returns {*}
*/
getValue() {
const value = {};
_.each(this.rows, row => {
value[row.keyInput.value] = row.value.getValue();
});
return value;
}
}
|
from ..taskapp.celery import app
from .models import Session, Offer
from django.core import files
import io
import requests
from slugify import slugify
@app.task
def create_offer(bot, item_name, item_description, giver_id,
contact_info, location_name, lat, lng, photo_file_id=None):
offer = Offer.objects.create(
item_name=item_name,
item_description=item_description,
giver=Session.objects.filter(telegram_user_id=giver_id).first(),
contact_info=contact_info,
location_name=location_name,
lat=lat,
lng=lng,
status=Offer.RECEIVER_NOT_ASSIGNED,
)
if photo_file_id is not None:
url = bot.get_file(photo_file_id)['file_path']
extension = url[url.rfind('.'):]
image = io.BytesIO(requests.get(url).content)
name = f'{slugify(item_name)[:20]}_{photo_file_id[-8:]}{extension}'
offer.photo.save(name, files.File(image))
offer.save()
|
import request from '@/utils/request'
export function GetAllRelationTree() {
return request({
url: '/Authorize/GetRelationTree',
method: 'get'
})
}
export function GetRelationTree(userID) {
return request({
url: '/Authorize/GetRelationTree?userID=' + userID,
method: 'get'
})
}
export function UpdateUserRelation(data) {
return request({
url: '/Authorize/UpdateUserRelation',
method: 'post',
data
})
}
export default { GetRelationTree, UpdateUserRelation, GetAllRelationTree }
|
import * as R from 'ramda'
import * as ObjectUtils from '@core/objectUtils'
import * as DateUtils from '@core/dateUtils'
import { uuidv4 } from '@core/uuid'
import * as Validation from '@core/validation/validation'
import * as Step from './processingStep'
import * as Calculation from './processingStepCalculation'
export const keys = {
dateCreated: ObjectUtils.keys.dateCreated,
dateExecuted: 'dateExecuted',
dateModified: ObjectUtils.keys.dateModified,
props: ObjectUtils.keys.props,
statusExec: 'statusExec',
uuid: ObjectUtils.keys.uuid,
temporary: ObjectUtils.keys.temporary,
validation: ObjectUtils.keys.validation,
scriptCommon: 'scriptCommon',
processingSteps: 'processingSteps',
}
export const keysProps = {
labels: ObjectUtils.keysProps.labels,
descriptions: ObjectUtils.keysProps.descriptions,
cycles: ObjectUtils.keysProps.cycles,
}
export const statusExec = {
error: 'error',
success: 'success',
running: 'running',
}
// ====== READ
export const {
getUuid,
getProps,
getPropsDiff,
getCycles,
getDateCreated,
getDateModified,
getDescriptions,
getDescription,
getLabels,
getLabel,
isTemporary,
} = ObjectUtils
export const getDateExecuted = ObjectUtils.getDate(keys.dateExecuted)
export const getStatusExec = R.propOr(null, keys.statusExec)
export const getScriptCommon = R.propOr(null, keys.scriptCommon)
// ===== READ - Steps
export const getProcessingSteps = R.propOr([], keys.processingSteps)
export const getStepByIdx = (stepIdx) =>
R.ifElse(R.always(stepIdx >= 0), R.pipe(getProcessingSteps, R.propOr(null, stepIdx)), R.always(null))
export const getStepPrev = (step) => getStepByIdx(Step.getIndex(step) - 1)
export const getStepNext = (step) => getStepByIdx(Step.getIndex(step) + 1)
// ====== CREATE
export const newProcessingChain = (props = {}) => ({
[keys.uuid]: uuidv4(),
[keys.props]: props,
[Calculation.keys.temporary]: true,
})
export const newProcessingStep = (processingChain, props = {}) => ({
[Step.keys.uuid]: uuidv4(),
[Step.keys.processingChainUuid]: getUuid(processingChain),
[Step.keys.index]: getProcessingSteps(processingChain).length,
[Step.keys.props]: props,
[Calculation.keys.temporary]: true,
})
export const newProcessingStepCalculation = (processingStep, nodeDefUuid = null, props = {}) => ({
[Calculation.keys.uuid]: uuidv4(),
[Calculation.keys.processingStepUuid]: Step.getUuid(processingStep),
[Calculation.keys.index]: Step.getCalculations(processingStep).length,
[Calculation.keys.nodeDefUuid]: nodeDefUuid,
[Calculation.keys.props]: props,
[Calculation.keys.temporary]: true,
})
// ====== CHECK
export const isDraft = R.ifElse(R.pipe(getDateExecuted, R.isNil), R.always(true), (chain) =>
DateUtils.isAfter(getDateModified(chain), getDateExecuted(chain))
)
// ====== UPDATE
export const assocProp = ObjectUtils.setProp
export const { dissocTemporary } = ObjectUtils
export const dissocProcessingSteps = R.dissoc(keys.processingSteps)
export const assocProcessingSteps = R.assoc(keys.processingSteps)
export const assocProcessingStep = (step) => R.assocPath([keys.processingSteps, Step.getIndex(step)], step)
export const dissocProcessingStepTemporary = (chain) => ({
...chain,
[keys.processingSteps]: getProcessingSteps(chain).filter((processingStep) => !Step.isTemporary(processingStep)),
})
export const dissocProcessingStep = (step) => (chain) => ({
...chain,
[keys.processingSteps]: getProcessingSteps(chain).filter((processingStep) => !Step.isEqual(processingStep)(step)),
})
// ====== VALIDATION
// The validation object contains the validation of chain, steps, calculations, index by uuids
export const { getValidation } = Validation
export const { hasValidation } = Validation
export const { assocValidation } = Validation
export const { dissocValidation } = Validation
export const getItemValidationByUuid = (uuid) => R.pipe(getValidation, Validation.getFieldValidation(uuid))
export const assocItemValidation = (uuid, validation) => (chain) =>
R.pipe(getValidation, Validation.assocFieldValidation(uuid, validation), (validationUpdated) =>
Validation.assocValidation(validationUpdated)(chain)
)(chain)
|
#!/usr/bin/env python3
'''
###############################################################################
###############################################################################
## ##
## _ ___ ___ ___ ___ ___ ##
## | | | __ / \ / __| _ | __| ##
## | |__| __ ( ) | (_ | _|__ \ ##
## |____|___ \___/ \___|_| \___/ ##
## v 1.0 (Stable) ##
## ##
## Written by Samuel Y. W. Low. ##
## Last modified 13-03-2020. ##
## ##
###############################################################################
###############################################################################
'''
# Import local libraries
from codes import inpxtr
from codes import rnpath
from codes import timing
from codes import gpsxtr
from codes import rinxtr
from codes import posvel
from codes import ambest
from codes import pubplt
def run():
# IMPORTING USER DEFINED PARAMETERS:
#
# -> The routine 'inpxtr.py' extracts out all user-specified parameters.
# -> It returns a dictionary object comprising each parameter.
inps = inpxtr.inpxtr()
n1 = inps['name1'] # Name of LEO1
n2 = inps['name2'] # Name of LEO2
# FINDING THE RINEX FILE PATHS:
#
# -> The routine 'rnpath.py' will output the path of the RINEX file.
# -> This is based on the 4-letter spacecraft ID input in 'config.txt'.
# -> Do not change any of the folder names in LEOGPS!
rinex1f, rinex2f = rnpath.rnpath( inps )
# FINDING ALL TIMING PARAMETERS:
#
# -> The routine 'timing.py', will take in three sets of timings.
# -> First, the user-specified start-stop times in 'config.txt'.
# -> Next, the two start-stop time lines based on both of the RINEX files.
# -> Then, 'timing.py' will output the intersection of all three timelines.
# -> The routine also error-checks the timesteps, based on the RINEX files.
timecheck = timing.tcheck( rinex1f, rinex2f, inps )
# CHECK FOR ANY TIMING CONFLICTS:
#
# -> If time conflicts arise, timing.tcheck(...) will return a False.
# -> One possible conflict is if the user-defined start-stop times,
# -> are completely out of the time line of the RINEX observation files.
# -> The routine will also print out an error log for the user to read.
if timecheck == False:
return None
# EXTRACTING LEOGPS SCENARIO START, STOP, STEP, AND RINEX STEP TIMES:
#
# -> If all is good, then 'timecheck' outputs start, stop and step times.
# -> This will be the start, stop, and step used for the entire scenario.
tstart, tstop, tstep, rnxstep = timecheck
# EXTRACTING ALL GPS EPHEMERIS AND CLOCK BIAS DATA FROM CDDIS.
#
# -> The routine 'gpsxtr.py' downloads GPS clock and ephemeris data.
# -> The routine then interpolates positions and clock biases.
# -> It estimates GPS satellite velocities using a first order derivative.
# -> It also outputs GPS satellites without clock issues (goodsats).
gpsdata, goodsats = gpsxtr.gpsxtr( inps, tstart, tstop, tstep )
# RINEX OBSERVABLES ARE EXTRACTED HERE, IN A NESTED DICTIONARY OBJECT.
#
# -> RINEX observables are extracted, screened, and marked for cycle slips.
# -> If no Doppler values found, they will be estimated in 'dopest.py'.
# -> Hatch filtering is an option, if the user toggles it in 'config.txt'.
# -> For more details on the RINEX parsing process, checkout 'rinxtr.py'.
rinex1 = rinxtr.rinxtr(rinex1f, inps, goodsats, tstart, tstop, rnxstep)
rinex2 = rinxtr.rinxtr(rinex2f, inps, goodsats, tstart, tstop, rnxstep)
# Check if the RINEX files are corrupted?
if rinex1 == False or rinex2 == False:
return None
# INITIALISE THE ARRAY OF TIME STEPS USED FOR PROCESSING.
ti, time, results = tstart, [], {}
while ti <= tstop:
time.append(ti)
ti = ti + tstep
print('Solving for absolute and relative positions now.')
# SOLVING FOR POSITIONS (ABSOLUTE AND RELATIVE).
#
# -> This for loop iterates through all steps generated by the list above.
# -> In doing so, it refers to RINEX observables generated by 'rinxtr.py'.
# -> Then, the routine will trilaterate absolute positions, estimate
# -> receiver biases, offset other errors such as Earth's rotation and
# -> relativistic effects, and finally estimate the velocities via Doppler.
# -> The routine 'ambest.py' will then calculate the precise baseline
# -> using the double-differenced baseline solution, with float ambiguity.
for t in time:
# What are the GPS observables and RINEX observables at t?
gps = gpsdata[t]
rx1 = rinex1[t]
rx2 = rinex2[t]
# Extract PVT and DOP values for LEO satellite 1, at time = t.
pos1, vel1, dop1, cb1 = posvel.posvel(t, goodsats, gps, rx1, inps, n1)
# Extract PVT and DOP values for LEO satellite 2, at time = t.
pos2, vel2, dop2, cb2 = posvel.posvel(t, goodsats, gps, rx2, inps, n2)
# Perform double-differencing to get baseline length.
baseline = ambest.ambest(t, gps, rx1, rx2, pos1, pos2, inps)
# Log the results into a dictionary.
# Result size: 1x3 1x3 1x3 1x1 1x3 1x3 1x3 1x1 1x3
results[t] = [pos1, vel1, dop1, cb1, pos2, vel2, dop2, cb2, baseline]
# FINALLY, WE PUBLISH THE RESULTS IN THE OUTPUTS FOLDER.
pubplt.leo_results( results, inps )
return None
|
from swsscommon import swsscommon
import os
import re
import time
import json
import redis
def getCrmCounterValue(dvs, key, counter):
counters_db = swsscommon.DBConnector(swsscommon.COUNTERS_DB, dvs.redis_sock, 0)
crm_stats_table = swsscommon.Table(counters_db, 'CRM')
for k in crm_stats_table.get(key)[1]:
if k[0] == counter:
return int(k[1])
return 0
def setReadOnlyAttr(dvs, obj, attr, val):
db = swsscommon.DBConnector(swsscommon.ASIC_DB, dvs.redis_sock, 0)
tbl = swsscommon.Table(db, "ASIC_STATE:{0}".format(obj))
keys = tbl.getKeys()
assert len(keys) == 1
swVid = keys[0]
r = redis.Redis(unix_socket_path=dvs.redis_sock, db=swsscommon.ASIC_DB)
swRid = r.hget("VIDTORID", swVid)
assert swRid is not None
ntf = swsscommon.NotificationProducer(db, "SAI_VS_UNITTEST_CHANNEL")
fvp = swsscommon.FieldValuePairs()
ntf.send("enable_unittests", "true", fvp)
fvp = swsscommon.FieldValuePairs([(attr, val)])
key = "SAI_OBJECT_TYPE_SWITCH:" + swRid
ntf.send("set_ro", key, fvp)
def test_CrmFdbEntry(dvs, testlog):
# disable ipv6 on Ethernet8 neighbor as once ipv6 link-local address is
# configured, server 2 will send packet which can switch to learn another
# mac and fail the test.
dvs.servers[2].runcmd("sysctl -w net.ipv6.conf.eth0.disable_ipv6=1")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_FDB_ENTRY', '1000')
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_fdb_entry_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_fdb_entry_available')
app_db = swsscommon.DBConnector(swsscommon.APPL_DB, dvs.redis_sock, 0)
cfg_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
# create a FDB entry
tbl = swsscommon.ProducerStateTable(app_db, "FDB_TABLE")
fvs = swsscommon.FieldValuePairs([("port","Ethernet8"),("type","dynamic")])
tbl.set("Vlan2:52-54-00-25-06-E9", fvs)
# create vlan
tbl = swsscommon.Table(cfg_db, "VLAN")
fvs = swsscommon.FieldValuePairs([("vlanid", "2")])
tbl.set("Vlan2", fvs)
# create vlan member
tbl = swsscommon.Table(cfg_db, "VLAN_MEMBER")
fvs = swsscommon.FieldValuePairs([("tagging_mode", "untagged")])
tbl.set("Vlan2|Ethernet8", fvs)
# update available counter
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_FDB_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_fdb_entry_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_fdb_entry_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# update available counter
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_FDB_ENTRY', '1000')
time.sleep(2)
# get counters
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_fdb_entry_available')
assert new_avail_counter == avail_counter
# enable ipv6 on server 2
dvs.servers[2].runcmd("sysctl -w net.ipv6.conf.eth0.disable_ipv6=0")
def test_CrmIpv4Route(dvs, testlog):
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet0|10.0.0.0/31", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_ROUTE_ENTRY', '1000')
# add static neighbor
dvs.runcmd("ip neigh replace 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
db = swsscommon.DBConnector(0, dvs.redis_sock, 0)
ps = swsscommon.ProducerStateTable(db, "ROUTE_TABLE")
fvs = swsscommon.FieldValuePairs([("nexthop","10.0.0.1"), ("ifname", "Ethernet0")])
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_available')
# add route and update available counter
ps.set("2.2.2.0/24", fvs)
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_ROUTE_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove route and update available counter
ps._del("2.2.2.0/24")
dvs.runcmd("ip neigh del 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_ROUTE_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_route_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|10.0.0.0/31")
time.sleep(2)
def test_CrmIpv6Route(dvs, testlog):
# Enable IPv6 routing
dvs.runcmd("sysctl net.ipv6.conf.all.disable_ipv6=0")
time.sleep(2)
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet0|fc00::1/126", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.servers[0].runcmd("ifconfig eth0 inet6 add fc00::2/126")
dvs.servers[0].runcmd("ip -6 route add default via fc00::1")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_ROUTE_ENTRY', '1000')
# get neighbor and arp entry
dvs.servers[0].runcmd("ping6 -c 4 fc00::1")
db = swsscommon.DBConnector(0, dvs.redis_sock, 0)
ps = swsscommon.ProducerStateTable(db, "ROUTE_TABLE")
fvs = swsscommon.FieldValuePairs([("nexthop","fc00::2"), ("ifname", "Ethernet0")])
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_available')
# add route and update available counter
ps.set("2001::/64", fvs)
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_ROUTE_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove route and update available counter
ps._del("2001::/64")
dvs.runcmd("ip -6 neigh del fc00::2 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_ROUTE_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_route_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|fc00::1/126")
time.sleep(2)
def test_CrmIpv4Nexthop(dvs, testlog):
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0|10.0.0.0/31", fvs)
intf_tbl.set("Ethernet0", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEXTHOP_ENTRY', '1000')
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_available')
# add nexthop and update available counter
dvs.runcmd("ip neigh replace 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEXTHOP_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove nexthop and update available counter
dvs.runcmd("ip neigh del 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEXTHOP_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_nexthop_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|10.0.0.0/31")
time.sleep(2)
def test_CrmIpv6Nexthop(dvs, testlog):
# Enable IPv6 routing
dvs.runcmd("sysctl net.ipv6.conf.all.disable_ipv6=0")
time.sleep(2)
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet0|fc00::1/126", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEXTHOP_ENTRY', '1000')
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_available')
# add nexthop and update available counter
dvs.runcmd("ip -6 neigh replace fc00::2 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEXTHOP_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove nexthop and update available counter
dvs.runcmd("ip -6 neigh del fc00::2 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEXTHOP_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_nexthop_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|fc00::1/126")
time.sleep(2)
def test_CrmIpv4Neighbor(dvs, testlog):
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet0|10.0.0.0/31", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEIGHBOR_ENTRY', '1000')
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_available')
# add neighbor and update available counter
dvs.runcmd("ip neigh replace 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEIGHBOR_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove neighbor and update available counter
dvs.runcmd("ip neigh del 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEIGHBOR_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv4_neighbor_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|10.0.0.0/31")
time.sleep(2)
def test_CrmIpv6Neighbor(dvs, testlog):
# Enable IPv6 routing
dvs.runcmd("sysctl net.ipv6.conf.all.disable_ipv6=0")
time.sleep(2)
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet0|fc00::1/126", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEIGHBOR_ENTRY', '1000')
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_available')
# add neighbor and update available counter
dvs.runcmd("ip -6 neigh replace fc00::2 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEIGHBOR_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove neighbor and update available counter
dvs.runcmd("ip -6 neigh del fc00::2 lladdr 11:22:33:44:55:66 dev Ethernet0")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEIGHBOR_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_ipv6_neighbor_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|fc00::1/126")
time.sleep(2)
def test_CrmNexthopGroup(dvs, testlog):
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet4", fvs)
intf_tbl.set("Ethernet0|10.0.0.0/31", fvs)
intf_tbl.set("Ethernet4|10.0.0.2/31", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("ifconfig Ethernet4 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_ENTRY', '1000')
# add neighbors
dvs.runcmd("ip neigh replace 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
dvs.runcmd("ip neigh replace 10.0.0.3 lladdr 11:22:33:44:55:66 dev Ethernet4")
db = swsscommon.DBConnector(0, dvs.redis_sock, 0)
ps = swsscommon.ProducerStateTable(db, "ROUTE_TABLE")
fvs = swsscommon.FieldValuePairs([("nexthop","10.0.0.1,10.0.0.3"), ("ifname", "Ethernet0,Ethernet4")])
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_available')
# add route and update available counter
ps.set("2.2.2.0/24", fvs)
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_ENTRY', '999')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_available')
assert new_used_counter - used_counter == 1
assert avail_counter - new_avail_counter == 1
# remove route and update available counter
ps._del("2.2.2.0/24")
dvs.runcmd("ip neigh del 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
dvs.runcmd("ip neigh del 10.0.0.3 lladdr 11:22:33:44:55:66 dev Ethernet4")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|10.0.0.0/31")
intf_tbl._del("Ethernet4|10.0.0.2/31")
time.sleep(2)
def test_CrmNexthopGroupMember(dvs, testlog):
# down, then up to generate port up signal
dvs.servers[0].runcmd("ip link set down dev eth0") == 0
dvs.servers[1].runcmd("ip link set down dev eth0") == 0
dvs.servers[0].runcmd("ip link set up dev eth0") == 0
dvs.servers[1].runcmd("ip link set up dev eth0") == 0
config_db = swsscommon.DBConnector(swsscommon.CONFIG_DB, dvs.redis_sock, 0)
intf_tbl = swsscommon.Table(config_db, "INTERFACE")
fvs = swsscommon.FieldValuePairs([("NULL","NULL")])
intf_tbl.set("Ethernet0", fvs)
intf_tbl.set("Ethernet4", fvs)
intf_tbl.set("Ethernet0|10.0.0.0/31", fvs)
intf_tbl.set("Ethernet4|10.0.0.2/31", fvs)
dvs.runcmd("ifconfig Ethernet0 up")
dvs.runcmd("ifconfig Ethernet4 up")
dvs.runcmd("crm config polling interval 1")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_MEMBER_ENTRY', '1000')
# add neighbors
dvs.runcmd("ip neigh replace 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
dvs.runcmd("ip neigh replace 10.0.0.3 lladdr 11:22:33:44:55:66 dev Ethernet4")
db = swsscommon.DBConnector(0, dvs.redis_sock, 0)
ps = swsscommon.ProducerStateTable(db, "ROUTE_TABLE")
fvs = swsscommon.FieldValuePairs([("nexthop","10.0.0.1,10.0.0.3"), ("ifname", "Ethernet0,Ethernet4")])
time.sleep(2)
# get counters
used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_used')
avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_available')
# add route and update available counter
ps.set("2.2.2.0/24", fvs)
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_MEMBER_ENTRY', '998')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_available')
assert new_used_counter - used_counter == 2
assert avail_counter - new_avail_counter == 2
# remove route and update available counter
ps._del("2.2.2.0/24")
dvs.runcmd("ip neigh del 10.0.0.1 lladdr 11:22:33:44:55:66 dev Ethernet0")
dvs.runcmd("ip neigh del 10.0.0.3 lladdr 11:22:33:44:55:66 dev Ethernet4")
setReadOnlyAttr(dvs, 'SAI_OBJECT_TYPE_SWITCH', 'SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_MEMBER_ENTRY', '1000')
time.sleep(2)
# get counters
new_used_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_used')
new_avail_counter = getCrmCounterValue(dvs, 'STATS', 'crm_stats_nexthop_group_member_available')
assert new_used_counter == used_counter
assert new_avail_counter == avail_counter
intf_tbl._del("Ethernet0|10.0.0.0/31")
intf_tbl._del("Ethernet4|10.0.0.2/31")
time.sleep(2)
def test_CrmAcl(dvs, testlog):
db = swsscommon.DBConnector(4, dvs.redis_sock, 0)
adb = swsscommon.DBConnector(1, dvs.redis_sock, 0)
dvs.runcmd("crm config polling interval 1")
time.sleep(1)
bind_ports = ["Ethernet0", "Ethernet4"]
old_table_used_counter = getCrmCounterValue(dvs, 'ACL_STATS:INGRESS:PORT', 'crm_stats_acl_table_used')
# create ACL table
ttbl = swsscommon.Table(db, "ACL_TABLE")
fvs = swsscommon.FieldValuePairs([("policy_desc", "test"), ("type", "L3"), ("ports", ",".join(bind_ports))])
ttbl.set("test", fvs)
# create ACL rule
rtbl = swsscommon.Table(db, "ACL_RULE")
fvs = swsscommon.FieldValuePairs([("priority", "55"), ("PACKET_ACTION", "FORWARD"), ("L4_SRC_PORT", "65000")])
rtbl.set("test|acl_test_rule", fvs)
time.sleep(2)
new_table_used_counter = getCrmCounterValue(dvs, 'ACL_STATS:INGRESS:PORT', 'crm_stats_acl_table_used')
table_used_counter = new_table_used_counter - old_table_used_counter
assert table_used_counter == 1
# get ACL table key
atbl = swsscommon.Table(adb, "ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE")
acl_tables = [k for k in atbl.getKeys() if k not in dvs.asicdb.default_acl_tables]
key = "ACL_TABLE_STATS:{0}".format(acl_tables[0].replace('oid:', ''))
entry_used_counter = getCrmCounterValue(dvs, key, 'crm_stats_acl_entry_used')
assert entry_used_counter == 1
cnt_used_counter = getCrmCounterValue(dvs, key, 'crm_stats_acl_counter_used')
assert entry_used_counter == 1
# remove ACL rule
rtbl._del("test|acl_test_rule")
time.sleep(2)
entry_used_counter = getCrmCounterValue(dvs, key, 'crm_stats_acl_entry_used')
assert entry_used_counter == 0
cnt_used_counter = getCrmCounterValue(dvs, key, 'crm_stats_acl_counter_used')
assert cnt_used_counter == 0
# remove ACL table
ttbl._del("test")
time.sleep(2)
new_table_used_counter = getCrmCounterValue(dvs, 'ACL_STATS:INGRESS:PORT', 'crm_stats_acl_table_used')
table_used_counter = new_table_used_counter - old_table_used_counter
assert table_used_counter == 0
counters_db = swsscommon.DBConnector(swsscommon.COUNTERS_DB, dvs.redis_sock, 0)
crm_stats_table = swsscommon.Table(counters_db, 'CRM')
keys = crm_stats_table.getKeys()
assert key not in keys
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2011-2021 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <ust/marker.h>
static void
end (void)
{}
int
main (void)
{
/* Some code to make sure that breakpoints on `main' and `ust/bar' marker
are set at different addresses. */
int a = 0;
int b = a;
trace_mark(ust, bar, "str %s", "FOOBAZ");
trace_mark(ust, bar2, "number1 %d number2 %d", 53, 9800);
end ();
return 0;
}
|
n,a,b,c = [int(x) for x in input().split()]
dp = [-1]*(n+1)
dp[0]= 0
for x in set([a,b,c]):
for i in range(1,n+1):
if i-x >= 0 and dp[i-x] >= 0:
dp[i] = max(dp[i-x] + 1, dp[i])
# print(dp)
print(dp[-1])
# print(max(dp))
# 0 1 2 3 4 5
# 2 1 1 1
# 3 1 2
# 5 1
|
/**
*
* @param {String} equation Equation as string eg. '(5 * 4 - (7 ** 2 + 6) / 6)'
* @returns {Number} Result of the equation string following BODMAS
* @Note This function only supports the following operators: Parentheses: ( ), Exponent: **, Mulitplication: *,
* Division: /, Addition: +, Subraction: -
*/
export function dMaths(equation) {
// Set to true to see step by step working
const DEBUG = false;
// Fixes spacing between operators and numbers
equation = fixSpacing(equation);
if (DEBUG) {
console.log(equation);
}
// Removes surrounging brackets eg. (5 * 4 - (7 ** 2 + 6) / 6) => 5 * 4 - (7 ** 2 + 6) / 6
let surroundingBracketRegex = /^\((?![-0-9.]+ [+-/*]+ [-0-9.]+\)).+\)$|^\([-0-9.]+ [*/+-]+ [-0-9.]+\)$/g;
if (surroundingBracketRegex.test(equation)) {
equation = equation.replace(/^\(|\)$/g, '');
}
let decimalRegex = /\./;
let rootRegex = /\*\* \([-0-9]+ \/ [-0-9]+\)/;
let boRegexCheck = /\([-0-9 .*/+-]+\)|\*\* \([-0-9]+ \/ [-0-9]+\)/;
let topORegex = /([-0-9.]+|\([-0-9]+ \/ [-0-9]+\)) \*\* ([-0-9.]+|\([-0-9]+ \/ [-0-9]+\))$/;
let bRegex = /\([-0-9 .*/+-]+\)/;
let oRegex = /(([-0-9.]+|\([-0-9]+ \/ [-0-9]+\)) \*\* ([-0-9.]+|\([-0-9]+ \/ [-0-9]+\)))( \*\* ([-0-9.]+|\([-0-9]+ \/ [-0-9]+\)))*/;
let dmRegex = /[-0-9.]+ [*/] [-0-9.]+/;
let asRegex = /[-0-9.]+ [+-] [-0-9.]+/;
/*
Test for brackets and call this function recursively until all blocks have been resolved.
Skip exponent blocks with inverse powers.
*/
if (bRegex.test(equation)) {
if (!rootRegex.test(equation.match(boRegexCheck)[0])) {
equation = equation.replace(bRegex, dMaths(equation.match(bRegex)[0]));
}
}
/*
Test for exponents and replace first block with result. Call this function recursively until all
blocks have been resolved. Solves Exponent blocks from the top down.
*/
if (oRegex.test(equation)) {
let eq = equation.match(oRegex)[0].match(topORegex)[0];
let result = eval(eq);
if (rootRegex.test(equation) && DEBUG) {
console.log(eq);
console.log(result);
}
equation = equation.replace(eq, result);
return dMaths(equation);
}
/*
Test for multiplication/division and replace first block with result. Call this function recursively
until all blocks have been resolved.
*/
if (dmRegex.test(equation)) {
let result = '';
let eq = equation.match(dmRegex)[0];
/*
Test for decimal value. Find smallest factor of 10 that will make both sides of the working block a
whole number, evaluate block, convert back to decimal then replace block in equation string with result.
*/
if (decimalRegex.test(eq)) {
let eqArr = equation.split(' ');
let decimalPlaces = 0;
if (decimalRegex.test(eqArr[0])) {
decimalPlaces = eqArr[0].length - eqArr[0].indexOf('.') - 1;
}
if (decimalRegex.test(eqArr[2]) && (eqArr[2].length - eqArr[2].indexOf('.')) > decimalPlaces) {
decimalPlaces = eqArr[2].length - eqArr[2].indexOf('.') - 1;
}
console.log(decimalPlaces);
let factor = 10 ** decimalPlaces;
eqArr[0] = eqArr[0] * factor;
eqArr[2] = eqArr[2] * factor;
eq = eqArr.join(' ');
result = eval(eq);
result = result
if (eqArr[1] === '*') {
result = result / factor / factor;
}
} else {
result = eval(eq);
}
if (DEBUG) {
console.log(eq);
}
equation = equation.replace(dmRegex, result);
return dMaths(equation);
}
/*
Test for addition/subtraction and replace first block with result. Call this function recursively
until all blocks have been resolved.
*/
if (asRegex.test(equation)) {
let result = '';
let eq = equation.match(asRegex)[0];
/*
Test for decimal value. Find smallest factor of 10 that will make both sides of the working block a
whole number, evaluate block, convert back to decimal then replace block in equation string with result.
*/
if (decimalRegex.test(eq)) {
let eqArr = equation.split(' ');
let decimalPlaces = 0;
if (decimalRegex.test(eqArr[0])) {
decimalPlaces = eqArr[0].length - eqArr[0].indexOf('.') - 1;
}
if (decimalRegex.test(eqArr[2]) && (eqArr[2].length - eqArr[2].indexOf('.')) > decimalPlaces) {
decimalPlaces = eqArr[2].length - eqArr[2].indexOf('.') - 1;
}
let factor = 10 ** decimalPlaces;
eqArr[0] = eqArr[0] * factor;
eqArr[2] = eqArr[2] * factor;
eq = eqArr.join(' ');
result = eval(eq);
result = result / factor;
} else {
result = eval(eq);
}
if (DEBUG) {
console.log(eq);
}
equation = equation.replace(asRegex, result);
return dMaths(equation);
}
return equation;
}
/**
*
* @param {String} equation Equation as string
* @returns {String} Equation string
* @Note This function only supports the following operators: Parentheses: ( ), Exponent: **, Mulitplication: *,
* Division: /, Addition: +, Subraction: -
*/
function fixSpacing(equation) {
equation.replace(/ {2,}/g, ' ');
let operatorRegex = /[)*/+][-0-9]|[-0-9.][(*/+-]|[*/+-]\(|\)[*/+-]|[)*/+-][-]/;
if (operatorRegex.test(equation)) {
let eq = equation.match(operatorRegex)[0];
let string = eq[0] + ' ' + eq[1];
equation = equation.replace(eq, string);
return fixSpacing(equation);
}
let bracketRegex = /\( [-0-9]|[-0-9.] \)/;
if (bracketRegex.test(equation)) {
let eq = equation.match(bracketRegex)[0];
let string = eq[0] + eq[2];
equation = equation.replace(eq, string);
return fixSpacing(equation);
}
return equation
}
|
import numpy as np
import scipy as sp
import scipy.spatial
def find_near_points(boundary, target, r=6):
"""
Returns a bool with which points in target are too close to boundary
Where too close is:
dist < r * boundary.h_max
Parameters:
boundary, required, class(boundary_element)
target, required, class(target_element)
r, optional, float
Returns:
bool(nt), with True elements denoting points in target_element
that are too close to boundary
"""
boundary.compute_tree()
target.compute_tree()
out = _find_near_points([boundary.x, boundary.y], [target.x, target.y], r,
boundary.tree, target.tree)
return out[0]
def _find_near_points(px, qx, r, ptree=None, qtree=None, \
slow_trees=False, **kwargs):
"""
Finds points in qx that are within a distance r of any point in px
This function is basically a convenience wrapper to the function:
scipy.spatial.cKDTree.query_ball_tree
Parameters:
px, required, tuple(dim), coordinates of px
qx, required, tuple(dim), coordinates of qx
r, required, float, radius of closeness
ptree, optional, cKDTree, tree for px
qtree, optional, cKDTree, tree for qx
slow_trees, optional, bool, take more time to form trees
Additionally, you may pass the keyword arguments:
p (minkowski norm)
eps (approximate search parameter)
see the documentation of sp.spatialcKDTree.query_ball_tree for details
The tuple px should have the same length as the dimension of the space
the ith element of px should be the coordinate for the ith dimension
and should be a numpy array of type float, with any shape
The tuple qx should be the same as qx but for q; must have the same
dimension but the underlying arrays need not have the same shape
If slow_trees, will create balanced kd-trees with compact nodes. This takes
longer but makes searches of the trees faster. If you intend to reuse
the trees, this is probably worth setting to True.
Outputs:
Tuple of (result, pxtree, qxtree)
result is a bool array with shape given by the shape of qx[0]
"""
# get the dim
dim = len(px)
# get the shapes
psh = px[0].shape
qsh = qx[0].shape
have_ptree = ptree is not None
have_qtree = qtree is not None
# if the trees don't exist, form them
if not have_ptree:
# put data into the correct format
pf = np.zeros([np.prod(psh),dim], dtype=float)
for i in range(dim):
pf[:,i] = px[i].flatten()
ptree = sp.spatial.cKDTree(pf, compact_nodes=slow_trees, \
balanced_tree=slow_trees, **kwargs)
if not have_qtree:
qf = np.zeros([np.prod(qsh),dim], dtype=float)
for i in range(dim):
qf[:,i] = qx[i].flatten()
qtree = sp.spatial.cKDTree(qf, compact_nodes=slow_trees, \
balanced_tree=slow_trees, **kwargs)
# determine which tree is bigger, run appropriate search
p_is_bigger = ptree.data.shape[0] > qtree.data.shape[0]
# find close points
if p_is_bigger:
groups = qtree.query_ball_tree(ptree, r)
else:
groups = ptree.query_ball_tree(qtree, r)
# massage output as needed
if p_is_bigger:
close = [len(x)>0 for x in groups]
out = np.array(close).reshape(qsh)
else:
out = np.zeros(np.prod(qsh), dtype=bool)
for group in groups:
if len(group) > 0:
out[np.array(group)] = True
out = out.reshape(qsh)
return out, ptree, qtree
|
import { isModelReference } from '../utils/reference';
export default {
/**
* Determines whether an attribute is a reference.
* If it is not, return `null` or `undefined`.
* Otherwise return an object with properties:
* - `id` The id of the referenced model (either m3 or `@ember-data/model`)
* - `type` The type of the referenced model (either m3 or `@ember-data/model`)
* `null` is also a valid type in which case `id` will be looked up in a global cache.
*
* Note that attribute references are all treated as synchronous.
* There is no ember-m3 analogue to `@ember-data/model` async relationships.
*
* @param {string} key
* @param {Object} value
* @param {string} modelName
* @param {M3SchemaInterface} schemaInterface
* @returns {Object}
*/
computeAttributeReference(key, value) {
if (
(Array.isArray(value) && isModelReference(value[0])) ||
isModelReference(value)
) {
return value;
}
return null;
},
/**
* Determines whether `value` is a nested model and compute
* a new m3 model rather than returning a simple object if so.
*
* @param {string} key
* @param {Object} value
* @param {string} modelName
* @param {schemaInterface} schemaInterface
* @returns {Object}
*/
computeNestedModel(key, value) {
if (!Array.isArray(value) && value !== null && typeof value === 'object') {
return { attributes: value };
}
return null;
},
/**
* Whether or not ember-m3 should handle this `modelName`.
*
* @param {string} modelName
* @returns {boolean}
*/
includesModel() {
return true;
},
/**
* If the `projectionModelName` represents a projection over some base type,
* return the model name of the base type to maintain shared data
* between all projections of the same type
*
* @param {string} projectionModelName
* @returns {string}
*/
// computeBaseModelName(projectionModelName) {
// return null;
// },
/*
models: {
'my-model-name': {
// an optional whitelist of attributes. If undefined, all attributes
// returned by the API will be available on the model
attributes: ['foo', 'bar', 'baz'],
// an optional list of attribute transforms. Use this if your API
// returns values whose types can't be encoded in JSON, such as dates.
// Each key is the name of an attribute as it appears in the payload,
// and each value is a function that takes the raw api value and returns
// the transformed value
transforms: {
dateAttr: function dateTransform(dateString) {
return dateString && new Date(Date.parse(dateString));
},
},
defaults: {
tag: 'span',
},
aliases: {
fullName: 'person.name',
},
}
}
*/
};
|
const quizData = {
quiz1: "clear",
quiz2: "float",
quiz3: "margin",
quiz4: ".content",
quiz5: "clear",
};
var count = 0;
var score = 0;
// listen to form submission and get user data
var userForm = document.getElementById("form");
userForm.addEventListener("submit", (e) => {
e.preventDefault();
var userData = new FormData(userForm);
correctAnswer(userData);
});
// compare user's with correct answers
function correctAnswer(userData) {
for (let answer of userData) {
var userKey = answer[0];
var userValue = answer[1];
if (userValue === quizData[userKey]) {
score++;
}
}
document.getElementById("score").innerText = scoreDiplay(score);
userForm.style.display = "none";
}
// display the score to user
function scoreDiplay(score) {
var score = (score / 5) * 100;
var message = "";
if (score < 50) {
message = "Poor score retake the quiz";
} else if (score < 80) {
message = "Average score keep it up!";
} else {
message = "Excellent!";
}
return score + "%: " + message;
}
|
class SkipBackend(Exception):
pass
class BackendRegistry(list):
def __init__(self, registry_name, iterable):
super(BackendRegistry, self).__init__(iterable)
self.registry_name = registry_name
def __add__(self, value):
if value.registry_name != self.registry_name:
raise TypeError(u'Unable to create registry with backends with different registry names')
if isinstance(value, BackendRegistry):
self.extend(value)
else:
self.append(value)
return self
def run(self, *args, **kwargs):
for backend in self:
try:
return backend.run(*args, **kwargs)
except SkipBackend:
continue
raise RuntimeError(u'No one from the following backends matches: %s' % ', '.join(map(str, self)))
class BackendMetaclass(type):
def __add__(cls, value):
if cls.registry_name != value.registry_name:
raise TypeError(u'Unable to create registry with backends with different registry names')
if isinstance(value, BackendRegistry):
return BackendRegistry(cls.registry_name, [cls]) + value
else:
return BackendRegistry(cls.registry_name, (cls, value))
class BaseBackend(object):
__metaclass__ = BackendMetaclass
registry_name = None
@classmethod
def run(cls, *args, **kwargs):
raise NotImplementedError()
|
from django.db import models
from analysis.person import Person
from analysis.web_simulation import WebSimulation
from analysis.virus import Virus
from web import settings
from django.utils import timezone
from django.urls import reverse
from data_structures.mwaytree import MWayTree, MWayTreeNode
from queue import Queue
from django.contrib.postgres.fields import ArrayField
class Experiment(models.Model):
'''An experiment by the user to test the herd immunity of a population.'''
title = models.CharField(max_length=settings.EXPER_TITLE_MAX_LENGTH,
unique=False,
help_text="Title of your experiment.")
population_size = models.IntegerField(help_text=(
"How large is the population?"))
vaccination_percent = models.FloatField(help_text=(
"What percentage of the population is initially vaccinated " +
"against the virus?"
))
virus_name = models.CharField(max_length=settings.EXPER_TITLE_MAX_LENGTH,
unique=False, null=True,
help_text="What virus are you testing?")
mortality_chance = models.FloatField(help_text=(
"How likely is a patient infected with the virus likely to succumb?"
))
reproductive_rate = models.FloatField(help_text=(
"How effective is the virus at spreading between individuals?"
))
initial_infected = models.IntegerField(help_text=(
"How many people in the population " +
"start out infected with the virus?"
))
def __str__(self):
'''Return the title of the Experiment instance.'''
return self.title
def get_absolute_url(self):
'''Returns a path to the experimental results after form submission.'''
path_components = {'pk': self.pk}
return reverse('simulator:simulation_detail', kwargs=path_components)
def generate_web_sim(self):
"""Update atttributes for Simulation, based on new data from an
Experiment instance.
Parameters:
self(Experiment): the calling Experiment instance
Returns:
WebSimulation: a new instance of the class
"""
# init population related fields
pop_size = self.population_size
# init related fields, virus fields
virus = Virus(self.virus_name, self.reproductive_rate,
self.mortality_chance)
initial_infected = self.initial_infected
vacc_percentage = self.vaccination_percent
# create the population
return WebSimulation(pop_size, vacc_percentage, virus,
initial_infected)
def make_basic_node(self, node):
"""Return an InfectedNode instance with an empty parent field
If there is already an InfectedNode instance for the node, retrieve
that from the db instead.
"""
infected_node, truth = InfectedNode.objects.get_or_create(
experiment=self,
identifier=node.id,
children=list(node.children.keys())
)
return infected_node
def store_infected_persons(self, population_tree):
"""Instaniates and saves instances of InfectedNode related to this
Experiment.
"""
# Create queue to store nodes not yet traversed in level-order
queue = Queue()
# Enqueue starting at the virus, and then all the initial infected
virus_node = population_tree.root
queue.put(virus_node)
# Loop until queue is empty
while queue.qsize() > 0:
# Dequeue node at front of queue
parent_node = queue.get()
# Set the node's children to point to their parent
infected_by_parent = list()
for node in parent_node.children:
# grab instance of MWayTreeNode
child = parent_node.children[node]
# enqueue the MWayTreeNode to be the next parent
queue.put(child)
# prepare the InfectedNodes for initialization
next_node = self.make_basic_node(child)
infected_by_parent.append(next_node)
# make basic node of the parent
parent_node = self.make_basic_node(parent_node)
for next_node in infected_by_parent:
# point out its relationship to the parent, and save
next_node.parent = parent_node
next_node.save()
# Save the parent in the db
parent_node.save()
def run_experiment(self):
'''Runs through the experiment, and generates time step graphs.'''
# update Simulation properties with form data
web_sim = self.generate_web_sim()
# run through the simulation, collect data to make TimeStep instances
data_collection = web_sim.run_and_collect(self)
# insert new TimeSteps into the db
for ts in data_collection[:-1]:
time_step = TimeStep.objects.create(
step_id=ts.get('step_id'),
total_infected=ts.get('total_infected'),
current_infected=ts.get('current_infected'),
dead=ts.get('dead'),
total_vaccinated=ts.get('total_vaccinated'),
alive=ts.get('alive'),
uninfected=ts.get('uninfected'),
uninteracted=ts.get('uninteracted'),
experiment=ts.get('experiment')
)
time_step.save()
# initialize population tree of infected persons
population_tree = data_collection[-1]
self.store_infected_persons(population_tree)
class TimeStep(models.Model):
'''A visual representation of a time step for a Simulation.'''
step_id = models.IntegerField(help_text=(
"What time step is this TimeStep for?"))
experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE,
help_text="The related Experiment model.")
total_infected = models.IntegerField(help_text=(
"People who contracted the virus thus far in the experiment."
))
current_infected = models.IntegerField(help_text=(
"People infected who are still alive in this step of the experiment."
))
dead = models.IntegerField(help_text="People thus far who have succumbed.")
total_vaccinated = models.IntegerField(help_text=(
"Amount of individuals who are now vaccinated in the population."
))
alive = models.IntegerField(help_text="People who are currently alive.")
uninfected = models.IntegerField(help_text=(
"People who have not had any interaction with the virus."
))
uninteracted = models.IntegerField(help_text=(
"Alive people in the"
+ " population who are both uninfected, not vaccinated."))
created = models.DateTimeField(auto_now_add=True,
help_text=("The date and time this TimeStep"
+ " was created. Auto-generated "
+ "when the model " +
"saves, used for ordering."))
def __str__(self):
'''Return a unique phrase identifying the TimeStep.'''
return f'{self.experiment} Step {self.step_id}'
class InfectedNode(models.Model):
"""
A node in the population tree of infected persons. Begins with the root
being the virus, then diverges into each person whom was infected by the
previous node.
"""
experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE,
help_text="The related Experiment.")
identifier = models.CharField(max_length=settings.EXPER_TITLE_MAX_LENGTH,
unique=False,
help_text=("identifier of the person/virus "
+ "in experiment."))
parent = models.ForeignKey('InfectedNode', on_delete=models.CASCADE,
help_text="Source of this person's infection.",
null=True)
children = ArrayField(
models.CharField(
max_length=settings.EXPER_TITLE_MAX_LENGTH,
unique=False), blank=True, null=True)
def __str__(self):
'''Return a unique phrase identifying the TimeStep.'''
return f'{self.experiment}: {self.identifier}'
|
const config = require('config');
const db = config.get('db');
module.exports = {
type: db.type || "mysql",
host: db.host || "localhost",
port: db.port || 3306,
username: db.username || "root",
password: db.password || "",
database: db.database || "contentry",
synchronize: db.synchronize || false,
logging: db.logging || false,
entities: ["dist/**/*.entity{.ts,.js}"],
migrationsTableName: "custom_migration_table",
migrations: ["dist/database/migrations/*{.ts,.js}"],
cli: {
entitiesDir: "src/**/*.entity.ts",
migrationsDir: "src/database/migrations"
},
};
|
#!/usr/bin/python3
import numpy as np
import pandas as pd
import dask.array as da
import sys
import os
#fluidity_fp = '/mnt/c/Users/julia/fluidity/fluidity-master/python'
DA_project_fp = '/mnt/c/Users/julia/Documents/Imperial/DA_project'
#sys.path.append(fluidity_fp)
sys.path.append(DA_project_fp)
import vtktools
ug1=vtktools.vtu(DA_project_fp + '/data/LSBU_c_0.vtu')
ug2=vtktools.vtu(DA_project_fp + '/data/LSBU_0.vtu')
print(ug1.GetFieldNames())
print(ug2.GetFieldNames())
#read the values of the tracers and copy in a vector named p
p = ug2.GetVectorField('Velocity')
#create a dask array
p = da.from_array(p, chunks = [5000, 63])
n = len(p)
print(n)
#create background matrix
Background = da.matmul(p, p.T)
Background.compute()
print(Background[0,0])
|
/*! Hammer.JS - v2.0.8 - 2016-04-23
* http://hammerjs.github.io/
*
* Copyright (c) 2016 Jorik Tangelder;
* Licensed under the MIT license */
!function(a,b,c,d){"use strict";function e(a,b,c){return setTimeout(j(a,c),b)}function f(a,b,c){return Array.isArray(a)?(g(a,c[b],c),!0):!1}function g(a,b,c){var e;if(a)if(a.forEach)a.forEach(b,c);else if(a.length!==d)for(e=0;e<a.length;)b.call(c,a[e],e,a),e++;else for(e in a)a.hasOwnProperty(e)&&b.call(c,a[e],e,a)}function h(b,c,d){var e="DEPRECATED METHOD: "+c+"\n"+d+" AT \n";return function(){var c=new Error("get-stack-trace"),d=c&&c.stack?c.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",f=a.console&&(a.console.warn||a.console.log);return f&&f.call(a.console,e,d),b.apply(this,arguments)}}function i(a,b,c){var d,e=b.prototype;d=a.prototype=Object.create(e),d.constructor=a,d._super=e,c&&la(d,c)}function j(a,b){return function(){return a.apply(b,arguments)}}function k(a,b){return typeof a==oa?a.apply(b?b[0]||d:d,b):a}function l(a,b){return a===d?b:a}function m(a,b,c){g(q(b),function(b){a.addEventListener(b,c,!1)})}function n(a,b,c){g(q(b),function(b){a.removeEventListener(b,c,!1)})}function o(a,b){for(;a;){if(a==b)return!0;a=a.parentNode}return!1}function p(a,b){return a.indexOf(b)>-1}function q(a){return a.trim().split(/\s+/g)}function r(a,b,c){if(a.indexOf&&!c)return a.indexOf(b);for(var d=0;d<a.length;){if(c&&a[d][c]==b||!c&&a[d]===b)return d;d++}return-1}function s(a){return Array.prototype.slice.call(a,0)}function t(a,b,c){for(var d=[],e=[],f=0;f<a.length;){var g=b?a[f][b]:a[f];r(e,g)<0&&d.push(a[f]),e[f]=g,f++}return c&&(d=b?d.sort(function(a,c){return a[b]>c[b]}):d.sort()),d}function u(a,b){for(var c,e,f=b[0].toUpperCase()+b.slice(1),g=0;g<ma.length;){if(c=ma[g],e=c?c+f:b,e in a)return e;g++}return d}function v(){return ua++}function w(b){var c=b.ownerDocument||b;return c.defaultView||c.parentWindow||a}function x(a,b){var c=this;this.manager=a,this.callback=b,this.element=a.element,this.target=a.options.inputTarget,this.domHandler=function(b){k(a.options.enable,[a])&&c.handler(b)},this.init()}function y(a){var b,c=a.options.inputClass;return new(b=c?c:xa?M:ya?P:wa?R:L)(a,z)}function z(a,b,c){var d=c.pointers.length,e=c.changedPointers.length,f=b&Ea&&d-e===0,g=b&(Ga|Ha)&&d-e===0;c.isFirst=!!f,c.isFinal=!!g,f&&(a.session={}),c.eventType=b,A(a,c),a.emit("hammer.input",c),a.recognize(c),a.session.prevInput=c}function A(a,b){var c=a.session,d=b.pointers,e=d.length;c.firstInput||(c.firstInput=D(b)),e>1&&!c.firstMultiple?c.firstMultiple=D(b):1===e&&(c.firstMultiple=!1);var f=c.firstInput,g=c.firstMultiple,h=g?g.center:f.center,i=b.center=E(d);b.timeStamp=ra(),b.deltaTime=b.timeStamp-f.timeStamp,b.angle=I(h,i),b.distance=H(h,i),B(c,b),b.offsetDirection=G(b.deltaX,b.deltaY);var j=F(b.deltaTime,b.deltaX,b.deltaY);b.overallVelocityX=j.x,b.overallVelocityY=j.y,b.overallVelocity=qa(j.x)>qa(j.y)?j.x:j.y,b.scale=g?K(g.pointers,d):1,b.rotation=g?J(g.pointers,d):0,b.maxPointers=c.prevInput?b.pointers.length>c.prevInput.maxPointers?b.pointers.length:c.prevInput.maxPointers:b.pointers.length,C(c,b);var k=a.element;o(b.srcEvent.target,k)&&(k=b.srcEvent.target),b.target=k}function B(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};b.eventType!==Ea&&f.eventType!==Ga||(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function C(a,b){var c,e,f,g,h=a.lastInterval||b,i=b.timeStamp-h.timeStamp;if(b.eventType!=Ha&&(i>Da||h.velocity===d)){var j=b.deltaX-h.deltaX,k=b.deltaY-h.deltaY,l=F(i,j,k);e=l.x,f=l.y,c=qa(l.x)>qa(l.y)?l.x:l.y,g=G(j,k),a.lastInterval=b}else c=h.velocity,e=h.velocityX,f=h.velocityY,g=h.direction;b.velocity=c,b.velocityX=e,b.velocityY=f,b.direction=g}function D(a){for(var b=[],c=0;c<a.pointers.length;)b[c]={clientX:pa(a.pointers[c].clientX),clientY:pa(a.pointers[c].clientY)},c++;return{timeStamp:ra(),pointers:b,center:E(b),deltaX:a.deltaX,deltaY:a.deltaY}}function E(a){var b=a.length;if(1===b)return{x:pa(a[0].clientX),y:pa(a[0].clientY)};for(var c=0,d=0,e=0;b>e;)c+=a[e].clientX,d+=a[e].clientY,e++;return{x:pa(c/b),y:pa(d/b)}}function F(a,b,c){return{x:b/a||0,y:c/a||0}}function G(a,b){return a===b?Ia:qa(a)>=qa(b)?0>a?Ja:Ka:0>b?La:Ma}function H(a,b,c){c||(c=Qa);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return Math.sqrt(d*d+e*e)}function I(a,b,c){c||(c=Qa);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return 180*Math.atan2(e,d)/Math.PI}function J(a,b){return I(b[1],b[0],Ra)+I(a[1],a[0],Ra)}function K(a,b){return H(b[0],b[1],Ra)/H(a[0],a[1],Ra)}function L(){this.evEl=Ta,this.evWin=Ua,this.pressed=!1,x.apply(this,arguments)}function M(){this.evEl=Xa,this.evWin=Ya,x.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function N(){this.evTarget=$a,this.evWin=_a,this.started=!1,x.apply(this,arguments)}function O(a,b){var c=s(a.touches),d=s(a.changedTouches);return b&(Ga|Ha)&&(c=t(c.concat(d),"identifier",!0)),[c,d]}function P(){this.evTarget=bb,this.targetIds={},x.apply(this,arguments)}function Q(a,b){var c=s(a.touches),d=this.targetIds;if(b&(Ea|Fa)&&1===c.length)return d[c[0].identifier]=!0,[c,c];var e,f,g=s(a.changedTouches),h=[],i=this.target;if(f=c.filter(function(a){return o(a.target,i)}),b===Ea)for(e=0;e<f.length;)d[f[e].identifier]=!0,e++;for(e=0;e<g.length;)d[g[e].identifier]&&h.push(g[e]),b&(Ga|Ha)&&delete d[g[e].identifier],e++;return h.length?[t(f.concat(h),"identifier",!0),h]:void 0}function R(){x.apply(this,arguments);var a=j(this.handler,this);this.touch=new P(this.manager,a),this.mouse=new L(this.manager,a),this.primaryTouch=null,this.lastTouches=[]}function S(a,b){a&Ea?(this.primaryTouch=b.changedPointers[0].identifier,T.call(this,b)):a&(Ga|Ha)&&T.call(this,b)}function T(a){var b=a.changedPointers[0];if(b.identifier===this.primaryTouch){var c={x:b.clientX,y:b.clientY};this.lastTouches.push(c);var d=this.lastTouches,e=function(){var a=d.indexOf(c);a>-1&&d.splice(a,1)};setTimeout(e,cb)}}function U(a){for(var b=a.srcEvent.clientX,c=a.srcEvent.clientY,d=0;d<this.lastTouches.length;d++){var e=this.lastTouches[d],f=Math.abs(b-e.x),g=Math.abs(c-e.y);if(db>=f&&db>=g)return!0}return!1}function V(a,b){this.manager=a,this.set(b)}function W(a){if(p(a,jb))return jb;var b=p(a,kb),c=p(a,lb);return b&&c?jb:b||c?b?kb:lb:p(a,ib)?ib:hb}function X(){if(!fb)return!1;var b={},c=a.CSS&&a.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(d){b[d]=c?a.CSS.supports("touch-action",d):!0}),b}function Y(a){this.options=la({},this.defaults,a||{}),this.id=v(),this.manager=null,this.options.enable=l(this.options.enable,!0),this.state=nb,this.simultaneous={},this.requireFail=[]}function Z(a){return a&sb?"cancel":a&qb?"end":a&pb?"move":a&ob?"start":""}function $(a){return a==Ma?"down":a==La?"up":a==Ja?"left":a==Ka?"right":""}function _(a,b){var c=b.manager;return c?c.get(a):a}function aa(){Y.apply(this,arguments)}function ba(){aa.apply(this,arguments),this.pX=null,this.pY=null}function ca(){aa.apply(this,arguments)}function da(){Y.apply(this,arguments),this._timer=null,this._input=null}function ea(){aa.apply(this,arguments)}function fa(){aa.apply(this,arguments)}function ga(){Y.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function ha(a,b){return b=b||{},b.recognizers=l(b.recognizers,ha.defaults.preset),new ia(a,b)}function ia(a,b){this.options=la({},ha.defaults,b||{}),this.options.inputTarget=this.options.inputTarget||a,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=a,this.input=y(this),this.touchAction=new V(this,this.options.touchAction),ja(this,!0),g(this.options.recognizers,function(a){var b=this.add(new a[0](a[1]));a[2]&&b.recognizeWith(a[2]),a[3]&&b.requireFailure(a[3])},this)}function ja(a,b){var c=a.element;if(c.style){var d;g(a.options.cssProps,function(e,f){d=u(c.style,f),b?(a.oldCssProps[d]=c.style[d],c.style[d]=e):c.style[d]=a.oldCssProps[d]||""}),b||(a.oldCssProps={})}}function ka(a,c){var d=b.createEvent("Event");d.initEvent(a,!0,!0),d.gesture=c,c.target.dispatchEvent(d)}var la,ma=["","webkit","Moz","MS","ms","o"],na=b.createElement("div"),oa="function",pa=Math.round,qa=Math.abs,ra=Date.now;la="function"!=typeof Object.assign?function(a){if(a===d||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var e=arguments[c];if(e!==d&&null!==e)for(var f in e)e.hasOwnProperty(f)&&(b[f]=e[f])}return b}:Object.assign;var sa=h(function(a,b,c){for(var e=Object.keys(b),f=0;f<e.length;)(!c||c&&a[e[f]]===d)&&(a[e[f]]=b[e[f]]),f++;return a},"extend","Use `assign`."),ta=h(function(a,b){return sa(a,b,!0)},"merge","Use `assign`."),ua=1,va=/mobile|tablet|ip(ad|hone|od)|android/i,wa="ontouchstart"in a,xa=u(a,"PointerEvent")!==d,ya=wa&&va.test(navigator.userAgent),za="touch",Aa="pen",Ba="mouse",Ca="kinect",Da=25,Ea=1,Fa=2,Ga=4,Ha=8,Ia=1,Ja=2,Ka=4,La=8,Ma=16,Na=Ja|Ka,Oa=La|Ma,Pa=Na|Oa,Qa=["x","y"],Ra=["clientX","clientY"];x.prototype={handler:function(){},init:function(){this.evEl&&m(this.element,this.evEl,this.domHandler),this.evTarget&&m(this.target,this.evTarget,this.domHandler),this.evWin&&m(w(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&n(this.element,this.evEl,this.domHandler),this.evTarget&&n(this.target,this.evTarget,this.domHandler),this.evWin&&n(w(this.element),this.evWin,this.domHandler)}};var Sa={mousedown:Ea,mousemove:Fa,mouseup:Ga},Ta="mousedown",Ua="mousemove mouseup";i(L,x,{handler:function(a){var b=Sa[a.type];b&Ea&&0===a.button&&(this.pressed=!0),b&Fa&&1!==a.which&&(b=Ga),this.pressed&&(b&Ga&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:Ba,srcEvent:a}))}});var Va={pointerdown:Ea,pointermove:Fa,pointerup:Ga,pointercancel:Ha,pointerout:Ha},Wa={2:za,3:Aa,4:Ba,5:Ca},Xa="pointerdown",Ya="pointermove pointerup pointercancel";a.MSPointerEvent&&!a.PointerEvent&&(Xa="MSPointerDown",Ya="MSPointerMove MSPointerUp MSPointerCancel"),i(M,x,{handler:function(a){var b=this.store,c=!1,d=a.type.toLowerCase().replace("ms",""),e=Va[d],f=Wa[a.pointerType]||a.pointerType,g=f==za,h=r(b,a.pointerId,"pointerId");e&Ea&&(0===a.button||g)?0>h&&(b.push(a),h=b.length-1):e&(Ga|Ha)&&(c=!0),0>h||(b[h]=a,this.callback(this.manager,e,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),c&&b.splice(h,1))}});var Za={touchstart:Ea,touchmove:Fa,touchend:Ga,touchcancel:Ha},$a="touchstart",_a="touchstart touchmove touchend touchcancel";i(N,x,{handler:function(a){var b=Za[a.type];if(b===Ea&&(this.started=!0),this.started){var c=O.call(this,a,b);b&(Ga|Ha)&&c[0].length-c[1].length===0&&(this.started=!1),this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:za,srcEvent:a})}}});var ab={touchstart:Ea,touchmove:Fa,touchend:Ga,touchcancel:Ha},bb="touchstart touchmove touchend touchcancel";i(P,x,{handler:function(a){var b=ab[a.type],c=Q.call(this,a,b);c&&this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:za,srcEvent:a})}});var cb=2500,db=25;i(R,x,{handler:function(a,b,c){var d=c.pointerType==za,e=c.pointerType==Ba;if(!(e&&c.sourceCapabilities&&c.sourceCapabilities.firesTouchEvents)){if(d)S.call(this,b,c);else if(e&&U.call(this,c))return;this.callback(a,b,c)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var eb=u(na.style,"touchAction"),fb=eb!==d,gb="compute",hb="auto",ib="manipulation",jb="none",kb="pan-x",lb="pan-y",mb=X();V.prototype={set:function(a){a==gb&&(a=this.compute()),fb&&this.manager.element.style&&mb[a]&&(this.manager.element.style[eb]=a),this.actions=a.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var a=[];return g(this.manager.recognizers,function(b){k(b.options.enable,[b])&&(a=a.concat(b.getTouchAction()))}),W(a.join(" "))},preventDefaults:function(a){var b=a.srcEvent,c=a.offsetDirection;if(this.manager.session.prevented)return void b.preventDefault();var d=this.actions,e=p(d,jb)&&!mb[jb],f=p(d,lb)&&!mb[lb],g=p(d,kb)&&!mb[kb];if(e){var h=1===a.pointers.length,i=a.distance<2,j=a.deltaTime<250;if(h&&i&&j)return}return g&&f?void 0:e||f&&c&Na||g&&c&Oa?this.preventSrc(b):void 0},preventSrc:function(a){this.manager.session.prevented=!0,a.preventDefault()}};var nb=1,ob=2,pb=4,qb=8,rb=qb,sb=16,tb=32;Y.prototype={defaults:{},set:function(a){return la(this.options,a),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(a){if(f(a,"recognizeWith",this))return this;var b=this.simultaneous;return a=_(a,this),b[a.id]||(b[a.id]=a,a.recognizeWith(this)),this},dropRecognizeWith:function(a){return f(a,"dropRecognizeWith",this)?this:(a=_(a,this),delete this.simultaneous[a.id],this)},requireFailure:function(a){if(f(a,"requireFailure",this))return this;var b=this.requireFail;return a=_(a,this),-1===r(b,a)&&(b.push(a),a.requireFailure(this)),this},dropRequireFailure:function(a){if(f(a,"dropRequireFailure",this))return this;a=_(a,this);var b=r(this.requireFail,a);return b>-1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(a){function b(b){c.manager.emit(b,a)}var c=this,d=this.state;qb>d&&b(c.options.event+Z(d)),b(c.options.event),a.additionalEvent&&b(a.additionalEvent),d>=qb&&b(c.options.event+Z(d))},tryEmit:function(a){return this.canEmit()?this.emit(a):void(this.state=tb)},canEmit:function(){for(var a=0;a<this.requireFail.length;){if(!(this.requireFail[a].state&(tb|nb)))return!1;a++}return!0},recognize:function(a){var b=la({},a);return k(this.options.enable,[this,b])?(this.state&(rb|sb|tb)&&(this.state=nb),this.state=this.process(b),void(this.state&(ob|pb|qb|sb)&&this.tryEmit(b))):(this.reset(),void(this.state=tb))},process:function(a){},getTouchAction:function(){},reset:function(){}},i(aa,Y,{defaults:{pointers:1},attrTest:function(a){var b=this.options.pointers;return 0===b||a.pointers.length===b},process:function(a){var b=this.state,c=a.eventType,d=b&(ob|pb),e=this.attrTest(a);return d&&(c&Ha||!e)?b|sb:d||e?c&Ga?b|qb:b&ob?b|pb:ob:tb}}),i(ba,aa,{defaults:{event:"pan",threshold:10,pointers:1,direction:Pa},getTouchAction:function(){var a=this.options.direction,b=[];return a&Na&&b.push(lb),a&Oa&&b.push(kb),b},directionTest:function(a){var b=this.options,c=!0,d=a.distance,e=a.direction,f=a.deltaX,g=a.deltaY;return e&b.direction||(b.direction&Na?(e=0===f?Ia:0>f?Ja:Ka,c=f!=this.pX,d=Math.abs(a.deltaX)):(e=0===g?Ia:0>g?La:Ma,c=g!=this.pY,d=Math.abs(a.deltaY))),a.direction=e,c&&d>b.threshold&&e&b.direction},attrTest:function(a){return aa.prototype.attrTest.call(this,a)&&(this.state&ob||!(this.state&ob)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=$(a.direction);b&&(a.additionalEvent=this.options.event+b),this._super.emit.call(this,a)}}),i(ca,aa,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[jb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||this.state&ob)},emit:function(a){if(1!==a.scale){var b=a.scale<1?"in":"out";a.additionalEvent=this.options.event+b}this._super.emit.call(this,a)}}),i(da,Y,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[hb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime>b.time;if(this._input=a,!d||!c||a.eventType&(Ga|Ha)&&!f)this.reset();else if(a.eventType&Ea)this.reset(),this._timer=e(function(){this.state=rb,this.tryEmit()},b.time,this);else if(a.eventType&Ga)return rb;return tb},reset:function(){clearTimeout(this._timer)},emit:function(a){this.state===rb&&(a&&a.eventType&Ga?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=ra(),this.manager.emit(this.options.event,this._input)))}}),i(ea,aa,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[jb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||this.state&ob)}}),i(fa,aa,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:Na|Oa,pointers:1},getTouchAction:function(){return ba.prototype.getTouchAction.call(this)},attrTest:function(a){var b,c=this.options.direction;return c&(Na|Oa)?b=a.overallVelocity:c&Na?b=a.overallVelocityX:c&Oa&&(b=a.overallVelocityY),this._super.attrTest.call(this,a)&&c&a.offsetDirection&&a.distance>this.options.threshold&&a.maxPointers==this.options.pointers&&qa(b)>this.options.velocity&&a.eventType&Ga},emit:function(a){var b=$(a.offsetDirection);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),i(ga,Y,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[ib]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime<b.time;if(this.reset(),a.eventType&Ea&&0===this.count)return this.failTimeout();if(d&&f&&c){if(a.eventType!=Ga)return this.failTimeout();var g=this.pTime?a.timeStamp-this.pTime<b.interval:!0,h=!this.pCenter||H(this.pCenter,a.center)<b.posThreshold;this.pTime=a.timeStamp,this.pCenter=a.center,h&&g?this.count+=1:this.count=1,this._input=a;var i=this.count%b.taps;if(0===i)return this.hasRequireFailures()?(this._timer=e(function(){this.state=rb,this.tryEmit()},b.interval,this),ob):rb}return tb},failTimeout:function(){return this._timer=e(function(){this.state=tb},this.options.interval,this),tb},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==rb&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),ha.VERSION="2.0.8",ha.defaults={domEvents:!1,touchAction:gb,enable:!0,inputTarget:null,inputClass:null,preset:[[ea,{enable:!1}],[ca,{enable:!1},["rotate"]],[fa,{direction:Na}],[ba,{direction:Na},["swipe"]],[ga],[ga,{event:"doubletap",taps:2},["tap"]],[da]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var ub=1,vb=2;ia.prototype={set:function(a){return la(this.options,a),a.touchAction&&this.touchAction.update(),a.inputTarget&&(this.input.destroy(),this.input.target=a.inputTarget,this.input.init()),this},stop:function(a){this.session.stopped=a?vb:ub},recognize:function(a){var b=this.session;if(!b.stopped){this.touchAction.preventDefaults(a);var c,d=this.recognizers,e=b.curRecognizer;(!e||e&&e.state&rb)&&(e=b.curRecognizer=null);for(var f=0;f<d.length;)c=d[f],b.stopped===vb||e&&c!=e&&!c.canRecognizeWith(e)?c.reset():c.recognize(a),!e&&c.state&(ob|pb|qb)&&(e=b.curRecognizer=c),f++}},get:function(a){if(a instanceof Y)return a;for(var b=this.recognizers,c=0;c<b.length;c++)if(b[c].options.event==a)return b[c];return null},add:function(a){if(f(a,"add",this))return this;var b=this.get(a.options.event);return b&&this.remove(b),this.recognizers.push(a),a.manager=this,this.touchAction.update(),a},remove:function(a){if(f(a,"remove",this))return this;if(a=this.get(a)){var b=this.recognizers,c=r(b,a);-1!==c&&(b.splice(c,1),this.touchAction.update())}return this},on:function(a,b){if(a!==d&&b!==d){var c=this.handlers;return g(q(a),function(a){c[a]=c[a]||[],c[a].push(b)}),this}},off:function(a,b){if(a!==d){var c=this.handlers;return g(q(a),function(a){b?c[a]&&c[a].splice(r(c[a],b),1):delete c[a]}),this}},emit:function(a,b){this.options.domEvents&&ka(a,b);var c=this.handlers[a]&&this.handlers[a].slice();if(c&&c.length){b.type=a,b.preventDefault=function(){b.srcEvent.preventDefault()};for(var d=0;d<c.length;)c[d](b),d++}},destroy:function(){this.element&&ja(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},la(ha,{INPUT_START:Ea,INPUT_MOVE:Fa,INPUT_END:Ga,INPUT_CANCEL:Ha,STATE_POSSIBLE:nb,STATE_BEGAN:ob,STATE_CHANGED:pb,STATE_ENDED:qb,STATE_RECOGNIZED:rb,STATE_CANCELLED:sb,STATE_FAILED:tb,DIRECTION_NONE:Ia,DIRECTION_LEFT:Ja,DIRECTION_RIGHT:Ka,DIRECTION_UP:La,DIRECTION_DOWN:Ma,DIRECTION_HORIZONTAL:Na,DIRECTION_VERTICAL:Oa,DIRECTION_ALL:Pa,Manager:ia,Input:x,TouchAction:V,TouchInput:P,MouseInput:L,PointerEventInput:M,TouchMouseInput:R,SingleTouchInput:N,Recognizer:Y,AttrRecognizer:aa,Tap:ga,Pan:ba,Swipe:fa,Pinch:ca,Rotate:ea,Press:da,on:m,off:n,each:g,merge:ta,extend:sa,assign:la,inherit:i,bindFn:j,prefixed:u});var wb="undefined"!=typeof a?a:"undefined"!=typeof self?self:{};wb.Hammer=ha,"function"==typeof define&&define.amd?define(function(){return ha}):"undefined"!=typeof module&&module.exports?module.exports=ha:a[c]=ha}(window,document,"Hammer");
|
const express = require('express')
const auth = require('../../middlewares/auth')
const validate = require('../../middlewares/validate')
const userValidation = require('../../validations/user.validation')
const userController = require('../../controllers/user.controller')
const router = express.Router()
router
.route('/')
.post(auth('manageUsers'), validate(userValidation.createUser), userController.createUser)
.get(auth('getUsers'), validate(userValidation.getUsers), userController.getUsers)
router.route('/me').get(auth(), userController.getCurrentUser)
router
.route('/:userId')
.get(auth('getUsers'), validate(userValidation.getUser), userController.getUser)
.patch(auth('manageUsers'), validate(userValidation.updateUser), userController.updateUser)
.delete(auth('manageUsers'), validate(userValidation.deleteUser), userController.deleteUser)
module.exports = router
/**
* @swagger
* tags:
* name: Users
* description: User management and retrieval
*/
/**
* @swagger
* path:
* /users:
* post:
* summary: Create a user
* description: Only admins can create other users.
* tags: [Users]
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* - email
* - password
* - role
* properties:
* name:
* type: string
* email:
* type: string
* format: email
* description: must be unique
* password:
* type: string
* format: password
* minLength: 8
* description: At least one number and one letter
* role:
* type: string
* enum: [user, admin]
* example:
* name: fake name
* email: fake@example.com
* password: password1
* role: user
* responses:
* "201":
* description: Created
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "400":
* $ref: '#/components/responses/DuplicateEmail'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*
* get:
* summary: Get all users
* description: Only admins can retrieve all users.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: name
* schema:
* type: string
* description: User name
* - in: query
* name: role
* schema:
* type: string
* description: User role
* - in: query
* name: sortBy
* schema:
* type: string
* description: sort by query in the form of field:desc/asc (ex. name:asc)
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* default: 10
* description: Maximum number of users
* - in: query
* name: page
* schema:
* type: integer
* minimum: 1
* default: 1
* description: Page number
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* type: object
* properties:
* results:
* type: array
* items:
* $ref: '#/components/schemas/User'
* page:
* type: integer
* example: 1
* limit:
* type: integer
* example: 10
* totalPages:
* type: integer
* example: 1
* totalResults:
* type: integer
* example: 1
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*/
/**
* @swagger
* path:
* /users/me:
* get:
* summary: Get a user
* description: Logged in users can fetch only their own user information. Only admins can fetch other users.
* tags: [Users]
* security:
* - bearerAuth: []
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*/
/**
* @swagger
* path:
* /users/{id}:
* get:
* summary: Get a user
* description: Logged in users can fetch only their own user information. Only admins can fetch other users.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* patch:
* summary: Update a user
* description: Logged in users can only update their own information. Only admins can update other users.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* email:
* type: string
* format: email
* description: must be unique
* password:
* type: string
* format: password
* minLength: 8
* description: At least one number and one letter
* example:
* name: fake name
* email: fake@example.com
* password: password1
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "400":
* $ref: '#/components/responses/DuplicateEmail'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* delete:
* summary: Delete a user
* description: Logged in users can delete only themselves. Only admins can delete other users.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* responses:
* "200":
* description: No content
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*/
|