text
stringlengths
27
775k
# A sample frontend app built on top of Ruby and Sinatra. It returns HTML. require 'sinatra' require 'open-uri' if ARGV.length != 3 raise 'Expected exactly three arguments: SERVER_PORT SERVER_TEXT BACKEND_URL' end server_port = ARGV[0] server_text = ARGV[1] backend_url = ARGV[2] set :port, server_port set :bind, '0.0.0.0' get '/' do content_type :html open(backend_url) do |content| "<h1>#{server_text}</h1><p>Response from backend:</p><pre>#{content.read.to_s}</pre>" end end
<?php namespace App\Http\Controllers\Admin\Auth; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Requests\Admin\RegistrationCMSUsers; use App\Http\Controllers\Controller; class IndexController extends Controller { /* * Display login form to admin */ public function login() { return view('admin.auth.login'); } /* * Display registration form to admin */ public function registration() { return view('admin.auth.registration'); } /* * Registration new user in storkCMS - not in website! */ public function registrationProceed(RegistrationCMSUsers $request){ $dataUser = $request->all(); $dataUser['password'] = Hash::make($dataUser['password']); $data = ['status' => 'success', 'message' => 'test']; return response()->json($data); } }
from json.decoder import JSONDecodeError import os from mstrio.utils.helper import exception_handler def print_url(response, *args, **kwargs): """Response hook to print url for debugging.""" print(response.url) def save_response(response, *args, **kwargs): """Response hook to save REST API responses to files structured by the API family.""" import json from pathlib import Path if response.status_code != 204: # Generate file name base_path = Path(__file__).parents[2] / 'tests/resources/auto-api-responses/' url = response.url.rsplit('api/', 1)[1] temp_path = url.split('/') file_name = '-'.join(temp_path[1:]) if len(temp_path) > 1 else temp_path[0] file_name = f'{file_name}-{response.request.method}' file_path = base_path if len(temp_path) == 1 else base_path / temp_path[0] path = str(file_path / file_name) # Create target directory & all intermediate directories if don't exists if not os.path.exists(str(file_path)): os.makedirs(file_path) print("Directory ", file_path, " created ") else: print("Directory ", file_path, " already exists") # Dump the response to JSON and Pickle # with open(path + '.pkl', 'wb') as f: # pickle.dump(response, f) with open(path + '.json', 'w') as f: try: json.dump(response.json(), f) except JSONDecodeError: exception_handler("Could not decode response. Skipping creating JSON file.", Warning)
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; typedef void UnityWidgetCreatedCallback(UnityWidgetController controller); class UnityWidgetController { final _UnityWidgetState _unityWidgetState; final MethodChannel channel; UnityWidgetController._( this.channel, this._unityWidgetState, ) { channel.setMethodCallHandler(_handleMethod); } static UnityWidgetController init( int id, _UnityWidgetState unityWidgetState) { final MethodChannel channel = MethodChannel('unity_view_$id'); return UnityWidgetController._( channel, unityWidgetState, ); } Future<bool> isReady() async { final bool isReady = await channel.invokeMethod('isReady'); return isReady; } Future<bool> createUnity() async { final bool isReady = await channel.invokeMethod('createUnity'); return isReady; } postMessage(String gameObject, methodName, message) { channel.invokeMethod('postMessage', <String, dynamic>{ 'gameObject': gameObject, 'methodName': methodName, 'message': message, }); } pause() async { print('Pressed paused'); await channel.invokeMethod('pause'); } resume() async { await channel.invokeMethod('resume'); } unload() async { await channel.invokeMethod('unload'); } Future<void> _dispose() async { await channel.invokeMethod('dispose'); } Future<dynamic> _handleMethod(MethodCall call) async { switch (call.method) { case "onUnityMessage": if (_unityWidgetState.widget != null) { _unityWidgetState.widget.onUnityMessage(this, call.arguments); } break; default: throw UnimplementedError("Unimplemented ${call.method} method"); } } } typedef onUnityMessageCallback = void Function( UnityWidgetController controller, dynamic handler); class UnityWidget extends StatefulWidget { final UnityWidgetCreatedCallback onUnityViewCreated; ///Event fires when the [UnityWidget] gets a message from unity. final onUnityMessageCallback onUnityMessage; final bool isARScene; UnityWidget( {Key key, @required this.onUnityViewCreated, this.onUnityMessage, this.isARScene = false}); @override _UnityWidgetState createState() => _UnityWidgetState(); } class _UnityWidgetState extends State<UnityWidget> { UnityWidgetController _controller; @override void initState() { // widget.controller = super.initState(); } @override void dispose() { super.dispose(); if (_controller != null) { _controller._dispose(); _controller = null; } } @override Widget build(BuildContext context) { final Map<String, dynamic> creationParams = <String, dynamic>{ 'ar': widget.isARScene, }; if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: 'unity_view', onPlatformViewCreated: _onPlatformViewCreated, creationParamsCodec: const StandardMessageCodec(), creationParams: creationParams, ); } else if (defaultTargetPlatform == TargetPlatform.iOS) { return UiKitView( viewType: 'unity_view', onPlatformViewCreated: _onPlatformViewCreated, creationParamsCodec: const StandardMessageCodec(), ); } return new Text( '$defaultTargetPlatform is not yet supported by this plugin'); } @override void didUpdateWidget(UnityWidget oldWidget) { super.didUpdateWidget(oldWidget); } void _onPlatformViewCreated(int id) { _controller = UnityWidgetController.init(id, this); if (widget.onUnityViewCreated != null) { widget.onUnityViewCreated(_controller); } print('********************************************'); print('Controller setup complete'); print('********************************************'); } }
# -*- coding: utf-8 -*- import logging import os import sys import fnmatch import weakref from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.Qt import QTabWidget, QTextEdit from PyQt5.QtCore import QIODevice, qWarning, QTextStream from pineboolib.fllegacy import FLFormSearchDB as FLFormSearchDB_legacy from pineboolib.flcontrols import FLTable from pineboolib.fllegacy import FLSqlQuery as FLSqlQuery_Legacy from pineboolib.fllegacy import FLSqlCursor as FLSqlCursor_Legacy from pineboolib.fllegacy import FLTableDB as FLTableDB_Legacy from pineboolib.fllegacy import FLFieldDB as FLFieldDB_Legacy from pineboolib.fllegacy import FLUtil as FLUtil_Legacy from pineboolib.fllegacy import FLReportViewer as FLReportViewer_Legacy from pineboolib.fllegacy import AQObjects from pineboolib.fllegacy.FLPosPrinter import FLPosPrinter as FLPosPrinter_Legacy import pineboolib from pineboolib.utils import filedir from pineboolib import decorators import traceback from PyQt5.Qt import QWidget # Cargar toda la API de Qt para que sea visible. from PyQt5.QtGui import * # noqa from PyQt5.QtCore import * # noqa from PyQt5.QtXml import QDomDocument String = str class StructMyDict(dict): def __getattr__(self, name): try: return self[name] except KeyError as e: raise AttributeError(e) def __setattr__(self, name, value): self[name] = value def Function(args, source): # Leer código QS embebido en Source # asumir que es una funcion anónima, tal que: # -> function($args) { source } # compilar la funcion y devolver el puntero qs_source = """ function anon(%s) { %s } """ % (args, source) print("Compilando QS en línea: ", qs_source) from pineboolib.flparser import flscriptparse from pineboolib.flparser import postparse from pineboolib.flparser.pytnyzer import write_python_file, string_template import io prog = flscriptparse.parse(qs_source) tree_data = flscriptparse.calctree(prog, alias_mode=0) ast = postparse.post_parse(tree_data) tpl = string_template f1 = io.StringIO() write_python_file(f1, ast, tpl) pyprog = f1.getvalue() print("Resultado: ", pyprog) glob = {} loc = {} exec(pyprog, glob, loc) # ... y lo peor es que funciona. W-T-F. # return loc["anon"] return getattr(loc["FormInternalObj"], "anon") def Object(x=None): if x is None: x = {} return StructMyDict(x) # def Array(x=None): # try: # if x is None: return {} # else: return list(x) # except TypeError: # return [x] class Array(object): dict_ = None key_ = None names_ = None def __init__(self, *args): self.names_ = [] self.dict_ = {} if not len(args): return elif isinstance(args[0], int) and len(args) == 1: return elif isinstance(args[0], list): for field in args[0]: self.names_.append(field) self.dict_[field] = field elif isinstance(args[0], str): for f in args: self.__setitem__(f, f) else: self.dict_ = args def __setitem__(self, key, value): # if isinstance(key, int): # key = str(key) if key not in self.names_: self.names_.append(key) self.dict_[key] = value def __getitem__(self, key): if isinstance(key, int): return self.dict_[self.names_[key]] else: # print("QSATYPE.DEBUG: Array.getItem() " ,key, self.dict_[key]) return self.dict_[key] def __getattr__(self, k): if k == 'length': return len(self.dict_) else: return self.dict_[k] def __len__(self): len_ = 0 for l in self.dict_: len_ = len_ + 1 return len_ def Boolean(x=False): return bool(x) def FLSqlQuery(*args): # if not args: return None query_ = FLSqlQuery_Legacy.FLSqlQuery(*args) return query_ def FLUtil(*args): return FLUtil_Legacy.FLUtil(*args) def AQUtil(*args): return FLUtil_Legacy.FLUtil(*args) def AQSql(*args): return AQObjects.AQSql(*args) def FLSqlCursor(action=None, cN=None): if action is None: return None return FLSqlCursor_Legacy.FLSqlCursor(action, True, cN) def FLTableDB(*args): if not args: return None return FLTableDB_Legacy.FLTableDB(*args) FLListViewItem = QtWidgets.QListView FLDomDocument = QDomDocument QTable = FLTable Color = QtGui.QColor QColor = QtGui.QColor QDateEdit = QtWidgets.QDateEdit def FLPosPrinter(*args, **kwargs): return FLPosPrinter_Legacy() @decorators.BetaImplementation def FLReportViewer(): return FLReportViewer_Legacy.FLReportViewer() """ class FLDomDocument(object): parser = None tree = None root_ = None string_ = None def __init__(self): self.parser = etree.XMLParser(recover=True, encoding='utf-8') self.string_ = None def setContent(self, value): try: self.string_ = value if value.startswith('<?'): value = re.sub(r'^\<\?.*?\?\>','', value, flags=re.DOTALL) self.tree = etree.fromstring(value, self.parser) #self.root_ = self.tree.getroot() return True except: return False def namedItem(self, name): return u"<%s" % name in self.string_ def toString(self, value = None): return self.string_ """ def FLCodBar(*args): from pineboolib.fllegacy.FLCodBar import FLCodBar as FLCodBar_Legacy return FLCodBar_Legacy(*args) def FLNetwork(*args): from pineboolib.fllegacy.FLNetwork import FLNetwork as FLNetwork_Legacy return FLNetwork_Legacy(*args) def print_stack(maxsize=1): for tb in traceback.format_list(traceback.extract_stack())[1:-2][-maxsize:]: print(tb.rstrip()) def check_gc_referrers(typename, w_obj, name): import threading import time def checkfn(): import gc time.sleep(2) gc.collect() obj = w_obj() if not obj: return # TODO: Si ves el mensaje a continuación significa que "algo" ha dejado # ..... alguna referencia a un formulario (o similar) que impide que se destruya # ..... cuando se deja de usar. Causando que los connects no se destruyan tampoco # ..... y que se llamen referenciando al código antiguo y fallando. print("HINT: Objetos referenciando %r::%r (%r) :" % (typename, obj, name)) for ref in gc.get_referrers(obj): if isinstance(ref, dict): x = [] for k, v in ref.items(): if v is obj: k = "(**)" + k x.insert(0, k) print(" - dict:", repr(x), gc.get_referrers(ref)) else: if "<frame" in str(repr(ref)): continue print(" - obj:", repr(ref), [x for x in dir(ref) if getattr(ref, x) is obj]) threading.Thread(target=checkfn).start() class FormDBWidget(QtWidgets.QWidget): closed = QtCore.pyqtSignal() cursor_ = None parent_ = None logger = logging.getLogger("qsatype.FormDBWidget") def __init__(self, action, project, parent=None): if not pineboolib.project._DGI.useDesktop(): self._class_init() return if pineboolib.project._DGI.localDesktop(): self.remote_widgets = {} super(FormDBWidget, self).__init__(parent) self._module = sys.modules[self.__module__] self._module.connect = self._connect self._module.disconnect = self._disconnect self._action = action self.cursor_ = None self.parent_ = parent self._formconnections = set([]) self._prj = project try: self._class_init() # timer = QtCore.QTimer(self) # timer.singleShot(250, self.init) self.init() except Exception: self.logger.exception("Error al inicializar la clase iface de QS:") def _connect(self, sender, signal, receiver, slot): print(" > > > connect:", self) from pineboolib.qsaglobals import connect signal_slot = connect(sender, signal, receiver, slot, caller=self) if not signal_slot: return False self._formconnections.add(signal_slot) def _disconnect(self, sender, signal, receiver, slot): print(" > > > disconnect:", self) from pineboolib.qsaglobals import disconnect signal_slot = disconnect(sender, signal, receiver, slot, caller=self) if not signal_slot: return False try: self._formconnections.remove(signal_slot) except KeyError: self.logger.exception("Error al eliminar una señal que no se encuentra") def __del__(self): self.doCleanUp() print("FormDBWidget: Borrando form para accion %r" % self._action.name) def obj(self): return self def parent(self): return self.parent_ def _class_init(self): """Constructor de la clase QS (p.ej. interna(context))""" pass def init(self): """Evento init del motor. Llama a interna_init en el QS""" pass def closeEvent(self, event): can_exit = True print("FormDBWidget: closeEvent para accion %r" % self._action.name) check_gc_referrers("FormDBWidget:" + self.__class__.__name__, weakref.ref(self), self._action.name) if can_exit: self.closed.emit() event.accept() # let the window close self.doCleanUp() else: event.ignore() return def doCleanUp(self): # Limpiar todas las conexiones hechas en el script for signal, slot in self._formconnections: try: signal.disconnect(slot) self.logger.info("Señal desconectada al limpiar: %s %s", signal, slot) except Exception: self.logger.exception("Error al limpiar una señal: %s %s", signal, slot) self._formconnections.clear() if hasattr(self, 'iface'): check_gc_referrers("FormDBWidget.iface:" + self.iface.__class__.__name__, weakref.ref(self.iface), self._action.name) del self.iface.ctx del self.iface def child(self, childName): try: parent = self ret = None while parent and not ret: ret = parent.findChild(QtWidgets.QWidget, childName) if not ret: parent = parent.parentWidget() except RuntimeError as rte: # FIXME: A veces intentan buscar un control que ya está siendo eliminado. # ... por lo que parece, al hacer el close del formulario no se desconectan sus señales. print("ERROR: Al buscar el control %r encontramos el error %r" % (childName, rte)) print_stack(8) import gc gc.collect() print("HINT: Objetos referenciando FormDBWidget::%r (%r) : %r" % (self, self._action.name, gc.get_referrers(self))) if hasattr(self, 'iface'): print("HINT: Objetos referenciando FormDBWidget.iface::%r : %r" % ( self.iface, gc.get_referrers(self.iface))) ret = None else: if ret is None: qWarning("WARN: No se encontro el control %s" % childName) # Para inicializar los controles si se llaman desde qsa antes de # mostrar el formulario. if isinstance(ret, FLFieldDB_Legacy.FLFieldDB): if not ret.cursor(): ret.initCursor() if not ret.editor_ and not ret.editorImg_: ret.initEditor() if isinstance(ret, FLTableDB_Legacy.FLTableDB): if not ret.tableRecords_: ret.tableRecords() ret.setTableRecordsCursor() # else: # print("DEBUG: Encontrado el control %r: %r" % (childName, ret)) return ret def accept(self): try: self.parent_.accept() except: pass def cursor(self): # if self.cursor_: # return self.cursor_ cursor = None parent = self while not cursor and parent: parent = parent.parentWidget() cursor = getattr(parent, "cursor_", None) if cursor: self.cursor_ = cursor else: if not self.cursor_: self.cursor_ = FLSqlCursor(self._action.table) return self.cursor_ """ FIX: Cuando usamos this como cursor """ def valueBuffer(self, name): return self.cursor().valueBuffer(name) def isNull(self, name): return self.cursor().isNull(name) def table(self): return self.cursor().table() def cursorRelation(self): return self.cursor().cursorRelation() def FLFormSearchDB(name): widget = FLFormSearchDB_legacy.FLFormSearchDB(name) widget.setWindowModality(QtCore.Qt.ApplicationModal) # widget.load() widget.cursor_.setContext(widget.iface) return widget class Date(object): date_ = None time_ = None def __init__(self, date_=None): super(Date, self).__init__() if not date_: self.date_ = QtCore.QDate.currentDate() self.time_ = QtCore.QTime.currentTime() else: self.date_ = QtCore.QDate(date_) self.time_ = QtCore.QTime("00:00:00") def toString(self, *args, **kwargs): texto = "%s-%s-%sT%s:%s:%s" % (self.date_.toString("dd"), self.date_.toString("MM"), self.date_.toString( "yyyy"), self.time_.toString("hh"), self.time_.toString("mm"), self.time_.toString("ss")) return texto def getYear(self): return self.date_.year() def getMonth(self): return self.date_.month() def getDay(self): return self.date_.day() def getHours(self): return self.time_.hour() def getMinutes(self): return self.time_.minute() def getSeconds(self): return self.time_.second() def getMilliseconds(self): return self.time_.msec() class Process(QtCore.QProcess): running = None stderr = None stdout = None def __init__(self, *args): super(Process, self).__init__() self.readyReadStandardOutput.connect(self.stdoutReady) self.readyReadStandardError.connect(self.stderrReady) self.stderr = None if args: self.runing = False self.setProgram(args[0]) argumentos = args[1:] self.setArguments(argumentos) def start(self): self.running = True super(Process, self).start() def stop(self): self.running = False super(Process, self).stop() def writeToStdin(self, stdin_): stdin_as_bytes = stdin_.encode('utf-8') self.writeData(stdin_as_bytes) # self.closeWriteChannel() def stdoutReady(self): self.stdout = str(self.readAllStandardOutput()) def stderrReady(self): self.stderr = str(self.readAllStandardError()) def __setattr__(self, name, value): if name == "workingDirectory": self.setWorkingDirectory(value) else: super(Process, self).__setattr__(name, value) def execute(comando): pro = QtCore.QProcess() array = comando.split(" ") programa = array[0] argumentos = array[1:] pro.setProgram(programa) pro.setArguments(argumentos) pro.start() pro.waitForFinished(30000) Process.stdout = pro.readAllStandardOutput() Process.stderr = pro.readAllStandardError() class RadioButton(QtWidgets.QRadioButton): def __ini__(self): super(RadioButton, self).__init__() self.setChecked(False) def __setattr__(self, name, value): if name == "text": self.setText(value) elif name == "checked": self.setChecked(value) else: super(RadioButton, self).__setattr__(name, value) def __getattr__(self, name): if name == "checked": return self.isChecked() class Dialog(QtWidgets.QDialog): _layout = None buttonBox = None okButtonText = None cancelButtonText = None okButton = None cancelButton = None _tab = None def __init__(self, title=None, f=None, desc=None): # FIXME: f no lo uso , es qt.windowsflg super(Dialog, self).__init__() if title: self.setWindowTitle(str(title)) self.setWindowModality(QtCore.Qt.ApplicationModal) self._layout = QtWidgets.QVBoxLayout() self.setLayout(self._layout) self.buttonBox = QtWidgets.QDialogButtonBox() self.okButton = QtWidgets.QPushButton("&Aceptar") self.cancelButton = QtWidgets.QPushButton("&Cancelar") self.buttonBox.addButton( self.okButton, QtWidgets.QDialogButtonBox.AcceptRole) self.buttonBox.addButton( self.cancelButton, QtWidgets.QDialogButtonBox.RejectRole) self.okButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) self._tab = QTabWidget() self._layout.addWidget(self._tab) self.oKButtonText = None self.cancelButtonText = None def add(self, _object): self._layout.addWidget(_object) def exec_(self): if self.okButtonText: self.okButton.setText(str(self.okButtonText)) if (self.cancelButtonText): self.cancelButton.setText(str(self.cancelButtonText)) self._layout.addWidget(self.buttonBox) return super(Dialog, self).exec_() def newTab(self, name): self._tab.addTab(QtWidgets.QWidget(), str(name)) def __getattr__(self, name): if name == "caption": name = self.setWindowTitle return getattr(super(Dialog, self), name) class GroupBox(QtWidgets.QGroupBox): def __init__(self): super(GroupBox, self).__init__() self._layout = QtWidgets.QVBoxLayout() self.setLayout(self._layout) def add(self, _object): self._layout.addWidget(_object) def __setattr__(self, name, value): if name == "title": self.setTitle(str(value)) else: super(GroupBox, self).__setattr__(name, value) class CheckBox(QWidget): _label = None _cb = None def __init__(self): super(CheckBox, self).__init__() self._label = QtWidgets.QLabel(self) self._cb = QtWidgets.QCheckBox(self) spacer = QtWidgets.QSpacerItem( 1, 1, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) _lay = QtWidgets.QHBoxLayout() _lay.addWidget(self._cb) _lay.addWidget(self._label) _lay.addSpacerItem(spacer) self.setLayout(_lay) def __setattr__(self, name, value): if name == "text": self._label.setText(str(value)) elif name == "checked": self._cb.setChecked(value) else: super(CheckBox, self).__setattr__(name, value) def __getattr__(self, name): if name == "checked": return self._cb.isChecked() else: return super(CheckBox, self).__getattr__(name) class ComboBox(QWidget): _label = None _combo = None def __init__(self): super(ComboBox, self).__init__() self._label = QtWidgets.QLabel(self) self._combo = QtWidgets.QComboBox(self) self._combo.setMinimumHeight(25) _lay = QtWidgets.QHBoxLayout() _lay.addWidget(self._label) _lay.addWidget(self._combo) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHeightForWidth(True) self._combo.setSizePolicy(sizePolicy) self.setLayout(_lay) def __setattr__(self, name, value): if name == "label": self._label.setText(str(value)) elif name == "itemList": self._combo.insertItems(len(value), value) elif name == "currentItem": self._combo.setCurrentText(str(value)) else: super(ComboBox, self).__setattr__(name, value) def __getattr__(self, name): if name == "currentItem": return self._combo.currentText() else: return super(ComboBox, self).__getattr__(name) class LineEdit(QWidget): _label = None _line = None def __init__(self): super(LineEdit, self).__init__() self._label = QtWidgets.QLabel(self) self._line = QtWidgets.QLineEdit(self) _lay = QtWidgets.QHBoxLayout() _lay.addWidget(self._label) _lay.addWidget(self._line) self.setLayout(_lay) def __setattr__(self, name, value): if name == "label": self._label.setText(str(value)) elif name == "text": self._line.setText(str(value)) else: super(LineEdit, self).__setattr__(name, value) def __getattr__(self, name): if name == "text": return self._line.text() else: return super(LineEdit, self).__getattr__(name) class Dir_Class(object): path_ = None home = None Files = "*.*" def __init__(self, path=None): self.path_ = path self.home = filedir("..") def entryList(self, patron, type_=None): # p = os.walk(self.path_) retorno = [] try: for file in os.listdir(self.path_): if fnmatch.fnmatch(file, patron): retorno.append(file) except Exception as e: print("Dir_Class.entryList:", e) return retorno def fileExists(self, name): return os.path.exists(name) def cleanDirPath(name): return str(name) Dir = Dir_Class class TextEdit(QTextEdit): pass class File(QtCore.QFile): fichero = None mode = None path = None ReadOnly = QIODevice.ReadOnly WriteOnly = QIODevice.WriteOnly ReadWrite = QIODevice.ReadWrite def __init__(self, rutaFichero): if isinstance(rutaFichero, tuple): rutaFichero = rutaFichero[0] self.fichero = str(rutaFichero) super(File, self).__init__(rutaFichero) self.path = os.path.dirname(self.fichero) # def open(self, mode): # super(File, self).open(self.fichero, mode) def read(self): if isinstance(self, str): f = File(self) f.open(File.ReadOnly) return f.read() in_ = QTextStream(self) return in_.readAll() def write(self, text): raise NotImplementedError( "File:: out_ << text not a valid Python operator") # encoding = text.property("encoding") # out_ = QTextStream(self) # out_ << text class QString(str): def mid(self, start, length=None): if length is not None: return self[start:] else: return self[start:start + length]
from gzip import GzipFile from bz2 import decompress as bz2_decompress from tempfile import NamedTemporaryFile from json import dumps import shutil from os import mkdir, unlink, path from os.path import isdir, isfile, join from Bio import Entrez, SeqIO Entrez.email = '[email protected]' import argparse import re from warnings import catch_warnings from codecs import getreader import time import random from six import BytesIO, StringIO, iteritems import jsonschema import cobra from cobra.core.gene import parse_gpr from cobra.manipulation import check_mass_balance, check_reaction_bounds, \ check_metabolite_compartment_formula from libsbml import SBMLValidator from flask import Flask, session, render_template, request, jsonify, url_for from werkzeug.exceptions import BadRequestKeyError from celery import Celery from flask_session import Session app = Flask(__name__, template_folder='.') SESSION_TYPE = 'redis' app.config.from_object(__name__) Session(app) app = Flask(__name__) app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' #initialize celery celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) FOLDER_NAME = 'genbank' if not isdir(FOLDER_NAME): mkdir(FOLDER_NAME) #else: #shutil.rmtree(FOLDER_NAME) def load_JSON(contents, filename): """returns model, [model_errors], "parse_errors" or None """ errors = [] try: model_json = contents.read().decode('utf8') except ValueError as e: return None, errors, "Invalid JSON: " + str(e) try: model = cobra.io.json.from_json(model_json) except Exception as e: errors.append("Invalid model: " + str(e)) model = None # This code is buggy. TODO fix jsonschema validation later # try: # jsonschema.validate(model_json, cobra.io.json.json_schema) # except jsonschema.ValidationError as e: # # render an infomrative error message # if len(e.absolute_path) > 0: # error_msg = "Error in " # for i in e.absolute_path: # if isinstance(i, int): # error_msg = error_msg.rstrip(".") + "[%d]." % i # else: # error_msg += str(i) + "." # errors.append(error_msg.rstrip(".") + ": " + e.message) # else: # errors.append(e.message) return model, errors, None def load_SBML(contents, filename): """returns model, [model_errors], "parse_errors" or None """ try: # this function fails if a model can not be created model, errors = cobra.io.sbml3.validate_sbml_model( contents, check_model=False) # checks are run later except cobra.io.sbml3.CobraSBMLError as e: return None, [], str(e) else: return model, errors, None def run_libsbml_validation(contents, filename): if filename.endswith(".gz"): filename = filename[:-3] elif filename.endswith(".bz2"): filename = filename[:-4] with NamedTemporaryFile(suffix=filename, delete=False) as outfile: outfile.write(contents.read()) contents.seek(0) # so the buffer can be re-read validator = SBMLValidator() validator.validate(str(outfile.name)) unlink(outfile.name) errors = [] for i in range(validator.getNumFailures()): failure = validator.getFailure(i) if failure.isWarning(): continue errors.append("L%d C%d: %s" % (failure.getLine(), failure.getColumn(), failure.getMessage())) return errors def decompress_file(body, filename): """returns BytesIO of decompressed file""" if filename.endswith(".gz"): # contents = zlib.decompress(body, 16 + zlib.MAX_WBITS) zip_contents = BytesIO(body) with GzipFile(fileobj=zip_contents, mode='rb') as zip_read: try: contents = BytesIO(zip_read.read()) except (IOError, OSError) as e: return None, "Error decompressing gzip file: " + str(e) zip_contents.close() elif filename.endswith(".bz2"): try: contents = BytesIO((bz2_decompress(body))) except IOError as e: return None, "Error decompressing bz2 file: " + str(e) else: contents = BytesIO(body.encode('utf8')) return contents, None def validate_model(model): errors = [] warnings = [] errors.extend(check_reaction_bounds(model)) errors.extend(check_metabolite_compartment_formula(model)) # test gpr for reaction in model.reactions: try: parse_gpr(reaction.gene_reaction_rule) except SyntaxError: errors.append("reaction '%s' has invalid gpr '%s'" % (reaction.id, reaction.gene_reaction_rule)) # test mass balance for reaction, balance in iteritems(check_mass_balance(model)): # check if it's a demand or exchange reaction if len(reaction.metabolites) == 1: warnings.append("reaction '%s' is not balanced. Should it " "be annotated as a demand or exchange " "reaction?" % reaction.id) elif "biomass" in reaction.id.lower(): warnings.append("reaction '%s' is not balanced. Should it " "be annotated as a biomass reaction?" % reaction.id) else: warnings.append("reaction '%s' is not balanced for %s" % (reaction.id, ", ".join(sorted(balance)))) # try solving solution = model.optimize() if solution.status != "optimal": errors.append("model can not be solved (status '%s')" % solution.status) return {"errors": errors, "warnings": warnings, "current": 0, "total": 0, "status": ''} # if there is no objective, then we know why the objective was low objectives_dict = cobra.util.solver.linear_reaction_coefficients(model) if len(objectives_dict) == 0: warnings.append("model has no objective function") elif solution.f <= 0: warnings.append("model can not produce nonzero biomass") elif solution.f <= 1e-3: warnings.append("biomass flux %s too low" % str(solution.f)) if len(objectives_dict) > 1: warnings.append("model should only have one reaction as the objective") return {"errors": errors, "warnings": warnings, "objective": solution.f, "current": 0, "total": 0, "status": ''} def gen_filepath(accession): return join(FOLDER_NAME, accession + '.gb') # def write_error(self, status_code, reason="", **kwargs): # self.write(reason) @celery.task(bind=True) def handle_uploaded_file(self, info, name, genbank_id): contents, decompress_error = decompress_file(info, name) if decompress_error: return { "errors": [decompress_error], "warnings": [], "current": 100, "total": 100, } errors = [] warnings = [] parse_errors = None if name.endswith(".json") or name.endswith(".json.gz") or name.endswith(".json.bz2"): print("im in") model, load_json_errors, load_json_parse_errors = load_JSON(contents, name) print(len(model.reactions)) print(load_json_errors) print(load_json_parse_errors) parse_errors = load_json_parse_errors else: print("diff ending") model, load_sbml_errors, load_sbml_parse_errors = load_SBML(contents, name) parse_errors = load_sbml_parse_errors libsbml_errors = run_libsbml_validation(contents, name) warnings.extend("(from libSBML) " + i for i in libsbml_errors) # if parsing failed, then send the error if parse_errors: return { "errors": parse_errors, "warnings": warnings, "current": 100, "total": 100, } if model is None: # parsed, but still could not generate model print("model failed") return { "errors": errors, # HERE? "warnings": warnings, "current": 100, "total": 100, } # model validation result = validate_model(model) self.update_state(state='PROGRESS', meta={'current': 20, 'total': 100, 'status': 'validating model'}) result["errors"].extend(errors) result["warnings"].extend(warnings) mylist = [y for y in (x.strip() for x in genbank_id.split(',')) if y != ''] model_genes = model.genes # #import IPython; IPython.embed() model_genes_id = [] for gene in model_genes: model_genes_id.append(gene.id) overallList = [] length = len(mylist) step = 70/length k = 0 counter = 1 for genID in mylist: self.update_state(state='PROGRESS', meta={'current': 30+k, 'total': 100, 'status': 'checking %d geneID and downloading corresponding genome from NCBI' %(counter)}) counter = counter + 1 print("next gene") gb_filepath = gen_filepath(genID) if not isfile(gb_filepath): dl = Entrez.efetch(db='nuccore', id=genID, rettype='gbwithparts', retmode='text') with open(gb_filepath, 'w') as outfile: outfile.write(dl.read()) dl.close() print('------------------ DONE writing') # #pseudocode gb_seq = SeqIO.read(gb_filepath, 'genbank') locus_list = [] for feature in gb_seq.features: if feature.type == 'CDS': locus_tag = feature.qualifiers.get('locus_tag', None) # [locus_tag] | None if locus_tag is not None: locus_list.append(locus_tag[0]) self.update_state(state='PROGRESS', meta={'current': 30+k+(step/3), 'total': 100, 'status': 'Retreiving the list of genes'}) #backup list gene_list = [] for feature in gb_seq.features: if feature.type == 'CDS': for i in feature: if i is 'gene': gene_list.append(i[0]) self.update_state(state='PROGRESS', meta={'current': 30+k+(0.66*step), 'total': 100, 'status': 'Checking model genes against reference genes'}) badGenes = list(set(model_genes_id) - set(locus_list)) # #backup search badGenes2 = list(set(badGenes) - set(gene_list)) genesToChange = list(set(badGenes).intersection(gene_list)) overallList = list(set(badGenes).intersection(badGenes2)) result['errors'].extend(['Model gene ' + x + ' was not found in reference genome(s)' for x in badGenes2]) k = k + step if len(genesToChange) != 0: result['warnings'].extend(['Change ' + x + ' to locus tag name' for x in genesToChange]) model_genes_id = list(set(model_genes_id) - set(locus_list)) # self.finish(result) # print('------------------ DONE getting genes') # #self.finish({ 'status': 'downloaded' }) result["current"] = 100 result["total"] = 100 return result @app.route('/status/<task_id>') def taskstatus(task_id): task = handle_uploaded_file.AsyncResult(task_id) #import IPython; IPython.embed() if task.state == 'PENDING': # job did not start yet response = { 'state': task.state, 'total': 1, 'current': 0, 'status': 'Pending...' } #or I can change this to only when its successful elif task.state != 'FAILURE': response = { 'state': task.state, 'model_warnings': task.info.get('warnings', []), 'model_errors': task.info.get('errors', []), 'total': task.info.get('total', ''), 'current': task.info.get('current', ''), 'status': task.info.get('status', '') } else: # something went wrong in the background job response = { 'state': task.state, 'current': 1, 'total': 1, 'status': str(task.info), # this is the exception raised } return jsonify(response) @app.route('/upload', methods=['POST']) def upload(): try: fileinfo = request.files['file'] geneinfo = request.form except BadRequestKeyError as e: print('Could not find file') raise e filename = fileinfo.filename gene_id = geneinfo['ncbi_accession'] print (gene_id) #data = request.form["ncbi_accession"] # option 1: synchronous, < 100ms # t = time.time() # contents, error = decompress_file(fileinfo.body, filename) # print(f'took {time.time() - t}') # option 2: synchronous with celery, < 100ms # t = time.time() # result = decompress_file.apply_async(args=(fileinfo.body, filename)) # contents, error = result.get() # print(f'took {time.time() - t}') # option 2: async within a HTTP query, < 2 seconds # contents, error = yield executor.submit( # decompress_file_fn, fileinfo["body"], filename) # option 3: task in background (actually synchronous), > 2 seconds task = handle_uploaded_file.apply_async( args=(fileinfo.stream.read().decode('utf8'), filename, gene_id) ) return jsonify({'Location': url_for('taskstatus', task_id=task.id)}) @app.route('/') def get(): return render_template('validator_form.html') if __name__ == "__main__": app.run(threaded=True, debug=True) # import argparse # parser = argparse.ArgumentParser( # description="web-based validator for COBRA models in SBML and JSON") # parser.add_argument("--port", type=int, default=5000) # parser.add_argument("--prefix", default="") # parser.add_argument("--debug", action="store_true") # args = parser.parse_args() # prefix = args.prefix # if len(prefix) > 0 and not prefix.startswith("/"): # prefix = "/" + prefix # run_standalone_server( # prefix=prefix, # port=args.port, # debug=args.debug)
package com.fuhj.itower.model; import java.util.Date; import java.util.List; import com.fuhj.itower.dao.Criteria; public class GElecInfoCriteria extends Criteria { public GElecInfoCriteria andGelecInfoIdIsNull() { addCriterion("gelec_info_id is null"); return this; } public GElecInfoCriteria andGelecInfoIdIsNotNull() { addCriterion("gelec_info_id is not null"); return this; } public GElecInfoCriteria andGelecInfoIdEqualTo(int value) { addCriterion("gelec_info_id =", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdNotEqualTo(int value) { addCriterion("gelec_info_id <>", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdGreaterThan(int value) { addCriterion("gelec_info_id >", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdGreaterThanOrEqualTo(int value) { addCriterion("gelec_info_id >=", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdLessThan(int value) { addCriterion("gelec_info_id <", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdLessThanOrEqualTo(int value) { addCriterion("gelec_info_id <=", new Integer(value), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdIn(List<Integer> values) { addCriterion("gelec_info_id in", values, "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdNotIn(List<Integer> values) { addCriterion("gelec_info_id not in", values, "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdBetween(int value1, int value2) { addCriterion("gelec_info_id between", new Integer(value1), new Integer(value2), "gelecInfoId"); return this; } public GElecInfoCriteria andGelecInfoIdNotBetween(int value1, int value2) { addCriterion("gelec_info_id not between", new Integer(value1), new Integer(value2), "gelecInfoId"); return this; } public GElecInfoCriteria andGCodeIsNull() { addCriterion("g_code is null"); return this; } public GElecInfoCriteria andGCodeIsNotNull() { addCriterion("g_code is not null"); return this; } public GElecInfoCriteria andGCodeEqualTo(String value) { addCriterion("g_code =", value, "gCode"); return this; } public GElecInfoCriteria andGCodeNotEqualTo(String value) { addCriterion("g_code <>", value, "gCode"); return this; } public GElecInfoCriteria andGCodeGreaterThan(String value) { addCriterion("g_code >", value, "gCode"); return this; } public GElecInfoCriteria andGCodeGreaterThanOrEqualTo(String value) { addCriterion("g_code >=", value, "gCode"); return this; } public GElecInfoCriteria andGCodeLessThan(String value) { addCriterion("g_code <", value, "gCode"); return this; } public GElecInfoCriteria andGCodeLessThanOrEqualTo(String value) { addCriterion("g_code <=", value, "gCode"); return this; } public GElecInfoCriteria andGCodeLike(String value) { addCriterion("g_code like", value, "gCode"); return this; } public GElecInfoCriteria andGCodeNotLike(String value) { addCriterion("g_code not like", value, "gCode"); return this; } public GElecInfoCriteria andGCodeIn(List<String> values) { addCriterion("g_code in", values, "gCode"); return this; } public GElecInfoCriteria andGCodeNotIn(List<String> values) { addCriterion("g_code not in", values, "gCode"); return this; } public GElecInfoCriteria andGCodeBetween(String value1, String value2) { addCriterion("g_code between", value1, value2, "gCode"); return this; } public GElecInfoCriteria andGCodeNotBetween(String value1, String value2) { addCriterion("g_code not between", value1, value2, "gCode"); return this; } public GElecInfoCriteria andProvinceIsNull() { addCriterion("province is null"); return this; } public GElecInfoCriteria andProvinceIsNotNull() { addCriterion("province is not null"); return this; } public GElecInfoCriteria andProvinceEqualTo(String value) { addCriterion("province =", value, "province"); return this; } public GElecInfoCriteria andProvinceNotEqualTo(String value) { addCriterion("province <>", value, "province"); return this; } public GElecInfoCriteria andProvinceGreaterThan(String value) { addCriterion("province >", value, "province"); return this; } public GElecInfoCriteria andProvinceGreaterThanOrEqualTo(String value) { addCriterion("province >=", value, "province"); return this; } public GElecInfoCriteria andProvinceLessThan(String value) { addCriterion("province <", value, "province"); return this; } public GElecInfoCriteria andProvinceLessThanOrEqualTo(String value) { addCriterion("province <=", value, "province"); return this; } public GElecInfoCriteria andProvinceLike(String value) { addCriterion("province like", value, "province"); return this; } public GElecInfoCriteria andProvinceNotLike(String value) { addCriterion("province not like", value, "province"); return this; } public GElecInfoCriteria andProvinceIn(List<String> values) { addCriterion("province in", values, "province"); return this; } public GElecInfoCriteria andProvinceNotIn(List<String> values) { addCriterion("province not in", values, "province"); return this; } public GElecInfoCriteria andProvinceBetween(String value1, String value2) { addCriterion("province between", value1, value2, "province"); return this; } public GElecInfoCriteria andProvinceNotBetween(String value1, String value2) { addCriterion("province not between", value1, value2, "province"); return this; } public GElecInfoCriteria andCityIsNull() { addCriterion("city is null"); return this; } public GElecInfoCriteria andCityIsNotNull() { addCriterion("city is not null"); return this; } public GElecInfoCriteria andCityEqualTo(String value) { addCriterion("city =", value, "city"); return this; } public GElecInfoCriteria andCityNotEqualTo(String value) { addCriterion("city <>", value, "city"); return this; } public GElecInfoCriteria andCityGreaterThan(String value) { addCriterion("city >", value, "city"); return this; } public GElecInfoCriteria andCityGreaterThanOrEqualTo(String value) { addCriterion("city >=", value, "city"); return this; } public GElecInfoCriteria andCityLessThan(String value) { addCriterion("city <", value, "city"); return this; } public GElecInfoCriteria andCityLessThanOrEqualTo(String value) { addCriterion("city <=", value, "city"); return this; } public GElecInfoCriteria andCityLike(String value) { addCriterion("city like", value, "city"); return this; } public GElecInfoCriteria andCityNotLike(String value) { addCriterion("city not like", value, "city"); return this; } public GElecInfoCriteria andCityIn(List<String> values) { addCriterion("city in", values, "city"); return this; } public GElecInfoCriteria andCityNotIn(List<String> values) { addCriterion("city not in", values, "city"); return this; } public GElecInfoCriteria andCityBetween(String value1, String value2) { addCriterion("city between", value1, value2, "city"); return this; } public GElecInfoCriteria andCityNotBetween(String value1, String value2) { addCriterion("city not between", value1, value2, "city"); return this; } public GElecInfoCriteria andDistrictIsNull() { addCriterion("district is null"); return this; } public GElecInfoCriteria andDistrictIsNotNull() { addCriterion("district is not null"); return this; } public GElecInfoCriteria andDistrictEqualTo(String value) { addCriterion("district =", value, "district"); return this; } public GElecInfoCriteria andDistrictNotEqualTo(String value) { addCriterion("district <>", value, "district"); return this; } public GElecInfoCriteria andDistrictGreaterThan(String value) { addCriterion("district >", value, "district"); return this; } public GElecInfoCriteria andDistrictGreaterThanOrEqualTo(String value) { addCriterion("district >=", value, "district"); return this; } public GElecInfoCriteria andDistrictLessThan(String value) { addCriterion("district <", value, "district"); return this; } public GElecInfoCriteria andDistrictLessThanOrEqualTo(String value) { addCriterion("district <=", value, "district"); return this; } public GElecInfoCriteria andDistrictLike(String value) { addCriterion("district like", value, "district"); return this; } public GElecInfoCriteria andDistrictNotLike(String value) { addCriterion("district not like", value, "district"); return this; } public GElecInfoCriteria andDistrictIn(List<String> values) { addCriterion("district in", values, "district"); return this; } public GElecInfoCriteria andDistrictNotIn(List<String> values) { addCriterion("district not in", values, "district"); return this; } public GElecInfoCriteria andDistrictBetween(String value1, String value2) { addCriterion("district between", value1, value2, "district"); return this; } public GElecInfoCriteria andDistrictNotBetween(String value1, String value2) { addCriterion("district not between", value1, value2, "district"); return this; } public GElecInfoCriteria andItProvinceIdIsNull() { addCriterion("it_province_id is null"); return this; } public GElecInfoCriteria andItProvinceIdIsNotNull() { addCriterion("it_province_id is not null"); return this; } public GElecInfoCriteria andItProvinceIdEqualTo(String value) { addCriterion("it_province_id =", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdNotEqualTo(String value) { addCriterion("it_province_id <>", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdGreaterThan(String value) { addCriterion("it_province_id >", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdGreaterThanOrEqualTo(String value) { addCriterion("it_province_id >=", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdLessThan(String value) { addCriterion("it_province_id <", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdLessThanOrEqualTo(String value) { addCriterion("it_province_id <=", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdLike(String value) { addCriterion("it_province_id like", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdNotLike(String value) { addCriterion("it_province_id not like", value, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdIn(List<String> values) { addCriterion("it_province_id in", values, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdNotIn(List<String> values) { addCriterion("it_province_id not in", values, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdBetween(String value1, String value2) { addCriterion("it_province_id between", value1, value2, "itProvinceId"); return this; } public GElecInfoCriteria andItProvinceIdNotBetween(String value1, String value2) { addCriterion("it_province_id not between", value1, value2, "itProvinceId"); return this; } public GElecInfoCriteria andItCityIdIsNull() { addCriterion("it_city_id is null"); return this; } public GElecInfoCriteria andItCityIdIsNotNull() { addCriterion("it_city_id is not null"); return this; } public GElecInfoCriteria andItCityIdEqualTo(String value) { addCriterion("it_city_id =", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdNotEqualTo(String value) { addCriterion("it_city_id <>", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdGreaterThan(String value) { addCriterion("it_city_id >", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdGreaterThanOrEqualTo(String value) { addCriterion("it_city_id >=", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdLessThan(String value) { addCriterion("it_city_id <", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdLessThanOrEqualTo(String value) { addCriterion("it_city_id <=", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdLike(String value) { addCriterion("it_city_id like", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdNotLike(String value) { addCriterion("it_city_id not like", value, "itCityId"); return this; } public GElecInfoCriteria andItCityIdIn(List<String> values) { addCriterion("it_city_id in", values, "itCityId"); return this; } public GElecInfoCriteria andItCityIdNotIn(List<String> values) { addCriterion("it_city_id not in", values, "itCityId"); return this; } public GElecInfoCriteria andItCityIdBetween(String value1, String value2) { addCriterion("it_city_id between", value1, value2, "itCityId"); return this; } public GElecInfoCriteria andItCityIdNotBetween(String value1, String value2) { addCriterion("it_city_id not between", value1, value2, "itCityId"); return this; } public GElecInfoCriteria andItDistrictIdIsNull() { addCriterion("it_district_id is null"); return this; } public GElecInfoCriteria andItDistrictIdIsNotNull() { addCriterion("it_district_id is not null"); return this; } public GElecInfoCriteria andItDistrictIdEqualTo(String value) { addCriterion("it_district_id =", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdNotEqualTo(String value) { addCriterion("it_district_id <>", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdGreaterThan(String value) { addCriterion("it_district_id >", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdGreaterThanOrEqualTo(String value) { addCriterion("it_district_id >=", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdLessThan(String value) { addCriterion("it_district_id <", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdLessThanOrEqualTo(String value) { addCriterion("it_district_id <=", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdLike(String value) { addCriterion("it_district_id like", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdNotLike(String value) { addCriterion("it_district_id not like", value, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdIn(List<String> values) { addCriterion("it_district_id in", values, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdNotIn(List<String> values) { addCriterion("it_district_id not in", values, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdBetween(String value1, String value2) { addCriterion("it_district_id between", value1, value2, "itDistrictId"); return this; } public GElecInfoCriteria andItDistrictIdNotBetween(String value1, String value2) { addCriterion("it_district_id not between", value1, value2, "itDistrictId"); return this; } public GElecInfoCriteria andItBillIdIsNull() { addCriterion("it_bill_id is null"); return this; } public GElecInfoCriteria andItBillIdIsNotNull() { addCriterion("it_bill_id is not null"); return this; } public GElecInfoCriteria andItBillIdEqualTo(int value) { addCriterion("it_bill_id =", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdNotEqualTo(int value) { addCriterion("it_bill_id <>", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdGreaterThan(int value) { addCriterion("it_bill_id >", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdGreaterThanOrEqualTo(int value) { addCriterion("it_bill_id >=", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdLessThan(int value) { addCriterion("it_bill_id <", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdLessThanOrEqualTo(int value) { addCriterion("it_bill_id <=", new Integer(value), "itBillId"); return this; } public GElecInfoCriteria andItBillIdIn(List<Integer> values) { addCriterion("it_bill_id in", values, "itBillId"); return this; } public GElecInfoCriteria andItBillIdNotIn(List<Integer> values) { addCriterion("it_bill_id not in", values, "itBillId"); return this; } public GElecInfoCriteria andItBillIdBetween(int value1, int value2) { addCriterion("it_bill_id between", new Integer(value1), new Integer(value2), "itBillId"); return this; } public GElecInfoCriteria andItBillIdNotBetween(int value1, int value2) { addCriterion("it_bill_id not between", new Integer(value1), new Integer(value2), "itBillId"); return this; } public GElecInfoCriteria andBillCodeIsNull() { addCriterion("bill_code is null"); return this; } public GElecInfoCriteria andBillCodeIsNotNull() { addCriterion("bill_code is not null"); return this; } public GElecInfoCriteria andBillCodeEqualTo(String value) { addCriterion("bill_code =", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeNotEqualTo(String value) { addCriterion("bill_code <>", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeGreaterThan(String value) { addCriterion("bill_code >", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeGreaterThanOrEqualTo(String value) { addCriterion("bill_code >=", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeLessThan(String value) { addCriterion("bill_code <", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeLessThanOrEqualTo(String value) { addCriterion("bill_code <=", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeLike(String value) { addCriterion("bill_code like", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeNotLike(String value) { addCriterion("bill_code not like", value, "billCode"); return this; } public GElecInfoCriteria andBillCodeIn(List<String> values) { addCriterion("bill_code in", values, "billCode"); return this; } public GElecInfoCriteria andBillCodeNotIn(List<String> values) { addCriterion("bill_code not in", values, "billCode"); return this; } public GElecInfoCriteria andBillCodeBetween(String value1, String value2) { addCriterion("bill_code between", value1, value2, "billCode"); return this; } public GElecInfoCriteria andBillCodeNotBetween(String value1, String value2) { addCriterion("bill_code not between", value1, value2, "billCode"); return this; } public GElecInfoCriteria andFaultSourceIsNull() { addCriterion("fault_source is null"); return this; } public GElecInfoCriteria andFaultSourceIsNotNull() { addCriterion("fault_source is not null"); return this; } public GElecInfoCriteria andFaultSourceEqualTo(String value) { addCriterion("fault_source =", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceNotEqualTo(String value) { addCriterion("fault_source <>", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceGreaterThan(String value) { addCriterion("fault_source >", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceGreaterThanOrEqualTo(String value) { addCriterion("fault_source >=", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceLessThan(String value) { addCriterion("fault_source <", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceLessThanOrEqualTo(String value) { addCriterion("fault_source <=", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceLike(String value) { addCriterion("fault_source like", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceNotLike(String value) { addCriterion("fault_source not like", value, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceIn(List<String> values) { addCriterion("fault_source in", values, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceNotIn(List<String> values) { addCriterion("fault_source not in", values, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceBetween(String value1, String value2) { addCriterion("fault_source between", value1, value2, "faultSource"); return this; } public GElecInfoCriteria andFaultSourceNotBetween(String value1, String value2) { addCriterion("fault_source not between", value1, value2, "faultSource"); return this; } public GElecInfoCriteria andAlarmDetailIsNull() { addCriterion("alarm_detail is null"); return this; } public GElecInfoCriteria andAlarmDetailIsNotNull() { addCriterion("alarm_detail is not null"); return this; } public GElecInfoCriteria andAlarmDetailEqualTo(String value) { addCriterion("alarm_detail =", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailNotEqualTo(String value) { addCriterion("alarm_detail <>", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailGreaterThan(String value) { addCriterion("alarm_detail >", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailGreaterThanOrEqualTo(String value) { addCriterion("alarm_detail >=", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailLessThan(String value) { addCriterion("alarm_detail <", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailLessThanOrEqualTo(String value) { addCriterion("alarm_detail <=", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailLike(String value) { addCriterion("alarm_detail like", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailNotLike(String value) { addCriterion("alarm_detail not like", value, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailIn(List<String> values) { addCriterion("alarm_detail in", values, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailNotIn(List<String> values) { addCriterion("alarm_detail not in", values, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailBetween(String value1, String value2) { addCriterion("alarm_detail between", value1, value2, "alarmDetail"); return this; } public GElecInfoCriteria andAlarmDetailNotBetween(String value1, String value2) { addCriterion("alarm_detail not between", value1, value2, "alarmDetail"); return this; } public GElecInfoCriteria andStationNameIsNull() { addCriterion("station_name is null"); return this; } public GElecInfoCriteria andStationNameIsNotNull() { addCriterion("station_name is not null"); return this; } public GElecInfoCriteria andStationNameEqualTo(String value) { addCriterion("station_name =", value, "stationName"); return this; } public GElecInfoCriteria andStationNameNotEqualTo(String value) { addCriterion("station_name <>", value, "stationName"); return this; } public GElecInfoCriteria andStationNameGreaterThan(String value) { addCriterion("station_name >", value, "stationName"); return this; } public GElecInfoCriteria andStationNameGreaterThanOrEqualTo(String value) { addCriterion("station_name >=", value, "stationName"); return this; } public GElecInfoCriteria andStationNameLessThan(String value) { addCriterion("station_name <", value, "stationName"); return this; } public GElecInfoCriteria andStationNameLessThanOrEqualTo(String value) { addCriterion("station_name <=", value, "stationName"); return this; } public GElecInfoCriteria andStationNameLike(String value) { addCriterion("station_name like", value, "stationName"); return this; } public GElecInfoCriteria andStationNameNotLike(String value) { addCriterion("station_name not like", value, "stationName"); return this; } public GElecInfoCriteria andStationNameIn(List<String> values) { addCriterion("station_name in", values, "stationName"); return this; } public GElecInfoCriteria andStationNameNotIn(List<String> values) { addCriterion("station_name not in", values, "stationName"); return this; } public GElecInfoCriteria andStationNameBetween(String value1, String value2) { addCriterion("station_name between", value1, value2, "stationName"); return this; } public GElecInfoCriteria andStationNameNotBetween(String value1, String value2) { addCriterion("station_name not between", value1, value2, "stationName"); return this; } public GElecInfoCriteria andStationCodeIsNull() { addCriterion("station_code is null"); return this; } public GElecInfoCriteria andStationCodeIsNotNull() { addCriterion("station_code is not null"); return this; } public GElecInfoCriteria andStationCodeEqualTo(String value) { addCriterion("station_code =", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeNotEqualTo(String value) { addCriterion("station_code <>", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeGreaterThan(String value) { addCriterion("station_code >", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeGreaterThanOrEqualTo(String value) { addCriterion("station_code >=", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeLessThan(String value) { addCriterion("station_code <", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeLessThanOrEqualTo(String value) { addCriterion("station_code <=", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeLike(String value) { addCriterion("station_code like", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeNotLike(String value) { addCriterion("station_code not like", value, "stationCode"); return this; } public GElecInfoCriteria andStationCodeIn(List<String> values) { addCriterion("station_code in", values, "stationCode"); return this; } public GElecInfoCriteria andStationCodeNotIn(List<String> values) { addCriterion("station_code not in", values, "stationCode"); return this; } public GElecInfoCriteria andStationCodeBetween(String value1, String value2) { addCriterion("station_code between", value1, value2, "stationCode"); return this; } public GElecInfoCriteria andStationCodeNotBetween(String value1, String value2) { addCriterion("station_code not between", value1, value2, "stationCode"); return this; } public GElecInfoCriteria andStationSysCodeIsNull() { addCriterion("station_SYS_Code is null"); return this; } public GElecInfoCriteria andStationSysCodeIsNotNull() { addCriterion("station_SYS_Code is not null"); return this; } public GElecInfoCriteria andStationSysCodeEqualTo(String value) { addCriterion("station_SYS_Code =", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeNotEqualTo(String value) { addCriterion("station_SYS_Code <>", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeGreaterThan(String value) { addCriterion("station_SYS_Code >", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeGreaterThanOrEqualTo(String value) { addCriterion("station_SYS_Code >=", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeLessThan(String value) { addCriterion("station_SYS_Code <", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeLessThanOrEqualTo(String value) { addCriterion("station_SYS_Code <=", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeLike(String value) { addCriterion("station_SYS_Code like", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeNotLike(String value) { addCriterion("station_SYS_Code not like", value, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeIn(List<String> values) { addCriterion("station_SYS_Code in", values, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeNotIn(List<String> values) { addCriterion("station_SYS_Code not in", values, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeBetween(String value1, String value2) { addCriterion("station_SYS_Code between", value1, value2, "stationSysCode"); return this; } public GElecInfoCriteria andStationSysCodeNotBetween(String value1, String value2) { addCriterion("station_SYS_Code not between", value1, value2, "stationSysCode"); return this; } public GElecInfoCriteria andOperatorIsNull() { addCriterion("operator is null"); return this; } public GElecInfoCriteria andOperatorIsNotNull() { addCriterion("operator is not null"); return this; } public GElecInfoCriteria andOperatorEqualTo(String value) { addCriterion("operator =", value, "operator"); return this; } public GElecInfoCriteria andOperatorNotEqualTo(String value) { addCriterion("operator <>", value, "operator"); return this; } public GElecInfoCriteria andOperatorGreaterThan(String value) { addCriterion("operator >", value, "operator"); return this; } public GElecInfoCriteria andOperatorGreaterThanOrEqualTo(String value) { addCriterion("operator >=", value, "operator"); return this; } public GElecInfoCriteria andOperatorLessThan(String value) { addCriterion("operator <", value, "operator"); return this; } public GElecInfoCriteria andOperatorLessThanOrEqualTo(String value) { addCriterion("operator <=", value, "operator"); return this; } public GElecInfoCriteria andOperatorLike(String value) { addCriterion("operator like", value, "operator"); return this; } public GElecInfoCriteria andOperatorNotLike(String value) { addCriterion("operator not like", value, "operator"); return this; } public GElecInfoCriteria andOperatorIn(List<String> values) { addCriterion("operator in", values, "operator"); return this; } public GElecInfoCriteria andOperatorNotIn(List<String> values) { addCriterion("operator not in", values, "operator"); return this; } public GElecInfoCriteria andOperatorBetween(String value1, String value2) { addCriterion("operator between", value1, value2, "operator"); return this; } public GElecInfoCriteria andOperatorNotBetween(String value1, String value2) { addCriterion("operator not between", value1, value2, "operator"); return this; } public GElecInfoCriteria andOperCodeIsNull() { addCriterion("oper_code is null"); return this; } public GElecInfoCriteria andOperCodeIsNotNull() { addCriterion("oper_code is not null"); return this; } public GElecInfoCriteria andOperCodeEqualTo(String value) { addCriterion("oper_code =", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeNotEqualTo(String value) { addCriterion("oper_code <>", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeGreaterThan(String value) { addCriterion("oper_code >", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeGreaterThanOrEqualTo(String value) { addCriterion("oper_code >=", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeLessThan(String value) { addCriterion("oper_code <", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeLessThanOrEqualTo(String value) { addCriterion("oper_code <=", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeLike(String value) { addCriterion("oper_code like", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeNotLike(String value) { addCriterion("oper_code not like", value, "operCode"); return this; } public GElecInfoCriteria andOperCodeIn(List<String> values) { addCriterion("oper_code in", values, "operCode"); return this; } public GElecInfoCriteria andOperCodeNotIn(List<String> values) { addCriterion("oper_code not in", values, "operCode"); return this; } public GElecInfoCriteria andOperCodeBetween(String value1, String value2) { addCriterion("oper_code between", value1, value2, "operCode"); return this; } public GElecInfoCriteria andOperCodeNotBetween(String value1, String value2) { addCriterion("oper_code not between", value1, value2, "operCode"); return this; } public GElecInfoCriteria andStartTimeIsNull() { addCriterion("start_time is null"); return this; } public GElecInfoCriteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return this; } public GElecInfoCriteria andStartTimeEqualTo(Date value) { addCriterion("start_time =", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeNotEqualTo(Date value) { addCriterion("start_time <>", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeGreaterThan(Date value) { addCriterion("start_time >", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeGreaterThanOrEqualTo(Date value) { addCriterion("start_time >=", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeLessThan(Date value) { addCriterion("start_time <", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeLessThanOrEqualTo(Date value) { addCriterion("start_time <=", value, "startTime"); return this; } public GElecInfoCriteria andStartTimeIn(List<Date> values) { addCriterion("start_time in", values, "startTime"); return this; } public GElecInfoCriteria andStartTimeNotIn(List<Date> values) { addCriterion("start_time not in", values, "startTime"); return this; } public GElecInfoCriteria andStartTimeBetween(Date value1, Date value2) { addCriterion("start_time between", value1, value2, "startTime"); return this; } public GElecInfoCriteria andStartTimeNotBetween(Date value1, Date value2) { addCriterion("start_time not between", value1, value2, "startTime"); return this; } public GElecInfoCriteria andEndTimeIsNull() { addCriterion("end_time is null"); return this; } public GElecInfoCriteria andEndTimeIsNotNull() { addCriterion("end_time is not null"); return this; } public GElecInfoCriteria andEndTimeEqualTo(Date value) { addCriterion("end_time =", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeNotEqualTo(Date value) { addCriterion("end_time <>", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeGreaterThan(Date value) { addCriterion("end_time >", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeGreaterThanOrEqualTo(Date value) { addCriterion("end_time >=", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeLessThan(Date value) { addCriterion("end_time <", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeLessThanOrEqualTo(Date value) { addCriterion("end_time <=", value, "endTime"); return this; } public GElecInfoCriteria andEndTimeIn(List<Date> values) { addCriterion("end_time in", values, "endTime"); return this; } public GElecInfoCriteria andEndTimeNotIn(List<Date> values) { addCriterion("end_time not in", values, "endTime"); return this; } public GElecInfoCriteria andEndTimeBetween(Date value1, Date value2) { addCriterion("end_time between", value1, value2, "endTime"); return this; } public GElecInfoCriteria andEndTimeNotBetween(Date value1, Date value2) { addCriterion("end_time not between", value1, value2, "endTime"); return this; } public GElecInfoCriteria andDurationIsNull() { addCriterion("duration is null"); return this; } public GElecInfoCriteria andDurationIsNotNull() { addCriterion("duration is not null"); return this; } public GElecInfoCriteria andDurationEqualTo(String value) { addCriterion("duration =", value, "duration"); return this; } public GElecInfoCriteria andDurationNotEqualTo(String value) { addCriterion("duration <>", value, "duration"); return this; } public GElecInfoCriteria andDurationGreaterThan(String value) { addCriterion("duration >", value, "duration"); return this; } public GElecInfoCriteria andDurationGreaterThanOrEqualTo(String value) { addCriterion("duration >=", value, "duration"); return this; } public GElecInfoCriteria andDurationLessThan(String value) { addCriterion("duration <", value, "duration"); return this; } public GElecInfoCriteria andDurationLessThanOrEqualTo(String value) { addCriterion("duration <=", value, "duration"); return this; } public GElecInfoCriteria andDurationLike(String value) { addCriterion("duration like", value, "duration"); return this; } public GElecInfoCriteria andDurationNotLike(String value) { addCriterion("duration not like", value, "duration"); return this; } public GElecInfoCriteria andDurationIn(List<String> values) { addCriterion("duration in", values, "duration"); return this; } public GElecInfoCriteria andDurationNotIn(List<String> values) { addCriterion("duration not in", values, "duration"); return this; } public GElecInfoCriteria andDurationBetween(String value1, String value2) { addCriterion("duration between", value1, value2, "duration"); return this; } public GElecInfoCriteria andDurationNotBetween(String value1, String value2) { addCriterion("duration not between", value1, value2, "duration"); return this; } public GElecInfoCriteria andOdometerIsNull() { addCriterion("odometer is null"); return this; } public GElecInfoCriteria andOdometerIsNotNull() { addCriterion("odometer is not null"); return this; } public GElecInfoCriteria andOdometerEqualTo(String value) { addCriterion("odometer =", value, "odometer"); return this; } public GElecInfoCriteria andOdometerNotEqualTo(String value) { addCriterion("odometer <>", value, "odometer"); return this; } public GElecInfoCriteria andOdometerGreaterThan(String value) { addCriterion("odometer >", value, "odometer"); return this; } public GElecInfoCriteria andOdometerGreaterThanOrEqualTo(String value) { addCriterion("odometer >=", value, "odometer"); return this; } public GElecInfoCriteria andOdometerLessThan(String value) { addCriterion("odometer <", value, "odometer"); return this; } public GElecInfoCriteria andOdometerLessThanOrEqualTo(String value) { addCriterion("odometer <=", value, "odometer"); return this; } public GElecInfoCriteria andOdometerLike(String value) { addCriterion("odometer like", value, "odometer"); return this; } public GElecInfoCriteria andOdometerNotLike(String value) { addCriterion("odometer not like", value, "odometer"); return this; } public GElecInfoCriteria andOdometerIn(List<String> values) { addCriterion("odometer in", values, "odometer"); return this; } public GElecInfoCriteria andOdometerNotIn(List<String> values) { addCriterion("odometer not in", values, "odometer"); return this; } public GElecInfoCriteria andOdometerBetween(String value1, String value2) { addCriterion("odometer between", value1, value2, "odometer"); return this; } public GElecInfoCriteria andOdometerNotBetween(String value1, String value2) { addCriterion("odometer not between", value1, value2, "odometer"); return this; } public GElecInfoCriteria andPetrolPriceIsNull() { addCriterion("petrol_price is null"); return this; } public GElecInfoCriteria andPetrolPriceIsNotNull() { addCriterion("petrol_price is not null"); return this; } public GElecInfoCriteria andPetrolPriceEqualTo(String value) { addCriterion("petrol_price =", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceNotEqualTo(String value) { addCriterion("petrol_price <>", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceGreaterThan(String value) { addCriterion("petrol_price >", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceGreaterThanOrEqualTo(String value) { addCriterion("petrol_price >=", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceLessThan(String value) { addCriterion("petrol_price <", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceLessThanOrEqualTo(String value) { addCriterion("petrol_price <=", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceLike(String value) { addCriterion("petrol_price like", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceNotLike(String value) { addCriterion("petrol_price not like", value, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceIn(List<String> values) { addCriterion("petrol_price in", values, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceNotIn(List<String> values) { addCriterion("petrol_price not in", values, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceBetween(String value1, String value2) { addCriterion("petrol_price between", value1, value2, "petrolPrice"); return this; } public GElecInfoCriteria andPetrolPriceNotBetween(String value1, String value2) { addCriterion("petrol_price not between", value1, value2, "petrolPrice"); return this; } public GElecInfoCriteria andMachineCountIsNull() { addCriterion("machine_count is null"); return this; } public GElecInfoCriteria andMachineCountIsNotNull() { addCriterion("machine_count is not null"); return this; } public GElecInfoCriteria andMachineCountEqualTo(int value) { addCriterion("machine_count =", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountNotEqualTo(int value) { addCriterion("machine_count <>", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountGreaterThan(int value) { addCriterion("machine_count >", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountGreaterThanOrEqualTo(int value) { addCriterion("machine_count >=", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountLessThan(int value) { addCriterion("machine_count <", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountLessThanOrEqualTo(int value) { addCriterion("machine_count <=", new Integer(value), "machineCount"); return this; } public GElecInfoCriteria andMachineCountIn(List<Integer> values) { addCriterion("machine_count in", values, "machineCount"); return this; } public GElecInfoCriteria andMachineCountNotIn(List<Integer> values) { addCriterion("machine_count not in", values, "machineCount"); return this; } public GElecInfoCriteria andMachineCountBetween(int value1, int value2) { addCriterion("machine_count between", new Integer(value1), new Integer(value2), "machineCount"); return this; } public GElecInfoCriteria andMachineCountNotBetween(int value1, int value2) { addCriterion("machine_count not between", new Integer(value1), new Integer(value2), "machineCount"); return this; } public GElecInfoCriteria andAreaTypeIsNull() { addCriterion("area_type is null"); return this; } public GElecInfoCriteria andAreaTypeIsNotNull() { addCriterion("area_type is not null"); return this; } public GElecInfoCriteria andAreaTypeEqualTo(String value) { addCriterion("area_type =", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeNotEqualTo(String value) { addCriterion("area_type <>", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeGreaterThan(String value) { addCriterion("area_type >", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeGreaterThanOrEqualTo(String value) { addCriterion("area_type >=", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeLessThan(String value) { addCriterion("area_type <", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeLessThanOrEqualTo(String value) { addCriterion("area_type <=", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeLike(String value) { addCriterion("area_type like", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeNotLike(String value) { addCriterion("area_type not like", value, "areaType"); return this; } public GElecInfoCriteria andAreaTypeIn(List<String> values) { addCriterion("area_type in", values, "areaType"); return this; } public GElecInfoCriteria andAreaTypeNotIn(List<String> values) { addCriterion("area_type not in", values, "areaType"); return this; } public GElecInfoCriteria andAreaTypeBetween(String value1, String value2) { addCriterion("area_type between", value1, value2, "areaType"); return this; } public GElecInfoCriteria andAreaTypeNotBetween(String value1, String value2) { addCriterion("area_type not between", value1, value2, "areaType"); return this; } public GElecInfoCriteria andDataOriginIsNull() { addCriterion("data_origin is null"); return this; } public GElecInfoCriteria andDataOriginIsNotNull() { addCriterion("data_origin is not null"); return this; } public GElecInfoCriteria andDataOriginEqualTo(String value) { addCriterion("data_origin =", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginNotEqualTo(String value) { addCriterion("data_origin <>", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginGreaterThan(String value) { addCriterion("data_origin >", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginGreaterThanOrEqualTo(String value) { addCriterion("data_origin >=", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginLessThan(String value) { addCriterion("data_origin <", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginLessThanOrEqualTo(String value) { addCriterion("data_origin <=", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginLike(String value) { addCriterion("data_origin like", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginNotLike(String value) { addCriterion("data_origin not like", value, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginIn(List<String> values) { addCriterion("data_origin in", values, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginNotIn(List<String> values) { addCriterion("data_origin not in", values, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginBetween(String value1, String value2) { addCriterion("data_origin between", value1, value2, "dataOrigin"); return this; } public GElecInfoCriteria andDataOriginNotBetween(String value1, String value2) { addCriterion("data_origin not between", value1, value2, "dataOrigin"); return this; } public GElecInfoCriteria andReasonIsNull() { addCriterion("reason is null"); return this; } public GElecInfoCriteria andReasonIsNotNull() { addCriterion("reason is not null"); return this; } public GElecInfoCriteria andReasonEqualTo(String value) { addCriterion("reason =", value, "reason"); return this; } public GElecInfoCriteria andReasonNotEqualTo(String value) { addCriterion("reason <>", value, "reason"); return this; } public GElecInfoCriteria andReasonGreaterThan(String value) { addCriterion("reason >", value, "reason"); return this; } public GElecInfoCriteria andReasonGreaterThanOrEqualTo(String value) { addCriterion("reason >=", value, "reason"); return this; } public GElecInfoCriteria andReasonLessThan(String value) { addCriterion("reason <", value, "reason"); return this; } public GElecInfoCriteria andReasonLessThanOrEqualTo(String value) { addCriterion("reason <=", value, "reason"); return this; } public GElecInfoCriteria andReasonLike(String value) { addCriterion("reason like", value, "reason"); return this; } public GElecInfoCriteria andReasonNotLike(String value) { addCriterion("reason not like", value, "reason"); return this; } public GElecInfoCriteria andReasonIn(List<String> values) { addCriterion("reason in", values, "reason"); return this; } public GElecInfoCriteria andReasonNotIn(List<String> values) { addCriterion("reason not in", values, "reason"); return this; } public GElecInfoCriteria andReasonBetween(String value1, String value2) { addCriterion("reason between", value1, value2, "reason"); return this; } public GElecInfoCriteria andReasonNotBetween(String value1, String value2) { addCriterion("reason not between", value1, value2, "reason"); return this; } public GElecInfoCriteria andMachinePowerIsNull() { addCriterion("machine_power is null"); return this; } public GElecInfoCriteria andMachinePowerIsNotNull() { addCriterion("machine_power is not null"); return this; } public GElecInfoCriteria andMachinePowerEqualTo(String value) { addCriterion("machine_power =", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerNotEqualTo(String value) { addCriterion("machine_power <>", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerGreaterThan(String value) { addCriterion("machine_power >", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerGreaterThanOrEqualTo(String value) { addCriterion("machine_power >=", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerLessThan(String value) { addCriterion("machine_power <", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerLessThanOrEqualTo(String value) { addCriterion("machine_power <=", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerLike(String value) { addCriterion("machine_power like", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerNotLike(String value) { addCriterion("machine_power not like", value, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerIn(List<String> values) { addCriterion("machine_power in", values, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerNotIn(List<String> values) { addCriterion("machine_power not in", values, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerBetween(String value1, String value2) { addCriterion("machine_power between", value1, value2, "machinePower"); return this; } public GElecInfoCriteria andMachinePowerNotBetween(String value1, String value2) { addCriterion("machine_power not between", value1, value2, "machinePower"); return this; } public GElecInfoCriteria andMachineTypeIsNull() { addCriterion("machine_type is null"); return this; } public GElecInfoCriteria andMachineTypeIsNotNull() { addCriterion("machine_type is not null"); return this; } public GElecInfoCriteria andMachineTypeEqualTo(String value) { addCriterion("machine_type =", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeNotEqualTo(String value) { addCriterion("machine_type <>", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeGreaterThan(String value) { addCriterion("machine_type >", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeGreaterThanOrEqualTo(String value) { addCriterion("machine_type >=", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeLessThan(String value) { addCriterion("machine_type <", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeLessThanOrEqualTo(String value) { addCriterion("machine_type <=", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeLike(String value) { addCriterion("machine_type like", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeNotLike(String value) { addCriterion("machine_type not like", value, "machineType"); return this; } public GElecInfoCriteria andMachineTypeIn(List<String> values) { addCriterion("machine_type in", values, "machineType"); return this; } public GElecInfoCriteria andMachineTypeNotIn(List<String> values) { addCriterion("machine_type not in", values, "machineType"); return this; } public GElecInfoCriteria andMachineTypeBetween(String value1, String value2) { addCriterion("machine_type between", value1, value2, "machineType"); return this; } public GElecInfoCriteria andMachineTypeNotBetween(String value1, String value2) { addCriterion("machine_type not between", value1, value2, "machineType"); return this; } public GElecInfoCriteria andMachineNoIsNull() { addCriterion("machine_NO is null"); return this; } public GElecInfoCriteria andMachineNoIsNotNull() { addCriterion("machine_NO is not null"); return this; } public GElecInfoCriteria andMachineNoEqualTo(String value) { addCriterion("machine_NO =", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoNotEqualTo(String value) { addCriterion("machine_NO <>", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoGreaterThan(String value) { addCriterion("machine_NO >", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoGreaterThanOrEqualTo(String value) { addCriterion("machine_NO >=", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoLessThan(String value) { addCriterion("machine_NO <", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoLessThanOrEqualTo(String value) { addCriterion("machine_NO <=", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoLike(String value) { addCriterion("machine_NO like", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoNotLike(String value) { addCriterion("machine_NO not like", value, "machineNo"); return this; } public GElecInfoCriteria andMachineNoIn(List<String> values) { addCriterion("machine_NO in", values, "machineNo"); return this; } public GElecInfoCriteria andMachineNoNotIn(List<String> values) { addCriterion("machine_NO not in", values, "machineNo"); return this; } public GElecInfoCriteria andMachineNoBetween(String value1, String value2) { addCriterion("machine_NO between", value1, value2, "machineNo"); return this; } public GElecInfoCriteria andMachineNoNotBetween(String value1, String value2) { addCriterion("machine_NO not between", value1, value2, "machineNo"); return this; } public GElecInfoCriteria andPersonIsNull() { addCriterion("person is null"); return this; } public GElecInfoCriteria andPersonIsNotNull() { addCriterion("person is not null"); return this; } public GElecInfoCriteria andPersonEqualTo(String value) { addCriterion("person =", value, "person"); return this; } public GElecInfoCriteria andPersonNotEqualTo(String value) { addCriterion("person <>", value, "person"); return this; } public GElecInfoCriteria andPersonGreaterThan(String value) { addCriterion("person >", value, "person"); return this; } public GElecInfoCriteria andPersonGreaterThanOrEqualTo(String value) { addCriterion("person >=", value, "person"); return this; } public GElecInfoCriteria andPersonLessThan(String value) { addCriterion("person <", value, "person"); return this; } public GElecInfoCriteria andPersonLessThanOrEqualTo(String value) { addCriterion("person <=", value, "person"); return this; } public GElecInfoCriteria andPersonLike(String value) { addCriterion("person like", value, "person"); return this; } public GElecInfoCriteria andPersonNotLike(String value) { addCriterion("person not like", value, "person"); return this; } public GElecInfoCriteria andPersonIn(List<String> values) { addCriterion("person in", values, "person"); return this; } public GElecInfoCriteria andPersonNotIn(List<String> values) { addCriterion("person not in", values, "person"); return this; } public GElecInfoCriteria andPersonBetween(String value1, String value2) { addCriterion("person between", value1, value2, "person"); return this; } public GElecInfoCriteria andPersonNotBetween(String value1, String value2) { addCriterion("person not between", value1, value2, "person"); return this; } public GElecInfoCriteria andContactIsNull() { addCriterion("contact is null"); return this; } public GElecInfoCriteria andContactIsNotNull() { addCriterion("contact is not null"); return this; } public GElecInfoCriteria andContactEqualTo(String value) { addCriterion("contact =", value, "contact"); return this; } public GElecInfoCriteria andContactNotEqualTo(String value) { addCriterion("contact <>", value, "contact"); return this; } public GElecInfoCriteria andContactGreaterThan(String value) { addCriterion("contact >", value, "contact"); return this; } public GElecInfoCriteria andContactGreaterThanOrEqualTo(String value) { addCriterion("contact >=", value, "contact"); return this; } public GElecInfoCriteria andContactLessThan(String value) { addCriterion("contact <", value, "contact"); return this; } public GElecInfoCriteria andContactLessThanOrEqualTo(String value) { addCriterion("contact <=", value, "contact"); return this; } public GElecInfoCriteria andContactLike(String value) { addCriterion("contact like", value, "contact"); return this; } public GElecInfoCriteria andContactNotLike(String value) { addCriterion("contact not like", value, "contact"); return this; } public GElecInfoCriteria andContactIn(List<String> values) { addCriterion("contact in", values, "contact"); return this; } public GElecInfoCriteria andContactNotIn(List<String> values) { addCriterion("contact not in", values, "contact"); return this; } public GElecInfoCriteria andContactBetween(String value1, String value2) { addCriterion("contact between", value1, value2, "contact"); return this; } public GElecInfoCriteria andContactNotBetween(String value1, String value2) { addCriterion("contact not between", value1, value2, "contact"); return this; } public GElecInfoCriteria andStartVoltageIsNull() { addCriterion("start_voltage is null"); return this; } public GElecInfoCriteria andStartVoltageIsNotNull() { addCriterion("start_voltage is not null"); return this; } public GElecInfoCriteria andStartVoltageEqualTo(String value) { addCriterion("start_voltage =", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageNotEqualTo(String value) { addCriterion("start_voltage <>", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageGreaterThan(String value) { addCriterion("start_voltage >", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageGreaterThanOrEqualTo(String value) { addCriterion("start_voltage >=", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageLessThan(String value) { addCriterion("start_voltage <", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageLessThanOrEqualTo(String value) { addCriterion("start_voltage <=", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageLike(String value) { addCriterion("start_voltage like", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageNotLike(String value) { addCriterion("start_voltage not like", value, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageIn(List<String> values) { addCriterion("start_voltage in", values, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageNotIn(List<String> values) { addCriterion("start_voltage not in", values, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageBetween(String value1, String value2) { addCriterion("start_voltage between", value1, value2, "startVoltage"); return this; } public GElecInfoCriteria andStartVoltageNotBetween(String value1, String value2) { addCriterion("start_voltage not between", value1, value2, "startVoltage"); return this; } public GElecInfoCriteria andStartLngIsNull() { addCriterion("start_lng is null"); return this; } public GElecInfoCriteria andStartLngIsNotNull() { addCriterion("start_lng is not null"); return this; } public GElecInfoCriteria andStartLngEqualTo(double value) { addCriterion("start_lng =", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngNotEqualTo(double value) { addCriterion("start_lng <>", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngGreaterThan(double value) { addCriterion("start_lng >", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngGreaterThanOrEqualTo(double value) { addCriterion("start_lng >=", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngLessThan(double value) { addCriterion("start_lng <", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngLessThanOrEqualTo(double value) { addCriterion("start_lng <=", new Double(value), "startLng"); return this; } public GElecInfoCriteria andStartLngIn(List<Double> values) { addCriterion("start_lng in", values, "startLng"); return this; } public GElecInfoCriteria andStartLngNotIn(List<Double> values) { addCriterion("start_lng not in", values, "startLng"); return this; } public GElecInfoCriteria andStartLngBetween(double value1, double value2) { addCriterion("start_lng between", new Double(value1), new Double(value2), "startLng"); return this; } public GElecInfoCriteria andStartLngNotBetween(double value1, double value2) { addCriterion("start_lng not between", new Double(value1), new Double(value2), "startLng"); return this; } public GElecInfoCriteria andStartLatIsNull() { addCriterion("start_lat is null"); return this; } public GElecInfoCriteria andStartLatIsNotNull() { addCriterion("start_lat is not null"); return this; } public GElecInfoCriteria andStartLatEqualTo(double value) { addCriterion("start_lat =", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatNotEqualTo(double value) { addCriterion("start_lat <>", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatGreaterThan(double value) { addCriterion("start_lat >", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatGreaterThanOrEqualTo(double value) { addCriterion("start_lat >=", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatLessThan(double value) { addCriterion("start_lat <", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatLessThanOrEqualTo(double value) { addCriterion("start_lat <=", new Double(value), "startLat"); return this; } public GElecInfoCriteria andStartLatIn(List<Double> values) { addCriterion("start_lat in", values, "startLat"); return this; } public GElecInfoCriteria andStartLatNotIn(List<Double> values) { addCriterion("start_lat not in", values, "startLat"); return this; } public GElecInfoCriteria andStartLatBetween(double value1, double value2) { addCriterion("start_lat between", new Double(value1), new Double(value2), "startLat"); return this; } public GElecInfoCriteria andStartLatNotBetween(double value1, double value2) { addCriterion("start_lat not between", new Double(value1), new Double(value2), "startLat"); return this; } public GElecInfoCriteria andStartAddrIsNull() { addCriterion("start_addr is null"); return this; } public GElecInfoCriteria andStartAddrIsNotNull() { addCriterion("start_addr is not null"); return this; } public GElecInfoCriteria andStartAddrEqualTo(String value) { addCriterion("start_addr =", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrNotEqualTo(String value) { addCriterion("start_addr <>", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrGreaterThan(String value) { addCriterion("start_addr >", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrGreaterThanOrEqualTo(String value) { addCriterion("start_addr >=", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrLessThan(String value) { addCriterion("start_addr <", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrLessThanOrEqualTo(String value) { addCriterion("start_addr <=", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrLike(String value) { addCriterion("start_addr like", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrNotLike(String value) { addCriterion("start_addr not like", value, "startAddr"); return this; } public GElecInfoCriteria andStartAddrIn(List<String> values) { addCriterion("start_addr in", values, "startAddr"); return this; } public GElecInfoCriteria andStartAddrNotIn(List<String> values) { addCriterion("start_addr not in", values, "startAddr"); return this; } public GElecInfoCriteria andStartAddrBetween(String value1, String value2) { addCriterion("start_addr between", value1, value2, "startAddr"); return this; } public GElecInfoCriteria andStartAddrNotBetween(String value1, String value2) { addCriterion("start_addr not between", value1, value2, "startAddr"); return this; } public GElecInfoCriteria andEndVoltageIsNull() { addCriterion("end_voltage is null"); return this; } public GElecInfoCriteria andEndVoltageIsNotNull() { addCriterion("end_voltage is not null"); return this; } public GElecInfoCriteria andEndVoltageEqualTo(String value) { addCriterion("end_voltage =", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageNotEqualTo(String value) { addCriterion("end_voltage <>", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageGreaterThan(String value) { addCriterion("end_voltage >", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageGreaterThanOrEqualTo(String value) { addCriterion("end_voltage >=", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageLessThan(String value) { addCriterion("end_voltage <", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageLessThanOrEqualTo(String value) { addCriterion("end_voltage <=", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageLike(String value) { addCriterion("end_voltage like", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageNotLike(String value) { addCriterion("end_voltage not like", value, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageIn(List<String> values) { addCriterion("end_voltage in", values, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageNotIn(List<String> values) { addCriterion("end_voltage not in", values, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageBetween(String value1, String value2) { addCriterion("end_voltage between", value1, value2, "endVoltage"); return this; } public GElecInfoCriteria andEndVoltageNotBetween(String value1, String value2) { addCriterion("end_voltage not between", value1, value2, "endVoltage"); return this; } public GElecInfoCriteria andEndLngIsNull() { addCriterion("end_lng is null"); return this; } public GElecInfoCriteria andEndLngIsNotNull() { addCriterion("end_lng is not null"); return this; } public GElecInfoCriteria andEndLngEqualTo(double value) { addCriterion("end_lng =", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngNotEqualTo(double value) { addCriterion("end_lng <>", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngGreaterThan(double value) { addCriterion("end_lng >", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngGreaterThanOrEqualTo(double value) { addCriterion("end_lng >=", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngLessThan(double value) { addCriterion("end_lng <", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngLessThanOrEqualTo(double value) { addCriterion("end_lng <=", new Double(value), "endLng"); return this; } public GElecInfoCriteria andEndLngIn(List<Double> values) { addCriterion("end_lng in", values, "endLng"); return this; } public GElecInfoCriteria andEndLngNotIn(List<Double> values) { addCriterion("end_lng not in", values, "endLng"); return this; } public GElecInfoCriteria andEndLngBetween(double value1, double value2) { addCriterion("end_lng between", new Double(value1), new Double(value2), "endLng"); return this; } public GElecInfoCriteria andEndLngNotBetween(double value1, double value2) { addCriterion("end_lng not between", new Double(value1), new Double(value2), "endLng"); return this; } public GElecInfoCriteria andEndLatIsNull() { addCriterion("end_lat is null"); return this; } public GElecInfoCriteria andEndLatIsNotNull() { addCriterion("end_lat is not null"); return this; } public GElecInfoCriteria andEndLatEqualTo(double value) { addCriterion("end_lat =", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatNotEqualTo(double value) { addCriterion("end_lat <>", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatGreaterThan(double value) { addCriterion("end_lat >", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatGreaterThanOrEqualTo(double value) { addCriterion("end_lat >=", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatLessThan(double value) { addCriterion("end_lat <", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatLessThanOrEqualTo(double value) { addCriterion("end_lat <=", new Double(value), "endLat"); return this; } public GElecInfoCriteria andEndLatIn(List<Double> values) { addCriterion("end_lat in", values, "endLat"); return this; } public GElecInfoCriteria andEndLatNotIn(List<Double> values) { addCriterion("end_lat not in", values, "endLat"); return this; } public GElecInfoCriteria andEndLatBetween(double value1, double value2) { addCriterion("end_lat between", new Double(value1), new Double(value2), "endLat"); return this; } public GElecInfoCriteria andEndLatNotBetween(double value1, double value2) { addCriterion("end_lat not between", new Double(value1), new Double(value2), "endLat"); return this; } public GElecInfoCriteria andEndAddrIsNull() { addCriterion("end_addr is null"); return this; } public GElecInfoCriteria andEndAddrIsNotNull() { addCriterion("end_addr is not null"); return this; } public GElecInfoCriteria andEndAddrEqualTo(String value) { addCriterion("end_addr =", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrNotEqualTo(String value) { addCriterion("end_addr <>", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrGreaterThan(String value) { addCriterion("end_addr >", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrGreaterThanOrEqualTo(String value) { addCriterion("end_addr >=", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrLessThan(String value) { addCriterion("end_addr <", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrLessThanOrEqualTo(String value) { addCriterion("end_addr <=", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrLike(String value) { addCriterion("end_addr like", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrNotLike(String value) { addCriterion("end_addr not like", value, "endAddr"); return this; } public GElecInfoCriteria andEndAddrIn(List<String> values) { addCriterion("end_addr in", values, "endAddr"); return this; } public GElecInfoCriteria andEndAddrNotIn(List<String> values) { addCriterion("end_addr not in", values, "endAddr"); return this; } public GElecInfoCriteria andEndAddrBetween(String value1, String value2) { addCriterion("end_addr between", value1, value2, "endAddr"); return this; } public GElecInfoCriteria andEndAddrNotBetween(String value1, String value2) { addCriterion("end_addr not between", value1, value2, "endAddr"); return this; } public GElecInfoCriteria andPic1IsNull() { addCriterion("pic1 is null"); return this; } public GElecInfoCriteria andPic1IsNotNull() { addCriterion("pic1 is not null"); return this; } public GElecInfoCriteria andPic1EqualTo(String value) { addCriterion("pic1 =", value, "pic1"); return this; } public GElecInfoCriteria andPic1NotEqualTo(String value) { addCriterion("pic1 <>", value, "pic1"); return this; } public GElecInfoCriteria andPic1GreaterThan(String value) { addCriterion("pic1 >", value, "pic1"); return this; } public GElecInfoCriteria andPic1GreaterThanOrEqualTo(String value) { addCriterion("pic1 >=", value, "pic1"); return this; } public GElecInfoCriteria andPic1LessThan(String value) { addCriterion("pic1 <", value, "pic1"); return this; } public GElecInfoCriteria andPic1LessThanOrEqualTo(String value) { addCriterion("pic1 <=", value, "pic1"); return this; } public GElecInfoCriteria andPic1Like(String value) { addCriterion("pic1 like", value, "pic1"); return this; } public GElecInfoCriteria andPic1NotLike(String value) { addCriterion("pic1 not like", value, "pic1"); return this; } public GElecInfoCriteria andPic1In(List<String> values) { addCriterion("pic1 in", values, "pic1"); return this; } public GElecInfoCriteria andPic1NotIn(List<String> values) { addCriterion("pic1 not in", values, "pic1"); return this; } public GElecInfoCriteria andPic1Between(String value1, String value2) { addCriterion("pic1 between", value1, value2, "pic1"); return this; } public GElecInfoCriteria andPic1NotBetween(String value1, String value2) { addCriterion("pic1 not between", value1, value2, "pic1"); return this; } public GElecInfoCriteria andPic2IsNull() { addCriterion("pic2 is null"); return this; } public GElecInfoCriteria andPic2IsNotNull() { addCriterion("pic2 is not null"); return this; } public GElecInfoCriteria andPic2EqualTo(String value) { addCriterion("pic2 =", value, "pic2"); return this; } public GElecInfoCriteria andPic2NotEqualTo(String value) { addCriterion("pic2 <>", value, "pic2"); return this; } public GElecInfoCriteria andPic2GreaterThan(String value) { addCriterion("pic2 >", value, "pic2"); return this; } public GElecInfoCriteria andPic2GreaterThanOrEqualTo(String value) { addCriterion("pic2 >=", value, "pic2"); return this; } public GElecInfoCriteria andPic2LessThan(String value) { addCriterion("pic2 <", value, "pic2"); return this; } public GElecInfoCriteria andPic2LessThanOrEqualTo(String value) { addCriterion("pic2 <=", value, "pic2"); return this; } public GElecInfoCriteria andPic2Like(String value) { addCriterion("pic2 like", value, "pic2"); return this; } public GElecInfoCriteria andPic2NotLike(String value) { addCriterion("pic2 not like", value, "pic2"); return this; } public GElecInfoCriteria andPic2In(List<String> values) { addCriterion("pic2 in", values, "pic2"); return this; } public GElecInfoCriteria andPic2NotIn(List<String> values) { addCriterion("pic2 not in", values, "pic2"); return this; } public GElecInfoCriteria andPic2Between(String value1, String value2) { addCriterion("pic2 between", value1, value2, "pic2"); return this; } public GElecInfoCriteria andPic2NotBetween(String value1, String value2) { addCriterion("pic2 not between", value1, value2, "pic2"); return this; } public GElecInfoCriteria andCreateTimeIsNull() { addCriterion("create_time is null"); return this; } public GElecInfoCriteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return this; } public GElecInfoCriteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return this; } public GElecInfoCriteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return this; } public GElecInfoCriteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return this; } public GElecInfoCriteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return this; } public GElecInfoCriteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return this; } public GElecInfoCriteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return this; } public GElecInfoCriteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return this; } public GElecInfoCriteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return this; } public GElecInfoCriteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return this; } public GElecInfoCriteria andCreatorIdIsNull() { addCriterion("creator_id is null"); return this; } public GElecInfoCriteria andCreatorIdIsNotNull() { addCriterion("creator_id is not null"); return this; } public GElecInfoCriteria andCreatorIdEqualTo(int value) { addCriterion("creator_id =", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdNotEqualTo(int value) { addCriterion("creator_id <>", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdGreaterThan(int value) { addCriterion("creator_id >", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdGreaterThanOrEqualTo(int value) { addCriterion("creator_id >=", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdLessThan(int value) { addCriterion("creator_id <", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdLessThanOrEqualTo(int value) { addCriterion("creator_id <=", new Integer(value), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdIn(List<Integer> values) { addCriterion("creator_id in", values, "creatorId"); return this; } public GElecInfoCriteria andCreatorIdNotIn(List<Integer> values) { addCriterion("creator_id not in", values, "creatorId"); return this; } public GElecInfoCriteria andCreatorIdBetween(int value1, int value2) { addCriterion("creator_id between", new Integer(value1), new Integer(value2), "creatorId"); return this; } public GElecInfoCriteria andCreatorIdNotBetween(int value1, int value2) { addCriterion("creator_id not between", new Integer(value1), new Integer(value2), "creatorId"); return this; } public GElecInfoCriteria andCreatorAgentIdIsNull() { addCriterion("creator_agent_id is null"); return this; } public GElecInfoCriteria andCreatorAgentIdIsNotNull() { addCriterion("creator_agent_id is not null"); return this; } public GElecInfoCriteria andCreatorAgentIdEqualTo(int value) { addCriterion("creator_agent_id =", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdNotEqualTo(int value) { addCriterion("creator_agent_id <>", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdGreaterThan(int value) { addCriterion("creator_agent_id >", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdGreaterThanOrEqualTo(int value) { addCriterion("creator_agent_id >=", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdLessThan(int value) { addCriterion("creator_agent_id <", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdLessThanOrEqualTo(int value) { addCriterion("creator_agent_id <=", new Integer(value), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdIn(List<Integer> values) { addCriterion("creator_agent_id in", values, "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdNotIn(List<Integer> values) { addCriterion("creator_agent_id not in", values, "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdBetween(int value1, int value2) { addCriterion("creator_agent_id between", new Integer(value1), new Integer(value2), "creatorAgentId"); return this; } public GElecInfoCriteria andCreatorAgentIdNotBetween(int value1, int value2) { addCriterion("creator_agent_id not between", new Integer(value1), new Integer(value2), "creatorAgentId"); return this; } public GElecInfoCriteria andStatusIsNull() { addCriterion("status is null"); return this; } public GElecInfoCriteria andStatusIsNotNull() { addCriterion("status is not null"); return this; } public GElecInfoCriteria andStatusEqualTo(int value) { addCriterion("status =", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusNotEqualTo(int value) { addCriterion("status <>", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusGreaterThan(int value) { addCriterion("status >", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusGreaterThanOrEqualTo(int value) { addCriterion("status >=", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusLessThan(int value) { addCriterion("status <", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusLessThanOrEqualTo(int value) { addCriterion("status <=", new Integer(value), "status"); return this; } public GElecInfoCriteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return this; } public GElecInfoCriteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return this; } public GElecInfoCriteria andStatusBetween(int value1, int value2) { addCriterion("status between", new Integer(value1), new Integer(value2), "status"); return this; } public GElecInfoCriteria andStatusNotBetween(int value1, int value2) { addCriterion("status not between", new Integer(value1), new Integer(value2), "status"); return this; } public GElecInfoCriteria andRemarkIsNull() { addCriterion("remark is null"); return this; } public GElecInfoCriteria andRemarkIsNotNull() { addCriterion("remark is not null"); return this; } public GElecInfoCriteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return this; } public GElecInfoCriteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return this; } public GElecInfoCriteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return this; } public GElecInfoCriteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return this; } public GElecInfoCriteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return this; } public GElecInfoCriteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return this; } public GElecInfoCriteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return this; } public GElecInfoCriteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return this; } public GElecInfoCriteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return this; } public GElecInfoCriteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return this; } public GElecInfoCriteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return this; } public GElecInfoCriteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return this; } }
import React, { Component, PropTypes } from 'react'; import { Route, Switch } from 'react-router-dom'; import { Layout, Menu, Breadcrumb } from 'antd'; import PostsPage from '../../pages/Posts'; import LoginPage from '../../pages/Login'; import NavBar from '../NavBar'; import './style.css'; const { Content, Footer } = Layout; export default function App() { return ( <Layout styleName='app'> <NavBar /> <Content styleName='content'> <Switch> <Route path='/login' component={LoginPage} /> <Route path='/register' component={LoginPage} /> <Route path='/' component={PostsPage} /> </Switch> </Content> <Footer styleName='footer'> 2017, Apollo advanced boilerplate </Footer> </Layout> ); }
SELECT DISTINCT k.*, harga.min as hargamin, harga.max as hargamax, count(kk.id) as jumlahkamar, foto.nama FROM public.kosan as k, public.kamar_kosan as kk, (select max(harga) as max, min(harga) as min, idkosan from public.kamar_kosan group by idkosan) as harga, (select max(foto.nama) as nama from public.foto, public.foto_kosan, public.kosan where foto_kosan.idfoto = foto.id AND kosan.id = foto_kosan.idkosan GROUP BY kosan.id) as foto WHERE k.terverifikasi = false AND kk.idkosan = k.id GROUP BY k.id, harga.max, harga.min, foto.nama
## Overview [Bug Report/Feature Request/Ask] Text here. ## Environment - OS: Ubuntu 18.04 - Python version: 3.7.3 --- (for bug report) ### Expected Behavior Text here. ### Actual Behavior Text here. ### Detail Text here. --- (for feature request) ### Feature Detail Text here. ### Motivation and Reason Text here. --- (for ask) ### Question Detail
# frozen_string_literal: true require "json" require "uri" module Miteru class Feeds class Ayashige < Feed HOST = "ayashige.herokuapp.com" URL = "https://#{HOST}" def urls url = url_for("/feed") res = JSON.parse(get(url)) domains = res.map { |item| item["domain"] } domains.map do |domain| [ "https://#{domain}", "http://#{domain}" ] end.flatten rescue HTTPResponseError => e puts "Failed to load ayashige feed (#{e})" [] end private def url_for(path) URI(URL + path) end end end end
import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; class MessageFile extends Equatable { final int index; final String filename; final int size; const MessageFile({ @required this.index, @required this.filename, @required this.size, }); @override List<Object> get props => [ index, filename, size, ]; }
import { Controller, Body, Post, Get, Param, Delete, Put, UsePipes, ValidationPipe } from "@nestjs/common"; import { ItempedidoService } from "./itempedido.service"; @Controller('/item') export class ItemPedidoController { constructor(private itemService: ItempedidoService ) { } @Get() showAllproduto(){ return this.itemService.readAll(); } @Post() createProduto(@Body() ItemPedido){ return this.itemService.create(ItemPedido); } @Get('id:') readProduto(@Param() id: number){ return this.itemService.read(id); } @Put('id:') upadateProduto(@Param('id') id: number, @Body() data) { return this.itemService.update(id, data); } }
package hello.world.angelkitchen.view.bottom_menu.bookmark import android.content.Intent import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.BaseTransientBottomBar.LENGTH_SHORT import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import hello.world.angelkitchen.R import hello.world.angelkitchen.base.BindingFragment import hello.world.angelkitchen.databinding.FragmentBookmarkBinding import hello.world.angelkitchen.view.bottom_menu.direction.DirectionAttachActivity import hello.world.angelkitchen.view.bottom_menu.search.search_result.SearchResultViewModel import hello.world.angelkitchen.view.bottom_menu.search.search_result.bottom_sheet.BottomSheetFragment @AndroidEntryPoint class BookmarkFragment : BindingFragment<FragmentBookmarkBinding>(R.layout.fragment_bookmark) { private val viewModel: BookmarkViewModel by activityViewModels() private val searchResultViewModel: SearchResultViewModel by activityViewModels() private val linearLayoutManager: LinearLayoutManager by lazy { LinearLayoutManager(activity) } private val sheet: BottomSheetFragment by lazy { BottomSheetFragment() } private lateinit var bookmarkAdapter: BookmarkAdapter override fun initView() { initRecyclerView() viewModel.getAllData().observe(this, { bookmarkAdapter.setData(it) }) } private fun initRecyclerView() { linearLayoutManager.apply { reverseLayout = true stackFromEnd = true } val decoration = DividerItemDecoration(activity, linearLayoutManager.orientation) bookmarkAdapter = BookmarkAdapter( emptyList(), onClickItem = { searchResultViewModel.touchItem(it) sheet.show(activity?.supportFragmentManager!!, "BookmarkFragment") }, onClickButton = { val intent = Intent(activity, DirectionAttachActivity::class.java) intent.putExtra("share_address", it.address) startActivity(intent) } ) binding.rvBookmark.apply { layoutManager = linearLayoutManager adapter = bookmarkAdapter addItemDecoration(decoration) } ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean = true override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { viewModel.deleteBookmark(viewModel.getAllData().value!![viewHolder.adapterPosition].number) Snackbar.make(binding.container, "삭제되었습니다.", LENGTH_SHORT).show() } }).apply { attachToRecyclerView(binding.rvBookmark) } } }
___x_cmd_scala_unpack(){ ___x_cmd_pkg_install___unzip "$name" "$version" "$osarch" } ___x_cmd_scala_unpack
package ru.ifmo.genetics.tools.microassembly; import ru.ifmo.genetics.utils.FileUtils; import ru.ifmo.genetics.utils.tool.ExecutionFailedException; import ru.ifmo.genetics.utils.tool.Parameter; import ru.ifmo.genetics.utils.tool.Tool; import ru.ifmo.genetics.utils.tool.inputParameterBuilder.FileMVParameterBuilder; import ru.ifmo.genetics.utils.tool.inputParameterBuilder.FileParameterBuilder; import ru.ifmo.genetics.utils.tool.inputParameterBuilder.IntParameterBuilder; import java.io.File; import java.io.IOException; public class ReadsMapper extends Tool { public static final String NAME = "reads-mapper"; public static final String DESCRIPTION = "maps reads on contigs"; // input parameters public final Parameter<File> indexFile = addParameter(new FileParameterBuilder("index-file") .mandatory() .withDescription("contigs index file path (without extension)") .create()); public final Parameter<File[]> readsFiles = addParameter(new FileMVParameterBuilder("reads-files") .mandatory() .withDescription("reads files") .create()); public final Parameter<File> resultingMapDir = addParameter(new FileParameterBuilder("resulting-map-dir") .optional() .withDefaultValue(workDir.append("map")) .withDescription("file with resulting map directory") .create()); public final Parameter<Integer> trimming = addParameter(new IntParameterBuilder("trimming") .optional() .withDefaultValue(0) .withDescription("length of trimming from right end") .create()); // internal variables // output parameters @Override protected void runImpl() throws ExecutionFailedException { try { FileUtils.createOrClearDir(resultingMapDir.get()); for (File f : readsFiles.get()) { info("Running mapping command for file " + f.getName() + "..."); String command = "bowtie --trim3 " + trimming.get() + " -a -m 10 -p " + availableProcessors.get(); String resultingFile = new File(resultingMapDir.get(), FileUtils.baseName(f) + ".map").toString(); command += " " + indexFile.get() + " " + f + " " + resultingFile; execCommand(command); } } catch (IOException e) { throw new ExecutionFailedException(e); } catch (InterruptedException e) { throw new ExecutionFailedException(e); } } @Override protected void cleanImpl() { } public ReadsMapper() { super(NAME, DESCRIPTION); } }
# Authentication-UI - RELEASE NOTES ## Version 1.0.0 - 18th April 2020 This is our most major release, which introduces the following features: -------------Ignore anything below here: AUtogenerated by (ReadMe Master templates)[] ## Version 1.1.9 (27th December 2017) A minor release, which fixed the following issues: - Patched security settings ## Version 1.1.8 (23rd Decemeber 2017) A bugfix release, which fixes the following issues: - If a `Tab`, is selected, it crashed. - Fixed bug where when using app and a call came in, the app tended to crash. ```other releases version bla bla version bla bla version bla bla...till say the first version ``` ## Version 0.0.1 (2nd January 2017) The first release with the following features: List the features of the app: - Tutorial feature - AppIntro which talks about the app before its started.
#this is the unittest for the function "win_query" #Input: #gamefield in current situation: Player 1(1) Player 2 (2) # |1|0|2| # |1|2|0| # |2|1|0| #Expected output: # "Player 2 is the winner! Game over! New game : 1, End game: 2, Current score: 3, highest winstreak: 4 utest_win_query: #Step 1: load the field information in the storage li t1, 1 sw t1, -100(sp) li t1, 0 sw t1, -104(sp) li t1, 2 sw t1, -108(sp) li t1, 1 sw t1, -112(sp) li t1, 2 sw t1, -116(sp) li t1, 0 sw t1, -120(sp) li t1, 2 sw t1, -124(sp) li t1, 1 sw t1, -128(sp) li t1, 0 sw t1, -132(sp) li t1, 2 sw t1, -244(sp) jal win_query li a7, 10 ecall .include "tictactoe.asm"
use crate::files::cursor::SeekMethod; use crate::files::filename; use crate::files::handle::{FileHandle, Handle}; use crate::filesystems; use crate::pipes; use super::current_process; use syscall::files::{DirEntryInfo, DirEntryType}; use syscall::result::SystemError; pub fn open_path(path_str: &'static str) -> Result<u32, SystemError> { let (drive, path) = filename::string_to_drive_and_path(path_str); let number = filesystems::get_fs_number(drive).ok_or(SystemError::NoSuchDrive)?; let fs = filesystems::get_fs(number).ok_or(SystemError::NoSuchFileSystem)?; let local_handle = fs.open(path).map_err(|_| SystemError::NoSuchEntity)?; Ok(current_process().open_file(number, local_handle).as_u32()) } pub fn close(handle: u32) -> Result<(), SystemError> { let pair_to_close = { let cur = current_process(); let prev = cur.close_file(FileHandle::new(handle)); match prev { Some(pair) => if !current_process().references_drive_and_handle(pair.0, pair.1) { Some(pair) } else { // Another handle in this process references the same file descriptor None }, None => None, } }; let pair = pair_to_close.ok_or(SystemError::BadFileDescriptor)?; match filesystems::get_fs(pair.0) { Some(fs) => fs.close(pair.1).map_err(|_| SystemError::IOError), None => Err(SystemError::NoSuchFileSystem), } } pub unsafe fn read(handle: u32, dest: *mut u8, length: usize) -> Result<usize, SystemError> { let drive_and_handle = current_process() .get_open_file_info(FileHandle::new(handle)) .ok_or(SystemError::BadFileDescriptor)?; let fs = filesystems::get_fs(drive_and_handle.0).ok_or(SystemError::NoSuchFileSystem)?; let buffer = core::slice::from_raw_parts_mut(dest, length); fs.read(drive_and_handle.1, buffer).map_err(|_| SystemError::IOError) } pub unsafe fn write(handle: u32, src: *const u8, length: usize) -> Result<usize, SystemError> { let drive_and_handle = current_process() .get_open_file_info(FileHandle::new(handle)) .ok_or(SystemError::BadFileDescriptor)?; let fs = filesystems::get_fs(drive_and_handle.0).ok_or(SystemError::NoSuchFileSystem)?; let buffer = core::slice::from_raw_parts(src, length); fs.write(drive_and_handle.1, buffer).map_err(|_| SystemError::IOError) } pub fn ioctl(handle: u32, command: u32, arg: u32) -> Result<u32, SystemError> { let drive_and_handle = current_process() .get_open_file_info(FileHandle::new(handle)) .ok_or(SystemError::BadFileDescriptor)?; let fs = filesystems::get_fs(drive_and_handle.0).ok_or(SystemError::NoSuchFileSystem)?; fs.ioctl(drive_and_handle.1, command, arg).map_err(|_| SystemError::IOError) } pub fn dup(to_duplicate: u32, to_replace: u32) -> Result<u32, SystemError> { let drive_and_handle = current_process() .get_open_file_info(FileHandle::new(to_duplicate)) .ok_or(SystemError::BadFileDescriptor)?; let (handle, pair_to_close) = { let cur = current_process(); let mut files = cur.get_open_files().write(); let handle = if to_replace == 0xffffffff { files.get_next_available_handle().ok_or(SystemError::MaxFilesExceeded)? } else { FileHandle::new(to_replace) }; let prev = files.set_handle_directly(handle, drive_and_handle.0, drive_and_handle.1); match prev { Some(pair) => if !current_process().references_drive_and_handle(pair.0, pair.1) { (handle, Some(pair)) } else { // Another handle in this process references the same file descriptor (handle, None) }, None => (handle, None), } }; let pair = pair_to_close.ok_or(SystemError::BadFileDescriptor)?; match filesystems::get_fs(pair.0) { Some(fs) => { fs.close(pair.1).map_err(|_| SystemError::IOError)?; Ok(handle.as_u32()) }, None => Err(SystemError::NoSuchFileSystem), } } pub fn pipe() -> Result<(u32, u32), SystemError> { let (read_local, write_local) = pipes::create_pipe().map_err(|_| SystemError::Unknown)?; let (read, write) = { let current = current_process(); let fs_number = unsafe { filesystems::PIPE_FS }; let read = current.open_file(fs_number, read_local).as_u32(); let write = current.open_file(fs_number, write_local).as_u32(); (read, write) }; Ok((read, write)) } pub fn seek(handle: u32, method: u32, cursor: u32) -> Result<u32, SystemError> { let seek_method = match method { 1 => SeekMethod::Relative(cursor as i32 as isize), _ => SeekMethod::Absolute(cursor as usize), }; let drive_and_handle = current_process() .get_open_file_info(FileHandle::new(handle)) .ok_or(SystemError::BadFileDescriptor)?; let fs = filesystems::get_fs(drive_and_handle.0).ok_or(SystemError::NoSuchFileSystem)?; fs.seek(drive_and_handle.1, seek_method) .map(|new_cursor| new_cursor as u32) .map_err(|_| SystemError::IOError) } pub fn open_dir(path_str: &'static str) -> Result<u32, SystemError> { let (drive, path) = filename::string_to_drive_and_path(path_str); let number = filesystems::get_fs_number(drive).ok_or(SystemError::NoSuchDrive)?; let fs = filesystems::get_fs(number).ok_or(SystemError::NoSuchFileSystem)?; let local_handle = fs.open_dir(path).map_err(|_| SystemError::NoSuchEntity)?; current_process().open_directory(number, local_handle).map(|handle| handle.as_u32()) } pub fn read_dir(handle: u32, index: usize, info: *mut DirEntryInfo) -> Result<(), SystemError> { let drive_and_handle = current_process() .get_open_dir_info(FileHandle::new(handle)) .ok_or(SystemError::BadFileDescriptor)?; let fs = filesystems::get_fs(drive_and_handle.0).ok_or(SystemError::NoSuchFileSystem)?; let entry = unsafe { &mut *info }; fs.read_dir(drive_and_handle.1, index, entry).map_err(|_| SystemError::NoSuchEntity) }
.code get_peb PROC mov rax, GS:[60h] ret get_peb ENDP END
git clone $1 $2 cd $2 # Install/update composer dependecies composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev cp .env.example .env # config setting to production usage sed -i "" 's/APP_ENV=local/APP_ENV=production/g' .env sed -i "" 's/APP_DEBUG=true/APP_DEBUG=false/g' .env sed -i "" 's/DB_DATABASE=homestead/DB_DATABASE='$3'/g' .env sed -i "" 's/DB_USERNAME=homestead/DB_USERNAME='$4'/g' .env sed -i "" 's/DB_PASSWORD=secret/DB_PASSWORD='$5'/g' .env # generate application key php artisan key:generate # Run database migrations php artisan migrate --force --seed # Install node modules npm install # Build assets using Laravel Mix npm run production
package ITS::WICS::XML2XLIFF::ITSProcessor; use strict; use warnings; # VERSION # ABSTRACT: Process and convert XML and XLIFF ITS (internal use only). use ITS qw(its_ns); use ITS::DOM::Element qw(new_element); use Exporter::Easy ( OK => [qw( its_requires_inline convert_atts localize_rules transfer_inline_its has_localizable_inline )]); #TODO: put all of these in one place our $XLIFF_NS = 'urn:oasis:names:tc:xliff:document:1.2'; our $ITSXLF_NS = 'http://www.w3.org/ns/its-xliff/'; =head1 EXPORTS The following function may be exported: =head2 C<its_requires_inline> Return true if converting the ITS info on the given element requires that it be rendered inline (as mrk) instead of structural (as its own source). Currently the only information tested for is terminology information. The arguments are the element being tested and the hash reference containing the global information pertaining to it. =cut # TODO: how about returning null if none is required, and returning a <mrk> element # when it is? That way we could copy the term info and remove it from the original # element here. It would save logic elsewhere. sub its_requires_inline { my ($el, $global) = @_; # any terminology information requires inlining if($el->att('term', its_ns())){ return 1; } return 0 unless $global; if(exists $global->{term}){ return 1; } return 0; } =head2 C<transfer_inline_its> Transfer ITS that is required to be on a mrk (not on a source) from one element (first argument) to the another (second argument). Arguments are the element to move the markup from and the element to move the markup to. =cut sub transfer_inline_its { my ($from, $to) = @_; #all of the terminology information has to be moved my $mtype = $from->att('mtype'); if($mtype =~ /term/){ $to->set_att('mtype', $from->att('mtype')); $from->remove_att('mtype'); my @term_atts = qw( termInfo termInfoRef termConfidence ); for my $att (@term_atts){ if (my $value = $from->att($att, $ITSXLF_NS)){ $from->remove_att($att, $ITSXLF_NS); $to->set_att("itsxlf:$att", $value, $ITSXLF_NS); } } } return; } =head2 C<has_localizable_inline> Arguments: an array ref containing attribute nodes, and the match index containing the global ITS info for an element. Returns true if there is any ITS information which must be placed as an attribute on the element which it applies to, if the element is inline. =cut sub has_localizable_inline { my ($atts, $index) = @_; if($index){ for my $key (keys %$index){ #everything except idValue generates local atts on <mrk> return 1 if ($key ne 'idValue'); } } for my $att(@$atts){ return 1 if($att->name ne 'xml:id'); } return 0; } =head2 C<convert_atts> Convert all XML ITS attributes into XLIFF ITS for the given element. The arguments are: first the local element where any new attributes should be placed; second an array ref containing the attribute nodes to be converted; and third the C<trans-unit> element currently being created. This is not necessary if the element in question is inline. =cut sub convert_atts { my ($el, $atts, $tu) = @_; my %atts; for (@$atts){ $atts{'{' . $_->namespace_URI . '}' . $_->local_name} = $_ } #TODO: there might be elements other than source and mrk someday my $inline = $el->local_name eq 'mrk' ? 1 : 0; for my $att (@$atts){ # ignore if already removed while processing other atts next if !$att->parent; my $att_ns = $att->namespace_URI || ''; my $att_name = $att->local_name; if($att_ns eq its_ns()){ if($att_name eq 'version'){ $att->remove; } # If there's a locNoteType but no locNote, then it # doesn't get processed (no reason to). if($att_name eq 'locNote'){ my $type = 'description'; if(my $typeNode = $atts{'{'.its_ns().'}'.'locNoteType'}){ $type = $typeNode->value; $typeNode->remove; } _process_locNote($el, $att->value, $type, $tu, $inline); $att->remove; }elsif($att_name eq 'translate'){ _process_translate($el, $att->value, $tu, $inline); $att->remove; # If there's a term* but no term, then it # doesn't get processed (no reason to). }elsif($att_name eq 'term'){ my ($infoRef, $conf) = (undef, undef); # default is undef if(my $infoRefNode = $atts{'{'.its_ns().'}'.'termInfoRef'}){ $infoRef = $infoRefNode->value; $infoRefNode->remove; } if(my $confNode = $atts{'{'.its_ns().'}'.'termConfidence'}){ $conf = $confNode->value; $confNode->remove; } _process_term( $el, term => $att->value, termInfoRef => $infoRef, termConfidence => $conf, ); $att->remove; } #default for ITS atts: leave them there }elsif($att->name eq 'xml:id'){ _process_idValue($att->value, $tu, $inline); $att->remove; # just remove any other attributes for now }else{ $att->remove; } } return; } =head2 C<localize_rules> Arguments are: first an element to have ITS metadata applied locally; second the translation unit containing the element; third the match index containing the global ITS info for the element; and fourth an array ref containing the local attribute nodes assumed to exist on the element being processed. This function converts ITS info contained in global rules matching the element into equivalent local markup on either the element itself or the trans-unit. =cut sub localize_rules { my ($el, $tu, $its_info, $atts) = @_; my %atts; for (@$atts){ $atts{'{' . $_->namespace_URI . '}' . $_->local_name} = $_ } #TODO: there might be elements other than source and mrk someday my $inline = $el->local_name eq 'mrk' ? 1 : 0; #each of these is a check that 1) the category is selected in a global #rule and 2) there is no local selection. TODO: clean this up? while (my ($name, $value) = each %$its_info){ if($name eq 'locNote' && # its:locNote !exists $atts{'{'.its_ns().'}'.'locNote'}){ my $type = $its_info->{locNoteType} || 'description'; _process_locNote($el, $value, $type, $tu, $inline) }elsif($name eq 'translate' && # its:translate !exists $atts{'{'.its_ns().'}'.'translate'}){ _process_translate($el, $value, $tu, $inline); }elsif($name eq 'idValue' && # xml:id !exists $atts{'{http://www.w3.org/XML/1998/namespace}id'}){ _process_idValue($value, $tu, $inline); }elsif($name eq 'term' && # its:term !exists $atts{'{'.its_ns().'}'.'term'}){ my %termHash; my @term_atts = qw( term termInfo termInfoRef termConfidence ); @termHash{@term_atts} = @$its_info{@term_atts}; _process_term($el, %termHash); } } return; } # pass in an element to be annotated, locNote and locNoteType values, # and whether the element is inline or not # TODO: too many params; use named ones. sub _process_locNote { my ($el, $note, $type, $tu, $inline) = @_; my $priority = $type eq 'alert' ? '1' : '2'; if($inline){ $el->set_att('comment', $note); $el->set_att('itsxlf:locNoteType', $type, $ITSXLF_NS); }else{ my $note = new_element('note', {}, $note, $XLIFF_NS); $note->set_att('priority', $priority); $note->paste($tu); } return; } # input element and it's ITS translate value, containing TU, and whether # it's inline # TODO: too many params; use named ones. sub _process_translate { my ($el, $translate, $tu, $inline) = @_; if($inline){ $el->set_att('mtype', $translate eq 'yes' ? 'x-its-translate-yes' : 'protected'); }else{ $tu->set_att('translate', $translate); } return; } sub _process_term { my ($el, %termInfo) = @_; $termInfo{term} eq 'yes' ? $el->set_att('mtype', 'term') : $el->set_att('mtype', 'x-its-term-no'); for my $name(qw(termInfoRef termConfidence termInfo)){ if (my $val = $termInfo{$name}){ $el->set_att("itsxlf:$name", $val, $ITSXLF_NS); } } return; } sub _process_idValue { my ($id, $tu, $inline) = @_; #this att is ignored on inline elements if(!$inline){ $tu->set_att('resname', $id); } return; } 1;
using System; using System.Collections.Generic; using System.Threading.Tasks; using Str.Wallpaper.Domain.Contracts; namespace Str.Wallpaper.Domain.Models { public sealed class DomainUser { #region Private Fields private readonly IUserSettingsRepository userRepository; private readonly IUserSessionService sessionService; #endregion Private Fields #region Constructor // ReSharper disable once UnusedMember.Global public DomainUser() { } // Needed by AutoMapper but never actually used... public DomainUser(IUserSettingsRepository UserRepository, IUserSessionService SessionService) { userRepository = UserRepository; sessionService = SessionService; SelectedCollections = new List<string>(); } #endregion Constructor #region Properties public string Id { get; set; } public string Username { get; set; } public string Password { get; set; } public List<string> SelectedCollections { get; set; } #endregion Properties #region Domain Properties public bool AreSettingsChanged { get; set; } public bool IsLoggingIn { get; set; } public bool IsOnline => SessionId != null; public Guid? SessionId { get; set; } #endregion Domain Properties #region Domain Methods public async Task LoadUserSettingsAsync() { await userRepository.LoadUserSettingsAsync(this); } public async Task SaveUserSettingsAsync() { await userRepository.SaveUserSettingsAsync(this); AreSettingsChanged = false; } public async Task<bool> CreateUserAsync() { return await sessionService.CreateUserAsync(this); } public async Task<bool> LoginAsync() { return await sessionService.LoginAsync(this); } public async Task DisconnectAsync() { await sessionService.DisconnectAsync(this); if (AreSettingsChanged) await SaveUserSettingsAsync(); SessionId = null; } #endregion Domain Methods } }
package com.github.skyfe79.android.helloandroidrck.action import com.github.skyfe79.android.reactcomponentkit.redux.Action data class ClickButtonAction(val message: String): Action
require 'spec_helper' require 'fakefs/spec_helpers' module LicenseFinder describe Nuget do it_behaves_like "a PackageManager" describe "#assemblies" do include FakeFS::SpecHelpers before do FileUtils.mkdir_p "app/packages" FileUtils.mkdir_p "app/Assembly1/" FileUtils.mkdir_p "app/Assembly1.Tests/" FileUtils.mkdir_p "app/Assembly2/" FileUtils.touch "app/Assembly1/packages.config" FileUtils.touch "app/Assembly1.Tests/packages.config" FileUtils.touch "app/Assembly2/packages.config" end it "finds dependencies all subdirectories containing a packages.config" do nuget = Nuget.new project_path: Pathname.new("app") expect(nuget.assemblies.map(&:name)).to match_array ['Assembly1', 'Assembly1.Tests', 'Assembly2'] end end describe "#current_packages" do include FakeFS::SpecHelpers before do FileUtils.mkdir_p "app/packages" FileUtils.mkdir_p "app/Assembly1/" FileUtils.mkdir_p "app/Assembly1.Tests/" FileUtils.mkdir_p "app/Assembly2/" FileUtils.touch "app/Assembly1/packages.config" FileUtils.touch "app/Assembly1.Tests/packages.config" FileUtils.touch "app/Assembly2/packages.config" end before do assembly_1_packages = <<-ONE <?xml version="1.0" encoding="utf-8"?> <packages> <package id="GoToDependency" version="4.84.4790.14417" targetFramework="net45" /> <package id="ObscureDependency" version="1.3.15" targetFramework="net45" /> <package id="OtherObscureDependency" version="2.4.2" targetFramework="net45" /> </packages> ONE assembly_1_tests_packages = <<-ONE <?xml version="1.0" encoding="utf-8"?> <packages> <package id="GoToDependency" version="4.84.4790.14417" targetFramework="net45" /> <package id="TestFramework" version="5.0.1" targetFramework="net45" /> </packages> ONE assembly_2_packages = <<-ONE <?xml version="1.0" encoding="utf-8"?> <packages> <package id="ObscureDependency" version="1.3.15" targetFramework="net45" /> <package id="CoolNewDependency" version="2.4.2" targetFramework="net45" /> </packages> ONE File.write("app/Assembly1/packages.config", assembly_1_packages) File.write("app/Assembly1.Tests/packages.config", assembly_1_tests_packages) File.write("app/Assembly2/packages.config", assembly_2_packages) end it "lists all the packages used in an assembly" do nuget = Nuget.new project_path: Pathname.new("app") deps = %w(GoToDependency ObscureDependency OtherObscureDependency TestFramework CoolNewDependency) expect(nuget.current_packages.map(&:name).uniq).to match_array(deps) end end end end
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import math import time import numpy as np import paddle import logging import argparse import functools sys.path[0] = os.path.join( os.path.dirname("__file__"), os.path.pardir, os.path.pardir) sys.path[1] = os.path.join( os.path.dirname("__file__"), os.path.pardir, os.path.pardir, os.path.pardir) from paddleslim.common import get_logger from paddleslim.quant import export_quant_infermodel from utility import add_arguments, print_arguments import imagenet_reader as reader _logger = get_logger(__name__, level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argparser=parser) # yapf: disable add_arg('use_gpu', bool, True, "Whether to use GPU or not.") add_arg('batch_size', int, 4, "train batch size.") add_arg('num_epoch', int, 1, "train epoch num.") add_arg('save_iter_step', int, 1, "save train checkpoint every save_iter_step iter num.") add_arg('learning_rate', float, 0.0001, "learning rate.") add_arg('weight_decay', float, 0.00004, "weight decay.") add_arg('use_pact', bool, True, "whether use pact quantization.") add_arg('checkpoint_path', str, None, "model dir to save quanted model checkpoints") add_arg('model_path_prefix', str, None, "storage directory of model + model name (excluding suffix)") add_arg('teacher_model_path_prefix', str, None, "storage directory of teacher model + teacher model name (excluding suffix)") add_arg('distill_node_name_list', str, None, "distill node name list", nargs="+") add_arg('checkpoint_filename', str, None, "checkpoint filename to export inference model") add_arg('export_inference_model_path_prefix', str, None, "inference model export path prefix") def export(args): place = paddle.CUDAPlace(0) if args.use_gpu else paddle.CPUPlace() exe = paddle.static.Executor(place) quant_config = { 'weight_quantize_type': 'channel_wise_abs_max', 'activation_quantize_type': 'moving_average_abs_max', 'not_quant_pattern': ['skip_quant'], 'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'] } train_config={ "num_epoch": args.num_epoch, # training epoch num "max_iter": -1, "save_iter_step": args.save_iter_step, "learning_rate": args.learning_rate, "weight_decay": args.weight_decay, "use_pact": args.use_pact, "quant_model_ckpt_path":args.checkpoint_path, "teacher_model_path_prefix": args.teacher_model_path_prefix, "model_path_prefix": args.model_path_prefix, "distill_node_pair": args.distill_node_name_list } export_quant_infermodel(exe, place, scope=None, quant_config=quant_config, train_config=train_config, checkpoint_path=os.path.join(args.checkpoint_path, args.checkpoint_filename), export_inference_model_path_prefix=args.export_inference_model_path_prefix) def main(): args = parser.parse_args() args.use_pact = bool(args.use_pact) print_arguments(args) export(args) if __name__ == '__main__': paddle.enable_static() main()
import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { SERVER_API_URL } from 'app/app.constants'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class LoginOAuth2Service { constructor(private http: HttpClient) {} login() { let port = location.port ? ':' + location.port : ''; if (port === ':9000') { port = ':8761'; } let contextPath = location.pathname; if (contextPath.endsWith('accessdenied')) { contextPath = contextPath.substring(0, contextPath.indexOf('accessdenied')); } if (!contextPath.endsWith('/')) { contextPath = contextPath + '/'; } // If you have configured multiple OIDC providers, then, you can update this URL to /login. // It will show a Spring Security generated login page with links to configured OIDC providers. location.href = `//${location.hostname}${port}${contextPath}oauth2/authorization/oidc`; } logout(): Observable<any> { // logout from the server return this.http.post(SERVER_API_URL + 'api/logout', {}, { observe: 'response' }).pipe( map((response: HttpResponse<any>) => { return response; }) ); } }
--- kernelspec: display_name: Python 3 language: python name: python3 --- ```{code-cell} ipython3 cat = 42 ```
<?php /** * DotBoost Technologies Inc. * DotKernel Application Framework * * @category DotKernel * @copyright Copyright (c) 2009-2015 DotBoost Technologies Inc. (http://www.dotboost.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * @version $Id: User.php 981 2015-06-11 13:51:41Z gabi $ */ /** * User Model * Here are all the actions related to the user * @category DotKernel * @package Frontend * @author DotKernel Team <[email protected]> */ class Post extends Dot_Model_User { private $_userAgent; private $_httpReferer; /** * Constructor * @access public */ public function __construct($userAgent = null, $httpReferer = null) { parent::__construct(); // if no userAgent is given on function call mark it as empty - if the userAgent is empty keep it empty // if the userAgent stays empty it can be used for robot detecting or devices with blank UA (usually bots) // HTTP Reffer is optional so mark it empty if there is no HTTP Reffer $this->_userAgent = (! is_null($userAgent)) ? $userAgent : ''; $this->_httpReferer = (! is_null($httpReferer)) ? $httpReferer : ''; } public function getPostList($page = 1) { $select = $this->db->select()->from('post'); $result = $this->db->fetchAll($select); return $result; } public function getCommentsList($postId, $page = 1) { $select = $this->db->select() ->from('comments') ->where('postId=?', $postId) ->join('user', 'user.id = comments.userId', ['username' => 'user.username']) ->order('data DESC'); $result = $this->db->fetchAll($select); return $result; } public function getReplysList($postId, $page = 1) { $select = $this->db->select() ->from('reply') ->where('postId=?', $postId) ->join('user', 'user.id = reply.userId', ['username' => 'user.username']) // ->order('data DESC') ; $result = $this->db->fetchAll($select); return $result; } public function getUploadUsername($postId, $page = 1) { $select = $this->db->select() ->from('user', ['username']) ->join('post', 'post.userId = user.id', []); $result = $this->db->fetchRow($select); return $result; } public function getCategoryName($postId, $page = 1) { $select = $this->db->select() ->from('post',[]) ->joinLeft('category','post.categoryId =category.id ',['categoryName'=>'name']); // $result = $this->db->fetchRow($select); return $result['categoryName']; } public function getCommentById($commentId) { $select = $this->db->select() ->from('comments') ->where('id=?', $commentId); $result = $this->db->fetchRow($select); return $result; } public function updateComment($id, $data) { $this->db->update('comments', $data, 'id = ' . $id); return true; } public function getCommentNumber($postId) { $select = $this->db->select() ->from('comments', 'count(*)') ->where('postId=?', $postId); $result = $this->db->fetchRow($select); return $result; } public function checkComments($userId, $postId, $text) { $select = $this->db->select() ->from('comments') ->where('userId=?', $userId) ->where('postId=?', $postId) ->where('text=?', $text); $result = $this->db->fetchAll($select); return (! empty($result)); } public function insertComment($data) { try { $insert = $this->db->insert('comments', $data); return true; } catch(Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; return false; } } public function insertReply($data) { try { $insert = $this->db->insert('reply', $data); return true; } catch(Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; return false; } } public function insertRating($data) { $insert = $this->db->insert('rating', $data); return true; } public function updateRating($id, $data) { $this->db->update('rating',$data, 'id = ' . $id); return true; } public function checkIfRatingExists($userId,$postId) { $select = $this->db->select()->from('rating') ->where('userId=?',$userId) ->where('postId=?', $postId) ; $result = $this->db->fetchAll($select); return $result[0]; } public function getPostById($postId) { $select = $this->db->select() ->from('post') ->where('id=?', $postId); $result = $this->db->fetchRow($select); return $result; } public function getCategoryList($page = 1) { $select = $this->db->select()->from('category'); $result = $this->db->fetchAll($select); return $result; } public function insertPost($data) { try { $insert = $this->db->insert('post', $data); return true; } catch(Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; return false; } } // public function nextPost($postId) // { // $select = $this->db->select()->from('post')->where('id=?',$postId); // $result= $this->db->fetchRow($select); // return $result; // } public function nextPost($postId) { // length of ids $select = $this->db->select()->from('post', array('row_count' => 'COUNT(*)')); $result = $this->db->fetchRow($select); // return $result['row_count']; $length = (int) $result['row_count']; //array of all ids $select2 = $this->db->select()->from('post', 'id'); $result2 = $this->db->fetchAll($select2); $l2 = count($result2); // return $l2; //finding curent id $select3 = $this->db->select() ->from('post') ->where('id=?', $postId); $result3 = $this->db->fetchRow($select3); $presentId = (int) $result3['id']; // return $result3['id']; //next button for($i = 0; $i < $l2; $i ++) { if($presentId == $result2[$i]['id'] && $i + 1) { $next = $result2[$i + 1]['id']; } } return $next; } public function prevPost($postId) { // length of ids $select = $this->db->select()->from('post', array('row_count' => 'COUNT(*)')); $result = $this->db->fetchRow($select); // return $result['row_count']; $length = (int) $result['row_count']; //array of all ids $select2 = $this->db->select()->from('post', 'id'); $result2 = $this->db->fetchAll($select2); $l2 = count($result2); // return $l2; //finding curent id $select3 = $this->db->select() ->from('post') ->where('id=?', $postId); $result3 = $this->db->fetchRow($select3); $presentId = (int) $result3['id']; // return $result3['id']; //next button for($i = 0; $i < $l2; $i ++) { if($presentId == $result2[$i]['id'] && $i + 1) { $prev = $result2[$i - 1]['id']; } } return $prev; } private function saveHistory($id) { $select = $this->db->select() ->from('post') ->where('id=?', $id); $result = $this->db->fetchRow($select); return $result; } public function getLastPostUploadedId() { $select = $this->db->select() ->from('post', 'id') ->order('id asc') ->limit('1'); $result = $this->db->fetchRow($select); return $result; } public function getFirstPostUploadedId() { $select = $this->db->select() ->from('post', 'id') ->order('id desc') ->limit('1'); $result = $this->db->fetchRow($select); return $result; } public function commentData($id) { $select = $this->db->select() ->from('comments') ->where('comments.id=?', $id) ->join('user', 'user.id = comments.userId', ['username' => 'user.username']) ; $result = $this->db->fetchAll($select); return $result; } public function commentData2($id) { $select = $this->db->select() ->from('user','username') ->where('user.id=?', $id) ; $result = $this->db->fetchRow($select); return $result['username']; } }
#!/bin/sh find . -name 'Icon?' -type f -delete
describe("Scanner", function() { var Scanner; beforeEach(function() { scanner = new Scanner(); }); });
import { EnteDto } from "../../modello-dto/iscritto-dto/ente-dto"; export class Ente extends EnteDto{ constructor(identificativo: string, email: string, password: string, sede: string, annoDiFondazione: Date){ super(identificativo, email, password, sede, annoDiFondazione); } }
## SortingNetworks ### Target frameworks * [net6.0](net6.0/SortingNetworks.md) * [net5.0](net5.0/SortingNetworks.md) * [netcoreapp3.1](netcoreapp3.1/SortingNetworks.md) * [netstandard2.1](netstandard2.1/SortingNetworks.md) * [netstandard1.3](netstandard1.3/SortingNetworks.md)
import deepEqual from 'deep-equal'; import clonedeep from 'lodash.clonedeep'; import {Callback} from 'reactive-properties'; import {providers} from 'ethers'; import {BalanceChecker, TokenDetailsWithBalance, Nullable, ensureNotNullish, ETHER_NATIVE_TOKEN, ProviderService, isAddressIncludedInLog} from '@unilogin/commons'; import {IERC20Interface} from '@unilogin/contracts'; import {TokensDetailsStore} from '../services/TokensDetailsStore'; import {BlockNumberState} from '../states/BlockNumberState'; import {InvalidObserverState} from '../utils/errors'; export type OnBalanceChange = (data: TokenDetailsWithBalance[]) => void; export class BalanceObserver { private lastTokenBalances: TokenDetailsWithBalance[] = []; private callbacks: OnBalanceChange[] = []; private unsubscribeBlockNumber: Nullable<Callback> = null; constructor( private balanceChecker: BalanceChecker, private walletAddress: string, private tokenDetailsStore: TokensDetailsStore, private blockNumberState: BlockNumberState, private providerService: ProviderService, ) {} async getErc20ContractsWithChangedBalances() { const ierc20adresses = this.tokenDetailsStore.tokensDetails .map(token => token.address) .filter(address => address !== ETHER_NATIVE_TOKEN.address); if (ierc20adresses.length === 0) return []; const filter = { address: ierc20adresses, fromBlock: this.blockNumberState.get(), toBlock: 'latest', topics: [IERC20Interface.events['Transfer'].topic], }; const logs: providers.Log[] = await this.providerService.getLogs(filter); const filteredLogs = logs.filter(isAddressIncludedInLog(this.walletAddress)); const changedAddresses = filteredLogs.reduce((acc, current) => acc.includes(current.address) ? acc : [...acc, current.address], [] as string[]); return changedAddresses; } async getBalances() { if (this.isInitialCall()) { return this.getInitialTokenBalances(); } const changedErc20contracts = await this.getErc20ContractsWithChangedBalances(); const addressesToUpdate = [ETHER_NATIVE_TOKEN.address, ...changedErc20contracts]; const tokenBalances: TokenDetailsWithBalance[] = []; for (const token of this.lastTokenBalances) { tokenBalances.push(await this.lazyGetTokenWithBalance(token, addressesToUpdate)); } return tokenBalances; } private isInitialCall() { return this.lastTokenBalances.length === 0; } private async lazyGetTokenWithBalance(token: TokenDetailsWithBalance, addressesToUpdate: string[]) { const balance = addressesToUpdate.includes(token.address) ? await this.balanceChecker.getBalance(this.walletAddress, token.address) : token.balance; return {...token, balance}; } private async getInitialTokenBalances() { const tokenBalances: TokenDetailsWithBalance[] = []; const addresses = this.tokenDetailsStore.tokensDetails.map(token => token.address); const tokensToUpdate = this.tokenDetailsStore.tokensDetails.filter(token => addresses.includes(token.address)); for (const token of tokensToUpdate) { const balance = await this.balanceChecker.getBalance(this.walletAddress, token.address); tokenBalances.push({...token, balance}); } return tokenBalances; } async checkBalanceNow() { const newTokenBalances = await this.getBalances(); if (!deepEqual(this.lastTokenBalances, newTokenBalances)) { this.lastTokenBalances = clonedeep(newTokenBalances); this.callbacks.forEach((callback) => callback(this.lastTokenBalances)); } } subscribe(callback: OnBalanceChange) { this.callbacks.push(callback); callback(this.lastTokenBalances); if (!this.unsubscribeBlockNumber) { this.checkBalanceNow(); this.unsubscribeBlockNumber = this.blockNumberState.subscribe(() => this.checkBalanceNow()); } const unsubscribe = () => { this.callbacks = this.callbacks.filter((element) => callback !== element); if (this.callbacks.length === 0) { this.stop(); } }; return unsubscribe; } stop() { ensureNotNullish(this.unsubscribeBlockNumber, InvalidObserverState); this.unsubscribeBlockNumber(); this.unsubscribeBlockNumber = null; this.lastTokenBalances = []; } }
module params !DEFAULT VALUES--------------------------------------------------------------- !Iterations to run integer :: NSTEPS=10000 integer :: ISTEPS=2000 integer :: VSTEPS=50 !Resolution integer :: NX = 64 integer :: NY = 64 integer :: NZ = 64 double precision :: DSPACE = 0.2d0, DTSIZE = 0.01d0 !Dump frequency - Wavefunction - Misc Utils integer :: dumpwf = 100, dumputil = 100 !GPE Type - 0 Natural Units - 1 Hamonic Oscillator Units integer :: RHSType = 1 double precision :: harm_osc_C = 300.0d0 double precision :: harm_osc_mu = 10.136d0 complex*16 :: GAMMAC = 0.0d0 logical :: rtNorm = .false. !Boundary Conditions - 0 reflective - 1 periodic integer :: BCX = 0 integer :: BCY = 0 integer :: BCZ = 0 !Noise Amplitude - 0.001d0 works well integer :: noiseamp = 0.000d0 !Flow Speed in X Dir - Start integer :: VOBS = 0 double precision :: VOBSCALE = 100.0 double precision :: DVDT = 0.0d0 double precision :: VTVTIME = 200.0d0 !Rotation term in GPE double precision :: OMEGA = 0.0d0 !Potential types - -1 none - 0 object - 3 afm-img logical :: enablePot = .true. logical :: enableTrap = .true. integer :: potType = -1 integer :: trapType = 0 !traptype 0: harmonic, 1: ring !Enable if you need to constantly recalculate the potential integer :: potRep = 0 !Object properties double precision :: RRX=2.0d0 double precision :: RRY=2.0d0 double precision :: RRZ=2.0d0 double precision :: OBJXDASH=0.0d0 double precision :: OBJYDASH=0.0d0 double precision :: OBJZDASH=0.0d0 double precision :: OBJHEIGHT=0.0d0 !Trap double precision :: TXDASH=0.0d0 double precision :: TYDASH=0.0d0 double precision :: TZDASH=0.0d0 double precision :: TXSCALE = 1.0d0 double precision :: TYSCALE = 1.0d0 double precision :: TZSCALE = 1.0d0 double precision :: TR0 = 0.0d0 !Floor double precision :: FLR = 0.0d0 !AFM-IMAGE character(2048) :: afm_filename integer :: afmRES = 256 double precision :: afmXScale=1000.0d0 double precision :: afmYscale=1000.0d0 double precision :: afmZscale=1.0d0 double precision :: TRUNCPARAM = 1.0d0 !pot-image character(2048) :: pot_filename !Initial initial condition 0 - default, 1 - Non-equilibrium, 2 - restart integer :: initialCondType = 0 !Non-equilibrium initial condition double precision :: ENERV = 0.75 double precision :: NV = 0.75 !initial condition resume character(2048) :: icr_filename double precision :: RESUMETIME = 0.0d0!1000.0*250.0*DTSIZE lastdump*dumpwf*dtsize integer :: RESUMESTEP = 1!1000*250 + 1 lastdump*dumpwf + 1 !GLOBALS---------------------------------------------------------------------- double precision :: VOB double precision,parameter :: PI = 4.0d0*ATAN(1.0d0) complex*16 :: DT,EYE = (0.0d0,1.0d0) double precision :: NORM,OLDNORM = 1.0d0 complex*16, dimension(:,:,:), ALLOCATABLE :: GRID,OBJPOT double precision :: TIME, rpKC, rpAMP double precision :: OBJXVEL = 0.0d0,OBJYVEL = 0.0d0,OBJZVEL = 0.0d0 integer :: INITSSTEP = 1 contains SUBROUTINE init_params IMPLICIT NONE afm_filename = repeat(" ", 2048) !Clear memory so entire string is blank pot_filename = repeat(" ", 2048) !Clear memory so entire string is blank icr_filename = repeat(" ", 2048) !Clear memory so entire string is blank include 'params.in' ALLOCATE(GRID(-NX/2:NX/2,-NY/2:NY/2,-NZ/2:NZ/2)) ALLOCATE(OBJPOT(-NX/2:NX/2,-NY/2:NY/2,-NZ/2:NZ/2)) END SUBROUTINE end module
# frozen_string_literal: true require "spec_helper" # This is a very thin test, since most of the functionality is tested # in the controller test. Here we just want to make sure that the CSS # class appears, for the UJS magic to kick in. describe "thread views" do context "for a signed in user" do include_context "signed in as a site user" let(:thread) { create(:message_thread_with_messages) } let!(:thread_view) { create(:thread_view, thread: thread, user: current_user, viewed_at: 1.day.from_now) } let(:view_message_id) { thread.messages.ordered_for_thread_view.ids.last } it "should output a page with the correct class" do visit thread_path(thread) expect(page).to have_css("#content[data-view-message-id=\"#{view_message_id}\"]") expect(page).to have_css("#message_#{view_message_id}") end end end
import 'toast.dart'; class ToastManager { factory ToastManager() => _instance; ToastManager._(); static late final ToastManager _instance = ToastManager._(); final Set<ToastFuture> toastSet = <ToastFuture>{}; void dismissAll({bool showAnim = false}) { toastSet.toList().forEach((ToastFuture v) { v.dismiss(showAnim: showAnim); }); } void removeFuture(ToastFuture future) { toastSet.remove(future); } void addFuture(ToastFuture future) { toastSet.add(future); } }
/* * Copyright (c) 2018-2019 The University of Sheffield. * * This file is part of gatelib-interaction * (see https://github.com/GateNLP/gatelib-interaction). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gate.lib.interaction.process.tests.integration; import gate.lib.interaction.process.pipes.Process4ObjectStream; import gate.lib.interaction.process.tests.Utils; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.junit.Test; /** * * @author Johann Petrak */ public class TestProcess4ObjectStream { /** * Ohhhhhh a test! */ @Test public void testAll() { Process4ObjectStream process = Process4ObjectStream.create(new File("."), null, ("java -cp "+Utils.getClassPath()+ " gate.lib.interaction.process.tests.integration.EchoObjectStream") .split("\\s+",-1)); assertTrue(process.isAlive()); // send something to the echo process Object obj = process.process("Something"); // make sure we got it back properly assertEquals("Something", obj); // send the stop signal process.process("STOP"); // stop process process.stop(); assertFalse(process.isAlive()); } }
// Copyright 2017 TODO Group. All rights reserved. // SPDX-License-Identifier: Apache-2.0 const logSymbols = require('log-symbols') class SymbolFormatter { format (result) { return `${logSymbols[result.getStatus()]} ${result.rule.id}: ${result.message}` } } module.exports = new SymbolFormatter()
## Summary Generates hash for JSON objects. ## Usage // If you're not on babel use: // require('babel/polyfill') npm install json-hash var assert = require('assert') var hash = require('json-hash') // hash.digest(any, options?) assert.equal(hash.digest({foo:1,bar:1}), hash.digest({bar:1,foo:1})) We're compatible with browserify by using a JavaScript implementation of SHA1. If you want to use nodejs one, pass `hash.digest(foo, { crypto: require('crypto') })`. ## Changes * 2.0.0 - defaults to internal js implementation of sha1, pass { crypto: require('crypto') } to use nodejs one.
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; import { table } from '../../functions/common/table'; import { FunctionHelp } from '.'; import { FunctionFactory } from '../../functions/types'; export const help: FunctionHelp<FunctionFactory<typeof table>> = { help: i18n.translate('xpack.canvas.functions.tableHelpText', { defaultMessage: 'Configure a {datatable} element', values: { datatable: 'datatable', }, }), args: { font: i18n.translate('xpack.canvas.functions.table.args.fontHelpText', { defaultMessage: 'Font style', }), paginate: i18n.translate('xpack.canvas.functions.table.args.paginateHelpText', { defaultMessage: 'Show pagination controls. If set to false only the first page will be displayed', }), perPage: i18n.translate('xpack.canvas.functions.table.args.perPageHelpText', { defaultMessage: 'Show this many rows per page. You probably want to raise this is disabling pagination', }), showHeader: i18n.translate('xpack.canvas.functions.table.args.showHeaderHelpText', { defaultMessage: 'Show or hide the header row with titles for each column', }), }, };
<?php namespace app\components\helpers; class StringHelper extends \yii\helpers\StringHelper { public static function truncateByWord($string, $length, $suffix = '...', $encoding = 'UTF-8') { if (mb_strlen($string, $encoding) <= $length) { return $string; } $tmp = mb_substr($string, 0, $length, $encoding); return mb_substr($tmp, 0, mb_strripos($tmp, ' ', 0, $encoding), $encoding) . $suffix; } }
export const PRIMARY_COLOR = '#1890ff' export const SUCCESS_COLOR = '#52c41a' export const WARNING_COLOR = '#faad14' export const DANGER_COLOR = '#ff4d4f' export const PRIMARY_BORDER_COLOR = '#40a9ff' export const SUCCESS_BORDER_COLOR = '#73d13d' export const WARNING_BORDER_COLOR = '#ffc53d' export const DANGER_BORDER_COLOR = '#ff7875' export const PRIMARY_BACKGROUND_COLOR = '#e6f7ff' export const SUCCESS_BACKGROUND_COLOR = '#f0ffe0' export const WARNING_BACKGROUND_COLOR = '#fffae0' export const DANGER_BACKGROUND_COLOR = '#ffe7e6' export const BLACK_COLOR = '#000000' export const TITLE_COLOR = '#262626' export const FONT_COLOR = '#595959' export const FONT2_COLOR = '#8c8c8c' export const FONT3_COLOR = '#bfbfbf' export const BORDER_COLOR = '#d9d9d9' export const DIVIDER_COLOR = '#f0f0f0' export const BACKGROUND_COLOR = '#f5f5f5' export const BACKGROUND2_COLOR = '#fafafa'
# hcl-sdk-button <!-- Auto Generated Below --> ## Properties | Property | Attribute | Description | Type | Default | | -------------- | --------------- | ----------- | --------- | ----------- | | `class` | `class` | | `string` | `undefined` | | `disabled` | `disabled` | | `boolean` | `undefined` | | `icon` | `icon` | | `string` | `undefined` | | `iconColor` | `icon-color` | | `string` | `undefined` | | `iconHeight` | `icon-height` | | `number` | `undefined` | | `iconWidth` | `icon-width` | | `number` | `undefined` | | `isFull` | `is-full` | | `boolean` | `undefined` | | `noBackground` | `no-background` | | `boolean` | `undefined` | | `noBorder` | `no-border` | | `boolean` | `undefined` | | `noTextColor` | `no-text-color` | | `boolean` | `undefined` | | `primary` | `primary` | | `boolean` | `undefined` | | `round` | `round` | | `boolean` | `undefined` | | `secondary` | `secondary` | | `boolean` | `undefined` | | `type` | `type` | | `string` | `undefined` | ## Dependencies ### Used by - [hcl-sdk-hcp-full-card](../hcl-sdk-hcp-full-card) - [hcl-sdk-home](../../screens/hcl-sdk-home) - [hcl-sdk-home-full](../../screens/hcl-sdk-home/hcl-sdk-home-full) - [hcl-sdk-home-min](../../screens/hcl-sdk-home/hcl-sdk-home-min) - [hcl-sdk-input](../hcl-sdk-input) - [hcl-sdk-search](../../screens/hcl-sdk-search) - [hcl-sdk-search-no-results](../hcl-sdk-search-no-results) - [hcl-sdk-search-result](../../screens/hcl-sdk-search-result) - [hcl-sdk-sort](../hcl-sdk-sort) ### Depends on - [hcl-sdk-icon](../hcl-sdk-icon) ### Graph ```mermaid graph TD; hcl-sdk-button --> hcl-sdk-icon hcl-sdk-hcp-full-card --> hcl-sdk-button hcl-sdk-home --> hcl-sdk-button hcl-sdk-home-full --> hcl-sdk-button hcl-sdk-home-min --> hcl-sdk-button hcl-sdk-input --> hcl-sdk-button hcl-sdk-search --> hcl-sdk-button hcl-sdk-search-no-results --> hcl-sdk-button hcl-sdk-search-result --> hcl-sdk-button hcl-sdk-sort --> hcl-sdk-button style hcl-sdk-button fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
/** * @jsx React.DOM */ var HELLO_COMPONENT = "\ /** @jsx React.DOM */\n\ var HelloMessage = React.createClass({\n\ render: function() {\n\ return <div>Hello {this.props.name}</div>;\n\ }\n\ });\n\ \n\ React.renderComponent(<HelloMessage name=\"John\" />, mountNode);\ "; var transformer = function(code) { return JSXTransformer.transform(code).code; } React.renderComponent( <ReactPlayground codeText={HELLO_COMPONENT} renderCode={true} transformer={transformer} />, document.getElementById('jsxCompiler') );
use super::Redirects; use crate::job::SharedJobs; use crate::parse::{Arg as ParseArg, Command as ParseCmd, SpecialStr}; use std::process::{Child, Command, Stdio}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct External { pub name: SpecialStr, pub args: Args, pub reds: Redirects, pub pipe: Option<Box<External>>, pub bg: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Args(Vec<Arg>); impl Args { pub fn eval(&self, jobs: &SharedJobs) -> anyhow::Result<Vec<String>> { let mut res = Vec::new(); for arg in self.0.iter() { match arg { Arg::Normal(s) => res.push(s.eval(jobs)?), Arg::Expand(s) => { for i in s.eval(jobs)?.split_whitespace() { res.push(i.to_string()); } } } } Ok(res) } } #[derive(Debug, Clone, PartialEq, Eq)] enum Arg { Normal(SpecialStr), Expand(SpecialStr), } impl From<ParseCmd> for External { fn from(cmd: ParseCmd) -> External { let ParseCmd { name, args: arg_reds, pipe, bg, } = cmd; let mut args = Vec::new(); let mut reds = Vec::new(); for arg in arg_reds { match arg { ParseArg::Arg(s) => { args.push(Arg::Normal(s)); } ParseArg::ExpandArg(s) => { args.push(Arg::Expand(s)); } ParseArg::Redirect(r) => { reds.push(r); } } } let args = Args(args); let reds = Redirects::new(reds); let pipe = pipe.map(|pipe| Box::new(Self::from(*pipe))); Self { name, args, reds, pipe, bg, } } } impl External { pub fn eval(&self, jobs: &SharedJobs) -> anyhow::Result<()> { let child = self.child(jobs, false)?; jobs.with(|jobs| { if self.bg { let (id, pid) = jobs.new_bg(child.id() as i32)?; println!("Job %{} ({}) has started.", id, pid); } else { jobs.new_fg(child.id() as i32)?; } Ok(()) }) } pub fn output(&self, jobs: &SharedJobs) -> anyhow::Result<String> { let child = self.child(jobs, true)?; let output = child.wait_with_output()?; Ok(String::from_utf8(output.stdout)?) } fn child(&self, jobs: &SharedJobs, output: bool) -> anyhow::Result<Child> { let mut child = Command::new(&self.name.eval(jobs)?); child.args(&self.args.eval(jobs)?); let heredoc = self .reds .redirect(&mut child, jobs, false, output || self.pipe.is_some())?; let mut child = child.spawn()?; if let Some(s) = heredoc { use std::io::Write; child.stdin.take().unwrap().write_all(&s)?; } if let Some(pipe) = &self.pipe { pipe.pipe_from(child, jobs, output) } else { Ok(child) } } fn pipe_from(&self, other: Child, jobs: &SharedJobs, output: bool) -> anyhow::Result<Child> { let mut child = Command::new(&self.name.eval(jobs)?); child.args(&self.args.eval(jobs)?); let heredoc = self .reds .redirect(&mut child, jobs, true, output || self.pipe.is_some())?; child.stdin(Stdio::from(other.stdout.unwrap())); let mut child = child.spawn()?; if let Some(s) = heredoc { use std::io::Write; child.stdin.take().unwrap().write_all(&s)?; } if let Some(pipe) = &self.pipe { pipe.pipe_from(child, jobs, output) } else { Ok(child) } } }
//===-- go-llvm-tree-integrity.cpp - tree integrity utils impl ------------===// // // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // //===----------------------------------------------------------------------===// // // Methods for class IntegrityVisitor. // //===----------------------------------------------------------------------===// #include "go-llvm-bexpression.h" #include "go-llvm-bstatement.h" #include "go-llvm-tree-integrity.h" #include "go-llvm.h" #include "llvm/IR/Instruction.h" IntegrityVisitor::IntegrityVisitor(Llvm_backend *be, TreeIntegCtl control) : be_(be), ss_(str_), control_(control), instShareCount_(0), stmtShareCount_(0), exprShareCount_(0) { acceptableNodes_.insert(N_Const); acceptableNodes_.insert(N_Call); // subject to acceptable target acceptableNodes_.insert(N_FcnAddress); acceptableNodes_.insert(N_Conditional); acceptableNodes_.insert(N_Var); acceptableNodes_.insert(N_Conversion); acceptableNodes_.insert(N_Deref); acceptableNodes_.insert(N_StructField); acceptableNodes_.insert(N_BinaryOp); // subject to acceptableOpcodes acceptableOpcodes_.insert(OPERATOR_PLUS); acceptableOpcodes_.insert(OPERATOR_MINUS); acceptableOpcodes_.insert(OPERATOR_EQEQ); acceptableOpcodes_.insert(OPERATOR_NOTEQ); } void IntegrityVisitor::dumpTag(const char *tag, void *ptr) { ss_ << tag << ": "; if (includePointers() == DumpPointers) ss_ << ptr; ss_ << "\n"; } void IntegrityVisitor::dump(Bnode *node) { dumpTag(node->isStmt() ? "stmt" : "expr", (void*) node); node->osdump(ss_, 0, be_->linemap(), false); } void IntegrityVisitor::dump(llvm::Instruction *inst) { dumpTag("inst", (void*) inst); inst->print(ss_); ss_ << "\n"; } bool IntegrityVisitor::shouldBeTracked(Bnode *child) { Bexpression *expr = child->castToBexpression(); if (expr && expr->value() && be_->moduleScopeValue(expr->value(), expr->btype())) return false; return true; } void IntegrityVisitor::deletePending(Bnode *node) { assert(shouldBeTracked(node)); auto it = nparent_.find(node); if (it == nparent_.end()) return; nparent_.erase(it); } // This helper routine is invoked in situations where the node // builder wants to "reparent" the children of a node, e.g. it has // a "foo" node with children X and Y, and it wants to convert it // into a "bar" node with the same children. Ex: // // foo bar // . . => . . // . . . . // X Y X Y // // In this situation we need to update "nparent_" to reflect the fact // that X and Y are no longer parented by foo. A complication can crop // up if sharing has already been established at the point where this // routine is called. For example, suppose that there is some other // node "baz" that has also installed "X" as a child: // // baz foo // . . . . // . . . . // W X Y // // If this situation arises, we need to preserve the existing nparent_ // mapping, so as to be able to repair the sharing later on. void IntegrityVisitor::unsetParent(Bnode *child, Bnode *parent, unsigned slot) { if (! shouldBeTracked(child)) return; auto it = nparent_.find(child); if (it == nparent_.end()) return; parslot pps = it->second; Bnode *prevParent = pps.first; unsigned prevSlot = pps.second; if (prevParent == parent || prevSlot == slot) nparent_.erase(it); } void IntegrityVisitor::unsetParent(llvm::Instruction *inst, Bexpression *exprParent, unsigned slot) { auto it = iparent_.find(inst); if (it == iparent_.end()) return; parslot pps = it->second; Bnode *prevParent = pps.first; unsigned prevSlot = pps.second; if (prevParent == exprParent || prevSlot == slot) iparent_.erase(it); } void IntegrityVisitor::setParent(Bnode *child, Bnode *parent, unsigned slot) { if (! shouldBeTracked(child)) return; auto it = nparent_.find(child); if (it != nparent_.end()) { parslot pps = it->second; Bnode *prevParent = pps.first; unsigned prevSlot = pps.second; if (prevParent == parent && prevSlot == slot) return; if (child->flavor() == N_Error) return; // Was this instance of sharing recorded previously? parslot ps = std::make_pair(parent, slot); auto it = sharing_.find(ps); if (it != sharing_.end()) return; // Keep track of this location for future use in repair operations. sharing_.insert(ps); // If the sharing at this subtree is repairable, don't // log an error, since the sharing will be undone later on. Bexpression *expr = child->castToBexpression(); if (expr != nullptr && doRepairs() == DontReportRepairableSharing && repairableSubTree(expr)) return; const char *wh = nullptr; if (child->isStmt()) { stmtShareCount_ += 1; wh = "stmt"; } else { exprShareCount_ += 1; wh = "expr"; } // capture a description of the error ss_ << "error: " << wh << " has multiple parents" << " [ID=" << child->id() << "]\n"; ss_ << "child " << wh << ":\n"; dump(child); ss_ << "parent 1: [ID=" << prevParent->id() << "]\n"; dump(prevParent); ss_ << "parent 2: [ID=" << parent->id() << "]\n"; dump(parent); return; } nparent_[child] = std::make_pair(parent, slot); } void IntegrityVisitor::setParent(llvm::Instruction *inst, Bexpression *exprParent, unsigned slot) { auto it = iparent_.find(inst); if (it != iparent_.end()) { parslot ps = it->second; Bnode *prevParent = ps.first; unsigned prevSlot = ps.second; if (prevParent == exprParent && prevSlot == slot) return; instShareCount_ += 1; ss_ << "error: instruction has multiple parents\n"; dump(inst); ss_ << "parent 1:\n"; dump(prevParent); ss_ << "parent 2:\n"; dump(exprParent); } else { iparent_[inst] = std::make_pair(exprParent, slot); } } bool IntegrityVisitor::repairableSubTree(Bexpression *root) { std::set<Bexpression *> visited; visited.insert(root); std::vector<Bexpression *> workList; workList.push_back(root); while (! workList.empty()) { Bexpression *e = workList.back(); workList.pop_back(); if (acceptableNodes_.find(e->flavor()) == acceptableNodes_.end()) return false; if (e->flavor() == N_Call) { // ok to duplicate runtime error calls, but not other calls Bfunction *target = e->getCallTarget(); if (!target || target->name() != "__go_runtime_error") return false; } if (e->flavor() == N_BinaryOp && acceptableOpcodes_.find(e->op()) == acceptableOpcodes_.end()) return false; for (auto &c : e->children()) { Bexpression *ce = c->castToBexpression(); assert(ce); if (visited.find(ce) == visited.end()) { visited.insert(ce); workList.push_back(ce); } } } return true; } class ScopedIntegrityCheckDisabler { public: ScopedIntegrityCheckDisabler(Llvm_backend *be) : be_(be), val_(be->nodeBuilder().integrityChecksEnabled()) { be_->nodeBuilder().setIntegrityChecks(false); } ~ScopedIntegrityCheckDisabler() { be_->nodeBuilder().setIntegrityChecks(val_); } private: Llvm_backend *be_; bool val_; }; bool IntegrityVisitor::repair(Bnode *node) { ScopedIntegrityCheckDisabler disabler(be_); std::set<Bexpression *> visited; for (auto &ps : sharing_) { Bnode *parent = ps.first; unsigned slot = ps.second; const std::vector<Bnode *> &pkids = parent->children(); Bexpression *child = pkids[slot]->castToBexpression(); assert(child); if (visited.find(child) == visited.end()) { // Repairable? if (!repairableSubTree(child)) return false; visited.insert(child); } Bexpression *childClone = be_->nodeBuilder().cloneSubtree(child); parent->replaceChild(slot, childClone); } sharing_.clear(); exprShareCount_ = 0; return true; } void IntegrityVisitor::visit(Bnode *node) { unsigned idx = 0; for (auto &child : node->children()) { if (visitMode() == BatchMode) visit(child); setParent(child, node, idx++); } Bexpression *expr = node->castToBexpression(); if (expr) { idx = 0; for (auto inst : expr->instructions()) setParent(inst, expr, idx++); } } bool IntegrityVisitor::examine(Bnode *node) { // Visit node (and possibly entire subtree at node, mode depending) visit(node); // Inst sharing and statement sharing are not repairable. if (instShareCount_ != 0 || stmtShareCount_ != 0) return false; if (exprShareCount_ != 0) return false; // If the checker is in incremental mode, don't attempt repairs // (those will be done later on). if (visitMode() == IncrementalMode) { sharing_.clear(); return true; } // Batch mode: return now if no sharing. if (sharing_.empty()) return true; // Batch mode: perform repairs. if (repair(node)) return true; // Repair failed -- return failure return false; }
module RequestHelpers def response_body JSON(response.body) end def auth_headers(user) session = user.sessions.create! token = JwtEncoder.encode(uuid: session.uuid) { 'Authorization' => "Bearer #{token}" } end end
--- layout: post title: Emacs 实践 date: 2019-03-29 08:00:00 +0800 categories: 七说八道 tag: 工具 --- ### 多行操作 - 删除行前的空格或者其他字符 ``` - C-space 标记起始点(左上角) - 移动到要删除的最后一行的字符后一个字符保证要删除区域在高亮部分 - C-x r c ``` - 在行前插入字符 ``` - C-space - 选择 - C-x r t - 输入需要的字符 ``` ### 矩阵操作命令 ``` - C-space set-mark-command 标记矩形区块的一个角(光标标记其相对的角)。 - C-x r k kill-rectangle 剪切当前的矩形区块,并将其保存在一个特殊的矩形区块缓冲区中。 - C-x r d delete-rectangle 删除当前的矩形区块,并不为粘贴而保存它。 - C-x r c clear-rectangle 清除当前的矩形区块,使用空白字符替换整个区域。 - C-x r o open-rectangle 打开当前的矩形区块,使用空白字符填充整个区域,并将该矩形区块的所有文本移动到右边。 - C-x r y yank-rectangle 在光标处,粘贴上一次剪切的矩形区块的内容,将所有的现有文本移动到右边。 ``` ### 使用emacs 格式化(整理)源程序 ```` 1、如果想要整理整个文件 M-x mark-whole-buffer 或者 C-x h //选中整个文件 M-x indent-region 或者 C-M-\ //格式化选中 2、只是整理某个函数 M-x mark-defun 或者 C-M-h //选中函数 M-x indent-region 或者 C-M-\ //格式化 ```` ### 删除末尾换行符^M ```` 1. M-% (esc % on Mac X11 Emacs) 2. ctrl-q ctrl-m RET (specifies ^M to replace) 3. ctrl-q ctrl-j RET (specifies a line return as the replacement) 4. ! (runs the replace on the entire file) ```` ### 删除空行 ```` M-x flush-lines RET ^[[:space:]]*$ RET ```` ### 查找替换 - 逐个查找 ``` C - s向下查找 C - r向上查找 按下C - s后输入要搜索的词,emacs会即时显示当前光标后第一个搜索到的结果,按C - s会跳到下一个结果,按C - r会跳到上一个结果。 按Enter结束查找或按C - g取消查找回到原来的地方。 按下C - s 或 C - r后,按M - p显示上一个搜索词,M - n显示下一个搜索词。类似C - p是上一行,C - n下一行。 按下C - s或 C - r后,输入要查找的词的头几个字,然后按C - w 会补全当前位置的单词。 ``` 2019-03-29
#!/bin/bash echo "Fully automated installation" if [[ -d data_l1 || -d data_l2 ]] ; then read -p "This will wipe data L1 & L2 data directories. Are you sure? (y/n) " -n 1 -r echo echo $REPLY if [[ $REPLY =~ ^[Yy]$ ]]; then ./clean.sh else echo "aborting" exit 1 fi fi ./setup.sh ./build-l1-geth.sh ./build-l2-geth.sh ./start-l1-geth-killable.sh & L1PID=$! ./start-l2-geth-killable.sh & L2PID=$! echo "sleep 10 sec while L1 and L2 nodes boot up" sleep 10 ./get-genesis-hashes.sh echo "killing L1 and L2 nodes" kill $L1PID kill $L2PID ./build-rollup-node.sh
/** * @fileoverview This file is generated by the Angular 2 template compiler. * Do not edit. * @suppress {suspiciousCode,uselessCode,missingProperties} */ /* tslint:disable */ import * as import0 from './item'; import * as import1 from '@angular/core/src/change_detection/change_detection'; import * as import2 from '@angular/core/src/linker/view'; import * as import3 from '@angular/core/src/linker/view_utils'; import * as import4 from '@angular/core/src/render/api'; import * as import5 from '@angular/core/src/metadata/view'; import * as import6 from '@angular/core/src/linker/query_list'; import * as import7 from '@angular/core/src/linker/view_type'; import * as import8 from '@angular/core/src/linker/component_factory'; import * as import9 from '../../util/form'; import * as import10 from '../../config/config'; import * as import11 from '@angular/core/src/linker/element_ref'; import * as import12 from './item-reorder'; import * as import13 from '@angular/core/src/linker/view_container'; import * as import14 from '../../node_modules/@angular/common/src/directives/ng_if.ngfactory'; import * as import15 from '@angular/core/src/linker/template_ref'; import * as import16 from '@angular/common/src/directives/ng_if'; import * as import17 from '../label/label.ngfactory'; import * as import18 from '../label/label'; import * as import19 from './item-reorder.ngfactory'; export class Wrapper_Item { /*private*/ _eventHandler:Function; context:import0.Item; /*private*/ _changed:boolean; /*private*/ _expr_0:any; /*private*/ _expr_1:any; constructor(p0:any,p1:any,p2:any,p3:any,p4:any) { this._changed = false; this.context = new import0.Item(p0,p1,p2,p3,p4); this._expr_0 = import1.UNINITIALIZED; this._expr_1 = import1.UNINITIALIZED; } ngOnDetach(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any):void { } ngOnDestroy():void { } check_color(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_0,currValue))) { this._changed = true; this.context.color = currValue; this._expr_0 = currValue; } } check_mode(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_1,currValue))) { this._changed = true; this.context.mode = currValue; this._expr_1 = currValue; } } ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean { var changed:any = this._changed; this._changed = false; return changed; } checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void { } handleEvent(eventName:string,$event:any):boolean { var result:boolean = true; return result; } subscribe(view:import2.AppView<any>,_eventHandler:any):void { this._eventHandler = _eventHandler; } } export class Wrapper_ItemContent { /*private*/ _eventHandler:Function; context:import0.ItemContent; /*private*/ _changed:boolean; constructor() { this._changed = false; this.context = new import0.ItemContent(); } ngOnDetach(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any):void { } ngOnDestroy():void { } ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean { var changed:any = this._changed; this._changed = false; return changed; } checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void { } handleEvent(eventName:string,$event:any):boolean { var result:boolean = true; return result; } subscribe(view:import2.AppView<any>,_eventHandler:any):void { this._eventHandler = _eventHandler; } } export class Wrapper_ItemDivider { /*private*/ _eventHandler:Function; context:import0.ItemDivider; /*private*/ _changed:boolean; /*private*/ _expr_0:any; /*private*/ _expr_1:any; constructor(p0:any,p1:any,p2:any,p3:any) { this._changed = false; this.context = new import0.ItemDivider(p0,p1,p2,p3); this._expr_0 = import1.UNINITIALIZED; this._expr_1 = import1.UNINITIALIZED; } ngOnDetach(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any):void { } ngOnDestroy():void { } check_color(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_0,currValue))) { this._changed = true; this.context.color = currValue; this._expr_0 = currValue; } } check_mode(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_1,currValue))) { this._changed = true; this.context.mode = currValue; this._expr_1 = currValue; } } ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean { var changed:any = this._changed; this._changed = false; return changed; } checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void { } handleEvent(eventName:string,$event:any):boolean { var result:boolean = true; return result; } subscribe(view:import2.AppView<any>,_eventHandler:any):void { this._eventHandler = _eventHandler; } } export class Wrapper_ItemGroup { /*private*/ _eventHandler:Function; context:import0.ItemGroup; /*private*/ _changed:boolean; constructor() { this._changed = false; this.context = new import0.ItemGroup(); } ngOnDetach(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any):void { } ngOnDestroy():void { } ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean { var changed:any = this._changed; this._changed = false; return changed; } checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void { } handleEvent(eventName:string,$event:any):boolean { var result:boolean = true; return result; } subscribe(view:import2.AppView<any>,_eventHandler:any):void { this._eventHandler = _eventHandler; } } var renderType_Item_Host:import4.RenderComponentType = import3.createRenderComponentType('',0,import5.ViewEncapsulation.None,([] as any[]),{}); class View_Item_Host0 extends import2.AppView<any> { _el_0:any; compView_0:import2.AppView<import0.Item>; _Item_0_3:Wrapper_Item; _query_Label_0_0:import6.QueryList<any>; _query_Button_0_1:import6.QueryList<any>; _query_Icon_0_2:import6.QueryList<any>; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any) { super(View_Item_Host0,renderType_Item_Host,import7.ViewType.HOST,viewUtils,parentView,parentIndex,parentElement,import1.ChangeDetectorStatus.CheckAlways); } createInternal(rootSelector:string):import8.ComponentRef<any> { this._el_0 = import3.selectOrCreateRenderHostElement(this.renderer,'ion-list-header',new import3.InlineArray2(2,'class','item'),rootSelector,(null as any)); this.compView_0 = new View_Item0(this.viewUtils,this,0,this._el_0); this._Item_0_3 = new Wrapper_Item(this.injectorGet(import9.Form,this.parentIndex),this.injectorGet(import10.Config,this.parentIndex),new import11.ElementRef(this._el_0),this.renderer,this.injectorGet(import12.ItemReorder,this.parentIndex,(null as any))); this._query_Label_0_0 = new import6.QueryList<any>(); this._query_Button_0_1 = new import6.QueryList<any>(); this._query_Icon_0_2 = new import6.QueryList<any>(); this._query_Label_0_0.reset(([] as any[])); this._Item_0_3.context.contentLabel = this._query_Label_0_0.first; this.compView_0.create(this._Item_0_3.context); this.init(this._el_0,((<any>this.renderer).directRenderer? (null as any): [this._el_0]),(null as any)); return new import8.ComponentRef_<any>(0,this,this._el_0,this._Item_0_3.context); } injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any { if (((token === import0.Item) && (0 === requestNodeIndex))) { return this._Item_0_3.context; } return notFoundResult; } detectChangesInternal(throwOnChange:boolean):void { if (this._Item_0_3.ngDoCheck(this,this._el_0,throwOnChange)) { this.compView_0.markAsCheckOnce(); } if (!throwOnChange) { if (this._query_Button_0_1.dirty) { this._query_Button_0_1.reset(([] as any[])); this._Item_0_3.context._buttons = this._query_Button_0_1; this._query_Button_0_1.notifyOnChanges(); } if (this._query_Icon_0_2.dirty) { this._query_Icon_0_2.reset(([] as any[])); this._Item_0_3.context._icons = this._query_Icon_0_2; this._query_Icon_0_2.notifyOnChanges(); } if ((this.numberOfChecks === 0)) { this._Item_0_3.context.ngAfterContentInit(); } } this.compView_0.detectChanges(throwOnChange); } destroyInternal():void { this.compView_0.destroy(); } visitRootNodesInternal(cb:any,ctx:any):void { cb(this._el_0,ctx); } visitProjectableNodesInternal(nodeIndex:number,ngContentIndex:number,cb:any,ctx:any):void { if (((nodeIndex == 0) && (ngContentIndex == 0))) { } if (((nodeIndex == 0) && (ngContentIndex == 1))) { } if (((nodeIndex == 0) && (ngContentIndex == 2))) { } if (((nodeIndex == 0) && (ngContentIndex == 3))) { } if (((nodeIndex == 0) && (ngContentIndex == 4))) { } } } export const ItemNgFactory:import8.ComponentFactory<import0.Item> = new import8.ComponentFactory<import0.Item>('ion-list-header,ion-item,[ion-item],ion-item-divider',View_Item_Host0,import0.Item); const styles_Item:any[] = ([] as any[]); var renderType_Item:import4.RenderComponentType = import3.createRenderComponentType('',5,import5.ViewEncapsulation.None,styles_Item,{}); export class View_Item0 extends import2.AppView<import0.Item> { _viewQuery_Label_0:import6.QueryList<any>; _el_0:any; _el_1:any; _anchor_2:any; /*private*/ _vc_2:import13.ViewContainer; _TemplateRef_2_5:any; _NgIf_2_6:import14.Wrapper_NgIf; _anchor_3:any; /*private*/ _vc_3:import13.ViewContainer; _TemplateRef_3_5:any; _NgIf_3_6:import14.Wrapper_NgIf; _el_4:any; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any) { super(View_Item0,renderType_Item,import7.ViewType.COMPONENT,viewUtils,parentView,parentIndex,parentElement,import1.ChangeDetectorStatus.CheckOnce); } createInternal(rootSelector:string):import8.ComponentRef<any> { const parentRenderNode:any = this.renderer.createViewRoot(this.parentElement); this._viewQuery_Label_0 = new import6.QueryList<any>(); this.projectNodes(parentRenderNode,0); this._el_0 = import3.createRenderElement(this.renderer,parentRenderNode,'div',new import3.InlineArray2(2,'class','item-inner'),(null as any)); this._el_1 = import3.createRenderElement(this.renderer,this._el_0,'div',new import3.InlineArray2(2,'class','input-wrapper'),(null as any)); this.projectNodes(this._el_1,1); this._anchor_2 = this.renderer.createTemplateAnchor(this._el_1,(null as any)); this._vc_2 = new import13.ViewContainer(2,1,this,this._anchor_2); this._TemplateRef_2_5 = new import15.TemplateRef_(this,2,this._anchor_2); this._NgIf_2_6 = new import14.Wrapper_NgIf(this._vc_2.vcRef,this._TemplateRef_2_5); this.projectNodes(this._el_1,3); this.projectNodes(this._el_0,4); this._anchor_3 = this.renderer.createTemplateAnchor(this._el_0,(null as any)); this._vc_3 = new import13.ViewContainer(3,0,this,this._anchor_3); this._TemplateRef_3_5 = new import15.TemplateRef_(this,3,this._anchor_3); this._NgIf_3_6 = new import14.Wrapper_NgIf(this._vc_3.vcRef,this._TemplateRef_3_5); this._el_4 = import3.createRenderElement(this.renderer,parentRenderNode,'div',new import3.InlineArray2(2,'class','button-effect'),(null as any)); this.init((null as any),((<any>this.renderer).directRenderer? (null as any): [ this._el_0, this._el_1, this._anchor_2, this._anchor_3, this._el_4 ] ),(null as any)); return (null as any); } injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any { if (((token === import15.TemplateRef) && (2 === requestNodeIndex))) { return this._TemplateRef_2_5; } if (((token === import16.NgIf) && (2 === requestNodeIndex))) { return this._NgIf_2_6.context; } if (((token === import15.TemplateRef) && (3 === requestNodeIndex))) { return this._TemplateRef_3_5; } if (((token === import16.NgIf) && (3 === requestNodeIndex))) { return this._NgIf_3_6.context; } return notFoundResult; } detectChangesInternal(throwOnChange:boolean):void { const currVal_2_0_0:any = this.context._viewLabel; this._NgIf_2_6.check_ngIf(currVal_2_0_0,throwOnChange,false); this._NgIf_2_6.ngDoCheck(this,this._anchor_2,throwOnChange); const currVal_3_0_0:any = this.context._shouldHaveReorder; this._NgIf_3_6.check_ngIf(currVal_3_0_0,throwOnChange,false); this._NgIf_3_6.ngDoCheck(this,this._anchor_3,throwOnChange); this._vc_2.detectChangesInNestedViews(throwOnChange); this._vc_3.detectChangesInNestedViews(throwOnChange); if (!throwOnChange) { if (this._viewQuery_Label_0.dirty) { this._viewQuery_Label_0.reset([this._vc_2.mapNestedViews(View_Item1,(nestedView:View_Item1):any => { return [nestedView._Label_0_3.context]; })]); this.context.viewLabel = this._viewQuery_Label_0.first; } } } destroyInternal():void { this._vc_2.destroyNestedViews(); this._vc_3.destroyNestedViews(); } createEmbeddedViewInternal(nodeIndex:number):import2.AppView<any> { if ((nodeIndex == 2)) { return new View_Item1(this.viewUtils,this,2,this._anchor_2,this._vc_2); } if ((nodeIndex == 3)) { return new View_Item2(this.viewUtils,this,3,this._anchor_3,this._vc_3); } return (null as any); } } class View_Item1 extends import2.AppView<any> { _el_0:any; _Label_0_3:import17.Wrapper_Label; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any,declaredViewContainer:import13.ViewContainer) { super(View_Item1,renderType_Item,import7.ViewType.EMBEDDED,viewUtils,parentView,parentIndex,parentElement,import1.ChangeDetectorStatus.CheckAlways,declaredViewContainer); } createInternal(rootSelector:string):import8.ComponentRef<any> { this._el_0 = import3.createRenderElement(this.renderer,(null as any),'ion-label',import3.EMPTY_INLINE_ARRAY,(null as any)); this._Label_0_3 = new import17.Wrapper_Label(this.parentView.parentView.injectorGet(import10.Config,this.parentView.parentIndex),new import11.ElementRef(this._el_0),this.renderer,(null as any),(null as any),(null as any),(null as any)); this.projectNodes(this._el_0,2); this.init(this._el_0,((<any>this.renderer).directRenderer? (null as any): [this._el_0]),(null as any)); return (null as any); } injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any { if (((token === import18.Label) && (0 === requestNodeIndex))) { return this._Label_0_3.context; } return notFoundResult; } detectChangesInternal(throwOnChange:boolean):void { this._Label_0_3.ngDoCheck(this,this._el_0,throwOnChange); } dirtyParentQueriesInternal():void { (<View_Item0>this.parentView)._viewQuery_Label_0.setDirty(); } visitRootNodesInternal(cb:any,ctx:any):void { cb(this._el_0,ctx); } } class View_Item2 extends import2.AppView<any> { _el_0:any; compView_0:import2.AppView<import12.Reorder>; _Reorder_0_3:import19.Wrapper_Reorder; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any,declaredViewContainer:import13.ViewContainer) { super(View_Item2,renderType_Item,import7.ViewType.EMBEDDED,viewUtils,parentView,parentIndex,parentElement,import1.ChangeDetectorStatus.CheckAlways,declaredViewContainer); } createInternal(rootSelector:string):import8.ComponentRef<any> { this._el_0 = import3.createRenderElement(this.renderer,(null as any),'ion-reorder',import3.EMPTY_INLINE_ARRAY,(null as any)); this.compView_0 = new import19.View_Reorder0(this.viewUtils,this,0,this._el_0); this._Reorder_0_3 = new import19.Wrapper_Reorder(this.parentView.parentView.injectorGet(import0.Item,this.parentView.parentIndex),new import11.ElementRef(this._el_0)); this.compView_0.create(this._Reorder_0_3.context); var disposable_0:Function = import3.subscribeToRenderElement(this,this._el_0,new import3.InlineArray2(2,'click',(null as any)),this.eventHandler(this.handleEvent_0)); this.init(this._el_0,((<any>this.renderer).directRenderer? (null as any): [this._el_0]),[disposable_0]); return (null as any); } injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any { if (((token === import12.Reorder) && (0 === requestNodeIndex))) { return this._Reorder_0_3.context; } return notFoundResult; } detectChangesInternal(throwOnChange:boolean):void { this._Reorder_0_3.ngDoCheck(this,this._el_0,throwOnChange); this.compView_0.detectChanges(throwOnChange); } destroyInternal():void { this.compView_0.destroy(); } visitRootNodesInternal(cb:any,ctx:any):void { cb(this._el_0,ctx); } handleEvent_0(eventName:string,$event:any):boolean { this.compView_0.markPathToRootAsCheckOnce(); var result:boolean = true; result = (this._Reorder_0_3.handleEvent(eventName,$event) && result); return result; } }
export class UsuarioDto { nome: string; login: string; senha: string; }
package edit import ( "github.com/getclasslabs/go-tools/pkg/tracer" "github.com/getclasslabs/user/internal/domains" "github.com/getclasslabs/user/internal/service/userService" ) type Edit struct { userService.Profile Twitter string `json:"twitter,omitempty"` Facebook string `json:"facebook,omitempty"` Instagram string `json:"instagram,omitempty"` Description string `json:"description,omitempty"` Telephone string `json:"telephone,omitempty"` Address string `json:"address,omitempty"` //teacher Formation string `json:"formation,omitempty"` Specialization string `json:"specialization,omitempty"` WorkingTime int `json:"workingTime,omitempty"` } func (e *Edit) Do(i *tracer.Infos, email string) error { i.TraceIt("editing profile service") defer i.Span.Finish() if err := e.editCommonInfo(i, email); err != nil { return err } if err := e.editTeacherInfo(i, email); err != nil { return err } return nil } func (e *Edit) editCommonInfo(i *tracer.Infos, email string) error { u := domains.User{ Domain: domains.Domain{ Tracer: i, Email: email, }, FirstName: e.FirstName, LastName: e.LastName, BirthDate: e.BirthDate, Gender: e.Gender, Nickname: e.Nickname, Twitter: e.Twitter, Facebook: e.Facebook, Instagram: e.Instagram, Description: e.Description, Telephone: e.Telephone, Address: e.Address, } err := u.Edit() if err != nil { return err } return nil } func (e *Edit) editTeacherInfo(i *tracer.Infos, email string) error { t := domains.Teacher{ Domain: domains.Domain{ Tracer: i, Email: email, }, Formation: e.Formation, Specialization: e.Specialization, WorkingTime: e.WorkingTime, } err := t.Edit() if err != nil { return err } return nil }
import React from 'react' import ButtonStyles from "./ButtonStyle.module.css"; export default (props) => ( <div className={ButtonStyles.buttonContainer}> <a className={ButtonStyles.button} href={props.to}> {props.children}</a> </div> )
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fostor.Ginkgo.Users.Dto; namespace Fostor.Ginkgo.Web.Views.Shared.Components.UserSelector { public class UserSelectorViewModel { public List<UserDto> Users { get; set; } public string TagName { get; set; } public string SelectedValue { get; set; } public bool IsRequired { get; set; } public bool IsDisabled { get; set; } public bool Multiple { get; set; } public bool UseIdAsValue { get; set; } } }
package snabbdom.modules import scala.scalajs.js import scala.scalajs.js.annotation.JSImport import scala.scalajs.js.annotation.JSImport.Default @JSImport("snabbdom/modules/class", Default) @js.native object `class` extends js.Object @JSImport("snabbdom/modules/attributes", Default) @js.native object attributes extends js.Object @JSImport("snabbdom/modules/props", Default) @js.native object props extends js.Object @JSImport("snabbdom/modules/style", Default) @js.native object style extends js.Object @JSImport("snabbdom/modules/eventlisteners", Default) @js.native object eventlisteners extends js.Object
DROP DATABASE `agenda`; CREATE DATABASE `agenda`; USE agenda; CREATE TABLE `persona` ( `idPersona` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(45) NOT NULL, `telefono` varchar(20) NOT NULL, `email` varchar(20), `cumpleaños` varchar(20), `nombreLocalidad` int(11) NOT NULL, `nombreCategoria` int(11) NOT NULL, PRIMARY KEY (`idPersona`), FOREIGN KEY (`idLocalidad`) REFERENCES localidad (`idLocalidad`), FOREIGN KEY (`idCategoria`) REFERENCES categoria (`idCategoria`), ); CREATE TABLE `localidad` ( `idLocalidad` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(45) NOT NULL, PRIMARY KEY (`idLocalidad`) ); CREATE TABLE `categoria` ( `idCategoria` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(45) NOT NULL, PRIMARY KEY (`idCategoria`) );
# coding: utf-8 require 'thor' require 'hiyoko/scraper' require 'hiyoko/db' require 'hiyoko/lessons' require 'hiyoko/proj-generator' require 'hiyoko/viewer' require 'pp' module Hiyoko class CLI < Thor desc "prepare", "setup lessons" def prepare() if DB.prepare() != nil then url = "https://sites.google.com/a/gclue.jp/swift-docs/ni-yinki100-ios" scraper = Scraper.new(url) scraper.scrapeList() entries = scraper.getEntries() entries = scraper.getEntries() Lessons.setup_lessons(entries) puts "All set. Let's fly!" else lessons = Lessons.all if lessons.empty? then puts "not yet initilalized!" puts "Please execute the following command: " puts "hiyoko prepare" else puts "Already set. Let's fly!" end end end option :chap, type: :string, alias: '-c', desc: 'show progress selected by chapter' option :chap_num, type: :string, alias: '-n', desc: 'show progress selected by chapter number' option :shincyoku, type: :boolean, alias: '-c', desc: 'show progress by percentage' desc "progress", "show your progress" def progress() if DB.prepare() != nil then puts "not yet initilalized!" puts "please execute the following command: " puts "hiyoko prepare" exit end lessons = Lessons.all if lessons.empty? then puts "not yet initilalized!" puts "please execute the following command: " puts "hiyoko prepare" else if options[:chap] then lessons = Lessons.where("chap = :chap", chap: options[:chap]) Viewer.showProgress(lessons) elsif options[:chap_num] then lessons = Lessons.where("chap_number = :chap_num", chap_num: options[:chap_num]) Viewer.showProgress(lessons) elsif options[:shincyoku] then total = lessons.count complete_num = lessons.where('status = :status', status: 1).count progress_percentage = complete_num.to_f / total.to_f * 100.0 puts "your progress: " + progress_percentage.to_d.floor(2).to_s + ' % ' else Viewer.showProgress(lessons) end end end option :url, type: :string, alias: '-u', desc: 'setup by url' option :target, type: :string, alias: '-t', desc: 'setup by [chap number]-[topic number]' option :swift2, type: :boolean, alias: '-s', desc: 'replace println with print' desc "generate", "setup xcode project" def generate() if DB.prepare() != nil then puts "not yet initilalized!" puts "please execute the following command: " puts "hiyoko prepare" exit end lessons = Lessons.all if lessons.empty? then puts "not yet initilalized!" puts "hiyoko prepare" end if options[:url] then url = options[:url] scraper = Scraper.new(url) if options[:swift2] then scraper.scrapeCodeForSwift2(url) else scraper.scrapeCode(url) end scraper.scrapeTitle(url) project_name = scraper.getTitle() proj_generator = ProjGenerator.new(project_name) proj_generator.create_dir() proj_generator.create_files(scraper.getCodes()) lesson = Lessons.where("url = :url", url: url) lesson.first.status = 1 lesson.first.save puts 'Complete!' elsif options[:target] then if /(\d{2,2})-(\d{3,3})/ =~ options[:target] then chap_number = $1 topic_number = $2 lesson = Lessons.where("chap_number = :chap_number", chap_number: chap_number) .where("topic_number = :topic_number", topic_number: topic_number) url = lesson.first.url scraper = Scraper.new(url) scraper.scrapeCode(url) proj_generator = ProjGenerator.new(options[:target]) proj_generator.create_dir() proj_generator.create_files(scraper.getCodes()) lesson.first.status = 1 lesson.first.save puts 'Complete!' end else exit end end end end
using Jasper; using Jasper.Persistence.Postgresql; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; namespace Ponger { internal class JasperConfig : JasperOptions { public JasperConfig() { // Listen for incoming messages using the // lightweight TCP transport at port // 2222 Endpoints .ListenAtPort(2222) // Use message persistence here .Durable(); } public override void Configure(IHostEnvironment hosting, IConfiguration config) { if (hosting.IsDevelopment()) { // In development mode, we're just going to have the message persistence // schema objects dropped and rebuilt on app startup so you're // always starting from a clean slate Advanced.StorageProvisioning = StorageProvisioning.Rebuild; } // Just the normal work to get the connection string out of // application configuration var connectionString = config.GetConnectionString("postgresql"); // Setting up Sql Server-backed message persistence Extensions.PersistMessagesWithPostgresql(connectionString, "pongs"); } } }
Abbe.t abbe.t Abbé.t abbé.t Abbess.t abbess.t Abbot.t abbot.t accompanist.t accountant.t administrator.t admiral.t adviser.t advisor.t agent.t aide.t Ambassador.t ambassador.t analyst.t arbitrator.t Archbishop.t archbishop.t archdeacon.t architect.t archivist.t assessor.t asshole.t assistant.t associate.t attorney.t auditor.t bailiff.t best_man bosun.t broker.t Brother.t brother.t buyer.t candidate.t Captain.t captain.t cardinal.t chairman.t chairwoman.t chancellor.t chaplain.t chief.t clerk.t Commander.t commander.t Commissioner.t commissioner.t complainant.t Comptroller.t comptroller.t Congressman.t congressman.t contractor.t coordinator.t coroner.t correspondent.t councillor.t counsellor.t counselor.t Deaconess.t deaconess.t Deacon.t deacon.t Dean.t dean.t defendant.t defender.t delegate.t Democrat.t Deputy.t deputy.t diplomat.t director.t Doctor.t doctor.t Duchess.t duchess.t Duke.t duke.t economist.t editor.t emir.t Emir.t emissary.t emperor.t empress.t engineer.t executive.t executor.t Father.t father.t foreman.t founder.t General.t general.t Governor.t governor.t Headmaster.t headmaster.t Headmistress.t headmistress.t head.t Inspector.t inspector.t intern.t Justice.t justice.t King.t king.t Knight.t knight.t lawyer.t leader.t leutenant.t librarian.t litigator.t lobbyist.t maid_of_honor Major.t major.t manager.t Marquise.t marquise.t Marshall.t marshall.t Master-at-Arms.t Master-at-arms.t master-at-arms.t Master.t master.t mate.t Mayor.t mayor.t Minister.t minister.t Mother.t mother.t officer.t owner.t partner.t Pastor.t pastor.t Postmaster.t postmaster.t Premier.t premier.t President.t president.t Prime_Minister prime_minister private.t Professor.t professor.t proprietor.t prosecutor.t Quarter-master.t quarter-master.t Ranger.t ranger.t Representative.t representative.t Republican.t Sainte.t Saint.t Sargent.t sargent.t seaman.t secretary.t Seigneur.t seigneur.t Seignior.t seignior.t senator.t Senator.t Shah.t shah.t Sheriff.t sheriff.t Sister.t sister.t Skipper.t skipper.t Solicitor.t solicitor.t Speaker.t speaker.t spokesman.t spokesperson.t spokeswoman.t sponsor.t Superintendent.t superintendent.t Treasurer.t treasurer.t undersecretary.t underwriter.t Vice-Admiral.t Vice-admiral.t vice-admiral.t Viceroy.t viceroy.t Warden.t warden.t
import ExpressionReference from './ExpressionReference' import ExpressionReferenceComponent from './ExpressionReferenceComponent' import DropExpressionReference from './DropExpressionReference' export default { name: 'expression-reference', configure: function(config) { config.addNode(ExpressionReference) config.addComponent(ExpressionReference.type, ExpressionReferenceComponent) // FIXME // config.addDragAndDrop(DropExpressionReference); } }
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {ChangeDetectionStrategy, Component, Input} from '@angular/core'; import {Extent, Scale} from '../lib/public_types'; import { getDomSizeInformedTickCount, getScaleRangeFromDomDim, } from './chart_view_utils'; @Component({ selector: 'line-chart-grid-view', template: `<svg> <line *ngFor="let tick of getXTicks()" [class.zero]="tick === 0" [attr.x1]="getDomX(tick)" y1="0" [attr.x2]="getDomX(tick)" [attr.y2]="domDim.height" ></line> <line *ngFor="let tick of getYTicks()" [class.zero]="tick === 0" x1="0" [attr.y1]="getDomY(tick)" [attr.x2]="domDim.width" [attr.y2]="getDomY(tick)" ></line> </svg>`, styles: [ ` :host { display: block; overflow: hidden; } svg { height: 100%; width: 100%; } line { stroke: #ccc; stroke-width: 1px; } .zero { stroke: #aaa; stroke-width: 1.5px; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LineChartGridView { @Input() viewExtent!: Extent; @Input() xScale!: Scale; @Input() xGridCount!: number; @Input() yScale!: Scale; @Input() yGridCount!: number; @Input() domDim!: {width: number; height: number}; getDomX(dataX: number): number { return this.xScale.forward( this.viewExtent.x, getScaleRangeFromDomDim(this.domDim, 'x'), dataX ); } getDomY(dataY: number): number { return this.xScale.forward( this.viewExtent.y, getScaleRangeFromDomDim(this.domDim, 'y'), dataY ); } getXTicks() { return this.xScale.ticks( this.viewExtent.x, getDomSizeInformedTickCount(this.domDim.width, this.xGridCount) ); } getYTicks() { return this.xScale.ticks( this.viewExtent.y, getDomSizeInformedTickCount(this.domDim.height, this.yGridCount) ); } }
#!/bin/bash echo "Breaking OPA Gatekeeper.." echo "Changing the failurePolicy to Fail..." kubectl get ValidatingWebhookConfiguration gatekeeper-validating-webhook-configuration -o yaml | sed 's/failurePolicy.*/failurePolicy: Fail/g' | kubectl apply -f - echo "Scaling deployments to zero..." kubectl -n gatekeeper-system scale --replicas=0 deploy/gatekeeper-audit kubectl -n gatekeeper-system scale --replicas=0 deploy/gatekeeper-controller-manager kubectl -n gatekeeper-system get pods -o wide
package com.github.jhanne82.documenttree.utils; import com.github.jhanne82.documenttree.simulation.documenttree.retrieval.EulerianDistance; import org.junit.Test; import static junit.framework.TestCase.assertEquals; public class EulerianDistanceTest { Double[] documentVector = {0.1, 0.2, 0.3, 0.4, null}; Double[] searchVector = {0.5, 0.6, 0.7, 0.8, 0d }; @Test public void calcRelevanceTest() { double expectedRel = 1.25; double calcRel = EulerianDistance.calcRelevance( documentVector, searchVector ); assertEquals( expectedRel, calcRel ); } }
-- @testpoint: truncate table drop table if exists alter_table_tb08; create table alter_table_tb08 ( c1 int, c2 bigint, c3 varchar(20) ); insert into alter_table_tb08 values('11',null,'sss'); insert into alter_table_tb08 values('21','','sss'); insert into alter_table_tb08 values('31',66,''); insert into alter_table_tb08 values('41',66,null); insert into alter_table_tb08 values('41',66,null); select * from alter_table_tb08; truncate table alter_table_tb08; select * from alter_table_tb08; drop table if exists alter_table_tb08;
package com.johnowl.rules import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class VariablesParserTest { private val parser = VariablesParser() @Test fun `should add Int as Number`() { val variables = parser.parse(mapOf("number" to 100)) assertEquals("100", variables["number"]) } @Test fun `should add String as Text`() { val variables = parser.parse(mapOf("name" to "johnowl")) assertEquals("johnowl", variables["name"]) } @Test fun `should add list itens as Text`() { val variables = parser.parse(mapOf("roles" to listOf("beta", "alpha"))) assertEquals("['beta' 'alpha']", variables["roles"]) } @Test fun `should add list itens as Numbers`() { val variables = parser.parse(mapOf("numbers" to listOf(20, 50, 30))) assertEquals("[Number(20) Number(50) Number(30)]", variables["numbers"]) } @Test fun `should add list itens as Numbers and Text`() { val variables = parser.parse(mapOf("things" to listOf(20, 50, 30, "text1", 200, "text2"))) assertEquals("[Number(20) Number(50) Number(30) 'text1' Number(200) 'text2']", variables["things"]) } }
// Copyright (c) Simon Fraser University. All rights reserved. // Licensed under the MIT license. // // Authors: // George He <[email protected]> // Duo Lu <[email protected]> // Tianzheng Wang <[email protected]> #pragma once #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <bits/hash_bytes.h> #include <unistd.h> #include <time.h> #include <string.h> #include <immintrin.h> #include <tbb/spin_mutex.h> #include <tbb/spin_rw_mutex.h> #include <iostream> #include <string> #include <cstdint> #include <cstring> #include <cmath> #include <algorithm> #include <array> #include <utility> #include <tuple> #include <atomic> #include <queue> #include <limits> #include <chrono> #include <vector> #include <random> #include <climits> #include <functional> #include <cassert> #include <thread> #include <boost/lockfree/queue.hpp> #ifdef TEST_MODE #define MAX_INNER_SIZE 3 #define MAX_LEAF_SIZE 4 #define SIZE_ONE_BYTE_HASH 1 #define SIZE_PMEM_POINTER 16 #else #define MAX_INNER_SIZE 128 #define MAX_LEAF_SIZE 64 #define SIZE_ONE_BYTE_HASH 1 #define SIZE_PMEM_POINTER 16 #endif #if MAX_LEAF_SIZE > 64 #error "Number of kv pairs in LeafNode must be <= 64." #endif static const uint64_t offset = std::numeric_limits<uint64_t>::max() >> (64 - MAX_LEAF_SIZE); enum Result { Insert, Update, Split, Abort, Delete, Remove, NotFound }; #ifdef PMEM #include <libpmemobj.h> #define PMEMOBJ_POOL_SIZE ((size_t)(1024 * 1024 * 1) * 1000) /* 11 GB */ POBJ_LAYOUT_BEGIN(FPtree); POBJ_LAYOUT_ROOT(FPtree, struct List); POBJ_LAYOUT_TOID(FPtree, struct LeafNode); POBJ_LAYOUT_END(FPtree); POBJ_LAYOUT_BEGIN(Array); POBJ_LAYOUT_TOID(Array, struct Log); POBJ_LAYOUT_END(Array); inline PMEMobjpool *pop; #endif static uint8_t getOneByteHash(uint64_t key); struct KV { uint64_t key; uint64_t value; KV() {} KV(uint64_t key, uint64_t value) { this->key = key; this->value = value; } }; struct LeafNodeStat { uint64_t kv_idx; // bitmap index of key uint64_t count; // number of kv in leaf uint64_t min_key; // min key excluding key }; // This Bitset class implements bitmap of size <= 64 // The bitmap iterates from right to left - starting from least significant bit // off contains 0 on some significant bits when bitmap size < 64 class Bitset { public: uint64_t bits; Bitset() { bits = 0; } ~Bitset() {} Bitset(const Bitset& bts) { bits = bts.bits; } Bitset& operator=(const Bitset& bts) { bits = bts.bits; return *this; } inline void set(const size_t pos) { bits |= ((uint64_t)1 << pos); } inline void reset(const size_t pos) { bits &= ~((uint64_t)1 << pos); } inline void clear() { bits = 0; } inline bool test(const size_t pos) const { return bits & ((uint64_t)1 << pos); } inline void flip() { bits ^= offset; } inline bool is_full() { return bits == offset; } inline size_t count() { return __builtin_popcountl(bits); } inline size_t first_set() { size_t idx = __builtin_ffsl(bits); return idx ? idx - 1 : MAX_LEAF_SIZE; } inline size_t first_zero() { size_t idx = __builtin_ffsl(bits ^ offset); return idx? idx - 1 : MAX_LEAF_SIZE; } void print_bits() { for (uint64_t i = 0; i < 64; i++) { std::cout << ((bits >> i) & 1); } std::cout << std::endl; } }; /******************************************************* Define node struture ********************************************************/ struct BaseNode { bool isInnerNode; friend class FPtree; public: BaseNode(); } __attribute__((aligned(64))); struct InnerNode : BaseNode { uint64_t nKey; uint64_t keys[MAX_INNER_SIZE]; BaseNode* p_children[MAX_INNER_SIZE + 1]; friend class FPtree; public: InnerNode(); InnerNode(uint64_t key, BaseNode* left, BaseNode* right); InnerNode(const InnerNode& inner); ~InnerNode(); // for using mempool only where constructor is not called void init(uint64_t key, BaseNode* left, BaseNode* right); // return index of child in p_children when searching key in this innernode uint64_t findChildIndex(uint64_t key); // remove key at index, default remove right child (or left child if false) void removeKey(uint64_t index, bool remove_right_child); // add key at index pos, default add child to the right void addKey(uint64_t index, uint64_t key, BaseNode* child, bool add_child_right); } __attribute__((aligned(64))); struct LeafNode : BaseNode { __attribute__((aligned(64))) uint8_t fingerprints[MAX_LEAF_SIZE]; Bitset bitmap; KV kv_pairs[MAX_LEAF_SIZE]; #ifdef PMEM TOID(struct LeafNode) p_next; #else LeafNode* p_next; #endif std::atomic<uint64_t> lock; friend class FPtree; public: #ifndef PMEM LeafNode(); LeafNode(const LeafNode& leaf); LeafNode& operator=(const LeafNode& leaf); #endif inline bool isFull() { return this->bitmap.is_full(); } void addKV(struct KV kv); // find index of kv that has kv.key = key, return MAX_LEAF_SIZE if key not found uint64_t findKVIndex(uint64_t key); // return min key in leaf uint64_t minKey(); bool Lock() { uint64_t expected = 0; return std::atomic_compare_exchange_strong(&lock, &expected, 1); } void Unlock() { this->lock = 0; } void getStat(uint64_t key, LeafNodeStat& lstat); } __attribute__((aligned(64))); #ifdef PMEM struct argLeafNode { size_t size; bool isInnerNode; Bitset bitmap; __attribute__((aligned(64))) uint8_t fingerprints[MAX_LEAF_SIZE]; KV kv_pairs[MAX_LEAF_SIZE]; uint64_t lock; argLeafNode(LeafNode* leaf) { isInnerNode = false; size = sizeof(struct LeafNode); memcpy(fingerprints, leaf->fingerprints, sizeof(leaf->fingerprints)); memcpy(kv_pairs, leaf->kv_pairs, sizeof(leaf->kv_pairs)); bitmap = leaf->bitmap; lock = 1; } argLeafNode(struct KV kv) { isInnerNode = false; size = sizeof(struct LeafNode); kv_pairs[0] = kv; fingerprints[0] = getOneByteHash(kv.key); bitmap.set(0); lock = 0; } }; static int constructLeafNode(PMEMobjpool *pop, void *ptr, void *arg); struct List { TOID(struct LeafNode) head; }; /* uLog */ struct Log { TOID(struct LeafNode) PCurrentLeaf; TOID(struct LeafNode) PLeaf; }; static const uint64_t sizeLogArray = 128; static boost::lockfree::queue<Log*> splitLogQueue = boost::lockfree::queue<Log*>(sizeLogArray); static boost::lockfree::queue<Log*> deleteLogQueue = boost::lockfree::queue<Log*>(sizeLogArray); #endif struct Stack //TODO: Get rid of Stack { public: static const uint64_t kMaxNodes = 32; InnerNode* innerNodes[kMaxNodes]; uint64_t num_nodes; Stack() : num_nodes(0) {} ~Stack() { num_nodes = 0; } inline void push(InnerNode* node) { assert(num_nodes < kMaxNodes && "Error: exceed max stack size"); this->innerNodes[num_nodes++] = node; } InnerNode* pop() { return num_nodes == 0 ? nullptr : this->innerNodes[--num_nodes]; } inline bool isEmpty() { return num_nodes == 0; } inline InnerNode* top() { return num_nodes == 0 ? nullptr : this->innerNodes[num_nodes - 1]; } inline void clear() { num_nodes = 0; } }; static thread_local Stack stack_innerNodes; static thread_local InnerNode* inners[32]; static thread_local short ppos[32]; struct FPtree { BaseNode *root; tbb::speculative_spin_rw_mutex speculative_lock; InnerNode* right_most_innnerNode; // for bulkload public: FPtree(); FPtree(int); ~FPtree(); BaseNode* getRoot () { return this->root; } void printFPTree(std::string prefix, BaseNode *root); // return flse if kv.key not found, otherwise set kv.value to value associated with kv.key uint64_t find(uint64_t key); // return false if kv.key not found, otherwise update value associated with key bool update(struct KV kv); // return false if key already exists, otherwise insert kv bool insert(struct KV kv); // delete key from tree bool deleteKey(uint64_t key); // TODO: fix/optimize iterator based scan methods // initialize scan by finding the first kv with kv.key >= key void scanInitialize(uint64_t key); KV scanNext(); bool scanComplete(); uint64_t rangeScan(uint64_t key, uint64_t scan_size, char* result); #ifdef PMEM bool bulkLoad(float load_factor); void recoverSplit(Log* uLog); void recoverDelete(Log* uLog); void recover(); void showList(); #endif private: // return leaf that may contain key, does not push inner nodes LeafNode* findLeaf(uint64_t key); // return leaf that may contain key, push all innernodes on traversal path into stack LeafNode* findLeafAndPushInnerNodes(uint64_t key); uint64_t findSplitKey(LeafNode* leaf); uint64_t splitLeaf(LeafNode* leaf); void updateParents(uint64_t splitKey, InnerNode* parent, BaseNode* leaf); void splitLeafAndUpdateInnerParents(LeafNode* reachedLeafNode, Result decision, struct KV kv, bool updateFunc, uint64_t prevPos); // merge parent with sibling, may incur further merges. Remove key from indexNode after void removeLeafAndMergeInnerNodes(short i, short indexNode_level); // try transfer a key from sender to receiver, sender and receiver should be immediate siblings // If receiver & sender are inner nodes, will assume the only child in receiver is at index 0 // return false if cannot borrow key from sender bool tryBorrowKey(InnerNode* parent, uint64_t receiver_idx, uint64_t sender_idx); uint64_t minKey(BaseNode* node); LeafNode* minLeaf(BaseNode* node); LeafNode* maxLeaf(BaseNode* node); void sortKV(); uint64_t size_volatile_kv; KV volatile_current_kv[MAX_LEAF_SIZE]; LeafNode* current_leaf; uint64_t bitmap_idx; friend class Inspector; };
require 'minitest/autorun' require 'prawn/qrcode' require 'prawn/document' class TestQrcodeInContext < Minitest::Test def test_render_with_margin context = Prawn::Document.new assert(context.print_qr_code('HELOWORLD', margin: 0)) end def test_render_with_alignment context = Prawn::Document.new left = context.print_qr_code('HELLOWORLD', align: :left) center = context.print_qr_code('HELLOWORLD', align: :center) right = context.print_qr_code('HELLOWORLD', align: :right) assert(left.anchor[0] < center.anchor[0]) assert(center.anchor[0] < right.anchor[0]) end end
--- layout: post title: Aula 05 #image: /img/hello_world.jpeg --- # Escalares (Tipos e operações) & # Vetores (Arrays e Hashes) ## Apresentação [Escalares](/introprog2021/pdf/aula05a.pdf) [Vetores](/introprog2021/pdf/aula05b.pdf) ## Material para aula Arquivo em formato fasta: [dmel-gene-r5.45.fasta](/introprog2021/files/dmel-gene-r5.45.fasta) MD5 = 185057f6340dc01e022cbbbc7a51f343 ## Exemplos {% highlight perl linenos %}# exemplo01 #! /usr/bin/perl # atribuindo valores as variaveis $y = 1; # inteiro positivo $z = -5; # inteiro negativo $x = 3.14; # real em ponto flutuante $w = 2.75e-6; # real em notação científica $t = 0377; # octal $u = 0xffff; # hexadecimal $s = 0b1100; # binario $string1 = "Oi, eu sou uma string!"; # string $string2 = 'Oi, eu tb sou uma string'; # string $string3 = "ATCGATCGATCGATCGATTGGATC"; # string print "\$y \= $y\n"; print "\$z \= $z\n"; print "\$x \= $x\n"; print "\$w \= $w\n"; print "\$t \= $t\n"; print "\$u \= $u\n"; print "\$s \= $s\n\n"; print "$string1\n$string2\n$string3\n\n"; exit; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo02 #! /usr/bin/perl # script para testar operacoes matematicas # testando $a = 1; print "Atribuicao\: \$a \= $a\n"; #++$a; #print "Auto\-acrescimo\: \$a \= $a\n"; #--$a; #print "Auto\-decrescimo\: \$a \= $a\n"; #$b = 3 + 1; #print "Soma\: \$b \= $b\n"; #$c = $a + $b; #print "Soma\: \$c \= $c\n"; #$d = $b * $c; #print "Multiplicacao\: \$d \= $d\n"; #$e = $d / $b; #print "Divisao\: \$e \= $e\n"; #$f = sqrt($b); #print "Raiz quadrada\: \$f \= $f\n"; #$g = ($a + $b) * $c; #print "Equacao\: \$g \= $g\n"; #$h = $g % 2; #print "Modulo\: \$h \= $h\n"; #$i = $d % $b; #print "Modulo\: \$i \= $i\n"; #$j = $c ** $f; #print "Potenciacao\: \$j \= $j\n"; #$j += 5; #print "Adicao e atribuicao\: \$j \= $j\n"; #$j -= $e; #print "Subtracao e atribuicao\: \$j \= $j\n"; exit; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo03 #! /usr/bin/perl # script para entender arrays # criando o array de nomes @gene_names = ( "gene1", "gene2", "gene3", "gene4", "gene5" ); exit; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo04 # continuacao do script para entender arrays # criando o array de IDs @gene_IDs = ( "FBgn0033056", "FBgn0037888", "FBgn0034742", "FBgn0032640", "FBgn0259204" ); {% endhighlight %} ======== {% highlight perl linenos %}# exemplo05 # continuacao do script para entender arrays # acessando os elementos individuais do array print "$gene_IDs[0] \= $gene_names[0]\;\n"; print "$gene_IDs[1] \= $gene_names[1]\;\n"; print "$gene_IDs[2] \= $gene_names[2]\;\n"; print "$gene_IDs[3] \= $gene_names[3]\;\n"; print "$gene_IDs[4] \= $gene_names[4]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo06 # continuacao do script para entender arrays #adicionando elementos no array $gene_names[5] = "CG15556"; $gene_IDs[5] = "FBgn0039821"; print "$gene_IDs[5] \= $gene_names[5]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo07 # adicionando mais elementos no array $gene_names[7] = "CG9773"; $gene_IDs[7] = "FBgn0037609"; print "$gene_IDs[6] \= $gene_names[6]\;\n"; print "$gene_IDs[7] \= $gene_names[7]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo08 # adicionando mais elementos no array $gene_names[6] = "CG7059"; $gene_IDs[6] = "FBgn0038957"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo09 # o que faz a funcao push()? push(@gene_names, "RabX4"); push(@gene_IDs, "FBgn0051118"); print "\nExemplo07\:\n"; print "$gene_IDs[0] \= $gene_names[0]\;\n"; print "$gene_IDs[1] \= $gene_names[1]\;\n"; print "$gene_IDs[2] \= $gene_names[2]\;\n"; print "$gene_IDs[3] \= $gene_names[3]\;\n"; print "$gene_IDs[4] \= $gene_names[4]\;\n"; print "$gene_IDs[5] \= $gene_names[5]\;\n"; print "$gene_IDs[6] \= $gene_names[6]\;\n"; print "$gene_IDs[7] \= $gene_names[7]\;\n"; print "$gene_IDs[8] \= $gene_names[8]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo10 # o que faz a funcao pop()? pop(@gene_names); pop(@gene_IDs); print "\nExemplo10\:\n"; print "$gene_IDs[0] \= $gene_names[0]\;\n"; print "$gene_IDs[1] \= $gene_names[1]\;\n"; print "$gene_IDs[2] \= $gene_names[2]\;\n"; print "$gene_IDs[3] \= $gene_names[3]\;\n"; print "$gene_IDs[4] \= $gene_names[4]\;\n"; print "$gene_IDs[5] \= $gene_names[5]\;\n"; print "$gene_IDs[6] \= $gene_names[6]\;\n"; print "$gene_IDs[7] \= $gene_names[7]\;\n"; print "$gene_IDs[8] \= $gene_names[8]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo11 # o que faz a funcao shift()? $gene_name01 = shift(@gene_names); $gene_id01 = shift(@gene_IDs); print "\nExemplo11\:\n"; print "$gene_id01 \= $gene_name01\;\n"; print "Novo array\:\n"; print "$gene_IDs[0] \= $gene_names[0]\;\n"; print "$gene_IDs[1] \= $gene_names[1]\;\n"; print "$gene_IDs[2] \= $gene_names[2]\;\n"; print "$gene_IDs[3] \= $gene_names[3]\;\n"; print "$gene_IDs[4] \= $gene_names[4]\;\n"; print "$gene_IDs[5] \= $gene_names[5]\;\n"; print "$gene_IDs[6] \= $gene_names[6]\;\n"; print "$gene_IDs[7] \= $gene_names[7]\;\n"; print "$gene_IDs[8] \= $gene_names[8]\;\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo12 # o que faz a funcao unshift()? unshift(@gene_names, $gene_name01); unshift(@gene_IDs, $gene_id01); print "\nExemplo12\:\n"; print "$gene_IDs[0] \= $gene_names[0]\;\n"; print "$gene_IDs[1] \= $gene_names[1]\;\n"; print "$gene_IDs[2] \= $gene_names[2]\;\n"; print "$gene_IDs[3] \= $gene_names[3]\;\n"; print "$gene_IDs[4] \= $gene_names[4]\;\n"; print "$gene_IDs[5] \= $gene_names[5]\;\n"; print "$gene_IDs[6] \= $gene_names[6]\;\n"; print "$gene_IDs[7] \= $gene_names[7]\;\n"; print "$gene_IDs[8] \= $gene_names[8]\;\n\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo13 # funcao splice() para substituicao # uso: splice (@array, inicio, tamanho, @lista_substituir) @nums = (1..20); print "\nExemplo13\:\n"; print "Antes - @nums\n"; splice(@nums,5 ,5 , 21..25); print "Depois - @nums\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo14 # funcao split() # transformar string em array # strings $var_music = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_Mando = "This is the way"; # transformar strings em arrays @music = split('-', $var_music); @Mando = split(' ', $var_Mando); print "$music[5]\n"; print "$Mando[3]\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo15 # funcao join() # transformar array em string $string1 = join( ' ', @music ); $string2 = join( '-', @Mando ); print "\nExemplo15\:\n"; print "$string1\n"; print "$string2\n"; {% endhighlight %} ======== {% highlight perl linenos %}# exemplo16 #! /usr/bin/perl # script para entender hashes # criando o hash de genes %genes = ("FBgn0033056", "CG7856", "FBgn0037888", "scpr-B", "FBgn0034742", "CG424", "FBgn0032640", "Sgt", "FBgn0259204", "CG42308", "FBgn0039821", "CG15556", "FBgn0038957", "CG7059", "FBgn0037609", "CG9773"); exit; {% endhighlight %} ========
import jseu from 'js-encoding-utils'; import {getTestEnv} from './prepare'; import {HashTypes} from '../src/params'; const env = getTestEnv(); const pbkdf = env.library; const envName = env.envName; const hashes: Array<HashTypes> = ['SHA-256', 'SHA-384', 'SHA-512', 'SHA-1', 'MD5', 'SHA3-512', 'SHA3-384', 'SHA3-256', 'SHA3-224']; const sample = { pbkdf1: { p: 'password', pbuf: '70617373776f7264', s: 'dc04deff5a33c22df3aa82085f9c2d0f5477af73cd500dfe53162d70ba096a03', c: 2048, dkLen: 16, key: { 'SHA-256': '2e460082f6002d377042bbfd7c3fcf61', 'SHA-384': 'bc3d241bd9975babb7bb7fd0c843c9e0', 'SHA-512': '2b875a1a163ade05f788ba386033c20a', 'SHA-1': '55ce9e9aa9bf733f193e66620365fe0e', 'MD5': '9238c6bfe098e5c4e7b68549233cc8ef', 'SHA3-512': '5e51493668d6d08d8403b9322d03f914', 'SHA3-384': 'da16920c20a843b164ce67e3190de57b', 'SHA3-256': '0541ae8ceb63e2bd2a7e0537b309c526', 'SHA3-224': '8c0660f7416a588fcd2a7827126f3ac7', } }, pbkdf2: { p: 'password', pbuf: '70617373776f7264', s: 'dc04deff5a33c22df3aa82085f9c2d0f5477af73cd500dfe53162d70ba096a03', c: 2048, dkLen: 32, key: { 'SHA-256': 'bf3d09d429fbf71bbb384a6421447da32096ff8a010c7042d3e29194237792d2', 'SHA-384': 'f4e9e3377bfdb37695b41d163b67f6a8de017db98ea69bd5163f9d771a141878', 'SHA-512': 'ff055f4a1f3b9b70de87ecd942c7aed9d1e5b77d5b4d36f92389ead9f6c359bf', 'SHA-1': 'ca95cba5373ca0b86ad1dd7b31fb51d77f4cdc424c1d9b704620cee505bdc772', 'MD5': '28ecf8c0c5435581175b094cb7626fff5dca051755dcab43add58cff48abfe8f', 'SHA3-512': '37c793ab40a84e92a93ed199c6c54e49344af0e5c0567cc109433636c8ef27e0', 'SHA3-384': 'd56ef64f984bc0efde9e1435bacf9d9474b58604ecbaa30a956373c1eb563124', 'SHA3-256': '1e82ef43d6995443375993377b660d3cb48388ca8e74001278a2f9d93fcefb13', 'SHA3-224': '7c50d5924695c32542f9ea53010c5c7f16985377757ddd4185bbad95bda209e1', } } }; describe(`${envName}: Test for PBKDF 1 and 2`, () => { beforeAll( async () => { }); it('PBKDF2 with password string', async () => { const array = await Promise.all( hashes.map( async (h) => { const key = await pbkdf.pbkdf2( sample.pbkdf2.p, jseu.encoder.hexStringToArrayBuffer(sample.pbkdf2.s), sample.pbkdf2.c, sample.pbkdf2.dkLen, h ); return jseu.encoder.arrayBufferToHexString(key) === sample.pbkdf2.key[h]; })); expect(array.every( (elem) => elem)).toBeTruthy(); }, 10000); it('PBKDF2 with password buffer', async () => { const array = await Promise.all( hashes.map( async (h) => { const key = await pbkdf.pbkdf2( jseu.encoder.hexStringToArrayBuffer(sample.pbkdf2.pbuf), jseu.encoder.hexStringToArrayBuffer(sample.pbkdf2.s), sample.pbkdf2.c, sample.pbkdf2.dkLen, h ); return jseu.encoder.arrayBufferToHexString(key) === sample.pbkdf2.key[h]; })); expect(array.every( (elem) => elem)).toBeTruthy(); }, 10000); it('PBKDF1 with password string', async () => { const array = await Promise.all( hashes.map( async (h) => { const key = await pbkdf.pbkdf1( sample.pbkdf1.p, jseu.encoder.hexStringToArrayBuffer(sample.pbkdf1.s), sample.pbkdf1.c, sample.pbkdf1.dkLen, h ); return jseu.encoder.arrayBufferToHexString(key) === sample.pbkdf1.key[h]; })); expect(array.every( (elem) => elem)).toBeTruthy(); }, 10000); it('PBKDF1 with password buffer', async () => { const array = await Promise.all( hashes.map( async (h) => { const key = await pbkdf.pbkdf1( jseu.encoder.hexStringToArrayBuffer(sample.pbkdf1.pbuf), jseu.encoder.hexStringToArrayBuffer(sample.pbkdf1.s), sample.pbkdf1.c, sample.pbkdf1.dkLen, h ); return jseu.encoder.arrayBufferToHexString(key) === sample.pbkdf1.key[h]; })); expect(array.every( (elem) => elem)).toBeTruthy(); }, 10000); });
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Windows.Controls; using System.Windows.Input; using ICSharpCode.Core; namespace ICSharpCode.SharpDevelop.Gui.Pads { public sealed class JumpToAddressCommand : AbstractComboBoxCommand { MemoryPad pad; ComboBox comboBox; protected override void OnOwnerChanged(EventArgs e) { this.pad = this.Owner as MemoryPad; if (this.pad == null) return; comboBox = this.ComboBox as ComboBox; if (this.comboBox == null) return; comboBox.KeyUp += (s, ea) => { if (ea.Key == Key.Enter) Run(); }; comboBox.IsEditable = true; comboBox.Width = 130; base.OnOwnerChanged(e); } public override void Run() { if (this.pad != null && this.comboBox != null) { pad.JumpToAddress(comboBox.Text); } base.Run(); } } public abstract class ItemMemoryCommand : AbstractCommand { protected MemoryPad pad; protected override void OnOwnerChanged(EventArgs e) { this.pad = this.Owner as MemoryPad; if (this.pad == null) return; base.OnOwnerChanged(e); } } public sealed class RefreshAddressCommand : ItemMemoryCommand { public override void Run() { if (this.pad == null) return; this.pad.Refresh(); } } public sealed class NextAddressCommand : ItemMemoryCommand { public override void Run() { if (this.pad == null) return; this.pad.MoveToNextAddress(); } } public sealed class PreviousAddressCommand : ItemMemoryCommand { public override void Run() { if (this.pad == null) return; this.pad.MoveToPreviousAddress(); } } public sealed class DisplayByteSizeCommand : AbstractComboBoxCommand { MemoryPad pad; ComboBox comboBox; protected override void OnOwnerChanged(EventArgs e) { this.pad = this.Owner as MemoryPad; if (this.pad == null) return; comboBox = this.ComboBox as ComboBox; if (this.comboBox == null) return; comboBox.SelectionChanged += (s, ea) => { Run(); }; comboBox.Items.Add(1); comboBox.Items.Add(2); comboBox.Items.Add(4); comboBox.Text = "1"; comboBox.Width = 30; comboBox.IsEditable = false; base.OnOwnerChanged(e); } public override void Run() { if (this.pad != null && this.comboBox != null) { pad.DisplayByteSize = Convert.ToByte(this.comboBox.SelectedValue); pad.DisplayMemory(); } base.Run(); } } }
# frozen_string_literal: true require 'spec_helper' describe 'acts_as_removable' do class MyModel < ActiveRecord::Base acts_as_removable attr_accessor :callback_before_remove, :callback_after_remove, :callback_before_unremove, :callback_after_unremove before_remove do |r| r.callback_before_remove = true end after_remove do |r| r.callback_after_remove = true end before_unremove do |ur| ur.callback_before_unremove = true end after_unremove do |ur| ur.callback_after_unremove = true end end class MySecondModel < ActiveRecord::Base acts_as_removable column_name: :use_this_column end before do # setup database db_file = File.expand_path(File.join(File.dirname(__FILE__), '..', 'tmp', 'acts_as_removable.db')) Dir.mkdir(File.dirname(db_file)) unless File.exist?(File.dirname(db_file)) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: "#{File.expand_path(File.join(File.dirname(__FILE__), '..'))}/tmp/acts_as_removable.db" ) ActiveRecord::Base.connection.execute("DROP TABLE IF EXISTS 'my_models'") ActiveRecord::Base.connection.create_table(:my_models) do |t| t.timestamp :removed_at end ActiveRecord::Base.connection.execute("DROP TABLE IF EXISTS 'my_second_models'") ActiveRecord::Base.connection.create_table(:my_second_models) do |t| t.string :name t.timestamp :use_this_column end end it 'test column and check method' do [[MyModel.create!, :removed_at], [MySecondModel.create!, :use_this_column]].each do |r, column_name| expect(r.removed?).to be(false) expect(r.send(column_name)).to be(nil) r.remove expect(r.removed?).to be(true) expect(r.send(column_name)).to be_kind_of(Time) end end it 'test scopes' do MyModel.delete_all MySecondModel.delete_all MyModel.create! MyModel.create!.remove! MySecondModel.create! MySecondModel.create!.remove! expect(MyModel.count).to be(2) expect(MyModel.actives.count).to be(1) expect(MyModel.removed.count).to be(1) expect(MyModel.unscoped.count).to be(2) expect(MySecondModel.count).to be(2) expect(MySecondModel.actives.count).to be(1) expect(MySecondModel.removed.count).to be(1) expect(MySecondModel.unscoped.count).to be(2) end it 'test callbacks' do r = MyModel.create! expect(r.callback_before_remove).to be(nil) expect(r.callback_after_remove).to be(nil) expect(r.callback_before_unremove).to be(nil) expect(r.callback_after_unremove).to be(nil) r.remove expect(r.callback_before_remove).to be(true) expect(r.callback_after_remove).to be(true) expect(r.callback_before_unremove).to be(nil) expect(r.callback_after_unremove).to be(nil) r.unremove expect(r.callback_before_remove).to be(true) expect(r.callback_after_remove).to be(true) expect(r.callback_before_unremove).to be(true) expect(r.callback_after_unremove).to be(true) end end
package zachinio.choreographer.animation import android.animation.Animator import android.view.View import io.reactivex.Completable import java.lang.ref.WeakReference class ScaleAnimation( view: View, private val xScale: Float, private val yScale: Float, private val duration: Long ) : Animation() { private var viewWeak: WeakReference<View> = WeakReference(view) override fun animate(): Completable { return Completable.create { viewWeak.get() ?.animate() ?.setDuration(duration) ?.scaleX(xScale) ?.scaleY(yScale) ?.setListener(object : AnimationListener(){ override fun onAnimationEnd(p0: Animator?) { it.onComplete() } }) } } }
using System; using System.Collections; using System.Collections.Generic; namespace SimpleContainer { internal sealed class DependencyDictionary : IEnumerable<DependencyLink> { private readonly Dictionary<Type, DependencyLink> links = new Dictionary<Type, DependencyLink>(); public DependencyNode this[Type key] { get { if (links.TryGetValue(key, out var link)) return link.Node; return null; } set { if (links.TryGetValue(key, out var link)) { link.Node = value; } link = DependencyLink.Create(key, value); links.Add(key, link); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<DependencyLink> GetEnumerator() { foreach (var link in links.Values) { yield return link; } } public void Add(Type type) { links.Add(type, DependencyLink.Create(type, null)); } public void Add(Type type, DependencyNode node) { links.Add(type, DependencyLink.Create(type, node)); } } }
// run-pass // To avoid having to `or` gate `_` as an expr. #![feature(generic_arg_infer)] fn foo() -> [u8; 3] { let x: [u8; _] = [0; _]; x } fn main() { assert_eq!([0; _], foo()); }
import HostedFieldType from '../hosted-field-type'; export default interface HostedInputValues { [HostedFieldType.CardCode]?: string; [HostedFieldType.CardCodeVerification]?: string; [HostedFieldType.CardExpiry]?: string; [HostedFieldType.CardName]?: string; [HostedFieldType.CardNumber]?: string; [HostedFieldType.CardNumberVerification]?: string; }
package com.yhy.mybatis.mapper.teacher; import com.yhy.mybatis.bean.Teacher; public interface TeacherMapper { //获取指定老师,及老师下的所有学生 public Teacher getTeacher(int id); public Teacher getTeacher2(int id); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>Fastcoo</title> <meta name="description" content="A responsive bootstrap 4 admin dashboard template by hencework" /> <!-- Favicon --> <?php include APPPATH.'views/includes/styles.php';?> </head> <body> <?php include APPPATH.'views/includes/header.php';?> <nav class="hk-breadcrumb" aria-label="breadcrumb"> <ol class="breadcrumb breadcrumb-light bg-transparent"> <li class="breadcrumb-item"><a href="#"><i class="glyphicon glyphicon-home"></i> Home</a></li> <li class="breadcrumb-item active" aria-current="page">Schedule Management</li> <li class="breadcrumb-item active" aria-current="page">CS Schedule</li> </ol> </nav> <div class = "container"> <div class="breadcrumb-line"> <div class="hk-pg-header"> <h4><i data-feather="arrow-left-circle"></i></i> <span class="text-semibold"></span>CS Schedule</h4> </div> </div> <section class="hk-sec-wrapper"> <div class="panel-heading"> <h5 class="panel-title">CS Schedule</h5> </div><br> <section class="hk-sec-wrapper"> <form action="" method="post" name="schedule"> <div class="col-md-4"> <div class="form-group"> <label>Call Status</label> <select name="sch_type" id="sch_type" class="form-control" onchange="changeView(this.value)" required=""> <option value="">Select Status</option> <option value="YES">Schedule</option> <option value="NO">Not Schedule</option> </select> </div> </div> </form> </section> <section class="hk-sec-wrapper"> <div class="panel panel-flat"> <div class="panel-heading"> <h5 class="panel-title">Update Wrong Area </h5> </div> <div class="panel-body"> <div id="contentwrapper" class="contentwrapper"> <div class="alert alert-info"> <div class="row"> <div class="col-md-8"></div> <div class="col-md-4" align="center"> <a href="" class=""> <i class="fa fa-file-excel-o fa-2x"></i> <br> Update Wrong Area</a> </div> </div> </div> <div class="panel panel-default"> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <tbody><tr> <td>(1) AWB No(Existing)</td> <td>(2) Area</td> <td>(2) Channel</td> </tr> </tbody></table> <span class="alert" style="color:#F00;"> </span> <form class="stdform" method="post" enctype="multipart/form-data" name="add_ship" action=""> <label><strong>Import File</strong></label><br> <span class="field"> <input type="file" name="uploadedfile" value="" size="20" class="btn btn" required=""> <span id="weight" class="alert"></span></span><br><br> <button type="submit" class="btn btn-primary" name="submit" value="submit">UpLoad</button> </form> </div> </div> </div> </div> </div> </div> </section> </section> <?php include APPPATH.'views/includes/footer.php';?>
module Gitlab module Metrics # Class that sends certain metrics to InfluxDB at a specific interval. # # This class is used to gather statistics that can't be directly associated # with a transaction such as system memory usage, garbage collection # statistics, etc. class Sampler # interval - The sampling interval in seconds. def initialize(interval = Metrics.settings[:sample_interval]) interval_half = interval.to_f / 2 @interval = interval @interval_steps = (-interval_half..interval_half).step(0.1).to_a @last_step = nil @metrics = [] @last_minor_gc = Delta.new(GC.stat[:minor_gc_count]) @last_major_gc = Delta.new(GC.stat[:major_gc_count]) if Gitlab::Metrics.mri? require 'allocations' Allocations.start end end def start Thread.new do Thread.current.abort_on_exception = true loop do sleep(sleep_interval) sample end end end def sample sample_memory_usage sample_file_descriptors sample_objects sample_gc flush ensure GC::Profiler.clear @metrics.clear end def flush Metrics.submit_metrics(@metrics.map(&:to_hash)) end def sample_memory_usage add_metric('memory_usage', value: System.memory_usage) end def sample_file_descriptors add_metric('file_descriptors', value: System.file_descriptor_count) end if Metrics.mri? def sample_objects sample = Allocations.to_hash counts = sample.each_with_object({}) do |(klass, count), hash| name = klass.name next unless name hash[name] = count end # Symbols aren't allocated so we'll need to add those manually. counts['Symbol'] = Symbol.all_symbols.length counts.each do |name, count| add_metric('object_counts', { count: count }, type: name) end end else def sample_objects end end def sample_gc time = GC::Profiler.total_time * 1000.0 stats = GC.stat.merge(total_time: time) # We want the difference of GC runs compared to the last sample, not the # total amount since the process started. stats[:minor_gc_count] = @last_minor_gc.compared_with(stats[:minor_gc_count]) stats[:major_gc_count] = @last_major_gc.compared_with(stats[:major_gc_count]) stats[:count] = stats[:minor_gc_count] + stats[:major_gc_count] add_metric('gc_statistics', stats) end def add_metric(series, values, tags = {}) prefix = sidekiq? ? 'sidekiq_' : 'rails_' @metrics << Metric.new("#{prefix}#{series}", values, tags) end def sidekiq? Sidekiq.server? end # Returns the sleep interval with a random adjustment. # # The random adjustment is put in place to ensure we: # # 1. Don't generate samples at the exact same interval every time (thus # potentially missing anything that happens in between samples). # 2. Don't sample data at the same interval two times in a row. def sleep_interval while step = @interval_steps.sample if step != @last_step @last_step = step return @interval + @last_step end end end end end end
package uk.nhsbsa.services.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class PartnerPage extends BasePage{ @FindBy(id = "label-no") private final WebElement noPartnerRadioButton = null; @FindBy(id = "next-button") private final WebElement nextButton = null; public PartnerPage(WebDriver driver) { super(driver); } public PartnerPage answerPartnerQuestion() { noPartnerRadioButton.click(); return this; } public ClaimBenefitPage moveToClaimBenefit() { nextButton.click(); return PageFactory.initElements(driver, ClaimBenefitPage.class); } }
package entity // Pagination is default struct response for pagination configuration type Pagination struct { Template string Page int NextPage int PrevPage int Rows int TotalPage int // ListPage contain list number page ["1","2","3"] ListPage []int }
require "release_manager/version" require "release_manager/module_deployer" require "release_manager/release" require "release_manager/changelog" require 'release_manager/logger' require 'release_manager/workflow_action' require 'release_manager/sandbox' class String def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end def red colorize(31) end def green colorize(32) end def fatal red end def yellow colorize(33) end end module ReleaseManager def self.gitlab_server if ENV['GITLAB_API_ENDPOINT'] if data = ENV['GITLAB_API_ENDPOINT'].match(/(https?\:\/\/[\w\.]+)/) return data[1] end end 'https://gitlab.com' end end
require 'hacker_news_notifier/version' require 'hacker_news_notifier/title_checker' require 'hacker_news_notifier/ping' module HackerNewsNotifier class Notifier def check(title) title_checker = TitleChecker.new ping = Ping.new ping.ping if title_checker.title_exists(title, 10) end end end
set -e set_tuna_conda() { conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/ conda config --set show_channel_urls yes } set_tuna_conda
using System; using System.Collections.Generic; using System.Text.Json.Serialization; namespace GameBox.Admin.UI.Model { public class OrderListModel { [JsonPropertyName("username")] public string Username { get; set; } [JsonPropertyName("timeStamp")] public DateTime TimeStamp { get; set; } [JsonPropertyName("price")] public decimal Price { get; set; } [JsonPropertyName("gamesCount")] public int GamesCount { get; set; } [JsonPropertyName("games")] public IEnumerable<GameOrderModel> Games { get; set; } } }
import requests def get_current_region(): """ works only from ec2 machine :return: """ r = requests.get("http://169.254.169.254/latest/dynamic/instance-identity/document") response_json = r.json() return response_json.get("region")
 using System.ComponentModel.DataAnnotations.Schema; namespace Ccr.Data.EntityFramework.Core { public abstract class HasStaticStore<TEntity, TStaticEntityStore> : IHaveStaticStore where TStaticEntityStore : StaticEntityStore<TEntity> where TEntity : class { [NotMapped] public virtual bool IsDatabaseGeneratedValueSimulated => false; } }
package demo.movie.app.repo import demo.movie.app.model.dto.CastMemberDto import demo.movie.app.model.dto.Credits import demo.movie.app.model.dto.CrewMemberDto import demo.movie.app.model.dto.Genre import demo.movie.app.model.dto.tv.TvDetailDto import demo.movie.app.model.dto.tv.TvPreviewDto import demo.movie.app.model.dto.tv.TvResponseResult import demo.movie.app.model.repo.tv.TvSeriesRepo import demo.movie.app.model.services.BaseNetworkService import io.reactivex.rxjava3.core.Observable import okhttp3.internal.immutableListOf import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations class TvRepoTest { private companion object { val PROPER_RESPONSE_TV = TvResponseResult( immutableListOf( TvPreviewDto( id = 2, voteAverage = 1.1, title = "TITLE", originalName = "TITLE_ORIGINAL", releaseDate = "11-11-1111", posterPath = "/asdibasduvbasduv.jpg" ) ) ) const val PROPER_TV_DETAILS_ID = 2 val PROPER_TV_DETAILS_RESPONSE = TvDetailDto( id = 2, credits = Credits( id = 1, cast = immutableListOf( CastMemberDto( id = 10000, character = "Batman", profile_path = "path", name = "Donald Duck", order = 1, ), CastMemberDto( id = 12000, character = "Joker", profile_path = "path", name = "Mickey Mouse", order = 1, ) ), crew = immutableListOf( CrewMemberDto( id = 2341, job = "director", name = "Christopher Nolan", profilePath = "/hguavhbnasdv", ) ) ), genres = immutableListOf( Genre(1, "thriller"), Genre(2, "action") ), originalLanguage = "en", overview = "hehehe, description", posterPath = "/1idsuvmd", recommendations = PROPER_RESPONSE_TV, firstAirDate = "2019-09-12", status = "Returning Series", title = "Tenet plus batman", voteAverage = 2.1, episodeRuntime = listOf(50, 40), lastAirDate = "2020-11-01", ) } @Mock private lateinit var networkService: BaseNetworkService private lateinit var tvSeriesRepo: TvSeriesRepo @Before fun setUp() { MockitoAnnotations.initMocks(this) tvSeriesRepo = TvSeriesRepo(networkService) } @Test fun testGetPopular() { Mockito.`when`(networkService.getPopularTv()).thenReturn( Observable.just(PROPER_RESPONSE_TV) ) tvSeriesRepo.getPopular().contains(PROPER_RESPONSE_TV) } @Test fun testGetTrendingPerDay() { Mockito.`when`(networkService.getTrendingPerDayTv()).thenReturn( Observable.just(PROPER_RESPONSE_TV) ) tvSeriesRepo.getTrendingPerDay().contains(PROPER_RESPONSE_TV) } @Test fun testGetTrendingPerWeek() { Mockito.`when`(networkService.getTrendingPerWeekTv()).thenReturn( Observable.just(PROPER_RESPONSE_TV) ) tvSeriesRepo.getTrendingPerWeek().contains(PROPER_RESPONSE_TV) } @Test fun testGetTopRated() { Mockito.`when`(networkService.getTopRatedTv()).thenReturn( Observable.just(PROPER_RESPONSE_TV) ) tvSeriesRepo.getTopRated().contains(PROPER_RESPONSE_TV) } @Test fun testGetTvDetails() { Mockito.`when`(networkService.getTvDetails(Mockito.anyInt())).thenReturn( Observable.just(PROPER_TV_DETAILS_RESPONSE) ) tvSeriesRepo.getTvDetails(PROPER_TV_DETAILS_ID).contains(PROPER_TV_DETAILS_RESPONSE) } }
# frozen_string_literal: true require 'dry/monads' require 'dry/monads/do' module FinancialAssistance module Operations module Application class RequestDetermination send(:include, Dry::Monads[:result, :do]) include Acapi::Notifiers require 'securerandom' FAA_SCHEMA_FILE_PATH = File.join(FinancialAssistance::Engine.root, 'lib', 'schemas', 'financial_assistance.xsd') # @param [ Hash ] params Applicant Attributes # @return [ BenefitMarkets::Entities::Applicant ] applicant Applicant def call(application_id:) application = yield find_application(application_id) application = yield validate(application) payload_param = yield construct_payload(application) payload_value = yield validate_payload(payload_param) payload = yield publish(payload_value, application) Success(payload) end private def find_application(application_id) application = FinancialAssistance::Application.find(application_id) Success(application) rescue Mongoid::Errors::DocumentNotFound Failure("Unable to find Application with ID #{application_id}.") end def validate(application) return Success(application) if application.submitted? Failure("Application is in #{application.aasm_state} state. Please submit application.") end def construct_payload(application) payload = ::FinancialAssistance::ApplicationController.new.render_to_string( "financial_assistance/events/financial_assistance_application", :formats => ["xml"], :locals => { :financial_assistance_application => application } ) Success(payload) end def validate_payload(payload_str) payload_xml = Nokogiri::XML.parse(payload_str) faa_xsd = Nokogiri::XML::Schema(File.open(FAA_SCHEMA_FILE_PATH)) if faa_xsd.valid?(payload_xml) Success(payload_str) else Failure(faa_xsd.validate(payload_xml).map(&:message)) end end # change the operation name to request_eligibility_determination #change the method name as request_eligibility_determination def publish(payload, application) notify("acapi.info.events.assistance_application.submitted", { :correlation_id => SecureRandom.uuid.gsub("-",""), :body => payload, :family_id => application.family_id.to_s, :assistance_application_id => application.hbx_id.to_s }) Success(payload) end end end end end
package com.ruoyi.code.controller; import com.ruoyi.code.domain.Rfe; import com.ruoyi.code.service.IRfeService; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.UUID; /** * 补充材料(RFE)Controller * * @author ruoyi * @date 2020-06-06 */ @Controller @RequestMapping("/code/rfe") public class RfeController extends BaseController { private String prefix = "code/rfe"; @Autowired private IRfeService rfeService; @RequiresPermissions("code:rfe:view") @GetMapping("/{trust_id}") public String rfe(@PathVariable("trust_id") String trust_id, ModelMap mmap) { mmap.put("trust_id", trust_id); return prefix + "/rfe"; } /** * 查询补充材料(RFE)列表 */ @RequiresPermissions("code:rfe:list") @PostMapping("/list/{trust_id}") @ResponseBody public TableDataInfo list(@PathVariable("trust_id") String trust_id,Rfe rfe) { startPage(); rfe.setTrustId(trust_id); List<Rfe> list = rfeService.selectRfeList(rfe); return getDataTable(list); } /** * 导出补充材料(RFE)列表 */ @RequiresPermissions("code:rfe:export") @Log(title = "补充材料(RFE)", businessType = BusinessType.EXPORT) @PostMapping("/export") @ResponseBody public AjaxResult export(Rfe rfe) { List<Rfe> list = rfeService.selectRfeList(rfe); ExcelUtil<Rfe> util = new ExcelUtil<Rfe>(Rfe.class); return util.exportExcel(list, "rfe"); } /** * 新增补充材料(RFE) */ @GetMapping("/add/{trust_id}") public String add(@PathVariable("trust_id") String trust_id,ModelMap mmap) { String uuid = UUID.randomUUID().toString().replaceAll("-",""); mmap.put("id",uuid); mmap.put("trust_id",trust_id); return prefix + "/add"; } /** * 新增保存补充材料(RFE) */ @RequiresPermissions("code:rfe:add") @Log(title = "补充材料(RFE)", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(Rfe rfe) { return toAjax(rfeService.insertRfe(rfe)); } /** * 修改补充材料(RFE) */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") String id, ModelMap mmap) { Rfe rfe = rfeService.selectRfeById(id); mmap.put("rfe", rfe); return prefix + "/edit"; } /** * 修改保存补充材料(RFE) */ @RequiresPermissions("code:rfe:edit") @Log(title = "补充材料(RFE)", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(Rfe rfe) { return toAjax(rfeService.updateRfe(rfe)); } /** * 删除补充材料(RFE) */ @RequiresPermissions("code:rfe:remove") @Log(title = "补充材料(RFE)", businessType = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(rfeService.deleteRfeByIds(ids)); } }
using Model; namespace Service { public class PaymentService : IPaymentService { public PaymentResult RemitPayment(decimal due, decimal payment) { PaymentResult result = new PaymentResult(); if (!ValidatePayment(payment)) { result.PaymentStatus = PaymentStatus.InvalidAmount; return result; } if (payment < due) { result.PaymentStatus = PaymentStatus.InsufficientFunds; return result; } result.PaymentStatus = PaymentStatus.Success; result.Change = payment - due; return result; } private bool ValidatePayment(decimal payment) { if (payment < 0) return false; if ((payment * 100) % 5 != 0) return false; return true; } } }
use warnings; use strict; package BTDT::Notification::Purchase; use base qw/BTDT::Notification/; =head1 NAME BTDT::Notification::Purchase =head1 ARGUMENTS C<purchase> =cut __PACKAGE__->mk_accessors(qw/purchase/); =head2 setup Sets up the email. =cut sub setup { my $self = shift; $self->SUPER::setup(@_); unless (UNIVERSAL::isa($self->purchase, "BTDT::Model::Purchase")) { $self->log->error((ref $self) . " called with invalid purchase argument"); return; } $self->to( $self->purchase->owner ); if ( $self->purchase->gift ) { my $tx = $self->purchase->transaction; $tx->current_user( BTDT::CurrentUser->superuser ); $self->subject( $tx->user->name . " bought you " . $self->purchase->description ); } else { if ( $self->purchase->description eq 'Hiveminder Pro' and not $self->to->was_pro_account ) { $self->subject("Welcome to Hiveminder Pro!"); } else { $self->subject("Your Hiveminder purchase: " . $self->purchase->description ); } } $self->body(<<"END_BODY"); You should be able to start using @{[$self->purchase->description]} immediately on hiveminder.com. Check out the exclusive features you can now use at @{[Jifty->web->url( path => '/pro' )]}. Your Hiveminder Pro upgrade is good until @{[$self->to->paid_until]}. If you have any questions or problems, please contact support\@hiveminder.com. Enjoy! END_BODY my $html = "<p>".$self->body."</p>"; $html =~ s{\n\n}{</p><p>}g; $html =~ s/(support\@hiveminder\.com)/<a href="mailto:$1">$1<\/a>/; $html =~ s/(hiveminder\.com)/<a href="https:\/\/$1">$1<\/a>/; $html =~ s{(Check out the exclusive features you can now use) at (http://.+/pro)\.}{<a href="$2">$1</a>!}; $self->html_body( $html ); } 1;
const Discord = require("discord.js"); const config = require("../config.json"); module.exports.run = async (bot, message) => { let HelpEmbed = new Discord.RichEmbed() .setColor("RANDOM") .setTitle(`${bot.user.username}'s Help Menu`) .setDescription(``) .setFooter(`Requested by ${message.author.tag}`, message.author.avatarURL) .setTimestamp(); return message.channel.send(HelpEmbed); } module.exports.help = { name: "help" }
package org.edx.mobile.model.api import com.google.gson.annotations.SerializedName data class CourseComponentStatusResponse( @SerializedName("last_visited_module_id") var lastVisitedModuleId: String? = null, @SerializedName("last_visited_module_path") var lastVisitedModulePaths: ArrayList<String> = arrayListOf(), @SerializedName("last_visited_block_id") var lastVisitedBlockId: String? = null )
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Collections; using System.Drawing; using MainKykc; namespace MainKykc { class DirectoryCrawler { private string path; protected const string FILE_FILTER = "*.lnk"; protected ArrayList foundFiles; public ArrayList getFoundFiles() { return this.foundFiles; } protected void setFoundFiles(ArrayList foundFiles) { this.foundFiles = foundFiles; } public string getPath() { return path; } private void setPath(string path) { this.path = path; this.omNomNom(); } public DirectoryCrawler(string path) { this.setPath(path); } protected void omNomNom() { DirectoryInfo di = new DirectoryInfo(this.getPath()); ArrayList rgFiles = new ArrayList(); rgFiles.AddRange(di.GetFiles(DirectoryCrawler.FILE_FILTER, SearchOption.AllDirectories)); this.setFoundFiles(rgFiles); } public ShellLinkList getList() { ShellLinkList retVal = new ShellLinkList(); ShellLinkCache cache = new ShellLinkCache(this.getPath()); ArrayList foundFiles = this.getFoundFiles(); foreach (FileInfo file in foundFiles) { try { ShellLink item = new ShellLink(file.FullName); Image cachedIcon = cache.getCachedIcon(item.UniqueHash); //System.Windows.Forms.MessageBox.Show(cachedIcon.ToString()); item.IconImage = cachedIcon; retVal.Add(item); } catch (System.Runtime.InteropServices.COMException e) { Util.writeDebugInfo(e.Message); } } cache.storeCache(retVal.getCache().OuterXml); return retVal; } } }
package com.android.aman.newsapp import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.WindowManager import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_splash.* class SplashActivity : AppCompatActivity() { private val SPLASH_TIME_OUT:Long = 5000 //Variables var backgroundImage: ImageView? = null //Animation var sideAnim: Animation? = null var bottomAnim: Animation? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //fullscreen view getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_splash) //Hooks backgroundImage =findViewById(R.id.imageView); //Animations sideAnim = AnimationUtils.loadAnimation(this,R.anim.side_anim); bottomAnim = AnimationUtils.loadAnimation(this,R.anim.bottom_anim); //set Animations on elements imageView.setAnimation(sideAnim); Handler().postDelayed({ // This method will be executed once the timer is over // Start your app main activity startActivity(Intent(this,MainActivity::class.java)) // close this activity finish() }, SPLASH_TIME_OUT) } }
#include "../src/log_rotate.h" #include <stdbool.h> #include <stdlib.h> #define DIR "." static bool exists(const char* const fname) { FILE* file; if ((file = fopen(fname, "r")) != NULL) { fclose(file); return true; } return false; } static bool TEST_FileOpenValidDIR(void) { bool testResult = false; LOG_File f = LOG_FileOpen(DIR); if ( exists(DIR"/"LOG_FILE) ) { testResult = true; LOG_FileClose(&f); remove(DIR"/"LOG_FILE); } return testResult; } static bool TEST_FileOpenRename(void) { bool testResult = true; unsigned iterations = 10U; for ( iterations = 10U ; iterations > 0; --iterations ) { LOG_File f = LOG_FileOpen(DIR); LOG_FileClose(&f); } for ( iterations = 9U ; iterations > 0; --iterations ) { char fileName[128]; sprintf(fileName, DIR"/"LOG_FILE".%u", iterations); if ( exists(fileName) ) { remove(fileName); } else { testResult = false; break; } } if ( true == testResult && exists(DIR"/"LOG_FILE) ) { remove(DIR"/"LOG_FILE); } return testResult; } static bool TEST_FileOpenNotValidDIR(void) { bool testResult = false; LOG_File f = LOG_FileOpen(DIR"/logs"); if ( exists(DIR"/logs/"LOG_FILE) ) { testResult = true; LOG_FileClose(&f); remove(DIR"/logs/"LOG_FILE); system("rm -r "DIR"/logs"); } return testResult; } static bool TEST_FileOpenNoPermissionDIR(void) { bool testResult = false; /* No permission to create file at root */ LOG_File f = LOG_FileOpen("/"); if ( NULL == f.file ) { testResult = true; } else { testResult = false; LOG_FileClose(&f); remove("/"LOG_FILE); } return testResult; } static bool TEST_FileClose(void) { bool testResult = false; LOG_File f = LOG_FileOpen(DIR); LOG_FileClose(&f); remove(DIR"/"LOG_FILE); if ( NULL == f.file ) { testResult = true; } return testResult; } static bool TEST_FileCloseNULL(void) { bool testResult = true; /* If no segmentation fault */ LOG_FileClose(NULL); return testResult; } int main(int argc, char* argv[]) { printf("Running tests:\n\n"); if ( true == TEST_FileOpenValidDIR() ) { printf("[SUCCESS] TEST_FileOpenValidDIR\n"); } else { printf("[FAIL] TEST_FileOpenValidDIR\n"); } if ( true == TEST_FileOpenNotValidDIR() ) { printf("[SUCCESS] TEST_FileOpenNotValidDIR\n"); } else { printf("[FAIL] TEST_FileOpenNotValidDIR\n"); } if ( true == TEST_FileOpenNoPermissionDIR() ) { printf("[SUCCESS] TEST_FileOpenNoPermissionDIR\n"); } else { printf("[FAIL] TEST_FileOpenNoPermissionDIR\n"); } if ( true == TEST_FileClose() ) { printf("[SUCCESS] TEST_FileClose\n"); } else { printf("[FAIL] TEST_FileClose\n"); } if ( true == TEST_FileCloseNULL() ) { printf("[SUCCESS] TEST_FileCloseNULL\n"); } else { printf("[FAIL] TEST_FileCloseNULL\n"); } if ( true == TEST_FileOpenRename() ) { printf("[SUCCESS] TEST_FileOpenRename\n"); } else { printf("[FAIL] TEST_FileOpenRename\n"); } return 0; }
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wrapper for interacting with speech API.""" from googlecloudsdk.api_lib.ml import content_source from googlecloudsdk.api_lib.ml.speech import exceptions from googlecloudsdk.api_lib.storage import storage_util from googlecloudsdk.api_lib.util import apis SPEECH_API = 'speech' SPEECH_API_VERSION = 'v1' def GetAudio(audio_path): """Determine whether path to audio is local, build RecognitionAudio message. Args: audio_path: str, the path to the audio. Raises: googlecloudsdk.api_lib.ml.speech.exceptions.AudioException, if audio is not found locally and does not appear to be Google Cloud Storage URL. Returns: speech_v1_messages.RecognitionAudio, the audio message. """ try: source = content_source.ContentSource.FromContentPath( audio_path, SPEECH_API, url_validator=storage_util.ObjectReference.IsStorageUrl) except content_source.UnrecognizedContentSourceError: raise exceptions.AudioException( 'Invalid audio source [{}]. The source must either ' 'be a local path or a Google Cloud Storage URL ' '(such as gs://bucket/object).'.format(audio_path)) audio = apis.GetMessagesModule( SPEECH_API, SPEECH_API_VERSION).RecognitionAudio() source.UpdateContent(audio) return audio
<?php namespace falkirks\chestrefill\dispatcher; use falkirks\chestrefill\Chest; use falkirks\chestrefill\ChestRefill; interface RefillDispatcher{ public function __construct(ChestRefill $chestRefill, array $args); public function attach(Chest $chest); public function detach(Chest $chest); public function cancel(); public function getArgs(); }
package com.burrowsapps.example.gif.ui.giflist import android.content.Context import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.test.ext.junit.runners.AndroidJUnit4 import com.burrowsapps.example.gif.data.ImageService import com.google.common.truth.Truth.assertThat import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.HiltTestApplication import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config import javax.inject.Inject @HiltAndroidTest @Config(application = HiltTestApplication::class) @RunWith(AndroidJUnit4::class) class GifAdapterTest { @get:Rule(order = 0) val hiltRule = HiltAndroidRule(this) @Inject @ApplicationContext internal lateinit var context: Context @Inject internal lateinit var imageService: ImageService private val gifImageInfo = GifImageInfo("http://some.url") private val gifImageInfo2 = GifImageInfo("http://some.url2") private val gifImageInfo3 = GifImageInfo("http://some.url3") private lateinit var viewHolder: GifAdapter.ViewHolder private lateinit var sut: GifAdapter @Before fun setUp() { hiltRule.inject() sut = GifAdapter( onItemClick = { }, imageService ).apply { add(listOf(gifImageInfo, gifImageInfo2)) } viewHolder = sut.onCreateViewHolder(ConstraintLayout(context), 0) } @Test fun testOnCreateViewHolder() { val parent = object : ViewGroup(context) { override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {} } assertThat(sut.onCreateViewHolder(parent, 0)) .isInstanceOf(GifAdapter.ViewHolder::class.java) } @Test fun testOnBindViewHolderOnAdapterItemClick() { sut.clear() sut.add(listOf(gifImageInfo, gifImageInfo2, GifImageInfo())) sut.onBindViewHolder(viewHolder, 0) assertThat(viewHolder.itemView.performClick()).isTrue() } @Test fun testGetItem() { sut.clear() val imageInfo = GifImageInfo() sut.add(listOf(imageInfo)) assertThat(sut.getItem(0)).isEqualTo(imageInfo) } @Test fun onViewRecycled() { sut.add(listOf(GifImageInfo())) sut.onBindViewHolder(viewHolder, 0) sut.onViewRecycled(viewHolder) } @Test fun testGetItemCountShouldReturnCorrectValues() { assertThat(sut.itemCount).isEqualTo(2) } @Test fun testGetListCountShouldReturnCorrectValues() { assertThat(sut.getItem(0)).isEqualTo(gifImageInfo) assertThat(sut.getItem(1)).isEqualTo(gifImageInfo2) } @Test fun testGetItemShouldReturnCorrectValues() { assertThat(sut.getItem(1)).isEqualTo(gifImageInfo2) } @Test fun testClearShouldClearAdapter() { sut.clear() assertThat(sut.itemCount).isEqualTo(0) } @Test fun testAddCollectionShouldReturnCorrectValues() { val imageInfos = listOf(gifImageInfo3) sut.add(imageInfos) assertThat(sut.getItem(0)).isEqualTo(gifImageInfo) assertThat(sut.getItem(1)).isEqualTo(gifImageInfo2) assertThat(sut.getItem(2)).isEqualTo(gifImageInfo3) } }