text
stringlengths
27
775k
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Antijank.Debugging { [ComImport, Guid("31BCFCE2-DAFB-11D2-9F81-00C04F79A0A3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMetaDataDispenserEx : IMetaDataDispenser { new uint DefineScope( ref Guid rclsid, uint dwCreateFlags, ref Guid riid, [MarshalAs(UnmanagedType.Interface, IidParameterIndex = 2)] out object ppIUnk ); new uint OpenScope( [MarshalAs(UnmanagedType.LPWStr)] string szScope, uint dwOpenFlags, ref Guid riid, [MarshalAs(UnmanagedType.Interface, IidParameterIndex = 2)] out object ppIUnk ); new uint OpenScopeOnMemory( IntPtr pData, uint cbData, uint dwOpenFlags, ref Guid riid, [MarshalAs(UnmanagedType.Interface, IidParameterIndex = 3)] out object ppIUnk ); void SetOption([In] in Guid optionId, [In, MarshalAs(UnmanagedType.Struct)] in object pValue); [return: MarshalAs(UnmanagedType.Struct)] object GetOption([In] in Guid optionId); uint OpenScopeOnITypeInfo( [MarshalAs(UnmanagedType.Interface)] ITypeInfo pITI, uint dwOpenFlags, ref Guid riid, [MarshalAs(UnmanagedType.Interface, IidParameterIndex = 2)] out object ppIUnk ); uint GetCORSystemDirectory( [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] char[] szBuffer, uint cchBuffer, out uint pchBuffer); uint FindAssembly( [MarshalAs(UnmanagedType.LPWStr)] string szAppBase, [MarshalAs(UnmanagedType.LPWStr)] string szPrivateBin, [MarshalAs(UnmanagedType.LPWStr)] string szGlobalBin, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] char[] szName, uint cchName, out uint pcName); uint FindAssemblyModule( [MarshalAs(UnmanagedType.LPWStr)] string szAppBase, [MarshalAs(UnmanagedType.LPWStr)] string szPrivateBin, [MarshalAs(UnmanagedType.LPWStr)] string szGlobalBin, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, [MarshalAs(UnmanagedType.LPWStr)] string szModuleName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] char[] szName, uint cchName, out uint pcName); } }
using Microsoft.Extensions.Options; using MongoDB.Driver; using vt_encrypchat.Data.Configuration; using vt_encrypchat.Data.Contracts.MongoDB; namespace vt_encrypchat.Data.MongoDB { public class MongoContext : IMongoContext { public MongoContext(IOptionsMonitor<MongoDbConfig> mongoOptionsMonitor) { var mongoDbConfig = mongoOptionsMonitor.CurrentValue; Client = new MongoClient(mongoDbConfig.ConnectionString); DefaultDatabase = Client.GetDatabase(mongoDbConfig.DefaultDatabase); } public MongoClient Client { get; } public IMongoDatabase DefaultDatabase { get; } } }
#!/usr/bin/env bash declare -A GROUP_TITLE=( ["fix"]="Bug fixes" ["chore"]="Maintenance" ["feat"]="Features" ) tags=$(git tag --list --sort='-version:refname' --merged HEAD) set -- $tags echo "# Changelog" echo echo "All notable changes to this project will be documented in this file." while (( "$#" > 1 )); do date=$(git log -1 --format="%ci" $1) echo echo "## $1 ($date)" GROUP="" git log --no-merges --date-order --format="%s" $2..$1^1 | sort | while read -r line do if [[ "$line" =~ ^(fix|feat|chore)(\(.*\))?!?:(.*)$ ]]; then NEXT_GROUP=${BASH_REMATCH[1]} if [[ $GROUP != $NEXT_GROUP ]]; then GROUP=$NEXT_GROUP echo echo "### ${GROUP_TITLE[${GROUP}]}" echo fi echo " - ${BASH_REMATCH[3]}" fi done shift done
package com.ctc.wstx.dtd; import javax.xml.stream.XMLStreamException; import com.ctc.wstx.io.WstxInputData; import com.ctc.wstx.sr.InputProblemReporter; import com.ctc.wstx.util.PrefixedName; /** * Specific attribute class for attributes that contain (unique) * identifiers. */ public final class DTDNmTokensAttr extends DTDAttribute { /* /////////////////////////////////////////////////// // Life-cycle /////////////////////////////////////////////////// */ /** * Main constructor. */ public DTDNmTokensAttr(PrefixedName name, DefaultAttrValue defValue, int specIndex, boolean nsAware, boolean xml11) { super(name, defValue, specIndex, nsAware, xml11); } @Override public DTDAttribute cloneWith(int specIndex) { return new DTDNmTokensAttr(mName, mDefValue, specIndex, mCfgNsAware, mCfgXml11); } /* /////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////// */ @Override public int getValueType() { return TYPE_NMTOKENS; } /* /////////////////////////////////////////////////// // Public API, validation /////////////////////////////////////////////////// */ /** * Method called by the validator * to let the attribute do necessary normalization and/or validation * for the value. */ @Override public String validate(DTDValidatorBase v, char[] cbuf, int start, int end, boolean normalize) throws XMLStreamException { //int origStart = start; /* First things first; let's ensure value is not empty (all * white space)... */ while (start < end && WstxInputData.isSpaceChar(cbuf[start])) { ++start; } // Empty value? if (start >= end) { return reportValidationProblem(v, "Empty NMTOKENS value"); } /* Then, let's have separate handling for normalizing and * non-normalizing case, since latter is trivially easy case: */ if (!normalize) { for (; start < end; ++start) { char c = cbuf[start]; if (!WstxInputData.isSpaceChar(c) && !WstxInputData.isNameChar(c, mCfgNsAware, mCfgXml11)) { return reportInvalidChar(v, c, "not valid as NMTOKENS character"); } } return null; // ok, all good } //boolean trimmed = (origStart != start); //origStart = start; --end; // so that it now points to the last char // Wouldn't absolutely have to trim trailing... but is easy to do while (end > start && WstxInputData.isSpaceChar(cbuf[end])) { --end; //trimmed = true; } /* Ok, now, need to check we only have valid chars, and maybe * also coalesce multiple spaces, if any. */ StringBuilder sb = null; while (start <= end) { int i = start; for (; i <= end; ++i) { char c = cbuf[i]; if (WstxInputData.isSpaceChar(c)) { break; } if (!WstxInputData.isNameChar(c, mCfgNsAware, mCfgXml11)) { return reportInvalidChar(v, c, "not valid as an NMTOKENS character"); } } if (sb == null) { sb = new StringBuilder(end - start + 1); } else { sb.append(' '); } sb.append(cbuf, start, (i - start)); start = i + 1; // Ok, any white space to skip? while (start <= end && WstxInputData.isSpaceChar(cbuf[start])) { ++start; } } /* 27-Nov-2005, TSa: Could actually optimize trimming, and often * avoid using StringBuilder... but let's only do it if it turns * out dealing with NMTOKENS normalization shows up on profiling... */ return sb.toString(); } /** * Method called by the validator * to ask attribute to verify that the default it has (if any) is * valid for such type. */ @Override public void validateDefault(InputProblemReporter rep, boolean normalize) throws XMLStreamException { String defValue = mDefValue.getValue(); int len = defValue.length(); // Then code similar to actual value validation: StringBuilder sb = null; int count = 0; int start = 0; main_loop: while (start < len) { char c = defValue.charAt(start); // Ok, any white space to skip? while (true) { if (!WstxInputData.isSpaceChar(c)) { break; } if (++start >= len) { break main_loop; } c = defValue.charAt(start); } int i = start+1; do { if (++i >= len) { break; } c = defValue.charAt(i); } while (!WstxInputData.isSpaceChar(c)); ++count; String token = defValue.substring(start, i); int illegalIx = WstxInputData.findIllegalNmtokenChar(token, mCfgNsAware, mCfgXml11); if (illegalIx >= 0) { reportValidationProblem(rep, "Invalid default value '"+defValue +"'; character #"+illegalIx+" (" +WstxInputData.getCharDesc(defValue.charAt(illegalIx)) +") not a valid NMTOKENS character"); } if (normalize) { if (sb == null) { sb = new StringBuilder(i - start + 32); } else { sb.append(' '); } sb.append(token); } start = i+1; } if (count == 0) { reportValidationProblem(rep, "Invalid default value '"+defValue +"'; empty String is not a valid NMTOKENS value"); return; } if (normalize) { mDefValue.setValue(sb.toString()); } } }
; ; void asm_swap(void *a, void *b) ; BITS 64 SECTION .text GLOBAL asm_swap asm_swap: ;MOV RCX, [RSI] ;MOV RDX, [RDI] ;MOV [RSI], RDX ;MOV [RDI], RCX ; OR PUSH QWORD [RSI] PUSH QWORD [RDI] POP QWORD [RSI] POP QWORD [RDI] _end: RET
# I prefer Markdown to reStructuredText. PyPi does not. This allows people to # install and not get any errors. try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): long_description = ( "Tavi (as in `Rikki Tikki Tavi " "<http://en.wikipedia.org/wiki/Rikki-Tikki-Tavi>`_) " "is an extremely thin Mongo object mapper for Python. It is a thin " "abstraction over `pymongo <http://api.mongodb.org/python/current/>`_ " "that allows you to easily model your applications and persist your " "data in MongoDB. See `README.md <http://github.com/bnadlerjr/tavi>`_ " "for more details." ) from setuptools import setup test_requirements = [ 'coverage==3.7.1', 'flake8==2.1.0', 'nose==1.3.1' ] setup( name='Tavi', version='1.4.1', author='Bob Nadler Jr.', author_email='bnadlerjr@gmail.com', packages=[ 'tavi', 'tavi.base', 'tavi.utils' ], url='https://github.com/bnadlerjr/tavi', license='LICENSE.txt', description='Super thin Mongo object mapper for Python.', long_description=long_description, include_package_data=True, zip_safe=False, install_requires=[ "inflection >= 0.2.0", "pymongo >= 2.4.1" ] + test_requirements, tests_require=test_requirements, test_suite="nose_collector" )
package io.kommons.designpatterns.cqrs.domain.model import io.kommons.AbstractValueObject import io.kommons.ToStringBuilder import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.MappedSuperclass @MappedSuperclass abstract class LongEntity: AbstractValueObject() { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null override fun equalProperties(other: Any): Boolean { return other is LongEntity && id == other.id } override fun buildStringHelper(): ToStringBuilder { return super.buildStringHelper() .add("id", id) } }
<?php namespace AppBundle\Manager; use AppBundle\Entity\User; use AppBundle\Repository\AdminRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\EntityManagerInterface; class AdminManager { /** * @var EntityManagerInterface */ private $entityManager; /** * @var AdminRepository */ private $adminRepository; public function __construct(EntityManagerInterface $entityManager, AdminRepository $adminRepository) { $this->entityManager = $entityManager; $this->adminRepository = $adminRepository; } /** * @param User $user * @param bool|null $flush */ public function createOrUpdate(User $user, ?bool $flush = true): void { /** @var int|null $id */ $id = $user->getId(); /** * Si id null, alors c'est une création */ if ($id === null) { $this->entityManager->persist($user); #TODO SwiftMailer } if ($flush === true) { $this->entityManager->flush(); } } /** * @param User $user */ public function delete(User $user) { $this->entityManager->remove($user); $this->entityManager->flush(); } /** * @return Collection|User[] */ public function findAll() { return $this->adminRepository->findAll(); } }
/** * @module Timer */ export default class Timer { private callback; private interval; private state; private intervalId; private timeoutId; private startTime; private remaining; constructor(cb: () => void, interval: number); start(): void; pause(): void; resume(): void; stop(): void; }
# Laravel-Snippets Misc useful tidbits i'm always searching across projects for. Figured I'd start putting them where I can find them. ### Install Install and usage instrcutions are included with each individual snippet.
## 感知机 1. 线性分类 ``` import pandas as pd import numpy as np from sklearn.datasets import load_iris import matplotlib.pyplot as plt #%matplotlib inline class Model: def __init__(self): self.w = np.ones(len(data[0]) - 1, dtype=np.float32) self.b = 0 self.l_rate = 0.1 # self.data = data def sign(self, x, w, b): y = np.dot(x, w) + b return y def fit(self, X_train, y_train): is_wrong = False while not is_wrong: wrong_count = 0 for d in range(len(X_train)): X = X_train[d] y = y_train[d] if y * self.sign(X, self.w, self.b) <= 0: self.w = self.w + self.l_rate * np.dot(y, X) self.b = self.b + self.l_rate * y wrong_count += 1 if wrong_count == 0: is_wrong = True return 'Perceptron Model!' def score(self): pass if __name__=="__main__": # load data iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df['label'] = iris.target df.columns = [ 'sepal length', 'sepal width', 'petal length', 'petal width', 'label' ] df.label.value_counts() data = np.array(df.iloc[:100, [0, 1, -1]]) X, y = data[:,:-1], data[:,-1] y = np.array([1 if i == 1 else -1 for i in y]) perceptron = Model() perceptron.fit(X, y) x_points = np.linspace(4, 7, 10) y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1] plt.plot(x_points, y_) plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0') plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1') plt.xlabel('sepal length') plt.ylabel('sepal width') plt.legend() ```
import { Loop } from "../../../loop.js"; /** @hidden */ declare function loop(g: SVGGElement, loop: Loop): SVGElement[]; export { loop };
package shuttle.coordinates.domain.usecase import kotlinx.coroutines.flow.Flow import shuttle.coordinates.domain.CoordinatesRepository import shuttle.coordinates.domain.model.CoordinatesResult class ObserveCurrentCoordinates( private val repository: CoordinatesRepository ) { operator fun invoke(): Flow<CoordinatesResult> = repository.observeCurrentCoordinates() }
var album={}; $(document).ready(function(){ $('.modal-hall-form').submit(function(){return false;}); $(document).delegate('.modal-hall__button','click',function(){ var text=[ $('#address-town').val(), $('#address-street').val(), $('#address-house').val(), $('#address-block').val() ]; $.ajax({ method:'GET', url:'http://geocode-maps.yandex.ru/1.x/', data:{ format:'json', geocode:text.join(', ') } }).done(function(data){ var pos =data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos.split(' '); $('input[name="Hall[geocode]"]').val(JSON.stringify(pos)); $('.modal-hall-form').submit(); }); }); }); album={ max:9, count:1, add:function(obj){ if(this.count<this.max){ obj.append(template.image); this.count++; } }, remove:function(obj){ $(obj).parent().remove(); this.count--; }, removeImage:function(obj){ var pos=$(obj).attr('data-index'), hall=$('.modal-hall-form').attr('data-id'); $(obj).parents('.modal-hall-form-params-album-content').find('a').each(function(index){ if(pos==$(this).attr('data-index')){ $.ajax({ url:'/ajax/removeimage/'+index, data:{hall:hall} }).done(function(){ $(obj).parent().remove(); }); } }); }, addImage:function(){ album.add($('.modal-hall-form-params-album-content')); } };
FactoryGirl.define do factory :admin_user do email "basicadmin@mvmanor.co.uk" password "p" password_confirmation "p" end factory :addition do booking_id 1 extra_id 1 end # :name, :description, :size, :capacity, :price, :picture, :rmcat_id factory :room do name "The New Room" description "The Really Good New Room" size "250" capacity "650" price "2500" picture_file_name 'room-controller-valid.jpg' picture_content_type 'image/jpeg' picture_file_size 1.megabyte # picture { File.new("#{Rails.root}/spec/support/images/room-controller-valid.jpg") } end factory :rmcat do rmtype "The New Roomcat" # association :rooms, factory: :room end factory :extra do extraimg_file_name 'extra-controller-valid.jpg' extraimg_content_type 'image/jpeg' extraimg_file_size 1.megabyte name "The New Extra" description "The brilliant new extra" quantity "1" price "100" end factory :extracat do extratype "Beautiful" end factory :enquiry do subject "Wedding" e_description "I'd like a wedding." end factory :user do email "basicuser@mvmanor.co.uk" password "u" password_confirmation "u" customer_name "Mr Customer" admin false customer false end # Admin factory :admin, class: User do email "basicadmin@mvmanor.co.uk" password "a" password_confirmation "a" admin true customer false end end
from os import system import sqlite3 import time db = sqlite3.connect("books.sqlite") imlec = db.cursor() imlec.execute("CREATE TABLE IF NOT EXISTS library (author, name)") imlec.execute("CREATE TABLE IF NOT EXISTS users (id, password, isWorker)") class Book(): def __init__(self, name, author): self.name = author self.name = author def addBook(name, author): add = "INSERT INTO library VALUES ('{}', '{}')".format(author, name) imlec.execute(add) db.commit() print("Book is added to the library!") def removeBook(name, author): query = "SELECT * FROM library WHERE name = '{}' and author = '{}'".format(name, author) list = query if query: remove = "DELETE FROM library WHERE name = '{}' AND author = '{}'".format(name, author) imlec.execute(remove) db.commit() print("Book has been removed!") else: print("The book you want to remove is not found!") def workerUI(): while True: system("cls") print(""" [1] Add Book [2] Remove Book """) workerOption = input("Your option: ") if workerOption == "1": name = input("Enter book name: ") author = input("Enter author name: ") addBook(name, author) input("Click 'enter' key to return to main menu!") elif workerOption == "2": name = input("Enter book name: ") author = input("Enter author name: ") removeBook(name, author) input("Click 'enter' key to return to main menu") else: print("Wrong input") input("Click 'enter' key to return main menu") def customerUI(): while True: print(""" [1] Get Book [2] Redeem Book """) customerOption = input("Your option: ") if customerOption == "1": pass # getBook() elif customerOption == "2": pass # redeemBook() else: print("Wrong input") input("Press 'enter' key to leave") while True: system("cls") print(""" ============================== Welcome To Library! ============================== [1] Customer login [2] Worker login """) option = input("Your option: ") if option == "1": pass # customer UI elif option == "2": ID = input("Enter your ID: ") PASSWORD = input("Enter your password: ") if ID == "2222" and PASSWORD == "1234": print("Succesfully logged in!") time.sleep(1) workerUI() else: print("Wrong input") input("Click 'enter' to return to main menu") else: print("Wrong input") print("Click 'enter' to return main menu") input() db.close()
# Задача 4. Вариант 44. # Напишите программу, которая выводит имя, под которым скрывается Борис Николаевич Бугаев. # Дополнительно необходимо вывести область интересов указанной личности, место рождения, # годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). # Для хранения всех необходимых данных требуется использовать переменные. После вывода информации # программа должна дожидаться пока пользователь нажмет Enter для выхода. # Golubev A. S. # 31.03.2016 print("Борис Николаевич Бугаев более известен, как русский писатель Андрей Белый.") year_of_birth = 1880 year_of_death = 1934 age_of_death = year_of_death - year_of_birth birthplace = "Москва, Российская империя" interess = "писатель, поэт, критик, мемуарист, стиховед" print("Место рождения:", birthplace) print("Год рождения:", year_of_birth) print("Возраст при смерти: ", age_of_death) print("Область интересов: ", interess) input("\n\nНажмите Enter для выхода.")
describe('render-jsx', () => { require('../common/test'); require('../renderer/test'); require('../component/test'); require('../dom/test'); });
package uk.co.hasali.epubreader.zip import java.io.ByteArrayInputStream import java.io.InputStream import java.util.zip.ZipInputStream internal class ZipInputStream(inputStream: InputStream) : IZipFile { private val mZipInputStream = ZipInputStream(inputStream) private val mEntries: MutableMap<String, IZipEntry> = mutableMapOf() init { var entry = mZipInputStream.nextEntry while (entry != null) { mEntries[entry.name] = ZipInputStreamEntry(entry.size, mZipInputStream.readBytes()) mZipInputStream.closeEntry() entry = mZipInputStream.nextEntry } } override fun getEntry(name: String?): IZipEntry? { return mEntries[name] } override fun close() { mZipInputStream.close() } private class ZipInputStreamEntry(override val size: Long, private val data: ByteArray) : IZipEntry { override fun getInputStream(): InputStream { return ByteArrayInputStream(data) } } }
import {expectType} from 'tsd'; import camelcaseKeys from './index.js'; expectType<Array<Record<'foo-bar', true>>>(camelcaseKeys([{'foo-bar': true}])); expectType<Record<'foo-bar', true>>(camelcaseKeys({'foo-bar': true})); expectType<Record<'foo-bar', true>>( camelcaseKeys({'foo-bar': true}, {deep: true}) ); expectType<Record<'foo-bar', true>>( camelcaseKeys({'foo-bar': true}, {deep: true, pascalCase: true}) ); expectType<Record<'foo-bar', true>>( camelcaseKeys({'foo-bar': true}, {exclude: ['foo', /bar/]}) ); expectType<Record<'foo-bar', true>>( camelcaseKeys({'foo-bar': true}, {stopPaths: ['foo']}) );
using System; using System.Collections.Generic; using System.Text; using Nom.Language; namespace Nom.TypeChecker { public class UnaryOpInstruction : AValueInstruction { public IRegister Arg { get; } public Parser.UnaryOperator Operator { get; } public UnaryOpInstruction(IRegister arg, Parser.UnaryOperator op, IRegister register) : base(register) { Arg = arg; Operator = op; } public override Ret Visit<Arg, Ret>(IInstructionVisitor<Arg, Ret> visitor, Arg arg = default(Arg)) { return visitor.VisitUnaryOpInstruction(this, arg); } } public partial interface IInstructionVisitor<in Arg, out Ret> { Func<UnaryOpInstruction, Arg, Ret> VisitUnaryOpInstruction { get; } } }
#!/usr/bin/env bash # Combined dist_train.sh and train-drone.sh MMDET=$HOME/Github/mmlab/mmdetection export PYTHONPATH=$PYTHONPATH:$MMDET PYTHON=${PYTHON:-"python"} GPUS=$1 # CONFIG=$1 CURDIR=`dirname "$0"` cd $CURDIR CURDIR=$PWD CONFIG=`ls $CURDIR/*.py` LOGFILE=$CURDIR/log.txt WORK_DIR=$CURDIR CHECKPOINT_FILE=$CURDIR/latest.pth if [ -f "$CHECKPOINT_FILE" ]; then echo "train-drone.sh: Found checkpoint file" cd $MMDET $PYTHON -m torch.distributed.launch --nproc_per_node=$GPUS \ $MMDET/tools/train.py $CONFIG --launcher pytorch \ --work_dir $WORK_DIR \ --resume_from $CHECKPOINT_FILE \ --validate 2>&1 | tee -a $LOGFILE else echo "train-drone.sh: No checkpoint, fresh start" cd $MMDET $PYTHON -m torch.distributed.launch --nproc_per_node=$GPUS \ $MMDET/tools/train.py $CONFIG --launcher pytorch \ --work_dir $WORK_DIR \ --validate 2>&1 | tee -a $LOGFILE fi
use core::ops::{Index, IndexMut}; pub struct NameTable { inner: [u8; 0x800], } impl NameTable { pub fn new() -> NameTable { NameTable { inner: [0u8; 0x800], } } pub fn addr(&self, addr: u16) -> usize { let addr = addr as usize; addr & 0x3FF + if addr < 0x2800 { 0 } else { 0x400 } } } impl Index<u16> for NameTable { type Output = u8; fn index(&self, index: u16) -> &u8 { &self.inner[self.addr(index)] } } impl IndexMut<u16> for NameTable { fn index_mut(&mut self, index: u16) -> &mut u8 { let addr = self.addr(index); &mut self.inner[addr] } }
{-# LANGUAGE TypeSynonymInstances, RecordWildCards #-} module PrettyPrint where import qualified Data.ByteString.Lazy as B import Text.Printf import Data.List import Data.Maybe import qualified Data.Map as M import Types -- Pretty printing lineHex bytes l = prettyHex $ extract (lineOffset l) (lineLength l) bytes extract :: Offset -> Word32 -> B.ByteString -> B.ByteString extract off len = B.take (fromIntegral len) . B.drop (fromIntegral off) lineOffset (Line o _ _ _) = o lineLength :: Line r -> Word32 lineLength (Line _ conds cmds audio) = fromIntegral $ 2 + 8 * length conds + 2 + 7 * length cmds + 2 + 2 * length audio ppLine :: Transscript -> Line ResReg -> String ppLine t (Line _ cs as xs) = spaces $ map ppConditional cs ++ map (ppCommand False t xs) as -- Varaint that does not generate invalid play commands exportLine :: Line ResReg -> String exportLine (Line _ cs as xs) = spaces $ map ppConditional cs ++ map (ppCommand True M.empty xs) as -- Group consecutive runs of numbers, if they do not have a description groupRuns :: (Eq a, Bounded a, Enum a) => (a -> Maybe b) -> [a] -> [Either b [a]] groupRuns l = go where go [] = [] go [x] = case l x of Nothing -> [Right [x]] Just s -> [Left s] go (x:xs) = case l x of Just l -> Left l : go xs Nothing -> case go xs of Right (y:ys):r' | x /= maxBound , succ x == y -> Right (x:y:ys) : r' r -> Right [x] : r ppPlayList :: Transscript -> PlayList -> String ppPlayList t xs = "[" ++ commas (map go (groupRuns (`M.lookup` t) xs)) ++ "]" where go (Left s) = quote s go (Right []) = error "Empty list in groupRuns result" go (Right l) | length l > 3 = show (head l) ++ ".." ++ show (last l) | otherwise = commas (map show l) ppOidList :: [OID] -> String ppOidList xs = "[" ++ commas (map go (groupRuns (const Nothing) xs)) ++ "]" where go (Left s) = s go (Right []) = error "Empty list in groupRuns result" go (Right l) | length l > 3 = show (head l) ++ ".." ++ show (last l) | otherwise = commas (map show l) ppPlayListList :: Transscript -> PlayListList -> String ppPlayListList t xs = "[" ++ commas (map (ppPlayList t) xs) ++ "]" ppConditional :: Conditional ResReg -> String ppConditional (Cond v1 o v2) = printf "%s%s%s?" (ppTVal v1) (ppCondOp o) (ppTVal v2) ppCondOp :: CondOp -> String ppCondOp Eq = "==" ppCondOp NEq = "!=" ppCondOp Lt = "< " ppCondOp Gt = "> " ppCondOp GEq = ">=" ppCondOp LEq = "<=" ppCondOp (Unknowncond b) = printf "?%s?" (prettyHex b) ppTVal :: Reg r => TVal r -> String ppTVal (Reg r) = ppReg r ppTVal (Const n) = show n ppResReg :: ResReg -> String ppResReg n = "$" ++ show n ppRegister :: Register -> String ppRegister (RegPos n) = "$" ++ show n ppRegister (RegName n) = "$" ++ n class Reg a where ppReg :: a -> String instance Reg ResReg where ppReg = ppResReg instance Reg Register where ppReg = ppRegister ppArithOp :: ArithOp -> String ppArithOp Inc = "+=" ppArithOp Dec = "-=" ppArithOp Mult = "*=" ppArithOp Div = "/=" ppArithOp Mod = "%=" ppArithOp And = "&=" ppArithOp Or = "|=" ppArithOp XOr = "^=" ppArithOp Set = ":=" ppCommand :: Reg r => Bool -> Transscript -> PlayList -> Command r -> String ppCommand True t xs p | any (not . validIndex xs) (indices p) = "" ppCommand _ t xs (Play n) = printf "P(%s)" $ ppPlayIndex t xs (fromIntegral n) ppCommand _ t xs (Random a b) = printf "P(%s)" $ ppPlayRange t xs [b..a] ppCommand _ t xs (PlayAll a b) = printf "PA(%s)" $ ppPlayRange t xs [b..a] ppCommand _ t xs (PlayAllVariant (Const 0)) = printf "PA*(%s)" (ppPlayAll t xs) ppCommand _ t xs (PlayAllVariant v) = printf "PA*(%s)(%s)" (ppPlayAll t xs) (ppTVal v) ppCommand _ t xs (RandomVariant (Const 0)) = printf "P*(%s)" (ppPlayAll t xs) ppCommand _ t xs (RandomVariant v) = printf "P*(%s)(%s)" (ppPlayAll t xs) (ppTVal v) ppCommand _ t xs Cancel = printf "C" ppCommand _ t xs (Jump v) = printf "J(%s)" (ppTVal v) ppCommand _ t xs (Timer r v) = printf "T(%s,%s)" (ppReg r) (ppTVal v) ppCommand _ t xs (NamedJump v) = printf "J(%s)" v ppCommand _ t xs (Game b) = printf "G(%d)" b ppCommand _ t xs (ArithOp o r n) = ppReg r ++ ppArithOp o ++ ppTVal n ppCommand _ t xs (Neg r) = printf "Neg(%s)" (ppReg r) ppCommand _ t xs (Unknown b r n) = printf "?(%s,%s) (%s)" (ppReg r) (ppTVal n) (prettyHex b) indices :: Command r -> [Int] indices (Play n) = [fromIntegral n] indices (Random a b) = map fromIntegral [b..a] indices (PlayAll a b) = map fromIntegral [b..a] indices _ = [] validIndex :: PlayList -> Int -> Bool validIndex xs n = n >= 0 && n < length xs ppPlayIndex :: Transscript -> PlayList -> Int -> String ppPlayIndex t xs n | validIndex xs n = transcribe t (xs !! n) | otherwise = "invalid_index_" ++ show n ppPlayRange :: Transscript -> PlayList -> [Word8] -> String ppPlayRange t xs = commas . map (ppPlayIndex t xs . fromIntegral) ppPlayAll :: Transscript -> PlayList -> String ppPlayAll t = commas . map (transcribe t) spaces = intercalate " " commas = intercalate "," quote s = printf "'%s'" s ppCommonGame :: Transscript -> Game -> String ppCommonGame t g = printf (unlines [" type: %d", " rounds: %d", " unknown (c): %d", " early rounds: %d", " repeat last media OID: %d", " unknown (x): %d", " unknown (w): %d", " unknown (v): %d", " start play list: %s", " round end play list: %s", " finish play list: %s", " round start play list: %s", " later round start play list: %s", " subgames: (%d)", "%s", " target scores: (%d) %s", " finish play lists: (%d)", "%s" ]) (gameType g) (gRounds g) (gUnknownC g) (gEarlyRounds g) (gRepeatLastMedia g) (gUnknownX g) (gUnknownW g) (gUnknownV g) (ppPlayListList t (gStartPlayList g)) (ppPlayListList t (gRoundEndPlayList g)) (ppPlayListList t (gFinishPlayList g)) (ppPlayListList t (gRoundStartPlayList g)) (ppPlayListList t (gLaterRoundStartPlayList g)) (length (gSubgames g)) (ppSubGames t (gSubgames g)) (length (gTargetScores g)) (show (gTargetScores g)) (length (gFinishPlayLists g))(indent 4 (map (ppPlayListList t) (gFinishPlayLists g))) ppGame :: Transscript -> Game -> String ppGame t g@(CommonGame {..}) = ppCommonGame t g ppGame t (Game6 {..}) = printf (unlines [" type: 6", " rounds: %d", " bonus rounds: %d", " rounds target: %d", " unknown (i): %d", " early rounds: %d", " unknown (q): %d", " repeat last media OID: %d", " unknown (x): %d", " unknown (w): %d", " unknown (v): %d", " start play list: %s", " round end play list: %s", " finish play list: %s", " round start play list: %s", " later round start play list: %s", " round start play list 2: %s", " later round start play list 2: %s", " bonus subgame count: %d", " subgames: (%d)", "%s", " target scores: (%d) %s", " bonus target scores: (%d) %s", " finish play lists: (%d)", "%s", " bonus finish play lists: (%d)", "%s", " bonus subgame ids: %s" ]) gRounds gBonusRounds gBonusTarget gUnknownI gEarlyRounds gUnknownQ gRepeatLastMedia gUnknownX gUnknownW gUnknownV (ppPlayListList t gStartPlayList) (ppPlayListList t gRoundEndPlayList) (ppPlayListList t gFinishPlayList) (ppPlayListList t gRoundStartPlayList) (ppPlayListList t gLaterRoundStartPlayList) (ppPlayListList t gRoundStartPlayList2) (ppPlayListList t gLaterRoundStartPlayList2) gBonusSubgameCount (length gSubgames) (ppSubGames t gSubgames) (length gTargetScores) (show gTargetScores) (length gBonusTargetScores) (show gBonusTargetScores) (length gFinishPlayLists) (indent 4 (map (ppPlayListList t) gFinishPlayLists)) (length gBonusFinishPlayLists) (indent 4 (map (ppPlayListList t) gBonusFinishPlayLists)) (show gBonusSubgameIds) ppGame t g@(Game7 {..}) = (ppCommonGame t g ++) $ printf (unlines [ " subgame groups: %s" ]) (show gSubgameGroups) ppGame t g@(Game8 {..}) = (ppCommonGame t g ++) $ printf (unlines [" game select OIDs: %s", " game select games: %s", " game select errors 1: %s", " game select errors 2: %s" ]) (show gGameSelectOIDs) (show gGameSelect) (ppPlayListList t gGameSelectErrors1) (ppPlayListList t gGameSelectErrors2) ppGame t g@(Game9 {..}) = (ppCommonGame t g ++) $ printf (unlines [" extra play lists (%d):","%s" ]) (length gExtraPlayLists) (indent 4 (map (ppPlayListList t) gExtraPlayLists)) ppGame t g@(Game10 {..}) = (ppCommonGame t g ++) $ printf (unlines [" extra play lists (%d):","%s" ]) (length gExtraPlayLists) (indent 4 (map (ppPlayListList t) gExtraPlayLists)) ppGame t g@(Game16 {..}) = (ppCommonGame t g ++) $ printf (unlines [" extra OIDs (%d): %s", " extra play lists (%d):","%s" ]) (length gExtraOIDs) (show gExtraOIDs) (length gExtraPlayLists) (indent 4 (map (ppPlayListList t) gExtraPlayLists)) ppGame t Game253 = printf (unlines [" type: 253" ]) ppSubGames :: Transscript -> [SubGame] -> String ppSubGames t = concatMap (uncurry (ppSubGame t)) . zip [0..] ppSubGame :: Transscript -> Int -> SubGame -> String ppSubGame t n (SubGame u oids1 oids2 oids3 plls) = printf (unlines [ " Subgame %d:" , " u: %s" , " oids1: %s" , " oids2: %s" , " oids3: %s" , " playlist: (%d)" , "%s" ]) n (prettyHex u) (ppOidList oids1) (ppOidList oids2) (ppOidList oids3) (length plls) (indent 8 (map (ppPlayListList t) plls)) indent :: Int -> [String] -> String indent n = intercalate "\n" . map (replicate n ' ' ++) checkLine :: Int -> Line ResReg -> [String] checkLine n_audio l@(Line _ _ _ xs) | any (>= fromIntegral n_audio) xs = return $ "Invalid audio index in line " ++ ppLine M.empty l checkLine n_audio _ = [] prettyHex :: B.ByteString -> String prettyHex = intercalate " " . map (printf "%02X") . B.unpack transcribe :: Transscript -> Word16 -> String transcribe t idx = fromMaybe (show idx) (M.lookup idx t) ppDesc :: [String] -> String ppDesc = intercalate "/"
import { ASObject } from '@awayfl/avm2'; export class AutomationAction extends ASObject { constructor () { super(); } // Static JS -> AS Bindings // Static AS -> JS Bindings // Instance JS -> AS Bindings _type: string; type: string; // Instance AS -> JS Bindings }
import { Injectable } from '@angular/core'; import {DataService} from '../data.service' import { HttpParams, HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class UploadFileService { constructor(private dataService:DataService) { } uploadfile(file, vehileId, imageType, editId?) { let formData = new FormData(); formData.append('file', file, file.name); // let params: HttpParams = new HttpParams(); // params.set("vehicleId", vehileId); // params.set("enumType", imageType); // if(editId){ // params.set("id", editId); // } const obj = { vehicleId : vehileId, enumType: imageType }; if(editId){ obj["id"] = editId; } const params = new HttpParams({ fromObject: { ...convertAnyToHttp(obj) } }); //let params = new HttpParams().set("vehicleId", vehileId).set("enumType", imageType).set("id", editId); console.log(params); this.dataService.sendPostImgRequest('jmc/api/v1/upload', formData, params).subscribe(data => { }) } } export function convertAnyToHttp(params: {}): { [param: string]: string | string[]; }{ params = Object.assign({}, params); Object.keys(params).forEach(key => { if(typeof params[key] === 'object'){ params[key] = JSON.stringify(params[key]); } else if(!params[key]) { delete params[key]; } }); return params; }
class Solution { Map<Character, Character> pairs = new HashMap<Character, Character>(); private void loadPairs() { this.pairs.put('(', ')'); this.pairs.put('{', '}'); this.pairs.put('[', ']'); } public boolean isValid(String s) { this.loadPairs(); boolean valid = true; Stack<Character> characters = new Stack<Character>(); for (int i=0;i<s.length();i++) { if (this.pairs.containsKey(s.charAt(i))){ characters.push(s.charAt(i)); } else if (this.pairs.containsValue(s.charAt(i)) && !characters.empty()) { Character match = s.charAt(i); Character stack = characters.pop(); if(match != this.pairs.get(stack)) { valid = false; break; } } else if (this.pairs.containsValue(s.charAt(i)) && characters.empty()) { valid = false; break; } } if (!characters.empty()) { valid = false; } return valid; } }
<?php namespace App; use App\Http\Resources\Post\PostsResource; use App\Http\Resources\User\UsersResource; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; class Post extends Model { protected $fillable = ['title', 'content', 'user_id']; public function user() { $this->belongsTo(User::class); } public function comments() { $this->hasMany(Comment::class); } public static function getPostByUserId($id): PostsResource { $posts = Post::all()->where('user_id', $id); return new PostsResource($posts); } public static function randomId() { return Post::all()->pluck('id')->random(); } public static function refreshUsersPosts() { for ($id = 1; $id <= User::all()->count(); $id++) { $u = UserPostsCounter::where('user_id', $id)->update(['counter' => 0]); } } public static function postCount($user_id) { $count = Post::all()->where('user_id', $user_id)->count(); return $count; } public static function increaseUserMaxPosts() { $user_id = Auth::id(); $user = UserPostCount::where('user_id', $user_id)->get(); dd($user); return response(['message' => 'User post has been increase']); } }
export {default as connect} from './connect' export {default as formize} from './formize' export {when} from './listener'
#!/bin/bash gcc pi-lace.c -o lacepi.out -lm -llace -llace14 -lpthread
! ! This PMMF is used in the convecting vortex regression test. ! module pmmf_sinusoidal_convecting_vortex #include <messenger.h> use mod_kinds, only: rk,ik use mod_constants, only: ZERO, HALF, ONE, TWO, THREE, FOUR, FIVE, EIGHT, PI use type_prescribed_mesh_motion_function, only: prescribed_mesh_motion_function_t implicit none private !> sinusoidal_convecting_vortex mesh motion. !! !! @author Eric Wolf !! @date 3/15/2017 !! !! !------------------------------------------------------------------------------- type, extends(prescribed_mesh_motion_function_t), public :: sinusoidal_convecting_vortex_pmmf private contains procedure :: init procedure :: compute_pos procedure :: compute_vel end type sinusoidal_convecting_vortex_pmmf !******************************************************************************** contains !> !! !! @author Eric Wolf !! @date 3/15/2017 !! !------------------------------------------------------------------------- subroutine init(self) class(sinusoidal_convecting_vortex_pmmf), intent(inout) :: self ! ! Set function name ! call self%set_name("sinusoidal_convecting_vortex") ! ! Set function options to default settings ! call self%add_option('L_X',20._rk) call self%add_option('L_Y',15._rk) call self%add_option('L_Z',1._rk) call self%add_option('GRID_MODE_X',1._rk) call self%add_option('GRID_MODE_Y',1._rk) call self%add_option('GRID_MODE_Z',1._rk) call self%add_option('GRID_FREQ_X',TWO*PI) call self%add_option('GRID_FREQ_Y',FOUR*PI) call self%add_option('GRID_FREQ_Z',1._rk) call self%add_option('GRID_AMP_X',2._rk) call self%add_option('GRID_AMP_Y',1.5_rk) call self%add_option('GRID_AMP_Z',0._rk) end subroutine init !************************************************************************* !> !! !! @author Eric Wolf !! @date 3/15/2017 !! !! !----------------------------------------------------------------------------------------- function compute_pos(self,time,node) result(val) class(sinusoidal_convecting_vortex_pmmf), intent(inout) :: self real(rk), intent(in) :: time real(rk), intent(in) :: node(3) integer(ik) :: ivar real(rk) :: val(3) real(rk) :: L_X, L_Y, L_Z, & GRID_MODE_X, GRID_MODE_Y, GRID_MODE_Z, & GRID_FREQ_X, GRID_FREQ_Y, GRID_FREQ_Z, & GRID_AMP_X, GRID_AMP_Y, GRID_AMP_Z L_X = self%get_option_value('L_X') L_Y = self%get_option_value('L_Y') L_Z = self%get_option_value('L_Z') GRID_MODE_X = self%get_option_value('GRID_MODE_X') GRID_MODE_Y = self%get_option_value('GRID_MODE_Y') GRID_MODE_Z = self%get_option_value('GRID_MODE_Z') GRID_FREQ_X = self%get_option_value('GRID_FREQ_X') GRID_FREQ_Y = self%get_option_value('GRID_FREQ_Y') GRID_FREQ_Z = self%get_option_value('GRID_FREQ_Z') GRID_AMP_X = self%get_option_value('GRID_AMP_X') GRID_AMP_Y = self%get_option_value('GRID_AMP_Y') GRID_AMP_Z = self%get_option_value('GRID_AMP_Z') val(1) = node(1) + & GRID_AMP_X* & sin(GRID_MODE_X*TWO*PI*node(1)/L_X)* & sin(GRID_MODE_Y*TWO*PI*node(2)/L_Y)* & sin(GRID_FREQ_X*time) val(2) = node(2) + & GRID_AMP_Y* & sin(GRID_MODE_X*TWO*PI*node(1)/L_X)* & sin(GRID_MODE_Y*TWO*PI*node(2)/L_Y)* & sin(GRID_FREQ_Y*time) val(3) = node(3) end function compute_pos !********************************************************************************** !> !! !! @author Eric Wolf !! @date 3/15/2017 !! !! !----------------------------------------------------------------------------------------- function compute_vel(self,time,node) result(val) class(sinusoidal_convecting_vortex_pmmf), intent(inout) :: self real(rk), intent(in) :: time real(rk), intent(in) :: node(3) integer(ik) :: ivar real(rk) :: val(3) real(rk) :: L_X, L_Y, L_Z, & GRID_MODE_X, GRID_MODE_Y, GRID_MODE_Z, & GRID_FREQ_X, GRID_FREQ_Y, GRID_FREQ_Z, & GRID_AMP_X, GRID_AMP_Y, GRID_AMP_Z L_X = self%get_option_value('L_X') L_Y = self%get_option_value('L_Y') L_Z = self%get_option_value('L_Z') GRID_MODE_X = self%get_option_value('GRID_MODE_X') GRID_MODE_Y = self%get_option_value('GRID_MODE_Y') GRID_MODE_Z = self%get_option_value('GRID_MODE_Z') GRID_FREQ_X = self%get_option_value('GRID_FREQ_X') GRID_FREQ_Y = self%get_option_value('GRID_FREQ_Y') GRID_FREQ_Z = self%get_option_value('GRID_FREQ_Z') GRID_AMP_X = self%get_option_value('GRID_AMP_X') GRID_AMP_Y = self%get_option_value('GRID_AMP_Y') GRID_AMP_Z = self%get_option_value('GRID_AMP_Z') val(1) = & GRID_AMP_X* & sin(GRID_MODE_X*TWO*PI*node(1)/L_X)* & sin(GRID_MODE_Y*TWO*PI*node(2)/L_Y)* & GRID_FREQ_X*cos(GRID_FREQ_X*time) val(2) = & GRID_AMP_Y* & sin(GRID_MODE_X*TWO*PI*node(1)/L_X)* & sin(GRID_MODE_Y*TWO*PI*node(2)/L_Y)* & GRID_FREQ_Y*cos(GRID_FREQ_Y*time) val(3) = ZERO end function compute_vel !********************************************************************************** end module pmmf_sinusoidal_convecting_vortex
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { NwbDialogConfig, NwbDialogService } from "@wizishop/ng-wizi-bulma"; import { Router } from "@angular/router"; import { FriendsService } from "src/app/services/friends.service"; import { AlertService } from "src/app/services/alert.service"; @Component({ selector: "app-user-item", templateUrl: "./user-item.component.html", styleUrls: ["./user-item.component.scss"], }) export class UserItemComponent implements OnInit { @Input() user; @Input() isFriend; @Input() showAddUserButton; @Input() showAddFriendButton; @Output() selectUser = new EventEmitter<any>(); addFriendDialogConfig: NwbDialogConfig = { title: "Add Friend", message: "Are you sure?", okButtonText: "Yes", cancelButtonText: "No", }; removeFriendDialogConfig: NwbDialogConfig = { title: "Remove Friend", message: "Are you sure?", okButtonText: "Yes", cancelButtonText: "No", }; constructor( private router: Router, private friendsService: FriendsService, private alertService: AlertService, private nwbDialog: NwbDialogService ) {} ngOnInit(): void {} addFriend() { const dialog = this.nwbDialog.open(this.addFriendDialogConfig); dialog.afterClosed().subscribe((fromOkButton) => this.friendsService.addFriend(this.user._id).subscribe((res) => { this.alertService.showMessage("Friend Added Successfully", false); this.router.navigateByUrl("/dashboard"); }) ); } removeFriend() { const dialog = this.nwbDialog.open(this.removeFriendDialogConfig); dialog.afterClosed().subscribe((fromOkButton) => this.friendsService.removeFriend(this.user._id).subscribe((res) => { this.alertService.showMessage("Friend Removed Successfully", false); this.router.navigateByUrl("/dashboard"); }) ); } addUser() { this.selectUser.emit(this.user); } }
@extends('layout.app') @push('on_ready') $("#rankings").addClass('active'); @endpush @section('title') | Rankings @endsection @section('pagetitle') <h1>{{season()->year}} {{league()->name}} Rankings @if($rankings) <small>Week {{$rankings->week->number}}</small> @endif </h1> @endsection @section('breadcrumb') <li class="active">Rankings</li> @endsection @section('content') <div class="row"> <div class="col-md-12"> @component('components.bars.action') {!! Form::select('week', [], null) !!} @endcomponent @component('components.box.default', ['title' => 'Rankings', 'collapse' => true]) @slot('body') @if($rankings) @include('widgets.rankings.large', ['rankings' => $rankings]) @else <p>There are no rankings to display at this time.</p> @endif @endslot @slot('footer') @if($rankings) @include('inserts.line.updated', ['when' => $rankings->updated_at]) @endif @endslot @endcomponent </div> </div> @endsection
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.cdsreimbursementclaimstubs.models.acc14 import play.api.http.Status import play.api.libs.json.{JsValue, Json} import uk.gov.hmrc.cdsreimbursementclaimstubs.utils.TimeUtils final case class Acc14ErrorResponse(value: JsValue, httpStatus: Int) object Acc14ErrorResponse { sealed trait Acc14ErrorResponseType extends Product with Serializable object Acc14ErrorResponseType { case object BAD_REQUEST_MISSING_DECLARATION extends Acc14ErrorResponseType case object NO_SECURITY_DEPOSITS extends Acc14ErrorResponseType case object TIME_OUT extends Acc14ErrorResponseType case object HTTP_METHOD_NOT_ALLOWED extends Acc14ErrorResponseType } def returnAcc14ErrorResponse(acc14ErrorResponseType: Acc14ErrorResponseType): Acc14ErrorResponse = acc14ErrorResponseType match { case Acc14ErrorResponseType.BAD_REQUEST_MISSING_DECLARATION => makeBadRequestMissingDeclarationResponse case Acc14ErrorResponseType.NO_SECURITY_DEPOSITS => makeNoSecurityDepositResponse case Acc14ErrorResponseType.TIME_OUT => makeTimeOutResponse case Acc14ErrorResponseType.HTTP_METHOD_NOT_ALLOWED => makeHttpMethodNotAllowedResponse } def makeBadRequestMissingDeclarationResponse = Acc14ErrorResponse( Json.parse( s""" |{ | "errorDetail": { | "timestamp": "${TimeUtils.iso8061DateTimeNow}", | "correlationId": "314ae2f9-d968-4f28-b9be-d9a72913fc71", | "errorCode": "400", | "errorMessage": "No declaration found", | "source": "Backend", | "sourceFaultDetail": { | "detail": [ | "086 - No declaration found" | ] | } | } |} |""".stripMargin ), Status.BAD_REQUEST ) def makeNoSecurityDepositResponse = Acc14ErrorResponse( Json.parse( s""" |{ | "errorDetail": { | "timestamp": "${TimeUtils.iso8061DateTimeNow}", | "correlationId": "314ae2f9-d968-4f28-b9be-d9a72913fc71", | "errorCode": "400", | "errorMessage": "No security deposits exist for Declaration ID and reason for security", | "source": "Backend", | "sourceFaultDetail": { | "detail": [ | "072 - No security deposits exist for Declaration ID and reason for security" | ] | } | } |} |""".stripMargin ), Status.BAD_REQUEST ) def makeTimeOutResponse = Acc14ErrorResponse( Json.parse( s""" |{ | "errorDetail": { | "timestamp": "${TimeUtils.iso8061DateTimeNow}", | "correlationId": "", | "errorCode": "500", | "errorMessage": "Send timeout", | "source": "ct-api", | "sourceFaultDetail": { | "detail": [ | "101504 - Send timeout" | ] | } | } |} |""".stripMargin ), Status.INTERNAL_SERVER_ERROR ) def makeHttpMethodNotAllowedResponse = Acc14ErrorResponse( Json.parse( s""" |{ | "errorDetail": { | "timestamp": "${TimeUtils.iso8061DateTimeNow}", | "correlationId": "", | "errorCode": "405", | "errorMessage": "HTTP METHOD NOT ALLOWED", | "source": "ct-api", | "sourceFaultDetail": { | "detail": [ | "101504 - HTTP METHOD NOT ALLOWED" | ] | } | } |} |""".stripMargin ), Status.METHOD_NOT_ALLOWED ) }
import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Comparator.comparingInt; public class Boise extends AlternativeWay { private static final int synX1125int = 1; private static final int synX1124int = 0; private static final int synX1123int = 0; private static final double synX1122double = 0.4645358041874744; private static final boolean synX1121boolean = false; private static final boolean synX1120boolean = true; private static final int synX1119int = 0; private static final int synX1118int = 48901706; private static final double synX1117double = 0.13534515364002309; private static final double synX1116double = 0.2556654705770298; private static final double synX1115double = 0.5717961202383431; public static final int uppermostTied = 2072580074; public Boise() { this.Pairs = (new java.util.LinkedList<>()); } public synchronized boolean isComplete() { double prices = synX1115double; return Pairs.size() >= NickSashes; } public java.util.Queue<Website> Pairs = null; public synchronized void installLayouts(Outgrowth ongoingWork) { double heightThreshold = synX1116double; java.util.function.Predicate<Website> ejemplo = new java.util.function.Predicate<Website>() { public synchronized boolean test(Website vig) { double symbolic = synX1117double; return vig.fixDidacticSystem() == ongoingWork.driveSecurity(); } }; Website senior = Pairs.stream().filter(ejemplo).max(comparingInt(Website::haveChip)).get(); Pairs.remove(senior); } public final int NickSashes = 30; public synchronized boolean determineAppeal(Outgrowth newSystem) { int marx = synX1118int; Pairs.forEach(Website::expansionThwart); java.util.List<Website> chapter = new java.util.ArrayList<>(); for (Website Framework : Pairs) synx161(newSystem, Framework, chapter); if (chapter.size() > synX1119int) { chapter.forEach(Website::rebalanceHeel); return synX1120boolean; } return synX1121boolean; } protected synchronized void enhanceFront(Website addendum, Outgrowth continuingMechanisms) { double elevationIndentured = synX1122double; if (this.isComplete() || continuingMechanisms.drawArithmeticHeadlines() == continuingMechanisms.comeLimitVarlet()) synx162(continuingMechanisms); java.util.List<Website> temperature = new java.util.LinkedList<>(); for (Website f : Pairs) synx163(f, addendum, continuingMechanisms, temperature); Website circulating = null; if (temperature.size() > synX1123int) circulating = (temperature.get(synX1124int)); if (circulating == null) synx164(addendum, continuingMechanisms); else synx165(circulating); } private synchronized void synx161( Outgrowth newSystem, Website Framework, java.util.List<Website> chapter) { if (newSystem.fixOrders().peek().equals(Framework.arriveIdentifying()) && newSystem.driveSecurity() == Framework.fixDidacticSystem()) { chapter.add(Framework); } } private synchronized void synx162(Outgrowth continuingMechanisms) { this.installLayouts(continuingMechanisms); } private synchronized void synx163( Website f, Website addendum, Outgrowth continuingMechanisms, java.util.List<Website> temperature) { if (f.arriveIdentifying() == addendum.arriveIdentifying() && f.fixDidacticSystem() == continuingMechanisms.driveSecurity()) temperature.add(f); } private synchronized void synx164(Website addendum, Outgrowth continuingMechanisms) { Pairs.add(addendum); continuingMechanisms.primedAbortSites( continuingMechanisms.drawArithmeticHeadlines() + synX1125int); } private synchronized void synx165(Website circulating) { circulating.rebalanceHeel(); } }
module Ethereum::Base module Secp256K1 N = 115792089237316195423570985008687907852837564279074904382605163141518161494337 UINT_MAX = 2**256 - 1 end end
import { assertType, replaceProperty, ReplaceProperty } from '..' test('replaceProperty()', () => { const subject = { a: 1, b: 2 } as const const actual = replaceProperty(subject, 'a', () => 1) assertType<{ a: () => 1, b: 2 }>(actual) expect(actual.a()).toBe(1) }) test('ReplaceProperty<>', () => { const subject = { a: 1, b: 2 } const actual = subject as ReplaceProperty<typeof subject, 'a', 1> assertType<{ a: 1, b: number }>(actual) })
/*===== testing script for procedure silly_shout by: Sharon Tuttle last modified: 2020-01-30 =====*/ prompt prompt ************************ prompt TESTING silly_shout prompt ************************ prompt set serveroutput on prompt =================== prompt test passes if it shows 3 "shouts" of HOWDY!!: prompt =================== exec silly_shout('howdy', 3) prompt =================== prompt test passes if it shows 5 "shouts" of CS 328 - RAH RAH RAH!!! prompt =================== exec silly_shout('CS 328 - rah rah rah!', 5) prompt =================== prompt test passes if see NO output (asked to shout 0 times) prompt =================== exec silly_shout('hi', 0) prompt =================== prompt test passes if it complains that it cannot "shout" moo -1 times: prompt =================== exec silly_shout('moo', -1) -- end of silly_shout_test.sql
class TGAccessMatrixVO { String? key; int? roleId; String? module; String? access; bool? create; bool? delete; bool? update; bool? read; TGAccessMatrixVO( {this.key, this.roleId, this.module, this.access, this.create, this.delete, this.update, this.read}); TGAccessMatrixVO.fromJson(Map<String, dynamic> json) { key = json['key']; roleId = json['roleId']; module = json['module']; access = json['access']; create = json['create']; delete = json['delete']; update = json['update']; read = json['read']; } Map<String, dynamic> toJson() => { 'key': key, 'roleId': roleId, 'module': module, 'access': access, 'create': create, 'delete': delete, 'update': update, 'read': read, }; bool operator ==(o) => o is TGAccessMatrixVO && key == o.key && roleId == o.roleId; int get hashCode => (key! + roleId.toString()).hashCode; }
--- layout: project_single title: "Tiles, colors and contours shape a gorgeous Mediterranean kitchen" slug: "tiles-colors-and-contours-shape-a-gorgeous-mediterranean-kitchen" parent: "mediterranean-decor-idea" --- Tiles, colors and contours shape a gorgeous Mediterranean kitchen - Decoist
use crate::*; use crate::register::{SvmReg, SvmReg160, SvmReg32, SvmReg512, SvmReg64}; use std::ffi::c_void; use svm_storage::traits::PageCache; use svm_storage::PageSliceCache; use crate::ctx_data_wrapper::SvmCtxDataWrapper; use log::debug; /// The number of allocated `SvmReg32` registers for each `SvmCtx` pub const REGS_32_COUNT: usize = 16; /// The number of allocated `SvmReg64` registers for each `SvmCtx` pub const REGS_64_COUNT: usize = 16; /// The number of allocated `SvmReg160` registers for each `SvmCtx` pub const REGS_160_COUNT: usize = 8; /// The number of allocated `SvmReg256` registers for each `SvmCtx` pub const REGS_256_COUNT: usize = 4; /// The number of allocated `SvmReg512` registers for each `SvmCtx` pub const REGS_512_COUNT: usize = 4; /// `SvmCtx` is a container for the accessible data by `wasmer` instances /// * `node_data` - A pointer to the *node* data /// * `regs_32` - A static array (`REGS_32_COUNT` elements) of `SvmReg32` /// * `regs_64` - A static array (`REGS_64_COUNT` elements) of `SvmReg64` /// * `regs_160` - A static array (`REGS_160_COUNT` elements) of `SvmReg160` /// * `regs_256` - A static array (`REGS_256_COUNT` elements) of `SvmReg256` /// * `regs_512` - A static array (`REGS_512_COUNT` elements) of `SvmReg512` /// * `storage` - An instance of `PageSliceCache` #[repr(C)] pub struct SvmCtx<PC: PageCache> { /// A pointer to the `node` data. For example the pointer will point a to struct having an access /// to the `Global State` of each account, in order to query an account for its balance. pub node_data: *const c_void, /// An array that holds the `SvmReg32` registers pub regs_32: [SvmReg; REGS_32_COUNT], /// An array that holds the `SvmReg64` registers pub regs_64: [SvmReg; REGS_64_COUNT], /// An array that holds the `SvmReg160` registers pub regs_160: [SvmReg; REGS_160_COUNT], /// An array that holds the `SvmReg256` registers pub regs_256: [SvmReg; REGS_256_COUNT], /// An array that holds the `SvmReg512` registers pub regs_512: [SvmReg; REGS_512_COUNT], /// An accessor to the contract's storage (of type `PageSliceCache`) pub storage: PageSliceCache<PC>, } unsafe impl<PC> Sync for SvmCtx<PC> where PC: PageCache {} unsafe impl<PC> Send for SvmCtx<PC> where PC: PageCache {} impl<PC> SvmCtx<PC> where PC: PageCache, { /// Initializes a new empty `SvmCtx` /// /// * `storage` - a mutably borrowed `PageSliceCache` pub fn new(data_wrapper: SvmCtxDataWrapper, storage: PageSliceCache<PC>) -> Self { let regs_32 = alloc_regs!(32, REGS_32_COUNT); let regs_64 = alloc_regs!(64, REGS_64_COUNT); let regs_160 = alloc_regs!(160, REGS_160_COUNT); let regs_256 = alloc_regs!(256, REGS_256_COUNT); let regs_512 = alloc_regs!(512, REGS_512_COUNT); Self { node_data: data_wrapper.unwrap(), regs_32, regs_64, regs_160, regs_256, regs_512, storage, } } } impl<PC> Drop for SvmCtx<PC> where PC: PageCache, { fn drop(&mut self) { debug!("Dropping `SvmCtx`..."); } }
//! The module contains a number of reusable components for implementing the client side of an //! HTTP/2 connection. use std::net::TcpStream; use std::io; use std::fmt; use std::error; use http::{HttpScheme, HttpResult, StreamId, Header, HttpError, ErrorCode}; use http::transport::TransportStream; use http::frame::{SettingsFrame, HttpSetting, FrameIR, PingFrame}; use http::connection::{SendFrame, ReceiveFrame, SendStatus, HttpConnection, EndStream}; use http::session::{Session, Stream, DefaultStream, DefaultSessionState, SessionState}; use http::session::Client as ClientMarker; use http::priority::SimplePrioritizer; #[cfg(feature="tls")] pub mod tls; /// Writes the client preface to the given `io::Write` instance. /// /// According to the HTTP/2 spec, a client preface is first a specific sequence of octets, followed /// by a settings frame. /// /// This helper method can be utilized by different transport layer implementations to prepare the /// preface that needs to be written before initializing an `HttpConnection` instance. /// /// # Returns /// /// Any error raised by the underlying `io::Write` instance is propagated. pub fn write_preface<W: io::Write>(stream: &mut W) -> Result<(), io::Error> { // The first part of the client preface is always this sequence of 24 // raw octets. let preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; try!(stream.write_all(preface)); // It is followed by the client's settings. // TODO: It doesn't really make sense to have the initial settings be sent here, outside of the // HttpConnection/Session. This should be moved to the initialization of the session! let settings = { let mut frame = SettingsFrame::new(); frame.add_setting(HttpSetting::EnablePush(0)); frame }; let mut buf = io::Cursor::new(Vec::with_capacity(16)); try!(settings.serialize_into(&mut buf)); try!(stream.write_all(buf.get_ref())); debug!("Sent client preface"); Ok(()) } /// A convenience wrapper type that represents an established client network transport stream. /// It wraps the stream itself, the scheme of the protocol to be used, and the remote /// host name. pub struct ClientStream<TS: TransportStream>(pub TS, pub HttpScheme, pub String); /// A marker trait for errors raised by attempting to establish an HTTP/2 /// connection. pub trait HttpConnectError: error::Error + Send + Sync {} impl<E> From<E> for HttpError where E: HttpConnectError + 'static { fn from(e: E) -> HttpError { HttpError::Other(Box::new(e)) } } /// A trait that can be implemented by structs that want to provide the /// functionality of establishing network connections for use by HTTP/2 connections. /// /// The `ClientStream` instance returned from the `connect` method needs to contain /// the `TransportStream` that can be used by an HTTP/2 connection, along with the /// appropriate scheme (depending on how the connection was established), and the remote /// host name. /// /// The transport stream needs to have already been initialized by writing the client /// preface. The helper function `write_preface` can be used for this purpose. pub trait HttpConnect { /// The type of the underlying transport stream that the `HttpConnection`s /// produced by this `HttpConnect` implementation will be based on. type Stream: TransportStream; /// The type of the error that can be produced by trying to establish the /// connection (i.e. calling the `connect` method). type Err: HttpConnectError + 'static; /// Establishes a network connection that can be used by HTTP/2 connections. fn connect(self) -> Result<ClientStream<Self::Stream>, Self::Err>; } /// A struct that establishes a cleartext TCP connection that can be used by an HTTP/2 /// connection. Defaults to using port 80. /// /// It assumes that the connection is based on prior knowledge of the server's /// support for HTTP/2. /// /// More information in the [spec](http://http2.github.io/http2-spec/#known-http) pub struct CleartextConnector<'a> { /// The host to which the connection should be established pub host: &'a str, /// The port on which the connection should be established pub port: u16, } impl<'a> CleartextConnector<'a> { /// Creates a new `CleartextConnector` that will attempt to establish a connection to the given /// host on port 80. pub fn new(host: &'a str) -> CleartextConnector { CleartextConnector { host: host, port: 80, } } /// Creates a new `CleartextConnector` that will attempt to establish a connection to the given /// host on the given port. pub fn with_port(host: &'a str, port: u16) -> CleartextConnector { CleartextConnector { host: host, port: port, } } } /// A newtype wrapping the `io::Error`, as it occurs when attempting to /// establish an HTTP/2 connection over cleartext TCP (with prior knowledge). #[derive(Debug)] pub struct CleartextConnectError(io::Error); impl fmt::Display for CleartextConnectError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Cleartext HTTP/2 connect error: {}", (self as &error::Error).description()) } } impl error::Error for CleartextConnectError { fn description(&self) -> &str { self.0.description() } fn cause(&self) -> Option<&error::Error> { self.0.cause() } } /// For convenience we make sure that `io::Error`s are easily convertible to /// the `CleartextConnectError`, if needed. impl From<io::Error> for CleartextConnectError { fn from(e: io::Error) -> CleartextConnectError { CleartextConnectError(e) } } /// The error is marked as an `HttpConnectError` impl HttpConnectError for CleartextConnectError {} impl<'a> HttpConnect for CleartextConnector<'a> { type Stream = TcpStream; type Err = CleartextConnectError; /// Establishes a cleartext TCP connection based on the host and port. /// If it is not possible, returns an `HttpError`. fn connect(self) -> Result<ClientStream<TcpStream>, CleartextConnectError> { let mut stream = try!(TcpStream::connect((self.host, self.port))); // Once the stream has been established, we need to write the client preface, // to ensure that the connection is indeed initialized. try!(write_preface(&mut stream)); // All done. Ok(ClientStream(stream, HttpScheme::Http, self.host.into())) } } /// A struct representing a request stream. It provides the headers that are to be sent when /// initiating the request, as well as a `Stream` instance that handles the received response and /// provides the request body. pub struct RequestStream<'n, 'v, S> where S: Stream { /// The list of headers that will be sent with the request. pub headers: Vec<Header<'n, 'v>>, /// The underlying `Stream` instance, which will handle the response, as well as optionally /// provide the body of the request. pub stream: S, } /// The struct extends the `HttpConnection` API with client-specific methods (such as /// `start_request`) and wires the `HttpConnection` to the client `Session` callbacks. pub struct ClientConnection<State = DefaultSessionState<ClientMarker, DefaultStream>> where State: SessionState { /// The underlying `HttpConnection` that will be used for any HTTP/2 /// communication. conn: HttpConnection, /// The state of the session associated to this client connection. Maintains the status of the /// connection streams. pub state: State, } impl<State> ClientConnection<State> where State: SessionState { /// Creates a new `ClientConnection` that will use the given `HttpConnection` /// for all its underlying HTTP/2 communication. /// /// The given `state` instance will handle the maintenance of the session's state. pub fn with_connection(conn: HttpConnection, state: State) -> ClientConnection<State> { ClientConnection { conn: conn, state: state, } } /// Returns the scheme of the underlying `HttpConnection`. #[inline] pub fn scheme(&self) -> HttpScheme { self.conn.scheme } /// Handles the next frame provided by the given frame receiver and expects it to be a /// `SETTINGS` frame. If it is not, it returns an error. /// /// The method is a convenience method that can be used during the initialization of the /// connection, as the first frame that any peer is allowed to send is an initial settings /// frame. pub fn expect_settings<Recv: ReceiveFrame, Sender: SendFrame>(&mut self, rx: &mut Recv, tx: &mut Sender) -> HttpResult<()> { let mut session = ClientSession::new(&mut self.state, tx); self.conn.expect_settings(rx, &mut session) } /// Starts a new request based on the given `RequestStream`. /// /// For now it does not perform any validation whether the given `RequestStream` is valid. pub fn start_request<S: SendFrame>(&mut self, req: RequestStream<State::Stream>, sender: &mut S) -> HttpResult<StreamId> { let end_stream = if req.stream.is_closed_local() { EndStream::Yes } else { EndStream::No }; let stream_id = self.state.insert_outgoing(req.stream); try!(self.conn.sender(sender).send_headers(req.headers, stream_id, end_stream)); Ok(stream_id) } /// Send a PING pub fn send_ping<S: SendFrame>(&mut self, sender: &mut S) -> HttpResult<()> { try!(self.conn.sender(sender).send_ping(0)); Ok(()) } /// Fully handles the next incoming frame provided by the given `ReceiveFrame` instance. /// Handling a frame may cause changes to the session state exposed by the `ClientConnection`. pub fn handle_next_frame<Recv: ReceiveFrame, Sender: SendFrame>(&mut self, rx: &mut Recv, tx: &mut Sender) -> HttpResult<()> { let mut session = ClientSession::new(&mut self.state, tx); self.conn.handle_next_frame(rx, &mut session) } /// Queues a new DATA frame onto the underlying `SendFrame`. /// /// Currently, no prioritization of streams is taken into account and which stream's data is /// queued cannot be relied on. pub fn send_next_data<S: SendFrame>(&mut self, sender: &mut S) -> HttpResult<SendStatus> { debug!("Sending next data..."); // A default "maximum" chunk size of 8 KiB is set on all data frames. const MAX_CHUNK_SIZE: usize = 8 * 1024; let mut buf = [0; MAX_CHUNK_SIZE]; let mut prioritizer = SimplePrioritizer::new(&mut self.state, &mut buf); self.conn.sender(sender).send_next_data(&mut prioritizer) } } /// An implementation of the `Session` trait specific to handling client HTTP/2 connections. /// /// While handling the events signaled by the `HttpConnection`, the struct will modify the given /// session state appropriately. /// /// The purpose of the type is to make it easier for client implementations to /// only handle stream-level events by providing a `Stream` implementation, /// instead of having to implement all session management callbacks. /// /// For example, by varying the `Stream` implementation it is easy to implement /// a client that streams responses directly into a file on the local file system, /// instead of keeping it in memory (like the `DefaultStream` does), without /// having to change any HTTP/2-specific logic. pub struct ClientSession<'a, State, S> where State: SessionState + 'a, S: SendFrame + 'a { state: &'a mut State, sender: &'a mut S, } impl<'a, State, S> ClientSession<'a, State, S> where State: SessionState + 'a, S: SendFrame + 'a { /// Returns a new `ClientSession` associated to the given state. #[inline] pub fn new(state: &'a mut State, sender: &'a mut S) -> ClientSession<'a, State, S> { ClientSession { state: state, sender: sender, } } } impl<'a, State, S> Session for ClientSession<'a, State, S> where State: SessionState + 'a, S: SendFrame + 'a { fn new_data_chunk(&mut self, stream_id: StreamId, data: &[u8], _: &mut HttpConnection) -> HttpResult<()> { debug!("Data chunk for stream {}", stream_id); let mut stream = match self.state.get_stream_mut(stream_id) { None => { debug!("Received a frame for an unknown stream!"); // TODO(mlalic): This can currently indicate two things: // 1) the stream was idle => PROTOCOL_ERROR // 2) the stream was closed => STREAM_CLOSED (stream error) return Ok(()); } Some(stream) => stream, }; // Now let the stream handle the data chunk stream.new_data_chunk(data); Ok(()) } fn new_headers<'n, 'v>(&mut self, stream_id: StreamId, headers: Vec<Header<'n, 'v>>, _conn: &mut HttpConnection) -> HttpResult<()> { debug!("Headers for stream {}", stream_id); let mut stream = match self.state.get_stream_mut(stream_id) { None => { debug!("Received a frame for an unknown stream!"); // TODO(mlalic): This means that the server's header is not associated to any // request made by the client nor any server-initiated stream (pushed) return Ok(()); } Some(stream) => stream, }; // Now let the stream handle the headers stream.set_headers(headers); Ok(()) } fn end_of_stream(&mut self, stream_id: StreamId, _: &mut HttpConnection) -> HttpResult<()> { debug!("End of stream {}", stream_id); let mut stream = match self.state.get_stream_mut(stream_id) { None => { debug!("Received a frame for an unknown stream!"); return Ok(()); } Some(stream) => stream, }; // Since this implies that the server has closed the stream (i.e. provided a response), we // close the local end of the stream, as well as the remote one; there's no need to keep // sending out the request body if the server's decided that it doesn't want to see it. stream.close(); Ok(()) } fn rst_stream(&mut self, stream_id: StreamId, error_code: ErrorCode, _: &mut HttpConnection) -> HttpResult<()> { debug!("RST_STREAM id={:?}, error={:?}", stream_id, error_code); self.state.get_stream_mut(stream_id).map(|stream| stream.on_rst_stream(error_code)); Ok(()) } fn new_settings(&mut self, _settings: Vec<HttpSetting>, conn: &mut HttpConnection) -> HttpResult<()> { debug!("Sending a SETTINGS ack"); conn.sender(self.sender).send_settings_ack() } fn on_ping(&mut self, ping: &PingFrame, conn: &mut HttpConnection) -> HttpResult<()> { debug!("Sending a PING ack"); conn.sender(self.sender).send_ping_ack(ping.opaque_data()) } fn on_pong(&mut self, _ping: &PingFrame, _conn: &mut HttpConnection) -> HttpResult<()> { debug!("Received a PING ack"); Ok(()) } } #[cfg(test)] mod tests { use super::{ClientSession, write_preface, RequestStream}; use http::{Header, ErrorCode, HttpError}; use http::tests::common::{TestStream, build_mock_client_conn, build_mock_http_conn, MockReceiveFrame, MockSendFrame}; use http::frame::{SettingsFrame, DataFrame, Frame, RawFrame}; use http::connection::{HttpFrame, SendStatus}; use http::session::{Session, SessionState, Stream, DefaultSessionState}; use http::session::Client as ClientMarker; /// Tests that a client connection is correctly initialized, by reading the /// server preface (i.e. a settings frame) as the first frame of the connection. #[test] fn test_init_client_conn() { let frames = vec![HttpFrame::SettingsFrame(SettingsFrame::new())]; let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); let mut receiver = MockReceiveFrame::new(frames); conn.expect_settings(&mut receiver, &mut sender).unwrap(); // We have read the server's response (the settings frame only, since no panic // ocurred) assert_eq!(receiver.recv_list.len(), 0); // We also sent an ACK already. assert_eq!(sender.sent.len(), 1); let frame = match HttpFrame::from_raw(&sender.sent[0]).unwrap() { HttpFrame::SettingsFrame(frame) => frame, _ => panic!("ACK not sent!"), }; assert!(frame.is_ack()); } /// Tests that a client connection fails to initialize when the server does /// not send a settings frame as its first frame (i.e. server preface). #[test] fn test_init_client_conn_no_settings() { let frames = vec![HttpFrame::DataFrame(DataFrame::new(1))]; let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); let mut receiver = MockReceiveFrame::new(frames); // We get an error since the first frame sent by the server was not // SETTINGS. assert!(conn.expect_settings(&mut receiver, &mut sender).is_err()); } /// A helper function that prepares a `TestStream` with an optional outgoing data stream. fn prepare_stream(data: Option<Vec<u8>>) -> TestStream { let mut stream = TestStream::new(); match data { None => stream.close_local(), Some(d) => stream.set_outgoing(d), }; return stream; } /// Tests that the `ClientConnection` correctly sends the next data, depending on the streams /// known to it. #[test] fn test_client_conn_send_next_data() { { // No streams => nothing sent. let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Nothing); } { // A locally closed stream (i.e. nothing to send) let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); conn.state.insert_outgoing(prepare_stream(None)); let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Nothing); } { // A stream with some data let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); conn.state.insert_outgoing(prepare_stream(Some(vec![1, 2, 3]))); let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Sent); // All of it got sent in the first go, so now we've got nothing? let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Nothing); } { // Multiple streams with data let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); conn.state.insert_outgoing(prepare_stream(Some(vec![1, 2, 3]))); conn.state.insert_outgoing(prepare_stream(Some(vec![1, 2, 3]))); conn.state.insert_outgoing(prepare_stream(Some(vec![1, 2, 3]))); for _ in 0..3 { let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Sent); } // All of it got sent in the first go, so now we've got nothing? let res = conn.send_next_data(&mut sender).unwrap(); assert_eq!(res, SendStatus::Nothing); } } /// Tests that the `ClientConnection::start_request` method correctly starts a new request. #[test] fn test_client_conn_start_request() { { // No body let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); let stream = RequestStream { headers: vec![ Header::new(b":method", b"GET"), ], stream: prepare_stream(None), }; conn.start_request(stream, &mut sender).unwrap(); // The stream is in the connection state? assert!(conn.state.get_stream_ref(1).is_some()); // The headers got sent? // (It'd be so much nicer to assert that the `send_headers` method got called) assert_eq!(sender.sent.len(), 1); match HttpFrame::from_raw(&sender.sent[0]).unwrap() { HttpFrame::HeadersFrame(ref frame) => { // The frame closed the stream? assert!(frame.is_end_of_stream()); } _ => panic!("Expected a Headers frame"), }; } { // With a body let mut conn = build_mock_client_conn(); let mut sender = MockSendFrame::new(); let stream = RequestStream { headers: vec![ Header::new(b":method", b"POST"), ], stream: prepare_stream(Some(vec![1, 2, 3])), }; conn.start_request(stream, &mut sender).unwrap(); // The stream is in the connection state? assert!(conn.state.get_stream_ref(1).is_some()); // The headers got sent? // (It'd be so much nicer to assert that the `send_headers` method got called) assert_eq!(sender.sent.len(), 1); match HttpFrame::from_raw(&sender.sent.remove(0)).unwrap() { HttpFrame::HeadersFrame(ref frame) => { // The stream is still open assert!(!frame.is_end_of_stream()); } _ => panic!("Expected a Headers frame"), }; } } /// Tests that a `ClientSession` notifies the correct stream when the /// appropriate callback is invoked. /// /// A better unit test would give a mock Stream to the `ClientSession`, /// instead of testing both the `ClientSession` and the `DefaultStream` /// in the same time... #[test] fn test_client_session_notifies_stream() { let mut state = DefaultSessionState::<ClientMarker, TestStream>::new(); state.insert_outgoing(TestStream::new()); let mut conn = build_mock_http_conn(); let mut sender = MockSendFrame::new(); { // Registering some data to stream 1... let mut session = ClientSession::new(&mut state, &mut sender); session.new_data_chunk(1, &[1, 2, 3], &mut conn).unwrap(); } // ...works. assert_eq!(state.get_stream_ref(1).unwrap().body, vec![1, 2, 3]); { // Some more... let mut session = ClientSession::new(&mut state, &mut sender); session.new_data_chunk(1, &[4], &mut conn).unwrap(); } // ...works. assert_eq!(state.get_stream_ref(1).unwrap().body, vec![1, 2, 3, 4]); // Now headers? let headers = vec![ Header::new(b":method", b"GET"), ]; { let mut session = ClientSession::new(&mut state, &mut sender); session.new_headers(1, headers.clone(), &mut conn).unwrap(); } assert_eq!(state.get_stream_ref(1).unwrap().headers.clone().unwrap(), headers); // Add another stream in the mix state.insert_outgoing(TestStream::new()); { // and send it some data let mut session = ClientSession::new(&mut state, &mut sender); session.new_data_chunk(3, &[100], &mut conn).unwrap(); } assert_eq!(state.get_stream_ref(3).unwrap().body, vec![100]); { // Finally, the stream 1 ends... let mut session = ClientSession::new(&mut state, &mut sender); session.end_of_stream(1, &mut conn).unwrap(); } // ...and gets closed. assert!(state.get_stream_ref(1).unwrap().is_closed()); // but not the other one. assert!(!state.get_stream_ref(3).unwrap().is_closed()); // Sanity check: both streams still found in the session assert_eq!(state.iter().collect::<Vec<_>>().len(), 2); // The closed stream is returned... let closed = state.get_closed(); assert_eq!(closed.len(), 1); // ...and is also removed from the session! assert_eq!(state.iter().collect::<Vec<_>>().len(), 1); } /// Tests that the `ClientSession` notifies the correct stream when it is reset by the peer. #[test] fn test_client_session_on_rst_stream() { let mut state = DefaultSessionState::<ClientMarker, TestStream>::new(); state.insert_outgoing(TestStream::new()); state.insert_outgoing(TestStream::new()); let mut conn = build_mock_http_conn(); let mut sender = MockSendFrame::new(); { let mut session = ClientSession::new(&mut state, &mut sender); session.rst_stream(3, ErrorCode::Cancel, &mut conn).unwrap(); } assert!(state.get_stream_ref(3) .map(|stream| { stream.errors.len() == 1 && stream.errors[0] == ErrorCode::Cancel }) .unwrap()); assert!(state.get_stream_ref(1).map(|stream| stream.errors.len() == 0).unwrap()); } /// Tests that the `ClientSession` signals the correct error to client code when told to go /// away by the peer. #[test] fn test_client_session_on_goaway() { let mut state = DefaultSessionState::<ClientMarker, TestStream>::new(); let mut conn = build_mock_http_conn(); let mut sender = MockSendFrame::new(); let res = { let mut session = ClientSession::new(&mut state, &mut sender); session.on_goaway(0, ErrorCode::ProtocolError, None, &mut conn) }; if let Err(HttpError::PeerConnectionError(err)) = res { assert_eq!(err.error_code(), ErrorCode::ProtocolError); assert_eq!(err.debug_data(), None); } else { panic!("Expected a PeerConnectionError"); } } /// Tests that the `write_preface` function correctly writes a client preface to /// a given `io::Write`. #[test] fn test_write_preface() { // The buffer (`io::Write`) into which we will write the preface. let mut written: Vec<u8> = Vec::new(); // Do it... write_preface(&mut written).unwrap(); // The first bytes written to the underlying transport layer are the // preface bytes. let preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; let frames_buf = &written[preface.len()..]; // Immediately after that we sent a settings frame... assert_eq!(preface, &written[..preface.len()]); let raw = RawFrame::parse(frames_buf).unwrap(); let frame: SettingsFrame = Frame::from_raw(&raw).unwrap(); // ...which was not an ack, but our own settings. assert!(!frame.is_ack()); } }
package systems.opalia.commons.core.mathx def log(base: Double, value: Double): Double = math.log(value) / math.log(base) def digitCount(base: Double, value: Double): Int = math.floor(log(base, value)).toInt + 1 def round(value: Double, pos: Int): Double = { val factor = math.pow(10d, pos) math.round(factor * value) / factor } def floor(value: Double, pos: Int): Double = { val factor = math.pow(10d, pos) math.floor(factor * value) / factor } def ceil(value: Double, pos: Int): Double = { val factor = math.pow(10d, pos) math.ceil(factor * value) / factor } // normalize percent in interval [0, 1] def normalizePercent(value: Double): Double = math.max(0d, math.min(1d, value)) // normalize angle in interval [0,2π] def normalizeAngle1(value: Double): Double = { val angle = value % (2d * math.Pi) if (angle < 0d) angle + (2d * math.Pi) else angle } // normalize angle in interval [-π,+π] def normalizeAngle2(value: Double): Double = { val angle = value % (2d * math.Pi) if (angle > math.Pi) angle - 2d * math.Pi else if (angle < -math.Pi) angle + 2d * math.Pi else angle } // normalize angle in interval [-π/2,+π/2] def normalizeAngle3(value: Double): Double = { val x = if (math.abs(value) % (2d * math.Pi) > math.Pi) -1d else 1d val angle = value % math.Pi if (angle > math.Pi / 2d) (math.Pi - angle) * x else if (angle < -math.Pi / 2d) (-math.Pi - angle) * x else angle * x } def parseUnsignedLong(chars: Iterable[Char], radix: Int, numberOfBytes: Int): Long = { def getNumericValue(char: Char): Int = { val value = Character.getNumericValue(char) if (value < 0 || value >= radix) throw new NumberFormatException("A digit value is out of range.") value } if (chars.isEmpty) throw new NumberFormatException("Expect non empty sequence of characters.") if (radix < 2 || radix > 36) throw new NumberFormatException("The radix value is out of range.") if (numberOfBytes <= 0 || numberOfBytes > java.lang.Long.BYTES) throw new NumberFormatException("The number of allowed bytes is out of range.") val max = digitCount(radix, math.pow(2, numberOfBytes * 8) - 1) if (chars.size > max) throw new NumberFormatException("The characters sequence is too long.") chars.foldLeft(0L)((a, b) => a * radix + getNumericValue(b)) }
<?php /* * Copyright (C) 2018 OpenSIPS Project * * This file is part of opensips-cp, a free Web Control Panel Application for * OpenSIPS SIP server. * * opensips-cp is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * opensips-cp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ require("../../../common/cfg_comm.php"); require("template/header.php"); require("lib/".$page_id.".main.js"); require ("../../../common/mi_comm.php"); $table=$config->table_rtpengine; $current_page="current_page_rtpengine"; session_load(); include("lib/db_connect.php"); if (isset($_POST['action'])) $action=$_POST['action']; else if (isset($_GET['action'])) $action=$_GET['action']; else $action=""; if (isset($_GET['page'])) $_SESSION[$current_page]=$_GET['page']; else if (!isset($_SESSION[$current_page])) $_SESSION[$current_page]=1; ############################### # state change # ############################### if ($action=="change_state"){ $state= $_GET['state']; $sock = $_GET['sock']; $mi_connectors=get_proxys_by_assoc_id(get_value('talk_to_this_assoc_id')); for ($i=0;$i<count($mi_connectors);$i++) { if ($state=="0") { mi_command("rtpengine_enable",array("url"=>$sock,"enable"=> "0") , $mi_connectors[$i], $errors); } else { mi_command("rtpengine_enable",array("url"=>$sock,"enable"=> "1") , $mi_connectors[$i], $errors); } } } ################# # start add new # ################# if ($action=="add") { extract($_POST); if(!$_SESSION['read_only']) { require("template/".$page_id.".add.php"); require("template/footer.php"); exit(); }else { $errors= "User with Read-Only Rights"; } } ################# # end add new # ################# #################### # start add verify # #################### if ($action=="add_verify") { $info=""; $errors=""; if(!$_SESSION['read_only']){ $rtpengine_sock=$_POST['rtpengine_sock']; $set_id=$_POST['set_id']; $sql = "SELECT * FROM ".$table." WHERE set_id = ? AND socket = ?"; $stm = $link->prepare($sql); if ($stm->execute(array($set_id, $rtpengine_sock)) === false) die('Failed to issue query, error message : ' . print_r($stm->errorInfo(), true)); $row = $stm->fetchAll(); if (count($row)>0) { $errors="Duplicate RTPEngine entry"; } else { $sql_command = "INSERT INTO ".$table." (set_id, socket) VALUES (?, ?) "; $stm = $link->prepare($sql_command); if ($stm->execute(array($set_id, $rtpengine_sock)) === false) { $errors= "Inserting record into DB failed: ".print_r($stm->errorInfo(), true); } else { $info="The new RTPengine was added"; } } }else{ $errors= "User with Read-Only Rights"; } } ################## # end add verify # ################## ################# # start edit # ################# if ($action=="edit") { if(!$_SESSION['read_only']){ extract($_POST); require("template/".$page_id.".edit.php"); require("template/footer.php"); exit(); }else{ $errors= "User with Read-Only Rights"; } } ############# # end edit # ############# ################# # start modify # ################# if ($action=="modify") { $info=""; $errors=""; if(!$_SESSION['read_only']){ $set_id=$_POST['set_id']; $rtpengine_sock=$_POST['rtpengine_sock']; $id=$_GET['id']; $sql = "SELECT * FROM ".$table." WHERE set_id = ? AND socket = ? AND id != ?"; $stm = $link->prepare($sql); if ($stm->execute(array($set_id, $rtpengine_sock, $id)) === false) die('Failed to issue query, error message : ' . print_r($stm->errorInfo(), true)); $row = $stm->fetchAll(); if (count($row)>0) { $errors="Duplicate RTPEngine socket"; } else { $sql_command = "UPDATE ".$table." SET set_id = ?, socket = ? WHERE id = ?"; $stm = $link->prepare($sql_command); if ($stm->execute(array($set_id, $rtpengine_sock, $id)) === false) { $errors= "Updating record in DB failed: ".print_r($stm->errorInfo(), true); } else { $info="The RTPEngine socket was modified"; } } }else{ $errors= "User with Read-Only Rights"; } } ################# # end modify # ################# ################ # start delete # ################ if ($action=="delete") { if(!$_SESSION['read_only']){ $id=$_GET['id']; $sql = "DELETE FROM ".$table." WHERE id= ?"; $stm = $link->prepare($sql); if ($stm->execute(array($id)) === false) die('Failed to issue query, error message : ' . print_r($stm->errorInfo(), true)); }else{ $errors= "User with Read-Only Rights"; } } ############## # end delete # ############## ################ # start search # ################ if ($action=="search") { $query=""; $_SESSION['rtpengine_sock'] = $_POST['rtpengine_sock']; $_SESSION['rtpengine_setid']= $_POST['rtpengine_setid']; $_SESSION[$current_page]=1; extract($_POST); if ($show_all=="Show All") { $_SESSION['rtpengine_setid']=""; $_SESSION['rtpengine_sock']=""; } else if($search=="Search"){ $_SESSION['rtpengine_setid']=$_POST['rtpengine_setid']; $_SESSION['rtpengine_sock'] =$_POST['rtpengine_sock']; } else if($_SESSION['read_only']){ $errors= "User with Read-Only Rights"; }else if ($delete=="Delete RTPproxy Sock"){ $set_id = $_POST['rtpengine_setid']; $rtpengine_sock = $_POST['rtpengine_sock']; $qvalues = array(); if($rtpengine_sock =="") { $query .= " AND socket LIKE %"; }else { $query .= " AND socket LIKE ?"; $qvalues[] = "%" . $rtpengine_sock . "%"; } if ($set_id!=""){ $query .= " AND set_id = ?"; $qvalues[] = $set_id; } $sql = "SELECT * FROM " . $table . " WHERE (1=1) " . $query; $stm = $link->prepare($sql); if ($stm->execute($qvalues) === false) die('Failed to issue query, error message : ' . print_r($stm->errorInfo(), true)); $row = $stm->fetchAll(); if (count($row)==0) { $errors="No Rule with such RTPEngine Sock ID"; $_SESSION['rtpengine_setid']=""; $_SESSION['rtpengine_sock']=""; }else{ $sql = "DELETE FROM ".$table." WHERE (1=1) " .$query; $stm = $link->prepare($sql); if ($stm->execute($qvalues) === false) die('Failed to issue query, error message : ' . print_r($stm->errorInfo(), true)); } print $result; } } ############## # end search # ############## ############## # start main # ############## require("template/".$page_id.".main.php"); if (!empty($errors)) { echo "Error stack: "; print_r($errors); } require("template/footer.php"); exit(); ############## # end main # ############## ?>
class AdminRole include Mongoid::Document include Mongoid::Timestamps has_many :users end
<?php namespace app\modules\rbac\controllers; use yii\rbac\Item; use yii2mod\rbac\base\ItemController; use amnah\yii2\user\models\Role; use Yii; use yii2mod\rbac\models\AuthItemModel; use yii\db\IntegrityException; /** * Class RoleController * * @package yii2mod\rbac\controllers */ class RoleController extends ItemController { /** * @var int */ protected $type = Item::TYPE_ROLE; /** * @var array */ protected $labels = [ 'Item' => 'Role', 'Items' => 'Roles', ]; public function actionCreate() { $model = new AuthItemModel(); $model->type = $this->type; if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', Yii::t('yii2mod.rbac', 'Role has been saved.')); //role $this->insertOrUpdateToRoleTable($model->name); return $this->redirect(['view', 'id' => $model->name]); } return $this->render('create', ['model' => $model]); } public function actionUpdate($id) { $model = $this->findModel($id); $oldRole = $model->name; if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', Yii::t('yii2mod.rbac', 'Role has been saved.')); //role $this->insertOrUpdateToRoleTable($model->name,$oldRole); return $this->redirect(['index']); } return $this->render('update', ['model' => $model]); } public function actionDelete($id) { $model = $this->findModel($id); $roleName = $model->name; try{ $this->deleteRole($roleName); Yii::$app->getAuthManager()->remove($model->item); Yii::$app->session->setFlash('success', Yii::t('yii2mod.rbac', 'Role has been deleted.')); }catch (IntegrityException $e){ Yii::$app->session->setFlash('error', Yii::t('yii2mod.rbac', 'Role cannot be deleted!')); return $this->redirect(Yii::$app->request->getReferrer()); } return $this->redirect(['index']); } /** * role table * @param $newRole * @param string $oldRole */ public function insertOrUpdateToRoleTable($newRole,$oldRole="") { $should = 0;//1=insert,2=update,0=nothing to do $role = null; if($oldRole){ $role = Role::find()->where(['name'=>$oldRole])->one(); if(!$role){ $role = Role::find()->where(['name'=>$newRole])->one(); if(!$role){ $should = 1; } }else{ $should = 2; } }else{ $role = Role::find()->where(['name'=>$newRole])->one(); if(!$role){ $should = 1; } } switch ($should){ case 1: $role = new Role; $role->name = $newRole; $role->created_at = date("Y-m-d H:i:s",time()); $role->can_admin = 0; $role->save(); break; case 2: $role->name = $newRole; $role->updated_at = date("Y-m-d H:i:s",time()); $role->save(); break; } } public function deleteRole($roleName) { $role = Role::find()->where(['name'=>$roleName])->one(); if($role)$role->delete(); } }
--- layout: post title: "[Python] Jupiter Notebook을 이용한 파이썬의 리스트와 튜플에 대한 간단한 설명" subtitle: "파이썬 리스트와 튜플의 사용" categories: dev tags: python comments: true --- > 파이썬의 튜플과 리스트를 쥬피터 노트북을 통해서 복습 ## 파이썬의 리스트와 튜플 ### 파이썬의 리스트와 튜플 + 리스트:변경가능[] + 튜플 : 변경불가능() ```python ## (1) 22, 44, 11 요소의 리스트 a_data 생성 ## (2) 길자, 길동, 길길 요소의 튜플 b_data생성 ## (3) b_data 튜플을 a_data 리스트에 추가 a_data = [22,44,11] b_data = ('길자','길동','길길') a_data.append(b_data) a_data ``` [22, 44, 11, ('길자', '길동', '길길')] ```python ## (4) b_data에서 2번째 요소까지 출력 b_data[:2] ``` ('길자', '길동') ```python ## (5) a_data를 튜플로 변경 ## 11을 10으로 변경하려면? a_data[2]=10 c_data=tuple(a_data) print(c_data) ``` (22, 44, 10, ('길자', '길동', '길길')) ## 리스트 복습 - append(추가요소) : 리스트 맨 마지막에 하나 추가 - pop() : 마지막요소를 지움 - extend([추가요소들]) : 리스트 마지막에 여러 개 추가 - remove('요소값') : 해당 요소값 지움 --- - insert(idx, '데이타') : 원하는 위치에 자료 삽입 --- [슬라이싱] - 리스트명(n:m) : n부터 m-1까지 데이타 추출 ```python movies = ['어밴져스','기생충','가디언스갤럭시','어떤영화','유명한 영화'] movies ``` ['어밴져스', '기생충', '가디언스갤럭시', '어떤영화', '유명한 영화'] (1) '어젠져스2' 추가 ```python movies.append('어젠져스2') movies ``` ['어밴져스', '기생충', '가디언스갤럭시', '어떤영화', '유명한 영화', '어젠져스2'] (2) 마지막요소 제거 ```python del movies[-1] movies ``` ['어밴져스', '기생충', '가디언스갤럭시', '어떤영화', '유명한 영화'] (3) '어벤져스2','기생충2' 요소를 한꺼번에 추가 ```python movies+['어벤져스2','기생충2'] ``` ['어밴져스', '기생충', '가디언스갤럭시', '어떤영화', '유명한 영화', '어벤져스2', '기생충2'] (4) '어벤져스2' 요소 제거 ```python del movies[5] ``` --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-8-82c9fc387d92> in <module> ----> 1 del movies[5] IndexError: list assignment index out of range (5) 4번째 위치에 '오래된 영화' 추가 ```python movies.insert(4,'오래된영화') movies ``` ['어밴져스', '기생충', '가디언스갤럭시', '어떤영화', '오래된영화', '유명한 영화'] (6) 영화목록에서 3번째에서 5번째까지 추출 ```python movies[3:6] ``` ['어떤영화', '오래된영화', '유명한 영화']
// run-fail // error-pattern:quux // ignore-emscripten no processes fn foo() -> ! { panic!("quux"); } fn main() { foo() == foo(); // these types wind up being defaulted to () }
/*---------------------------------------------------------------- // auth: Windragon // date: 2018 // desc: None // mdfy: None //----------------------------------------------------------------*/ using System; using System.Drawing; namespace WLib.Data.Calculate { /// <summary> /// 提供角度的相关操作 /// </summary> public class AngleCalculate { /// <summary> ///获取已知三点构成的角的弧度 /// </summary> /// <param name="center">中间点,即角的顶点</param> /// <param name="first">角的一个端点</param> /// <param name="second">角的另一个端点</param> /// <returns></returns> public static float GetRadian(Point center, Point first, Point second) { float dx1 = first.X - center.X; float dy1 = first.Y - center.Y; float dx2 = second.X - center.X; float dy2 = second.Y - center.Y; float c = (float)Math.Sqrt(dx1 * dx1 + dy1 * dy1) * (float)Math.Sqrt(dx2 * dx2 + dy2 * dy2); if (c == 0) return -1; return (float)Math.Acos((dx1 * dx2 + dy1 * dy2) / c); } /// <summary> /// 获取已知三点构成的角度 /// </summary> /// <param name="center">中间点,即角的顶点</param> /// <param name="first">角的一个端点</param> /// <param name="second">角的另一个端点</param> /// <returns></returns> public static float GetAngle(Point center, Point first, Point second) => GetRadian(center, first, second) * 180f / (float)Math.PI; } }
RailsCldr::Engine.routes.draw do namespace :numbers do scope "(:locale)", :locale => /#{RailsCldr::Engine.config.locales[:numbers].join("|")}/ do resource :currencies, format: :json, only: :show resource :numbers, format: :json, only: :show end end namespace :calendars do scope "(:locale)", :locale => /#{RailsCldr::Engine.config.locales[:numbers].join("|")}/ do resource :gregorians, format: :json, only: :show end end namespace :supplemental do resource :likely_subtags, format: :json, only: :show resource :time_data, format: :json, only: :show resource :week_data, format: :json, only: :show resource :currency_data, format: :json, only: :show resource :numbering_systems, format: :json, only: :show end end
<?php namespace Concerto\PanelBundle\Repository; /** * MessageRepository */ class MessageRepository extends AEntityRepository { }
package com.mysugr.sweetest.framework.base import com.mysugr.sweetest.framework.context.DependenciesTestContext import com.mysugr.sweetest.framework.context.StepsTestContext import com.mysugr.sweetest.internal.Steps import com.mysugr.sweetest.usecases.getDependencyDelegate import com.mysugr.sweetest.usecases.getStepsDelegate import dev.sweetest.internal.SweetestIntegrationsApi import dev.sweetest.internal.TestContext import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KClass @SweetestIntegrationsApi abstract class CommonBase : com.mysugr.sweetest.internal.TestElement { internal abstract val testContext: TestContext } // --- region: Public API (the following inline functions should just be wrappers over implementation functions!) inline fun <reified T : Any> CommonBase.dependency(): ReadOnlyProperty<CommonBase, T> = dependencyInternal(this, T::class) inline fun <reified T : Steps> CommonBase.steps(): ReadOnlyProperty<CommonBase, T> = stepsInternal(this, T::class) // --- region: Internal API @PublishedApi internal fun <T : Any> dependencyInternal(scope: CommonBase, type: KClass<T>): ReadOnlyProperty<CommonBase, T> = getDependencyDelegate(scope.testContext[DependenciesTestContext], type) @PublishedApi internal fun <T : Steps> stepsInternal(scope: CommonBase, type: KClass<T>): ReadOnlyProperty<CommonBase, T> = getStepsDelegate(scope.testContext[StepsTestContext], type)
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto package com.google.container.v1; public interface HttpLoadBalancingOrBuilder extends // @@protoc_insertion_point(interface_extends:google.container.v1.HttpLoadBalancing) com.google.protobuf.MessageOrBuilder { /** * <pre> * Whether the HTTP Load Balancing controller is enabled in the cluster. * When enabled, it runs a small pod in the cluster that manages the load * balancers. * </pre> * * <code>bool disabled = 1;</code> * @return The disabled. */ boolean getDisabled(); }
import {seq, opt, tok, star, alt, Expression, IStatementRunnable} from "../combi"; import {InstanceArrow, StaticArrow} from "../tokens/"; import {NewObject, ArrowOrDash, ComponentName, FieldChain, MethodCall, Cast} from "./"; import {ClassName} from "./class_name"; export class MethodCallChain extends Expression { public getRunnable(): IStatementRunnable { const fields = star(seq(new ArrowOrDash(), new ComponentName())); const after = star(seq(fields, tok(InstanceArrow), new MethodCall())); const localVariable = seq(new FieldChain(), tok(InstanceArrow)); const staticClass = seq(new ClassName(), tok(StaticArrow)); const ret = seq(alt(seq(opt(alt(localVariable, staticClass)), new MethodCall()), new NewObject(), new Cast()), after); return ret; } }
#启动管理后台前端 cd litemall-admin cnpm run dev cd ..
module load perl module load stajichlab module load maker/2.31.8 module load snap module load augustus/2.7 mkdir retrain ln -s ../MAKER/Mn35.all.functional.gff mkdir snap cd snap #maker2zff Mn35.all.functional.gff maker2zff -c 0 -e 0 Mn35.all.functional.gff fathom -categorize 1000 genome.ann genome.dna fathom -export 1000 -plus uni.ann uni.dna forge export.ann export.dna hmm-assembler.pl Mn35.retrain . > ../Mn35.retrain.hmm hmm-assembler.pl -x Mn35.retrain . > ../Mn35.retrain.length.hmm
import 'package:gssuite/apis/api.dart'; import 'package:url_launcher/url_launcher.dart'; mailto() async { final url = mail; if (await canLaunch(url)) { await launch(url); } else { throw 'Could not launch'; } }
#!/usr/bin/env bash cd "$(dirname "$0")" || exit 10 rm -r ./dist rm -r ./build python setup.py sdist bdist_wheel || exit 13 echo "Do you want to install package? (y|Y to install)" read answer if [[ "$answer" == "y" || "$answer" == "Y" ]] then pip install "$(ls ./dist/*.whl)" fi
#!/bin/bash SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" if [ -z "$1" ] then echo "Need parameter with git repo url" exit -1 fi echo "$1 -> $($SCRIPTDIR/../repo-to-pipeline.sh $1)"
package Catalyst::Model::Factory::PerRequest; use strict; use warnings; use MRO::Compat; use base 'Catalyst::Model::Factory'; our $VERSION = '0.10'; sub ACCEPT_CONTEXT { my ($self, $context, @args) = @_; my $id = '__'. ref $self; return $context->stash->{$id} ||= $self->next::method($context, @args); } 1; __END__ =head1 NAME Catalyst::Model::Factory::PerRequest - use a plain class as a Catalyst model, instantiating it once per Catalyst request =head1 SYNOPSIS This module works just like L<Catalyst::Model::Factory|Catalyst::Model::Factory>, except that a fresh instance of your adapted class is once per Catalyst request, not every time you ask for the object via C<< $c->model >>. =head1 CUSTOMIZING You can customize your subclass just like L<Catalyst::Model::Adaptor|Catalyst::Model::Adaptor>. Instead of C<$app>, though, you'll get C<$c>, the current request context. =head1 METHODS These methods are called by Catalyst, not by you: =head2 COMPONENT Load your class =head2 ACCEPT_CONTEXT Create an instance of your class and return it. =head1 SEE ALSO For all the critical documentation, see L<Catalyst::Model::Adaptor>.
// SPDX-License-Identifier: GPL-2.0-only #include <linux/clk.h> #include <linux/err.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/phy/phy.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/regmap.h> #include <linux/mfd/syscon.h> /* USB QSCRATCH Hardware registers */ #define QSCRATCH_GENERAL_CFG (0x08) #define HSUSB_PHY_CTRL_REG (0x10) /* PHY_CTRL_REG */ #define HSUSB_CTRL_DMSEHV_CLAMP BIT(24) #define HSUSB_CTRL_USB2_SUSPEND BIT(23) #define HSUSB_CTRL_UTMI_CLK_EN BIT(21) #define HSUSB_CTRL_UTMI_OTG_VBUS_VALID BIT(20) #define HSUSB_CTRL_USE_CLKCORE BIT(18) #define HSUSB_CTRL_DPSEHV_CLAMP BIT(17) #define HSUSB_CTRL_COMMONONN BIT(11) #define HSUSB_CTRL_ID_HV_CLAMP BIT(9) #define HSUSB_CTRL_OTGSESSVLD_CLAMP BIT(8) #define HSUSB_CTRL_CLAMP_EN BIT(7) #define HSUSB_CTRL_RETENABLEN BIT(1) #define HSUSB_CTRL_POR BIT(0) /* QSCRATCH_GENERAL_CFG */ #define HSUSB_GCFG_XHCI_REV BIT(2) /* USB QSCRATCH Hardware registers */ #define SSUSB_PHY_CTRL_REG (0x00) #define SSUSB_PHY_PARAM_CTRL_1 (0x04) #define SSUSB_PHY_PARAM_CTRL_2 (0x08) #define CR_PROTOCOL_DATA_IN_REG (0x0c) #define CR_PROTOCOL_DATA_OUT_REG (0x10) #define CR_PROTOCOL_CAP_ADDR_REG (0x14) #define CR_PROTOCOL_CAP_DATA_REG (0x18) #define CR_PROTOCOL_READ_REG (0x1c) #define CR_PROTOCOL_WRITE_REG (0x20) /* PHY_CTRL_REG */ #define SSUSB_CTRL_REF_USE_PAD BIT(28) #define SSUSB_CTRL_TEST_POWERDOWN BIT(27) #define SSUSB_CTRL_LANE0_PWR_PRESENT BIT(24) #define SSUSB_CTRL_SS_PHY_EN BIT(8) #define SSUSB_CTRL_SS_PHY_RESET BIT(7) /* SSPHY control registers - Does this need 0x30? */ #define SSPHY_CTRL_RX_OVRD_IN_HI(lane) (0x1006 + 0x100 * (lane)) #define SSPHY_CTRL_TX_OVRD_DRV_LO(lane) (0x1002 + 0x100 * (lane)) /* SSPHY SoC version specific values */ #define SSPHY_RX_EQ_VALUE 4 /* Override value for rx_eq */ /* Override value for transmit preemphasis */ #define SSPHY_TX_DEEMPH_3_5DB 23 /* Override value for mpll */ #define SSPHY_MPLL_VALUE 0 /* QSCRATCH PHY_PARAM_CTRL1 fields */ #define PHY_PARAM_CTRL1_TX_FULL_SWING_MASK GENMASK(26, 19) #define PHY_PARAM_CTRL1_TX_DEEMPH_6DB_MASK GENMASK(19, 13) #define PHY_PARAM_CTRL1_TX_DEEMPH_3_5DB_MASK GENMASK(13, 7) #define PHY_PARAM_CTRL1_LOS_BIAS_MASK GENMASK(7, 2) #define PHY_PARAM_CTRL1_MASK \ (PHY_PARAM_CTRL1_TX_FULL_SWING_MASK | \ PHY_PARAM_CTRL1_TX_DEEMPH_6DB_MASK | \ PHY_PARAM_CTRL1_TX_DEEMPH_3_5DB_MASK | \ PHY_PARAM_CTRL1_LOS_BIAS_MASK) #define PHY_PARAM_CTRL1_TX_FULL_SWING(x) \ (((x) << 20) & PHY_PARAM_CTRL1_TX_FULL_SWING_MASK) #define PHY_PARAM_CTRL1_TX_DEEMPH_6DB(x) \ (((x) << 14) & PHY_PARAM_CTRL1_TX_DEEMPH_6DB_MASK) #define PHY_PARAM_CTRL1_TX_DEEMPH_3_5DB(x) \ (((x) << 8) & PHY_PARAM_CTRL1_TX_DEEMPH_3_5DB_MASK) #define PHY_PARAM_CTRL1_LOS_BIAS(x) \ (((x) << 3) & PHY_PARAM_CTRL1_LOS_BIAS_MASK) /* RX OVRD IN HI bits */ #define RX_OVRD_IN_HI_RX_RESET_OVRD BIT(13) #define RX_OVRD_IN_HI_RX_RX_RESET BIT(12) #define RX_OVRD_IN_HI_RX_EQ_OVRD BIT(11) #define RX_OVRD_IN_HI_RX_EQ_MASK GENMASK(10, 7) #define RX_OVRD_IN_HI_RX_EQ(x) ((x) << 8) #define RX_OVRD_IN_HI_RX_EQ_EN_OVRD BIT(7) #define RX_OVRD_IN_HI_RX_EQ_EN BIT(6) #define RX_OVRD_IN_HI_RX_LOS_FILTER_OVRD BIT(5) #define RX_OVRD_IN_HI_RX_LOS_FILTER_MASK GENMASK(4, 2) #define RX_OVRD_IN_HI_RX_RATE_OVRD BIT(2) #define RX_OVRD_IN_HI_RX_RATE_MASK GENMASK(2, 0) /* TX OVRD DRV LO register bits */ #define TX_OVRD_DRV_LO_AMPLITUDE_MASK GENMASK(6, 0) #define TX_OVRD_DRV_LO_PREEMPH_MASK GENMASK(13, 6) #define TX_OVRD_DRV_LO_PREEMPH(x) ((x) << 7) #define TX_OVRD_DRV_LO_EN BIT(14) /* MPLL bits */ #define SSPHY_MPLL_MASK GENMASK(8, 5) #define SSPHY_MPLL(x) ((x) << 5) /* SS CAP register bits */ #define SS_CR_CAP_ADDR_REG BIT(0) #define SS_CR_CAP_DATA_REG BIT(0) #define SS_CR_READ_REG BIT(0) #define SS_CR_WRITE_REG BIT(0) struct usb_phy { void __iomem *base; struct device *dev; struct clk *xo_clk; struct clk *ref_clk; u32 rx_eq; u32 tx_deamp_3_5db; u32 mpll; }; struct phy_drvdata { struct phy_ops ops; u32 clk_rate; }; /** * Write register and read back masked value to confirm it is written * * @base - QCOM DWC3 PHY base virtual address. * @offset - register offset. * @mask - register bitmask specifying what should be updated * @val - value to write. */ static inline void usb_phy_write_readback(struct usb_phy *phy_dwc3, u32 offset, const u32 mask, u32 val) { u32 write_val, tmp = readl(phy_dwc3->base + offset); tmp &= ~mask; /* retain other bits */ write_val = tmp | val; writel(write_val, phy_dwc3->base + offset); /* Read back to see if val was written */ tmp = readl(phy_dwc3->base + offset); tmp &= mask; /* clear other bits */ if (tmp != val) dev_err(phy_dwc3->dev, "write: %x to QSCRATCH: %x FAILED\n", val, offset); } static int wait_for_latch(void __iomem *addr) { u32 retry = 10; while (true) { if (!readl(addr)) break; if (--retry == 0) return -ETIMEDOUT; usleep_range(10, 20); } return 0; } /** * Write SSPHY register * * @base - QCOM DWC3 PHY base virtual address. * @addr - SSPHY address to write. * @val - value to write. */ static int usb_ss_write_phycreg(struct usb_phy *phy_dwc3, u32 addr, u32 val) { int ret; writel(addr, phy_dwc3->base + CR_PROTOCOL_DATA_IN_REG); writel(SS_CR_CAP_ADDR_REG, phy_dwc3->base + CR_PROTOCOL_CAP_ADDR_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_CAP_ADDR_REG); if (ret) goto err_wait; writel(val, phy_dwc3->base + CR_PROTOCOL_DATA_IN_REG); writel(SS_CR_CAP_DATA_REG, phy_dwc3->base + CR_PROTOCOL_CAP_DATA_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_CAP_DATA_REG); if (ret) goto err_wait; writel(SS_CR_WRITE_REG, phy_dwc3->base + CR_PROTOCOL_WRITE_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_WRITE_REG); err_wait: if (ret) dev_err(phy_dwc3->dev, "timeout waiting for latch\n"); return ret; } /** * Read SSPHY register. * * @base - QCOM DWC3 PHY base virtual address. * @addr - SSPHY address to read. */ static int usb_ss_read_phycreg(struct usb_phy *phy_dwc3, u32 addr, u32 *val) { int ret; writel(addr, phy_dwc3->base + CR_PROTOCOL_DATA_IN_REG); writel(SS_CR_CAP_ADDR_REG, phy_dwc3->base + CR_PROTOCOL_CAP_ADDR_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_CAP_ADDR_REG); if (ret) goto err_wait; /* * Due to hardware bug, first read of SSPHY register might be * incorrect. Hence as workaround, SW should perform SSPHY register * read twice, but use only second read and ignore first read. */ writel(SS_CR_READ_REG, phy_dwc3->base + CR_PROTOCOL_READ_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_READ_REG); if (ret) goto err_wait; /* throwaway read */ readl(phy_dwc3->base + CR_PROTOCOL_DATA_OUT_REG); writel(SS_CR_READ_REG, phy_dwc3->base + CR_PROTOCOL_READ_REG); ret = wait_for_latch(phy_dwc3->base + CR_PROTOCOL_READ_REG); if (ret) goto err_wait; *val = readl(phy_dwc3->base + CR_PROTOCOL_DATA_OUT_REG); err_wait: return ret; } static int qcom_ipq806x_usb_hs_phy_init(struct phy *phy) { struct usb_phy *phy_dwc3 = phy_get_drvdata(phy); int ret; u32 val; ret = clk_prepare_enable(phy_dwc3->xo_clk); if (ret) return ret; ret = clk_prepare_enable(phy_dwc3->ref_clk); if (ret) { clk_disable_unprepare(phy_dwc3->xo_clk); return ret; } /* * HSPHY Initialization: Enable UTMI clock, select 19.2MHz fsel * enable clamping, and disable RETENTION (power-on default is ENABLED) */ val = HSUSB_CTRL_DPSEHV_CLAMP | HSUSB_CTRL_DMSEHV_CLAMP | HSUSB_CTRL_RETENABLEN | HSUSB_CTRL_COMMONONN | HSUSB_CTRL_OTGSESSVLD_CLAMP | HSUSB_CTRL_ID_HV_CLAMP | HSUSB_CTRL_DPSEHV_CLAMP | HSUSB_CTRL_UTMI_OTG_VBUS_VALID | HSUSB_CTRL_UTMI_CLK_EN | HSUSB_CTRL_CLAMP_EN | 0x70; /* use core clock if external reference is not present */ if (!phy_dwc3->xo_clk) val |= HSUSB_CTRL_USE_CLKCORE; writel(val, phy_dwc3->base + HSUSB_PHY_CTRL_REG); usleep_range(2000, 2200); /* Disable (bypass) VBUS and ID filters */ writel(HSUSB_GCFG_XHCI_REV, phy_dwc3->base + QSCRATCH_GENERAL_CFG); return 0; } static int qcom_ipq806x_usb_hs_phy_exit(struct phy *phy) { struct usb_phy *phy_dwc3 = phy_get_drvdata(phy); clk_disable_unprepare(phy_dwc3->ref_clk); clk_disable_unprepare(phy_dwc3->xo_clk); return 0; } static int qcom_ipq806x_usb_ss_phy_init(struct phy *phy) { struct usb_phy *phy_dwc3 = phy_get_drvdata(phy); int ret; u32 data; ret = clk_prepare_enable(phy_dwc3->xo_clk); if (ret) return ret; ret = clk_prepare_enable(phy_dwc3->ref_clk); if (ret) { clk_disable_unprepare(phy_dwc3->xo_clk); return ret; } /* reset phy */ data = readl(phy_dwc3->base + SSUSB_PHY_CTRL_REG); writel(data | SSUSB_CTRL_SS_PHY_RESET, phy_dwc3->base + SSUSB_PHY_CTRL_REG); usleep_range(2000, 2200); writel(data, phy_dwc3->base + SSUSB_PHY_CTRL_REG); /* clear REF_PAD if we don't have XO clk */ if (!phy_dwc3->xo_clk) data &= ~SSUSB_CTRL_REF_USE_PAD; else data |= SSUSB_CTRL_REF_USE_PAD; writel(data, phy_dwc3->base + SSUSB_PHY_CTRL_REG); /* wait for ref clk to become stable, this can take up to 30ms */ msleep(30); data |= SSUSB_CTRL_SS_PHY_EN | SSUSB_CTRL_LANE0_PWR_PRESENT; writel(data, phy_dwc3->base + SSUSB_PHY_CTRL_REG); /* * WORKAROUND: There is SSPHY suspend bug due to which USB enumerates * in HS mode instead of SS mode. Workaround it by asserting * LANE0.TX_ALT_BLOCK.EN_ALT_BUS to enable TX to use alt bus mode */ ret = usb_ss_read_phycreg(phy_dwc3, 0x102D, &data); if (ret) goto err_phy_trans; data |= (1 << 7); ret = usb_ss_write_phycreg(phy_dwc3, 0x102D, data); if (ret) goto err_phy_trans; ret = usb_ss_read_phycreg(phy_dwc3, 0x1010, &data); if (ret) goto err_phy_trans; data &= ~0xff0; data |= 0x20; ret = usb_ss_write_phycreg(phy_dwc3, 0x1010, data); if (ret) goto err_phy_trans; /* * Fix RX Equalization setting as follows * LANE0.RX_OVRD_IN_HI. RX_EQ_EN set to 0 * LANE0.RX_OVRD_IN_HI.RX_EQ_EN_OVRD set to 1 * LANE0.RX_OVRD_IN_HI.RX_EQ set based on SoC version * LANE0.RX_OVRD_IN_HI.RX_EQ_OVRD set to 1 */ ret = usb_ss_read_phycreg(phy_dwc3, SSPHY_CTRL_RX_OVRD_IN_HI(0), &data); if (ret) goto err_phy_trans; data &= ~RX_OVRD_IN_HI_RX_EQ_EN; data |= RX_OVRD_IN_HI_RX_EQ_EN_OVRD; data &= ~RX_OVRD_IN_HI_RX_EQ_MASK; data |= RX_OVRD_IN_HI_RX_EQ(phy_dwc3->rx_eq); data |= RX_OVRD_IN_HI_RX_EQ_OVRD; ret = usb_ss_write_phycreg(phy_dwc3, SSPHY_CTRL_RX_OVRD_IN_HI(0), data); if (ret) goto err_phy_trans; /* * Set EQ and TX launch amplitudes as follows * LANE0.TX_OVRD_DRV_LO.PREEMPH set based on SoC version * LANE0.TX_OVRD_DRV_LO.AMPLITUDE set to 110 * LANE0.TX_OVRD_DRV_LO.EN set to 1. */ ret = usb_ss_read_phycreg(phy_dwc3, SSPHY_CTRL_TX_OVRD_DRV_LO(0), &data); if (ret) goto err_phy_trans; data &= ~TX_OVRD_DRV_LO_PREEMPH_MASK; data |= TX_OVRD_DRV_LO_PREEMPH(phy_dwc3->tx_deamp_3_5db); data &= ~TX_OVRD_DRV_LO_AMPLITUDE_MASK; data |= 0x6E; data |= TX_OVRD_DRV_LO_EN; ret = usb_ss_write_phycreg(phy_dwc3, SSPHY_CTRL_TX_OVRD_DRV_LO(0), data); if (ret) goto err_phy_trans; data = 0; data &= ~SSPHY_MPLL_MASK; data |= SSPHY_MPLL(phy_dwc3->mpll); usb_ss_write_phycreg(phy_dwc3, 0x30, data); /* * Set the QSCRATCH PHY_PARAM_CTRL1 parameters as follows * TX_FULL_SWING [26:20] amplitude to 110 * TX_DEEMPH_6DB [19:14] to 32 * TX_DEEMPH_3_5DB [13:8] set based on SoC version * LOS_BIAS [7:3] to 9 */ data = readl(phy_dwc3->base + SSUSB_PHY_PARAM_CTRL_1); data &= ~PHY_PARAM_CTRL1_MASK; data |= PHY_PARAM_CTRL1_TX_FULL_SWING(0x6e) | PHY_PARAM_CTRL1_TX_DEEMPH_6DB(0x20) | PHY_PARAM_CTRL1_TX_DEEMPH_3_5DB(phy_dwc3->tx_deamp_3_5db) | PHY_PARAM_CTRL1_LOS_BIAS(0x9); usb_phy_write_readback(phy_dwc3, SSUSB_PHY_PARAM_CTRL_1, PHY_PARAM_CTRL1_MASK, data); err_phy_trans: return ret; } static int qcom_ipq806x_usb_ss_phy_exit(struct phy *phy) { struct usb_phy *phy_dwc3 = phy_get_drvdata(phy); /* Sequence to put SSPHY in low power state: * 1. Clear REF_PHY_EN in PHY_CTRL_REG * 2. Clear REF_USE_PAD in PHY_CTRL_REG * 3. Set TEST_POWERED_DOWN in PHY_CTRL_REG to enable PHY retention */ usb_phy_write_readback(phy_dwc3, SSUSB_PHY_CTRL_REG, SSUSB_CTRL_SS_PHY_EN, 0x0); usb_phy_write_readback(phy_dwc3, SSUSB_PHY_CTRL_REG, SSUSB_CTRL_REF_USE_PAD, 0x0); usb_phy_write_readback(phy_dwc3, SSUSB_PHY_CTRL_REG, SSUSB_CTRL_TEST_POWERDOWN, 0x0); clk_disable_unprepare(phy_dwc3->ref_clk); clk_disable_unprepare(phy_dwc3->xo_clk); return 0; } static const struct phy_drvdata qcom_ipq806x_usb_hs_drvdata = { .ops = { .init = qcom_ipq806x_usb_hs_phy_init, .exit = qcom_ipq806x_usb_hs_phy_exit, .owner = THIS_MODULE, }, .clk_rate = 60000000, }; static const struct phy_drvdata qcom_ipq806x_usb_ss_drvdata = { .ops = { .init = qcom_ipq806x_usb_ss_phy_init, .exit = qcom_ipq806x_usb_ss_phy_exit, .owner = THIS_MODULE, }, .clk_rate = 125000000, }; static const struct of_device_id qcom_ipq806x_usb_phy_table[] = { { .compatible = "qcom,ipq806x-usb-phy-hs", .data = &qcom_ipq806x_usb_hs_drvdata }, { .compatible = "qcom,ipq806x-usb-phy-ss", .data = &qcom_ipq806x_usb_ss_drvdata }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, qcom_ipq806x_usb_phy_table); static int qcom_ipq806x_usb_phy_probe(struct platform_device *pdev) { struct resource *res; resource_size_t size; struct phy *generic_phy; struct usb_phy *phy_dwc3; const struct phy_drvdata *data; struct phy_provider *phy_provider; phy_dwc3 = devm_kzalloc(&pdev->dev, sizeof(*phy_dwc3), GFP_KERNEL); if (!phy_dwc3) return -ENOMEM; data = of_device_get_match_data(&pdev->dev); phy_dwc3->dev = &pdev->dev; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -EINVAL; size = resource_size(res); phy_dwc3->base = devm_ioremap(phy_dwc3->dev, res->start, size); if (!phy_dwc3->base) { dev_err(phy_dwc3->dev, "failed to map reg\n"); return -ENOMEM; } phy_dwc3->ref_clk = devm_clk_get(phy_dwc3->dev, "ref"); if (IS_ERR(phy_dwc3->ref_clk)) { dev_dbg(phy_dwc3->dev, "cannot get reference clock\n"); return PTR_ERR(phy_dwc3->ref_clk); } clk_set_rate(phy_dwc3->ref_clk, data->clk_rate); phy_dwc3->xo_clk = devm_clk_get(phy_dwc3->dev, "xo"); if (IS_ERR(phy_dwc3->xo_clk)) { dev_dbg(phy_dwc3->dev, "cannot get TCXO clock\n"); phy_dwc3->xo_clk = NULL; } /* Parse device node to probe HSIO settings */ if (device_property_read_u32(&pdev->dev, "qcom,rx-eq", &phy_dwc3->rx_eq)) phy_dwc3->rx_eq = SSPHY_RX_EQ_VALUE; if (device_property_read_u32(&pdev->dev, "qcom,tx-deamp_3_5db", &phy_dwc3->tx_deamp_3_5db)) phy_dwc3->tx_deamp_3_5db = SSPHY_TX_DEEMPH_3_5DB; if (device_property_read_u32(&pdev->dev, "qcom,mpll", &phy_dwc3->mpll)) phy_dwc3->mpll = SSPHY_MPLL_VALUE; generic_phy = devm_phy_create(phy_dwc3->dev, pdev->dev.of_node, &data->ops); if (IS_ERR(generic_phy)) return PTR_ERR(generic_phy); phy_set_drvdata(generic_phy, phy_dwc3); platform_set_drvdata(pdev, phy_dwc3); phy_provider = devm_of_phy_provider_register(phy_dwc3->dev, of_phy_simple_xlate); if (IS_ERR(phy_provider)) return PTR_ERR(phy_provider); return 0; } static struct platform_driver qcom_ipq806x_usb_phy_driver = { .probe = qcom_ipq806x_usb_phy_probe, .driver = { .name = "qcom-ipq806x-usb-phy", .of_match_table = qcom_ipq806x_usb_phy_table, }, }; module_platform_driver(qcom_ipq806x_usb_phy_driver); MODULE_ALIAS("platform:phy-qcom-ipq806x-usb"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Andy Gross <agross@codeaurora.org>"); MODULE_AUTHOR("Ivan T. Ivanov <iivanov@mm-sol.com>"); MODULE_DESCRIPTION("DesignWare USB3 QCOM PHY driver");
-- phpMyAdmin SQL Dump -- version 4.2.7 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 06, 2015 at 06:17 AM -- Server version: 10.0.17-MariaDB -- PHP Version: 5.6.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `acs_cyber` -- -- -------------------------------------------------------- -- -- Table structure for table `competetion` -- CREATE TABLE IF NOT EXISTS `competetion` ( `competetion_number` int(11) NOT NULL, `game1` int(11) DEFAULT NULL, `game2` int(11) DEFAULT NULL, `game3` int(11) DEFAULT NULL, `result` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; -- -- Dumping data for table `competetion` -- -- -------------------------------------------------------- -- -- Table structure for table `game` -- CREATE TABLE IF NOT EXISTS `game` ( `game_number` int(11) NOT NULL, `hacker` int(11) DEFAULT NULL, `defender` int(11) DEFAULT NULL, `score_hacker` int(11) DEFAULT NULL, `score_defender` int(11) DEFAULT NULL, `vulnerability1` varchar(15) DEFAULT NULL, `vulnerability2` varchar(15) DEFAULT NULL, `vulnerability3` varchar(15) DEFAULT NULL, `winner` varchar(10) DEFAULT NULL, `bonus_hacker` int(11) DEFAULT NULL, `bonus_defender` int(11) DEFAULT NULL, `hacked_at1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `hacked_at2` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `hacked_at3` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=43 ; -- -- Dumping data for table `game` -- -- -------------------------------------------------------- -- -- Table structure for table `matched` -- CREATE TABLE IF NOT EXISTS `matched` ( `id` int(11) NOT NULL, `hacker` int(11) DEFAULT NULL, `defender` int(11) DEFAULT NULL, `competetion_number` int(11) DEFAULT NULL, `status` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; -- -- Dumping data for table `matched` -- -- -------------------------------------------------------- -- -- Table structure for table `moves` -- CREATE TABLE IF NOT EXISTS `moves` ( `id` int(11) NOT NULL, `move` varchar(500) DEFAULT NULL, `made_by` varchar(10) DEFAULT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `score_hacker` int(11) DEFAULT NULL, `score_defender` int(11) DEFAULT NULL, `game_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=308 ; -- -- Dumping data for table `moves` -- -- -------------------------------------------------------- -- -- Table structure for table `registration` -- CREATE TABLE IF NOT EXISTS `registration` ( `id` int(11) NOT NULL, `email` varchar(50) DEFAULT NULL, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `time` varchar(50) DEFAULT NULL, `country` varchar(100) DEFAULT NULL, `age` int(11) DEFAULT NULL, `gender` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; -- -- Dumping data for table `registration` -- -- -------------------------------------------------------- -- -- Table structure for table `wait` -- CREATE TABLE IF NOT EXISTS `wait` ( `number` int(11) NOT NULL, `id` int(11) DEFAULT NULL, `role` varchar(10) DEFAULT NULL, `status` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Indexes for dumped tables -- -- -- Indexes for table `competetion` -- ALTER TABLE `competetion` ADD PRIMARY KEY (`competetion_number`); -- -- Indexes for table `game` -- ALTER TABLE `game` ADD PRIMARY KEY (`game_number`); -- -- Indexes for table `matched` -- ALTER TABLE `matched` ADD PRIMARY KEY (`id`); -- -- Indexes for table `moves` -- ALTER TABLE `moves` ADD PRIMARY KEY (`id`); -- -- Indexes for table `registration` -- ALTER TABLE `registration` ADD PRIMARY KEY (`id`); -- -- Indexes for table `wait` -- ALTER TABLE `wait` ADD PRIMARY KEY (`number`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `competetion` -- ALTER TABLE `competetion` MODIFY `competetion_number` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `game` -- ALTER TABLE `game` MODIFY `game_number` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=43; -- -- AUTO_INCREMENT for table `matched` -- ALTER TABLE `matched` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `moves` -- ALTER TABLE `moves` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=308; -- -- AUTO_INCREMENT for table `registration` -- ALTER TABLE `registration` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `wait` -- ALTER TABLE `wait` MODIFY `number` int(11) NOT NULL AUTO_INCREMENT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
using System; namespace ZoomNet.Models.Webhooks { /// <summary> /// This event is triggered when an attendee joins a meeting. /// </summary> public class MeetingParticipantJoinedEvent : MeetingEvent { /// <summary> /// Gets or sets the date and time at which the participant joined the meeting. /// </summary> public DateTime JoinedOn { get; set; } /// <summary> /// Gets or sets the participant. /// </summary> public WebhookParticipant Participant { get; set; } } }
/** * DO NOT EDIT * * This file was automatically generated by * https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations * * To modify these typings, edit the source file(s): * lib/elements/dom-repeat.js */ import {PolymerElement} from '../../polymer-element.js'; import {TemplateInstanceBase, templatize, modelForElement} from '../utils/templatize.js'; import {Debouncer} from '../utils/debounce.js'; import {enqueueDebouncer, flush} from '../utils/flush.js'; import {OptionalMutableData} from '../mixins/mutable-data.js'; import {matches, translate} from '../utils/path.js'; import {timeOut, microTask} from '../utils/async.js'; export {DomRepeat}; /** * The `<dom-repeat>` element will automatically stamp and binds one instance * of template content to each object in a user-provided array. * `dom-repeat` accepts an `items` property, and one instance of the template * is stamped for each item into the DOM at the location of the `dom-repeat` * element. The `item` property will be set on each instance's binding * scope, thus templates should bind to sub-properties of `item`. * * Example: * * ```html * <dom-module id="employee-list"> * * <template> * * <div> Employee list: </div> * <dom-repeat items="{{employees}}"> * <template> * <div>First name: <span>{{item.first}}</span></div> * <div>Last name: <span>{{item.last}}</span></div> * </template> * </dom-repeat> * * </template> * * </dom-module> * ``` * * With the following custom element definition: * * ```js * class EmployeeList extends PolymerElement { * static get is() { return 'employee-list'; } * static get properties() { * return { * employees: { * value() { * return [ * {first: 'Bob', last: 'Smith'}, * {first: 'Sally', last: 'Johnson'}, * ... * ]; * } * } * }; * } * } * ``` * * Notifications for changes to items sub-properties will be forwarded to template * instances, which will update via the normal structured data notification system. * * Mutations to the `items` array itself should be made using the Array * mutation API's on the PropertyEffects mixin (`push`, `pop`, `splice`, * `shift`, `unshift`), and template instances will be kept in sync with the * data in the array. * * Events caught by event handlers within the `dom-repeat` template will be * decorated with a `model` property, which represents the binding scope for * each template instance. The model should be used to manipulate data on the * instance, for example `event.model.set('item.checked', true);`. * * Alternatively, the model for a template instance for an element stamped by * a `dom-repeat` can be obtained using the `modelForElement` API on the * `dom-repeat` that stamped it, for example * `this.$.domRepeat.modelForElement(event.target).set('item.checked', true);`. * This may be useful for manipulating instance data of event targets obtained * by event handlers on parents of the `dom-repeat` (event delegation). * * A view-specific filter/sort may be applied to each `dom-repeat` by supplying a * `filter` and/or `sort` property. This may be a string that names a function on * the host, or a function may be assigned to the property directly. The functions * should implemented following the standard `Array` filter/sort API. * * In order to re-run the filter or sort functions based on changes to sub-fields * of `items`, the `observe` property may be set as a space-separated list of * `item` sub-fields that should cause a re-filter/sort when modified. If * the filter or sort function depends on properties not contained in `items`, * the user should observe changes to those properties and call `render` to update * the view based on the dependency change. * * For example, for an `dom-repeat` with a filter of the following: * * ```js * isEngineer(item) { * return item.type == 'engineer' || item.manager.type == 'engineer'; * } * ``` * * Then the `observe` property should be configured as follows: * * ```html * <dom-repeat items="{{employees}}" filter="isEngineer" observe="type manager.type"> * ``` */ declare class DomRepeat extends OptionalMutableData( PolymerElement) { /** * An array containing items determining how many instances of the template * to stamp and that that each template instance should bind to. */ items: any[]|null|undefined; /** * The name of the variable to add to the binding scope for the array * element associated with a given template instance. */ as: string|null|undefined; /** * The name of the variable to add to the binding scope with the index * of the instance in the sorted and filtered list of rendered items. * Note, for the index in the `this.items` array, use the value of the * `itemsIndexAs` property. */ indexAs: string|null|undefined; /** * The name of the variable to add to the binding scope with the index * of the instance in the `this.items` array. Note, for the index of * this instance in the sorted and filtered list of rendered items, * use the value of the `indexAs` property. */ itemsIndexAs: string|null|undefined; /** * A function that should determine the sort order of the items. This * property should either be provided as a string, indicating a method * name on the element's host, or else be an actual function. The * function should match the sort function passed to `Array.sort`. * Using a sort function has no effect on the underlying `items` array. */ sort: Function|null|undefined; /** * A function that can be used to filter items out of the view. This * property should either be provided as a string, indicating a method * name on the element's host, or else be an actual function. The * function should match the sort function passed to `Array.filter`. * Using a filter function has no effect on the underlying `items` array. */ filter: Function|null|undefined; /** * When using a `filter` or `sort` function, the `observe` property * should be set to a space-separated list of the names of item * sub-fields that should trigger a re-sort or re-filter when changed. * These should generally be fields of `item` that the sort or filter * function depends on. */ observe: string|null|undefined; /** * When using a `filter` or `sort` function, the `delay` property * determines a debounce time in ms after a change to observed item * properties that must pass before the filter or sort is re-run. * This is useful in rate-limiting shuffling of the view when * item changes may be frequent. */ delay: number|null|undefined; /** * Count of currently rendered items after `filter` (if any) has been applied. * If "chunking mode" is enabled, `renderedItemCount` is updated each time a * set of template instances is rendered. */ readonly renderedItemCount: number|null|undefined; /** * Defines an initial count of template instances to render after setting * the `items` array, before the next paint, and puts the `dom-repeat` * into "chunking mode". The remaining items will be created and rendered * incrementally at each animation frame therof until all instances have * been rendered. */ initialCount: number|null|undefined; /** * When `initialCount` is used, this property defines a frame rate (in * fps) to target by throttling the number of instances rendered each * frame to not exceed the budget for the target frame rate. The * framerate is effectively the number of `requestAnimationFrame`s that * it tries to allow to actually fire in a given second. It does this * by measuring the time between `rAF`s and continuously adjusting the * number of items created each `rAF` to maintain the target framerate. * Setting this to a higher number allows lower latency and higher * throughput for event handlers and other tasks, but results in a * longer time for the remaining items to complete rendering. */ targetFramerate: number|null|undefined; readonly _targetFrameTime: number|null|undefined; connectedCallback(): void; disconnectedCallback(): void; /** * Forces the element to render its content. Normally rendering is * asynchronous to a provoking change. This is done for efficiency so * that multiple changes trigger only a single render. The render method * should be called if, for example, template rendering is required to * validate application state. */ render(): void; /** * Shows or hides the template instance top level child elements. For * text nodes, `textContent` is removed while "hidden" and replaced when * "shown." * * @param hidden Set to true to hide the children; * set to false to show them. */ _showHideChildren(hidden: boolean): void; /** * Returns the item associated with a given element stamped by * this `dom-repeat`. * * Note, to modify sub-properties of the item, * `modelForElement(el).set('item.<sub-prop>', value)` * should be used. * * @param el Element for which to return the item. * @returns Item associated with the element. */ itemForElement(el: HTMLElement): any; /** * Returns the inst index for a given element stamped by this `dom-repeat`. * If `sort` is provided, the index will reflect the sorted order (rather * than the original array order). * * @param el Element for which to return the index. * @returns Row index associated with the element (note this may * not correspond to the array index if a user `sort` is applied). */ indexForElement(el: HTMLElement): number|null; /** * Returns the template "model" associated with a given element, which * serves as the binding scope for the template instance the element is * contained in. A template model * should be used to manipulate data associated with this template instance. * * Example: * * let model = modelForElement(el); * if (model.index < 10) { * model.set('item.checked', true); * } * * @param el Element for which to return a template model. * @returns Model representing the binding scope for * the element. */ modelForElement(el: HTMLElement): TemplateInstanceBase|null; } declare global { interface HTMLElementTagNameMap { "dom-repeat": DomRepeat; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using OliDemos.Shop.Model; using OliDemos.Shop.Repository; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NSwag.Annotations; using OliDemos.Shop.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace OliDemos.Shop.Controllers { [ApiController] [Route("api/[controller]")] [OpenApiTag("data", Description = "The product controller to manage this entity")] public class ProductController : Controller { private const string AuthDesc = "Require authentication to do a request"; private readonly ProductService _serviceProduct; private readonly ILogger<ProductController> _logger; public ProductController(ProductService serv, ILogger<ProductController> logger) { _serviceProduct = serv ?? throw new ArgumentNullException(nameof(serv)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <summary> /// Devuelve un listado de todos los registros de datos /// </summary> /// <returns></returns> [HttpGet("all")] [OpenApiOperation("Bearer", AuthDesc)] public async Task<JsonResult> GetAllAsync() { return Json(await _serviceProduct.FindAll()); } /// <summary> /// Devueleve un listado filtrado de registros de datos /// </summary> /// <param name="page"></param> /// <param name="length"></param> /// <param name="search"></param> /// <param name="sort"></param> /// <param name="sortType"></param> /// <returns></returns> [HttpGet("index")] [OpenApiOperation("Bearer", AuthDesc)] public async Task<List<Product>> GetAsync(int minPrice = 0, int maxPrice = 0, int page = 0, int length = 25) { var result = await _serviceProduct.Find(q => { if (minPrice > 0) { q = q.Where(p => p.Price >= minPrice); } if (maxPrice > 0) { q = q.Where(p => p.Price <= maxPrice); } return q; //lambda end }, page, length); if (result.Count < 1) { HttpContext.Response.StatusCode = 404; return null; } else { return result; } } /// <summary> /// Devuelve un unico registro basado en su id /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] [OpenApiOperation("Bearer", AuthDesc)] public async Task<IActionResult> GetByIdAsync([FromRoute] ulong id) { var result = await _serviceProduct.FindOne(id); if (result is null) { return NotFound(); } else { return Ok(result); } } /// <summary> /// Agrega un registro con datos que entran en el cuerpo de la peticion /// </summary> /// <param name="data"></param> /// <returns></returns> [HttpPost] [Authorize(Roles = "Seller")] [OpenApiOperation("Bearer", AuthDesc)] public async Task<IActionResult> AddAsync([FromBody] Product product) { // set user onwer by claim id product.UserId = HttpContext.GetUserId(); try { var result = await _serviceProduct.StoreAnsyc(product); return StatusCode(201, new { product.Id, product.AtCreated }); } catch (Exception) { // ignore for now just send 400 return StatusCode(400); } } /// <summary> /// Agrega un registro con datos que entran en el cuerpo de la peticion /// </summary> /// <param name="data"></param> /// <returns></returns> [HttpPost("purchase")] [Authorize(Roles = "Client")] [OpenApiOperation("Bearer", AuthDesc)] [ProducesResponseType(StatusCodes.Status406NotAcceptable)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] public async Task<IActionResult> PurshaseAsync([FromBody] OrderRequest req) { try { var result = await _serviceProduct.PurchaseAsync(product: req.Product, user: HttpContext.GetUserId(), count: req.Count); return StatusCode(201, new { orderId = result }); } catch (InvalidOperationException err) when(err.Message.Equals(ProductService.NotStockMessage)) { return StatusCode(StatusCodes.Status406NotAcceptable, new { message = "No hay stock para la cantidad solicitada" }); } catch (InvalidOperationException err) when (err.Message.Equals(ProductService.ProductNotFound)) { return StatusCode(StatusCodes.Status404NotFound, new { message = "No hay el producto solicitado" }); } catch (Exception err) { _logger.LogDebug(err.Message); // ignore for now just send 400 return StatusCode(400); } } /// <summary> /// Actualiza un registro con datos que entran en el cuerpo de la peticion /// </summary> /// <param name="data"></param> /// <returns></returns> [HttpPut("{id}")] [OpenApiOperation("Bearer", AuthDesc)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task<IActionResult> UpdateAsync([FromRoute] ulong id, [FromBody] ProductEdition data) { try { await _serviceProduct.UpdateAsync(userId: HttpContext.GetUserId(), id: id, edition: data, force: HttpContext.IsAdmin()); } catch(InvalidOperationException err) when(err.Message == "not owner") { return Unauthorized(); } catch (Exception err) { _logger.LogDebug("Error:{0};\nMessage:{1}", err.GetType().Name, err.Message); } return NoContent(); } /// <summary> /// Elimina un registro basado en su id /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id}")] [Authorize(Roles = "Seller,Admin")] [OpenApiOperation("Bearer", AuthDesc)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task<IActionResult> DeleteAsync([FromRoute] ulong id) { try { await _serviceProduct.DeleteAsync(HttpContext.GetUserId(), id, HttpContext.IsAdmin()); } catch (InvalidOperationException err) when (err.Message == "not owner") { return Unauthorized(); } catch (Exception err) { _logger.LogDebug("Error:{0};\nMessage:{1}", err.GetType().Name, err.Message); } return NoContent(); } } }
# RequestQuery ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **language** | **string** | The query language in which the query is written. | [optional] [default to null] **userQuery** | **string** | The exact search request typed in by the user | [optional] [default to null] **query** | **string** | The query which may have been generated in some way from the userQuery | [default to null] <a name="RequestQuery.LanguageEnum"></a> ## Enum: RequestQuery.LanguageEnum * `Afts` (value: `'afts'`) * `Lucene` (value: `'lucene'`) * `Cmis` (value: `'cmis'`)
--- layout: post title: "npm package.json" date: 2020-02-23 tags: [npm,package.json] excerpt: "" etc: true comments: true --- [docs](https://docs.npmjs.com/files/package.json) ## npm 작성방법 JavaScript 객체 리터럴이 아니라 실제 JSON이어야합니다. ## name 패키지를 공개하려는 경우 package.json에서 가장 중요한 것은 `name`과 `version` 필드가 필요하다는 것입니다. `name`과 `version`은 완전히 고유 한 것으로 간주되는 식별자를 구성합니다. 패키지 변경 사항은 `version` 변경 사항과 함께 제공되어야합니다. 패키지를 게시하지 않으려는 경우 `name` 및 `version` 필드는 선택 사항입니다. 몇 가지 규칙: - `name`은 214 자 이하 여야합니다. 여기에는 범위가 지정된 패키지의 범위가 포함됩니다. - `name`은 점이나 밑줄로 시작할 수 없습니다. - 새 패키지는 `name`에 대문자가 없어야합니다. - `name`은 URL의 일부, 명령 행의 인수 및 폴더 이름이 됩니다. 따라서 `name`에는 URL이 안전하지 않은 문자를 사용할 수 없습니다. 몇 가지 팁 : - 핵심 노드 모듈과 동일한 `name`을 사용하지 마십시오. - `name`에 "js"또는 "node"를 넣지 마십시오. package.json 파일을 작성하고 있기 때문에 js라고 가정하고 "engines"필드를 사용하여 엔진을 지정할 수 있습니다. (아래 참조) - `name`은 아마도 require()에 인수로 전달 될 것이므로 짧지 만 합리적으로 설명해야합니다. - `name`을 붙이기 전에 npm 레지스트리에서 해당 `name`의 항목이 있는지 확인하십시오. ## version 패키지를 공개하려는 경우 package.json에서 가장 중요한 것은 `name`과 `version` 필드가 필요하다는 것입니다. `name`과 `version`은 완전히 고유 한 것으로 간주되는 식별자를 구성합니다. 패키지 변경 사항은 `version` 변경 사항과 함께 제공되어야합니다. 패키지를 게시하지 않으려는 경우 `name` 및 `version` 필드는 선택 사항입니다. 버전은 종속 노드로 npm과 함께 번들로 제공되는 node-semver로 구문 분석 할 수 있어야합니다. (`npm install semver`를 사용하여 직접 사용하십시오.) More on version numbers and ranges at semver. ## scripts "scripts"속성은 패키지 수명주기 동안 다양한 시간에 실행되는 스크립트 명령이 포함 된 사전입니다. 핵심은 수명주기 이벤트이며 값은 해당 시점에서 실행하는 명령입니다. 패키지 스크립트 작성에 대한 자세한 내용은 [npm-scripts](https://docs.npmjs.com/misc/scripts)를 참조하십시오. ## private package.json에서 "private": true를 설정하면 npm에서 게시를 거부합니다. 개인 저장소가 실수로 게시되는 것을 방지하는 방법입니다. 지정된 패키지가 특정 레지스트리 (예 : 내부 레지스트리)에만 공개되도록하려면 아래 설명 된 publishConfig 사전을 사용하여 공개시 레지스트리 구성 매개 변수를 대체하십시오. ## publishConfig 게시시 사용될 구성 값 세트입니다. 태그, 레지스트리 또는 액세스를 설정하여 지정된 패키지에 "최신"태그가 지정되지 않았거나 전역 공용 레지스트리에 게시되거나 범위가 지정된 모듈이 기본적으로 비공개인지 확인하는 것이 특히 편리합니다. 모든 구성 값을 재정의 할 수 있지만 “tag”, “registry” 및 “access” 만 게시 목적에 중요합니다. 재정의 할 수있는 구성 옵션 목록을 보려면 [npm-config](https://docs.npmjs.com/misc/config)를 참조하십시오. ## dependencies `Dependencies` 는 패키지 이름을 버전 범위에 매핑하는 간단한 개체에 지정됩니다. 버전 범위는 하나 이상의 공백으로 구분 된 설명자가있는 문자열입니다. tarball 또는 git URL로 종속성을 식별 할 수도 있습니다. `dependencies` Object에 `test harnesses` 또는 `transpilers`를 넣지 마십시오. 아래 devDependencies를 참조하십시오. 버전 범위 지정에 대한 자세한 내용은 [semver](https://docs.npmjs.com/misc/semver)를 참조하십시오. - **version** `version`과 정확히 일치해야합니다. - **>version** `version`보다 커야 합니다. - **>=version** `version`보다 크거나 같아야 합니다. - **<version** `version`보다 작아야 합니다. - **<=version** `version`보다 작거나 같아야 합니다. - **~version** `version`과 거의 동일합니다. [semver](https://docs.npmjs.com/misc/semver) 참조 - **^version** `version`과 호환 가능. [semver](https://docs.npmjs.com/misc/semver) 참조 - **1.2.x** 1.2.0, 1.2.1 등. 1.3.0은 아닙니다. - **http://...** [URLs as Dependencies](https://docs.npmjs.com/files/package.json#urls-as-dependencies) 참조 - __*__ 모든 `version`과 일치 - **""** (빈 문자열) __*__ 와 동일 - **version1 - version2** 왼쪽과 오른쪽은 동일 **>=version1 <=version2** - `range1 || range2` range1 또는 range2가 충족되면 전달합니다. - **git...** [Git URLs as Dependencies](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies) 참조 - **user/repo** [GitHub URL](https://docs.npmjs.com/files/package.json#github-urls) 참조 - **tag** 태그로 태그되고 게시 된 특정 버전. [npm-dist-tag](https://docs.npmjs.com/cli/dist-tag) 참조 - **path/path/path** [Local Paths](https://docs.npmjs.com/files/package.json#local-paths) 참조 예를 들어 다음은 모두 유효합니다. ~~~javascript { "dependencies" : { "foo" : "1.0.0 - 2.9999.9999" , "bar" : ">=1.0.2 <2.1.2" , "baz" : ">1.0.2 <=2.3.4" , "boo" : "2.0.1" , "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0" , "asd" : "http://asdf.com/asdf.tar.gz" , "til" : "~1.2" , "elf" : "~1.2.3" , "two" : "2.x" , "thr" : "3.3.x" , "lat" : "latest" , "dyl" : "file:../dyl" } } ~~~ ## devDependencies 프로그램에서 모듈을 다운로드하여 사용하려는 경우 사용중인 외부 테스트 또는 문서 프레임 워크를 다운로드하거나 빌드하지 않아도됩니다. 이 경우 이러한 추가 항목을 devDependencies 객체에 매핑하는 것이 가장 좋습니다. 이러한 것들은 패키지의 루트에서 `npm link` 또는 `npm install`을 수행 할 때 설치되며 다른 npm 구성 매개 변수처럼 관리 할 수 ​​있습니다. 주제에 대한 자세한 내용은 [npm-config](https://docs.npmjs.com/misc/config)를 참조하십시오. CoffeeScript 또는 다른 언어를 JavaScript로 컴파일하는 것과 같이 플랫폼별로 고유하지 않은 빌드 단계의 경우, **prepare** 스크립트를 사용하여 이를 수행하고 필요한 패키지를 devDependency로 만듭니다. 예: ~~~ { "name": "ethopia-waza", "description": "a delightfully fruity coffee varietal", "version": "1.2.3", "devDependencies": { "coffee-script": "~1.6.3" }, "scripts": { "prepare": "coffee -o lib/ -c src/waza.coffee" }, "main": "lib/waza.js" } ~~~ **prepare** 스크립트는 게시하기 전에 실행되므로 사용자가 직접 컴파일하지 않고도 기능을 사용할 수 있습니다. 개발 모드 (예 : 로컬에서 `npm install` 실행)에서는 이 스크립트도 실행되므로 쉽게 테스트 할 수 있습니다. ## URLs as Dependencies 버전 범위 대신 tarball URL을 지정할 수 있습니다. 이 tarball은 설치시 패키지에 로컬로 다운로드되어 설치됩니다. ## Git URLs as Dependencies Git URL은 다음과 같은 형식입니다. ~~~ <protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>] ~~~ `<protocol>` 은 **git**, **git+ssh**, **git+http**, **git+https** 또는 **git+** 파일 중 하나입니다. `#<commit-ish>`가 제공되면 해당 커밋을 정확하게 복제하는 데 사용됩니다. commit-ish의 형식이 `#semver:<semver>`이면 `<semver>`는 유효한 semver 범위 또는 정확한 버전 일 수 있으며 npm은 원격 저장소에서 해당 범위와 일치하는 태그 또는 참조를 찾습니다. 레지스트리 의존성. `#<commit-ish>` 또는 `#semver:<semver>`를 지정하지 않으면 `master`가 사용됩니다. 예: ~~~ git+ssh://git@github.com:npm/cli.git#v1.0.27 git+ssh://git@github.com:npm/cli#semver:^5.0 git+https://isaacs@github.com/npm/cli.git git://github.com/npm/cli.git#v1.0.27 ~~~
ori $ra,$ra,0xf addu $6,$4,$2 multu $0,$1 sll $3,$3,14 addiu $0,$6,28752 divu $4,$ra addiu $5,$1,-12106 srav $4,$4,$3 mflo $6 mult $3,$0 mtlo $1 lui $4,40975 addiu $4,$1,-30801 addiu $4,$4,-18330 mtlo $0 ori $5,$1,32393 mflo $4 lui $1,47290 ori $5,$5,10774 div $4,$ra lb $2,13($0) sb $0,7($0) mtlo $4 lb $4,1($0) mtlo $0 div $4,$ra sb $1,16($0) addu $2,$2,$2 mflo $5 addiu $2,$5,7627 divu $4,$ra divu $5,$ra divu $5,$ra mfhi $4 lb $1,8($0) mfhi $6 lb $4,15($0) addiu $0,$0,4025 mtlo $5 mflo $4 mult $3,$5 multu $4,$4 addiu $2,$2,-4457 mthi $4 ori $4,$2,60638 mfhi $0 mthi $1 div $1,$ra sb $3,14($0) mflo $3 sll $3,$3,5 mthi $6 srav $4,$1,$0 mflo $1 addiu $5,$1,-7601 sb $1,1($0) sb $0,0($0) addu $6,$0,$6 srav $1,$1,$1 lb $2,1($0) mtlo $0 mult $4,$1 lui $2,46924 sb $0,9($0) lui $1,26313 srav $5,$4,$4 lui $4,46243 addu $1,$1,$4 mult $3,$5 multu $1,$2 mthi $1 sll $3,$6,14 sb $6,13($0) lui $1,48123 mfhi $1 mult $4,$2 sb $5,8($0) ori $2,$2,15181 mflo $0 ori $5,$0,51528 sll $4,$1,17 sb $1,0($0) mtlo $1 sb $4,13($0) mult $2,$5 mult $1,$6 lui $0,53890 sb $1,14($0) multu $1,$2 mflo $0 addiu $0,$0,24602 sll $1,$4,7 lb $4,10($0) sll $5,$5,23 mfhi $1 addu $4,$2,$2 multu $5,$4 mtlo $2 addiu $1,$2,-6473 mfhi $4 addu $4,$2,$3 mfhi $6 addiu $4,$5,22937 mthi $4 lui $4,49818 sb $5,14($0) addu $1,$2,$2 mflo $2 mtlo $0 lui $0,5730 addiu $0,$2,14419 addu $2,$2,$5 mult $5,$5 mfhi $4 sb $4,3($0) addu $6,$4,$2 multu $0,$0 mflo $1 div $0,$ra sb $0,9($0) addu $5,$1,$2 mfhi $4 lb $3,12($0) srav $5,$1,$4 addu $0,$0,$1 lb $3,6($0) mtlo $1 lui $0,43994 mtlo $1 ori $0,$1,20950 lui $1,47787 multu $1,$6 divu $4,$ra mflo $4 sll $1,$6,24 ori $1,$1,44120 mthi $0 mflo $2 ori $5,$4,58226 addiu $4,$4,28509 sll $4,$0,27 sll $1,$0,10 mtlo $3 addu $6,$4,$3 lb $1,10($0) srav $0,$5,$3 srav $6,$4,$6 sll $6,$5,11 divu $4,$ra srav $4,$2,$0 mflo $1 divu $5,$ra ori $5,$5,30701 sll $5,$1,4 lui $5,3319 mthi $4 mthi $2 mult $4,$0 lui $4,64945 sb $2,6($0) ori $0,$4,31025 mult $2,$2 sll $1,$2,28 mtlo $1 sb $4,5($0) mult $0,$5 divu $5,$ra mthi $4 lb $6,8($0) mflo $0 ori $4,$0,27688 lb $5,0($0) mtlo $1 sb $4,0($0) addu $4,$3,$3 mflo $6 lui $6,47180 mult $4,$1 sb $0,0($0) mfhi $5 addu $1,$2,$2 divu $4,$ra addu $4,$4,$1 lui $2,14862 lui $5,27028 mult $6,$2 divu $3,$ra div $4,$ra mflo $4 sb $4,12($0) addiu $1,$0,-27916 addu $5,$1,$5 sb $5,15($0) multu $1,$1 div $1,$ra div $0,$ra ori $3,$4,34126 mtlo $4 multu $4,$4 sb $6,15($0) multu $1,$1 srav $5,$5,$5 multu $5,$1 lui $1,17775 sll $4,$5,17 sb $4,14($0) ori $3,$4,53370 addu $0,$6,$1 lb $5,4($0) sll $3,$3,13 mult $1,$1 mtlo $3 div $6,$ra mfhi $4 lui $6,35925 mflo $1 sb $1,16($0) addu $4,$3,$3 addiu $3,$3,-20888 lb $4,3($0) sll $2,$2,27 multu $6,$2 lui $0,1127 ori $2,$2,35733 mthi $1 sll $0,$2,4 addiu $3,$3,4437 mthi $6 mfhi $4 div $5,$ra sb $4,7($0) div $4,$ra divu $6,$ra sb $5,3($0) div $0,$ra lb $4,0($0) mflo $3 ori $4,$2,61602 mfhi $1 addiu $4,$5,-3950 mult $0,$2 sll $5,$2,24 addiu $5,$6,2774 srav $1,$0,$1 mult $1,$2 mflo $0 mflo $4 multu $4,$5 mtlo $4 ori $4,$4,14070 addiu $5,$1,-11472 mtlo $1 mflo $5 div $1,$ra addu $4,$4,$1 mult $5,$5 mtlo $6 mflo $6 ori $5,$5,45371 mtlo $4 sll $3,$5,9 lui $4,52966 mthi $5 divu $1,$ra mflo $0 div $4,$ra ori $0,$6,48186 mthi $4 div $5,$ra sll $4,$1,1 mflo $5 multu $6,$1 lui $5,23387 ori $4,$1,60075 ori $5,$6,59110 mfhi $4 srav $0,$2,$3 mtlo $2 sll $1,$0,14 ori $4,$2,29894 sll $5,$6,20 ori $3,$3,33604 addiu $4,$4,1289 addiu $5,$5,-8019 addiu $1,$5,-8550 lb $3,13($0) mult $5,$5 lui $6,63747 addiu $4,$1,-22135 mtlo $1 lb $4,3($0) srav $4,$4,$3 addiu $5,$2,-7662 sb $1,0($0) mtlo $4 srav $2,$0,$2 lb $6,11($0) mtlo $4 multu $1,$1 mtlo $4 ori $0,$4,56552 sb $3,11($0) mthi $0 sb $6,4($0) lui $4,18514 sb $0,12($0) mthi $6 sb $4,8($0) srav $5,$5,$5 addiu $4,$4,23294 multu $5,$6 sb $0,7($0) mtlo $1 div $6,$ra mtlo $4 divu $0,$ra lui $0,15376 ori $5,$5,7205 ori $4,$5,45008 divu $4,$ra divu $1,$ra mflo $4 sb $6,2($0) sb $1,12($0) addiu $5,$2,-17254 mfhi $0 addiu $0,$4,-2593 multu $4,$1 sb $1,0($0) mfhi $1 mflo $2 mfhi $4 mult $4,$4 lui $4,15293 divu $3,$ra lb $0,7($0) divu $3,$ra div $0,$ra lb $4,13($0) sll $5,$5,23 div $1,$ra mflo $4 lb $6,7($0) sll $1,$2,7 mthi $4 mthi $1 mthi $2 mtlo $1 div $4,$ra mult $5,$4 addiu $5,$2,-3531 mflo $0 mult $1,$1 addiu $4,$2,-4869 mthi $1 lui $5,11359 sll $2,$2,4 addiu $5,$2,9217 mflo $0 mflo $0 mtlo $5 addu $4,$4,$4 multu $5,$5 addu $1,$2,$3 div $4,$ra sb $4,6($0) mthi $2 sll $5,$5,23 lui $6,47538 srav $5,$5,$5 mfhi $0 srav $3,$3,$3 addiu $2,$2,11563 sb $4,10($0) lb $5,13($0) lb $2,6($0) mflo $1 mthi $4 mthi $3 mult $6,$4 multu $4,$5 addu $4,$4,$5 div $1,$ra mflo $5 mflo $5 srav $1,$3,$3 multu $2,$2 sb $6,5($0) sll $5,$5,16 mfhi $2 ori $2,$5,59760 lui $2,56260 mthi $4 srav $3,$1,$3 addu $3,$1,$3 mthi $6 addu $3,$0,$3 lb $2,12($0) sb $2,7($0) multu $4,$4 mthi $5 mtlo $2 addu $4,$0,$1 lb $3,3($0) lui $1,24471 multu $6,$4 addu $6,$6,$4 mthi $2 mult $5,$6 mult $4,$5 multu $2,$2 lui $2,17031 lb $4,3($0) lui $4,15991 ori $3,$4,5740 addu $4,$2,$5 multu $1,$2 lb $1,3($0) sb $4,8($0) sll $6,$2,5 sll $5,$5,0 lui $4,47455 sll $0,$2,22 multu $6,$4 lui $5,33020 mthi $6 srav $1,$4,$1 mfhi $4 mfhi $4 mfhi $2 multu $2,$2 lb $4,6($0) addiu $4,$4,22379 lui $2,46072 mult $4,$4 mtlo $6 sb $5,2($0) srav $4,$0,$0 multu $6,$1 addiu $1,$1,-24445 ori $0,$0,27315 ori $4,$4,38317 lb $6,6($0) mflo $2 lb $1,10($0) sb $5,12($0) sb $3,8($0) lui $4,48799 divu $3,$ra lb $0,13($0) addu $4,$4,$4 ori $2,$2,33977 mthi $1 srav $4,$4,$5 divu $4,$ra mfhi $5 mfhi $6 addu $6,$0,$4 mthi $5 mflo $4 mthi $5 ori $4,$2,35377 addu $5,$2,$1 mflo $4 ori $4,$1,52437 sll $5,$5,10 sb $1,5($0) sll $2,$2,23 mult $2,$1 mult $4,$4 addu $5,$5,$2 div $1,$ra sb $4,5($0) sb $4,7($0) addiu $5,$4,-2759 mflo $1 mult $0,$0 srav $1,$4,$1 mfhi $1 ori $1,$1,27754 divu $4,$ra addiu $1,$0,-714 mfhi $3 sll $4,$4,20 sb $3,2($0) lb $5,8($0) divu $3,$ra multu $0,$5 div $4,$ra sll $5,$5,19 mthi $0 mthi $3 addiu $1,$2,17780 srav $5,$0,$3 mthi $2 addu $4,$1,$1 addiu $6,$6,-15459 addu $4,$2,$4 lb $1,6($0) multu $1,$2 sb $3,11($0) mthi $2 mfhi $5 mflo $2 div $5,$ra sb $2,1($0) mtlo $5 divu $4,$ra mtlo $6 lb $1,3($0) lui $0,63004 mthi $1 mthi $4 addiu $5,$4,-18813 mflo $6 div $5,$ra addu $4,$4,$4 mflo $4 mfhi $4 mult $2,$1 srav $4,$4,$4 sb $0,6($0) srav $0,$1,$3 srav $3,$4,$3 ori $3,$3,18991 mflo $3 srav $5,$0,$1 div $4,$ra sb $2,2($0) lui $0,35019 mfhi $5 mfhi $6 addiu $4,$4,-8410 ori $1,$6,24974 sll $3,$5,17 sll $5,$2,3 sb $5,1($0) sb $2,4($0) divu $3,$ra srav $1,$4,$6 mfhi $4 divu $6,$ra multu $5,$0 sll $1,$5,24 mtlo $5 sb $5,12($0) lui $0,55612 sll $4,$4,20 multu $1,$4 divu $4,$ra srav $1,$3,$3 lui $4,8888 div $4,$ra srav $5,$4,$2 div $4,$ra div $1,$ra mflo $4 sb $2,6($0) addu $6,$4,$4 mult $3,$3 addiu $4,$3,20051 mthi $4 div $4,$ra addiu $4,$4,28252 sll $0,$5,0 addiu $0,$0,-2581 lui $5,16396 mthi $5 addu $4,$4,$4 mult $1,$1 lui $6,36232 lui $5,59708 multu $1,$4 mflo $6 lb $1,12($0) divu $2,$ra mtlo $3 srav $4,$6,$6 mult $4,$2 sb $1,13($0) srav $4,$4,$2 sb $2,5($0) multu $0,$0 mflo $4 srav $1,$4,$2 addiu $6,$6,7857 addiu $1,$6,25833 mflo $4 divu $5,$ra ori $1,$6,34283 srav $4,$5,$5 mfhi $3 mflo $1 ori $1,$5,56606 div $1,$ra mtlo $3 mtlo $5 mflo $6 addu $4,$2,$3 mtlo $1 mult $4,$1 mult $4,$5 multu $5,$5 mthi $4 mfhi $3 divu $6,$ra lui $1,45410 divu $4,$ra divu $1,$ra mfhi $4 mthi $3 mtlo $0 sll $5,$5,21 multu $4,$3 mfhi $5 addu $6,$1,$6 sb $5,7($0) lb $5,6($0) mfhi $3 sb $5,0($0) sb $2,11($0) lui $4,40755 srav $5,$4,$1 mult $1,$4 mult $4,$1 sb $4,5($0) addu $2,$5,$2 mult $4,$4 multu $4,$0 lui $4,59771 multu $1,$2 ori $6,$4,26978 div $5,$ra srav $1,$6,$4 divu $5,$ra addu $4,$1,$4 mflo $4 lui $4,60491 ori $0,$5,35541 sb $0,8($0) srav $4,$0,$4 ori $1,$1,48038 srav $0,$4,$4 lb $1,12($0) divu $4,$ra mtlo $4 addiu $4,$0,-32264 mflo $1 mtlo $4 addu $5,$6,$5 lui $1,11361 ori $2,$2,5380 mthi $5 addu $5,$4,$4 addu $0,$5,$5 divu $4,$ra mthi $6 mthi $2 addu $1,$1,$6 mfhi $1 lb $5,7($0) mthi $0 divu $0,$ra srav $2,$2,$2 mtlo $2 mult $5,$5 mfhi $4 srav $2,$2,$2 mtlo $4 srav $4,$5,$5 lui $1,62870 divu $6,$ra mult $4,$4 mthi $5 sll $6,$6,27 sb $4,14($0) mthi $3 multu $4,$1 mtlo $4 mflo $4 ori $4,$6,64912 mflo $2 multu $5,$4 mult $3,$6 sb $0,3($0) sll $4,$2,7 addiu $5,$4,-23522 lui $1,43019 lui $4,27024 lui $1,15866 multu $0,$0 srav $6,$4,$6 addiu $1,$6,3414 lb $6,16($0) mult $4,$1 mflo $5 sb $4,10($0) addu $4,$5,$5 addiu $4,$2,8219 mthi $1 mflo $3 mthi $6 mfhi $1 addiu $4,$4,-20729 mthi $2 sll $5,$4,30 sb $0,0($0) multu $1,$0 addu $5,$2,$5 div $1,$ra sb $1,4($0) multu $3,$2 sb $0,16($0) mfhi $0 ori $6,$6,37377 addu $1,$2,$4 multu $5,$0 mthi $6 ori $5,$4,44633 divu $1,$ra mult $1,$0 lb $1,6($0) divu $3,$ra sll $1,$5,0 mtlo $4 mtlo $5 addu $4,$6,$3 lb $5,3($0) lb $2,16($0) srav $6,$1,$3 mtlo $4 addu $3,$0,$3 addiu $4,$2,18323 mfhi $4 mfhi $4 srav $4,$0,$0 ori $0,$1,30783 mflo $2 mflo $4 srav $5,$5,$3 addu $1,$5,$1 addiu $6,$5,17925 divu $5,$ra ori $4,$4,43584 mfhi $4 divu $0,$ra multu $4,$4 ori $1,$5,38395 mult $1,$2 sb $4,1($0) div $4,$ra lui $4,18053 mflo $1 sll $4,$2,7 div $0,$ra lui $1,46315 mflo $1 mthi $5 mfhi $2 lb $5,8($0) lb $5,10($0) divu $3,$ra mtlo $1 srav $4,$4,$4 mfhi $5 sb $4,7($0) divu $0,$ra mfhi $1 mflo $3 mthi $2 div $5,$ra sll $4,$2,25 lb $2,3($0) divu $4,$ra lb $1,3($0) multu $4,$0 lb $4,8($0) mthi $4 sb $1,13($0) lb $5,1($0) div $5,$ra mtlo $6 sll $6,$4,1 multu $0,$1 addiu $6,$2,27710 addu $5,$5,$4 srav $5,$4,$5 addu $4,$4,$4 multu $5,$1 addu $4,$4,$3 addu $1,$1,$2 mtlo $6 mthi $1 multu $2,$1 sb $5,5($0) mfhi $3 lb $4,2($0) divu $1,$ra ori $2,$2,13954 mtlo $5 addu $0,$6,$6 mflo $2 srav $4,$4,$0 multu $5,$5 addiu $5,$3,26410 addu $0,$6,$3 multu $2,$2 div $5,$ra ori $3,$4,11640 sb $4,7($0) addu $4,$4,$0 addiu $1,$1,12530 mtlo $3 divu $4,$ra mfhi $4 div $5,$ra div $4,$ra mult $1,$5 divu $5,$ra mthi $5 addiu $2,$5,17592 multu $4,$4 multu $2,$2 lb $2,8($0) addiu $1,$4,-12752 div $1,$ra lb $6,15($0) mflo $5 sll $5,$6,16 addiu $1,$1,32642 sll $1,$4,11 divu $1,$ra multu $3,$3 addu $6,$2,$3 mflo $4 mfhi $5 mult $4,$4 div $5,$ra mthi $3 addiu $1,$2,7409 lui $4,58293 lb $1,14($0) mthi $3 sll $0,$0,28 lui $0,2027 lui $4,1881 srav $4,$5,$3 mflo $1 lb $3,9($0) sb $1,15($0) divu $0,$ra addu $6,$5,$5 lb $2,11($0) mthi $3 mthi $1 ori $3,$2,49523 sb $4,5($0) mthi $5 mult $5,$5 div $3,$ra lui $4,36709 sb $6,5($0) multu $6,$1 divu $5,$ra mfhi $1 addiu $5,$2,9109 mult $5,$5 multu $1,$1 div $1,$ra lui $2,29033 mthi $2 ori $3,$4,7302 lui $0,14545 mfhi $6 mthi $0 ori $6,$2,42490 sb $4,13($0) mthi $1 multu $1,$1 mult $5,$2 lb $0,4($0) addiu $1,$1,-27070 mult $1,$6 ori $5,$5,16167 sb $4,10($0) lb $1,3($0) sb $1,15($0) ori $4,$2,61762 addu $4,$4,$1
#!/usr/bin/env bash # 验证指定程序是否有效 或者是否能够在PATH中找到 in_path(){ # 找给定的命令 找到 返回 0 # 没找到 返回 1 # 函数执行完成后 恢复 #IFS是internal field separator 的缩写,shell的特殊环境变量。ksh根据IFS存储的值,可以是空格、tab、换行符或者其他自定义符号,来解析输入和输出的变量值。 # 具体请查看 http://xstarcd.github.io/wiki/shell/IFS.html cmd=$1 ourpath=$2 result=1 oldIFS=$IFS IFS=":" for directory in $ourpath ; do if [-x $directory/$cmd]; then reuslt=0 # 找到命令 😊 fi done IFS = $oldIFS return $reuslt } # -x 检查是否存在 checkForCmdInPath() { var=$1 if [ "$var" != "" ] ; then # 也可以使用 $(echo $var | cut -c1) # 殊途同归 if [ "${var%${var#?}}" = "/" ]; then if [ ! -x $var ]; then return 1 fi elif ! in_path $var "$PATH" ; then return 2 fi fi } if [ $# -ne 1 ]; then echo "使用: $0 command" >&2 exit 0 fi if [ "$BASH_SOURCE" = $0 ] ; then checkForCmdInPath "$1" case $? in 0) echo "$1 found in path" ;; 1) echo "$1 not found in path or not excutable" ;; 2) echo "$1 found in PATH" ;; esac fi exit 0
import sbt.Keys.organization val V = new { val Scala = "3.1.0" val laminar = "0.13.1" val http4s = "0.23.4" val sttp = "3.3.13" val circe = "0.14.1" val decline = "2.1.0" val weaver = "0.7.6" val doobieVersion = "1.0.0-RC1" val log4jVersion = "2.14.1" } scalaVersion := V.Scala name := "fluvii" version := "0.1-SNAPSHOT" val Dependencies = new { private val http4sModules = Seq("dsl", "ember-client", "ember-server", "circe").map("http4s-" + _) private val sttpModules = Seq("core", "circe") lazy val frontend = Seq( libraryDependencies ++= Seq( "com.softwaremill.sttp.client3" %%% "core" % V.sttp, "com.softwaremill.sttp.client3" %%% "circe" % V.sttp, "com.raquo" %%% "laminar" % V.laminar ) ) lazy val backend = Seq( libraryDependencies ++= http4sModules.map("org.http4s" %% _ % V.http4s) ++ Seq( "com.monovore" %% "decline" % V.decline, "org.xerial" % "sqlite-jdbc" % "3.23.1", "org.tpolecat" %% "doobie-core" % V.doobieVersion, "org.tpolecat" %% "doobie-hikari" % V.doobieVersion, "org.apache.logging.log4j" % "log4j-slf4j-impl" % V.log4jVersion, "com.lihaoyi" %% "sourcecode" % "0.2.7" ) ) lazy val shared = Def.settings( libraryDependencies += "io.circe" %%% "circe-core" % V.circe, libraryDependencies += "io.circe" %%% "circe-generic" % V.circe ) lazy val tests = Def.settings( libraryDependencies += "com.disneystreaming" %%% "weaver-cats" % V.weaver % Test, testFrameworks += new TestFramework("weaver.framework.CatsEffect") ) } lazy val root = (project in file(".")).aggregate(frontend, backend, shared.js, shared.jvm) lazy val frontend = (project in file("modules/frontend")) .dependsOn(shared.js) .enablePlugins(ScalaJSPlugin) .settings(scalaJSUseMainModuleInitializer := true) .settings( Dependencies.frontend, Dependencies.tests, Test / jsEnv := new org.scalajs.jsenv.jsdomnodejs.JSDOMNodeJSEnv() ) .settings( commonBuildSettings, name := "fluvii-fe" ) lazy val backend = (project in file("modules/backend")) .dependsOn(shared.jvm) .settings(Dependencies.backend) .settings(Dependencies.tests) .settings(commonBuildSettings) .enablePlugins(JavaAppPackaging) .enablePlugins(DockerPlugin) .settings( name := "fluvii", Test / fork := true, Universal / mappings += { val appJs = (frontend / Compile / fullOptJS).value.data appJs -> ("lib/prod.js") }, Universal / javaOptions ++= Seq( "--port 8080", "--mode prod" ), Docker / packageName := "laminar-http4s-example" ) lazy val shared = crossProject(JSPlatform, JVMPlatform) .crossType(CrossType.Pure) .in(file("modules/shared")) .jvmSettings(Dependencies.shared) .jsSettings(Dependencies.shared) .jsSettings(commonBuildSettings) .jvmSettings(commonBuildSettings) .settings( name := "fluvii-shared" ) ThisBuild / scalafixDependencies += "com.github.liancheng" %% "organize-imports" % "0.5.0" ThisBuild / semanticdbEnabled := false ThisBuild / scalacOptions += "-deprecation" lazy val fastOptCompileCopy = taskKey[Unit]("") val jsPath = "modules/backend/src/main/resources" fastOptCompileCopy := { val source = (frontend / Compile / fastOptJS).value.data IO.copyFile( source, baseDirectory.value / jsPath / "dev.js" ) } lazy val fullOptCompileCopy = taskKey[Unit]("") fullOptCompileCopy := { val source = (frontend / Compile / fullOptJS).value.data IO.copyFile( source, baseDirectory.value / jsPath / "prod.js" ) } lazy val commonBuildSettings: Seq[Def.Setting[_]] = Seq( scalaVersion := V.Scala, organization := "cz.kamenitxan", name := "Fluvii", startYear := Some(2021) ) addCommandAlias("runDev", ";fastOptCompileCopy; backend/reStart --mode dev") addCommandAlias("runProd", ";fullOptCompileCopy; backend/reStart --mode prod") val scalafixRules = Seq( "OrganizeImports", "DisableSyntax", "LeakingImplicitClassVal", "NoValInForComprehension" ).mkString(" ") val CICommands = Seq( "clean", "backend/compile", "backend/test", "frontend/compile", "frontend/fastOptJS", "frontend/test", s"scalafix --check $scalafixRules" ).mkString(";") val PrepareCICommands = Seq( s"scalafix $scalafixRules" ).mkString(";") addCommandAlias("ci", CICommands) addCommandAlias("preCI", PrepareCICommands)
from typing import Optional from src.rest_client.groups.groups import GroupRestClient from src.rest_client.utils import with_rest_client, external_call @with_rest_client(GroupRestClient) async def get_all_groups( client: GroupRestClient, query: Optional[str] = None, faculty: Optional[int] = None, **kwargs ): with external_call(client) as rest_client: data, status = await rest_client.all_groups(query=query, faculty=faculty) return data["suggestions"], status @with_rest_client(GroupRestClient) async def is_group_exists( client: GroupRestClient, group: str, faculty: Optional[int] = None, **kwargs ): with external_call(client) as rest_client: data, status = await rest_client.exists(group_code=group, faculty=faculty) return data, status
//! # algorand-rs //! //! This crate is a WORK IN PROGRESS! //! //! **algorand-rs** aims at becoming a rusty algorand sdk. //! //! ```rust //! use algorand_rs::Algod; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let algod = Algod::new() //! .bind("http://localhost:4001") //! .auth("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") //! .client_v1()?; //! //! println!("Algod versions: {:?}", algod.versions()?.versions); //! //! Ok(()) //! } //! ``` //! //! ## Objectives //! //! - [ ] Example-driven API development //! - [ ] Clear error messages //! - [ ] Async requests //! - [ ] Builder pattern and sensible defaults //! - [ ] Thorough test suite //! - [ ] Comprehensive documentation // TODO #![deny(missing_docs)] pub mod client; pub mod core; pub mod crypto; pub(crate) mod encoding; pub mod error; pub mod transaction; // Re-exports pub use crate::core::{MicroAlgos, Round}; pub use client::algod::Algod; pub use client::indexer::Indexer; pub use client::kmd::Kmd;
@extends('layout/app') @section('title', 'Edit Buku') @section('content') <div class="container mt-2"> <div class="col-md-8 manage-wrapper bg-light me-1"> <h3><i class="uil uil-edit me-1"></i> Update Book</h3> <p> Update data buku dengan benar dan tepat! Data anda akan diakses oleh banyak orang. </p> <form action="{{url('book/'.$book->id)}}" method="POST"> @csrf @method('PUT') <div class="mb-3"> <label class="form-label">Judul Buku</label> <input type="text" class="form-control @error ('judul') is-invalid @enderror placeholder="Masukkan Judul Game" name="judul" value="{{$book->judul}}"> @error('judul') <small class="text-danger">{{$message}}</small> @enderror </div> <div class="mb-3"> <label class="form-label @error('penulis') is-invalid @enderror">Penulis</label> <input type="text" class="form-control" placeholder="Masukkan Nama Penulis" name="penulis" value="{{$book->penulis}}"> @error('penulis') <small class="text-danger">{{$message}}</small> @enderror </div> <div class="mb-3"> <label class="form-label @error('jumlah_halaman') is-invalid @enderror">Jumlah Halaman</label> <input type="number" class="form-control" placeholder="Masukkan Jumlah Halaman" name="jumlah_halaman" value="{{$book->jumlah_halaman}}"> @error('jumlah_halaman') <small class="text-danger">{{$message}}</small> @enderror </div> <div class="mb-3"> <label class="form-label @error('tahun_terbit') is-invalid @enderror">Tahun Terbit</label> <input type="number" class="form-control" placeholder="Masukkan Tahun Terbit" name="tahun_terbit" value="{{$book->tahun_terbit}}"> @error('tahun_terbit') <small class="text-danger">{{$message}}</small> @enderror </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> @endsection
mod block; mod expr; mod item; mod stmt; pub(crate) use block::parse_block; pub(crate) use expr::parse_expr; pub(crate) use item::parse_item; pub(crate) use stmt::parse_stmt;
<?php namespace TYPO3\CMS\Core\Mail; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Adapter for Swift_Mailer to be used by TYPO3 extensions */ class MailMessage extends \Swift_Message { /** * @var \TYPO3\CMS\Core\Mail\Mailer */ protected $mailer; /** * @var string This will be added as X-Mailer to all outgoing mails */ protected $mailerHeader = 'TYPO3'; /** * TRUE if the message has been sent. * * @var bool */ protected $sent = false; /** * Holds the failed recipients after the message has been sent * * @var array */ protected $failedRecipients = array(); /** * @return void */ private function initializeMailer() { $this->mailer = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\Mailer::class); } /** * Sends the message. * * @return int the number of recipients who were accepted for delivery */ public function send() { $this->initializeMailer(); $this->sent = true; $this->getHeaders()->addTextHeader('X-Mailer', $this->mailerHeader); return $this->mailer->send($this, $this->failedRecipients); } /** * Checks whether the message has been sent. * * @return bool */ public function isSent() { return $this->sent; } /** * Returns the recipients for which the mail was not accepted for delivery. * * @return array the recipients who were not accepted for delivery */ public function getFailedRecipients() { return $this->failedRecipients; } /** * Set the return-path (the bounce address) of this message. * * @param string $address * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setReturnPath($address) { $address = $this->idnaEncodeAddresses($address); return parent::setReturnPath($address); } /** * Set the sender of this message. * * This does not override the From field, but it has a higher significance. * * @param string $address * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setSender($address, $name = null) { $address = $this->idnaEncodeAddresses($address); return parent::setSender($address, $name); } /** * Set the from address of this message. * * You may pass an array of addresses if this message is from multiple people. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setFrom($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setFrom($addresses, $name); } /** * Set the reply-to address of this message. * * You may pass an array of addresses if replies will go to multiple people. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setReplyTo($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setReplyTo($addresses, $name); } /** * Set the to addresses of this message. * * If multiple recipients will receive the message an array should be used. * Example: array('receiver@domain.org', 'other@domain.org' => 'A name') * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setTo($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setTo($addresses, $name); } /** * Set the Cc addresses of this message. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setCc($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setCc($addresses, $name); } /** * Set the Bcc addresses of this message. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setBcc($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setBcc($addresses, $name); } /** * Ask for a delivery receipt from the recipient to be sent to $addresses. * * @param array $addresses * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setReadReceiptTo($addresses) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setReadReceiptTo($addresses); } /** * IDNA encode email addresses. Accepts addresses in all formats that SwiftMailer supports * * @param string|array $addresses * @return string|array */ protected function idnaEncodeAddresses($addresses) { if (!is_array($addresses)) { return $this->idnaEncodeAddress($addresses); } $newAddresses = []; foreach ($addresses as $email => $name) { if (ctype_digit($email)) { $newAddresses[] = $this->idnaEncodeAddress($name); } else { $newAddresses[$this->idnaEncodeAddress($email)] = $name; } } return $newAddresses; } /** * IDNA encode the domain part of an email address if it contains non ASCII characters * * @param mixed $email * @return mixed * @see \TYPO3\CMS\Core\Utility\GeneralUtility::validEmail */ protected function idnaEncodeAddress($email) { // Early return in case input is not a string if (!is_string($email)) { return $email; } // Split on the last "@" since adresses like "foo@bar"@example.org are valid $atPosition = strrpos($email, '@'); if (!$atPosition || $atPosition + 1 === strlen($email)) { // Return if no @ found or it is placed at the very beginning or end of the email return $email; } $domain = substr($email, $atPosition + 1); $local = substr($email, 0, $atPosition); $domain = \TYPO3\CMS\Core\Utility\GeneralUtility::idnaEncode($domain); return $local . '@' . $domain; } }
import { ZipFileUnzipped } from "./ZipFileUnzipped" import stream from "stream" import { createAssertNode, ScriptError, PathInfo } from "../utility" test("assert", async () => { const container = { interpolator: (node) => node.value, fs: { ensureDir: jest.fn(async (dirPath) => { expect(typeof dirPath).toBe("string") }), }, util: { pathInfo: async (path) => { switch (path) { case "outdir/filedir.txt": case "outdir/dir/": case "./outdir": case ".": return new PathInfo({ isDirectory: () => true, isFile: () => false, size: 0, mode: 0o777, }) case "outdir/dir/file.txt": case "outdir/dirfile.txt/": case "./filesize.zip": case "./filedir.zip": case "./dirfile.zip": case "./somefile.zip": case "./withfilemissing.zip": return new PathInfo({ isDirectory: () => false, isFile: () => true, size: 100, mode: 0o777, }) default: return new PathInfo() } }, }, yauzl: { open: jest.fn(async (path) => { expect(typeof path).toBe("string") const openReadStream = async () => new stream.Readable({ read(size) { this.push("The quick brown fox jumps over the lazy dog\n") this.push(null) }, }) let entries = null switch (path) { default: case "./somefile.zip": entries = [ { uncompressedSize: 0, fileName: "dir/" }, { uncompressedSize: 100, fileName: "dir/file.txt", openReadStream, }, ] break case "./filesize.zip": entries = [ { uncompressedSize: 0, fileName: "dir/" }, { uncompressedSize: 50, fileName: "dir/file.txt", openReadStream, }, ] break case "./filedir.zip": // File is a directory entries = [ { uncompressedSize: 50, fileName: "filedir.txt", openReadStream, }, ] break case "./dirfile.zip": // Directory is a file entries = [ { uncompressedSize: 0, fileName: "dirfile.txt/", openReadStream, }, ] break case "./withfilemissing.zip": entries = [ { uncompressedSize: 100, fileName: "notthere.txt", openReadStream, }, ] break } expect(entries).not.toBeNull() return { close: jest.fn(async () => null), walkEntries: jest.fn(async (callback) => { // Assuming that callback returns a Promise await Promise.all(entries.map(callback)) }), } }), }, } const assertion = new ZipFileUnzipped(container) // With bad zip path await expect( assertion.assert(createAssertNode(assertion, {})) ).rejects.toThrow(ScriptError) await expect( assertion.assert(createAssertNode(assertion, { file: 1 })) ).rejects.toThrow(ScriptError) // With bad toDirectory path await expect( assertion.assert(createAssertNode(assertion, { file: "" })) ).rejects.toThrow(ScriptError) await expect( assertion.assert(createAssertNode(assertion, { file: "", toDirectory: 1 })) ).rejects.toThrow(ScriptError) // With file not present await expect( assertion.assert( createAssertNode(assertion, { file: "./missing.zip", toDirectory: "./outdir", }) ) ).rejects.toThrow(ScriptError) // With all files unzipped and the same await expect( assertion.assert( createAssertNode(assertion, { file: "./somefile.zip", toDirectory: "./outdir", }) ) ).resolves.toBe(true) // With output directory missing await expect( assertion.assert( createAssertNode(assertion, { file: "./somefile.zip", toDirectory: "./notthere", }) ) ).rejects.toThrow(ScriptError) // With a file missing await expect( assertion.assert( createAssertNode(assertion, { file: "./withfilemissing.zip", toDirectory: "./outdir", }) ) ).resolves.toBe(false) // With a file as different size await expect( assertion.assert( createAssertNode(assertion, { file: "./filesize.zip", toDirectory: "./outdir", }) ) ).resolves.toBe(false) // With a file as a directory await expect( assertion.assert( createAssertNode(assertion, { file: "./filedir.zip", toDirectory: "./outdir", }) ) ).rejects.toThrow(ScriptError) // With a directory as a file await expect( assertion.assert( createAssertNode(assertion, { file: "./dirfile.zip", toDirectory: "./outdir", }) ) ).rejects.toThrow(ScriptError) // With bad zip file container.yauzl.open = jest.fn(async () => { throw Error() }) await expect( assertion.assert( createAssertNode(assertion, { file: "./somefile.zip", toDirectory: "./outdir", }) ) ).resolves.toBe(false) }) test("rectify", async () => { const container = { fs: { ensureDir: jest.fn(async () => undefined), createWriteStream: jest.fn(async () => { return new stream.Writable({ write(chunk, encoding, callback) { callback() }, }) }), }, util: { pathInfo: async (path) => { switch (path) { default: return new PathInfo() } }, pipeToPromise: async (readable, writeable) => {}, }, yauzl: { open: jest.fn(async (path) => { const openReadStream = async () => new stream.Readable({ read(size) { this.push("The quick brown fox jumps over the lazy dog\n") this.push(null) }, }) let entries = [ { uncompressedSize: 0, fileName: "a/" }, { uncompressedSize: 100, fileName: "a/file.txt", openReadStream, }, { uncompressedSize: 100, fileName: "b/file.txt", openReadStream, }, ] return { close: jest.fn(async () => null), walkEntries: jest.fn(async (callback) => { // Assuming that callback returns a Promise await Promise.all(entries.map(callback)) }), } }), }, } const assertion = new ZipFileUnzipped(container) assertion.expandedFilePath = "/xyz.zip" assertion.expandedToPath = "/" await expect(assertion.rectify()).resolves.toBeUndefined() // If zip file cannot be opened container.yauzl.open = jest.fn(async () => { throw new Error() }) await expect(assertion.rectify()).rejects.toThrow(Error) }) test("result", () => { const assertion = new ZipFileUnzipped({}) assertion.expandedFilePath = "blah.zip" assertion.expandedToPath = "file/" expect(assertion.result()).toEqual({ file: assertion.expandedFilePath, toDirectory: assertion.expandedToPath, }) })
package top.cnzw.kotlin.mc.iwq import taboolib.common.platform.Plugin import taboolib.common.platform.function.console import taboolib.common.platform.function.getDataFolder import taboolib.module.lang.sendLang import top.cnzw.kotlin.mc.iwq.util.DataBaseHandler import top.cnzw.kotlin.mc.iwq.util.WebSocketClient object InteractWithQQ : Plugin() { override fun onLoad() { //TODO Metrics if (getDataFolder().exists()) console().sendLang("Plugin-OnLoad") else console().sendLang("Plugin-FirstLoad") } override fun onEnable() { console().sendLang("Plugin-OnEnable") if (getDataFolder().exists()) DataBaseHandler.connect() else DataBaseHandler.init() WebSocketClient.init() } override fun onDisable() { console().sendLang("Plugin-OnDisable") WebSocketClient.close() } }
package ru.stonks.entity.bot case class BotCommandWithInput( botCommand: BotCommand, userInput: Option[String] )
# What did the king say he would do for the person or people who revealed the dream to him and interpreted it? The king said he would give that person or persons gifts, a reward, and great honor.
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen //Copyright 2006-2011 Jeroen van Menen // // 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. #endregion Copyright using System; using System.Collections.Specialized; using System.Drawing; using WatiN.Core.DialogHandlers; using WatiN.Core.Actions; namespace WatiN.Core.Native { public interface INativeElement { /// <summary> /// Gets a collection consisting of the immediate children of this element. /// </summary> INativeElementCollection Children { get; } /// <summary> /// Gets a collection consisting of all descendants of this element. /// </summary> INativeElementCollection AllDescendants { get; } /// <summary> /// Gets a collection consisting of the immediate rows within a TABLE or TBODY element. /// </summary> /// <exception cref="InvalidOperationException">Thrown if applied to an element of the wrong type</exception> INativeElementCollection TableRows { get; } /// <summary> /// Gets a collection consisting of the immediate tbodies within a TABLE element. /// </summary> /// <exception cref="InvalidOperationException">Thrown if applied to an element of the wrong type</exception> INativeElementCollection TableBodies { get; } /// <summary> /// Gets a collection consisting of the immediate cells within a TR element. /// </summary> /// <exception cref="InvalidOperationException">Thrown if applied to an element of the wrong type</exception> INativeElementCollection TableCells { get; } /// <summary> /// Gets a collection consisting of the options within a SELECT element. /// </summary> INativeElementCollection Options { get; } /// <summary> /// Returns the text displayed after this element when it's wrapped /// in a Label element; otherwise it returns <c>null</c>. /// </summary> string TextAfter { get; } /// <summary> /// Returns the text displayed before this element when it's wrapped /// in a Label element; otherwise it returns <c>null</c>. /// </summary> string TextBefore { get; } /// <summary> /// Gets the next sibling of this element in the Dom of the HTML page. /// </summary> /// <value>The next sibling.</value> INativeElement NextSibling { get; } /// <summary> /// Gets the previous sibling of this element in the Dom of the HTML page. /// </summary> /// <value>The previous sibling.</value> INativeElement PreviousSibling { get; } /// <summary> /// Gets the parent element of this element. /// If the parent type is known you can cast it to that type. /// </summary> /// <value>The parent.</value> /// <example> /// The following example shows you how to use the parent property. /// Assume your web page contains a bit of html that looks something /// like this: /// /// div /// a id="watinlink" href="http://watin.sourceforge.net" / /// a href="http://sourceforge.net/projects/watin" / /// /div /// div /// a id="watinfixturelink" href="http://watinfixture.sourceforge.net" / /// a href="http://sourceforge.net/projects/watinfixture" / /// /div /// Now you want to click on the second link of the watin project. Using the /// parent property the code to do this would be: /// /// <code> /// Div watinDiv = (Div) ie.Link("watinlink").Parent; /// watinDiv.Links[1].Click(); /// </code> /// </example> INativeElement Parent { get; } /// <summary> /// This methode can be used if the attribute isn't available as a property of /// Element or a subclass of Element. /// </summary> /// <param name="attributeName">The attribute name. This could be different then named in /// the HTML. It should be the name of the property exposed by the element DOM object.</param> /// <returns>The value of the attribute if available; otherwise <c>null</c> is returned.</returns> string GetAttributeValue(string attributeName); void SetAttributeValue(string attributeName, string value); string GetStyleAttributeValue(string attributeName); void SetStyleAttributeValue(string attributeName, string value); void SetFocus(); void FireEvent(string eventName, NameValueCollection eventProperties); void FireEventNoWait(string eventName, NameValueCollection eventProperties); bool IsElementReferenceStillValid(); string TagName { get; } /// <summary> /// Should fire the (on)Select event on the element. /// </summary> void Select(); /// <summary> /// Called when to submit the form. /// </summary> void SubmitForm(); /// <summary> /// Called when the file upload dialog should be filled in /// </summary> /// <param name="dialogWatcher">To inject a dialog handler into to handle the file upload dialog.</param> /// <param name="fileName">The file name to enter into the dialog filename field.</param> void SetFileUploadFile(DialogWatcher dialogWatcher, string fileName); /// <summary> /// Waits until the element is fully loaded in the DOM and/or ready to be used. /// </summary> void WaitUntilReady(); /// <summary> /// Gets the bounds of the element. /// </summary> /// <returns>The element bounds in screen coordinates</returns> Rectangle GetElementBounds(); /// <summary> /// Gets the java script element reference to this element. /// </summary> /// <returns></returns> string GetJavaScriptElementReference(); void Pin(); ITypeTextAction CreateTypeTextAction(TextField textField); ISelectAction CreateSelectAction(Option option); } }
<?php //IMathAS. Records tags/untags for messages //(c) 2007 David Lippman require("../init.php"); if (!isset($_GET['threadid'])) { exit; } $ischanged = false; $stm = $DBH->prepare("UPDATE imas_msgs SET isread=(isread^8) WHERE msgto=:msgto AND id=:id"); $stm->execute(array(':msgto'=>$userid, ':id'=>$_GET['threadid'])); if ($stm->rowCount()>0) { $ischanged = true; } if ($ischanged) { echo "OK"; } else { echo "Error"; } ?>
import Alt from './' import ActionListeners from '../utils/ActionListeners' import AltManager from '../utils/AltManager' import DispatcherRecorder from '../utils/DispatcherRecorder' import atomic from '../utils/atomic' import connectToStores from '../utils/connectToStores' import chromeDebug from '../utils/chromeDebug' import makeFinalStore from '../utils/makeFinalStore' import withAltContext from '../utils/withAltContext' import AltContainer from '../../AltContainer' Alt.addons = { ActionListeners, AltContainer, AltManager, DispatcherRecorder, atomic, chromeDebug, connectToStores, makeFinalStore, withAltContext } export default Alt
package com.jiangkang.gradle.kotlin object Versions { //project settings const val compileSdkVersion = 28 const val buildToolsVersion = "28.0.3" const val minSdkVersion = 21 const val targetSdkVersion = 28 const val versionCode = 3 const val versionName = "3.0" }
<head> <style> .kotak { border-radius: 25px; border: 2px solid #73AD21; padding-top: 0px; padding-left: 20px; padding-right: 0px; width: 300px; height: 250px; } .button { border-radius: 25px; background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> </head> <body> <div class="kotak"> <form action="/olaheditpegawai" method="post"> @csrf <h1 style="text-align: center">Edit Pegawai</h1> @foreach($result as $key=>$temp) Current Username : {{$temp['username_user']}} <br>New Username:<input type="text" placeholder="username" name="username_user"> <br>old Password: <input type="text" placeholder="old Password" id="old_password" name="old_password"> <br>new Password: <input type="text" placeholder="Password" id="password_user" name="password"> <input type="hidden" name="username" value="{{$temp['username_user']}}"> @endforeach <br> <input type="submit" value="Edit" class="button"><br> </form> @if($errors->any()) <ul> @foreach($errors->all() as $e) <li>{{$e}}</li> @endforeach </ul> @endif </div> </body>
import React, { useState, useEffect } from "react"; import Permissions from 'react-native-permissions'; import { View, Text, TouchableOpacity, Image, StyleSheet, Alert } from "react-native"; import { LinearGradient } from 'expo-linear-gradient'; import FontAwesome from "react-native-vector-icons/FontAwesome"; import MusicFiles from "react-native-get-music-files"; import { MusicProvider } from "../context/MusicContext"; import TrackPlayer, { usePlaybackState } from "react-native-track-player"; import { moderateScale } from "react-native-size-matters"; import Constants from 'expo-constants'; import SeekBar from "../components/SeekBar"; import Hamburger from "../../assets/images/hamburger.png"; import { color } from "../config"; import CardMusic from "../components/CardMusic"; import Controller from "../components/Controller"; import MusicListModal from "../components/MusicListModal"; const NowPlaying = ({ navigation }) => { const playbackState = usePlaybackState(); const [modalVisible, setModalVisible] = useState(false); const [music, setMusic] = useState({ selected: {}, list: [] }); useEffect(() => { setupPlayer(); navigation.setParams({ handleModal }); fetchMusic(); const onTrackChange = TrackPlayer.addEventListener('playback-track-changed', async (data) => { const track = await TrackPlayer.getTrack(data.nextTrack); setMusic(prevState => ({ ...prevState, selected: track })); }); return () => { onTrackChange.remove(); } }, []); const setupPlayer = async () => { await TrackPlayer.setupPlayer(); TrackPlayer.updateOptions({ stopWithApp: false, capabilities: [ TrackPlayer.CAPABILITY_PLAY, TrackPlayer.CAPABILITY_PAUSE, TrackPlayer.CAPABILITY_SKIP_TO_NEXT, TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS, TrackPlayer.CAPABILITY_STOP ], compactCapabilities: [ TrackPlayer.CAPABILITY_PLAY, TrackPlayer.CAPABILITY_PAUSE ] }); }; const togglePlayback = async () => { const currentTrack = await TrackPlayer.getCurrentTrack(); if(currentTrack){ if (playbackState === TrackPlayer.STATE_PAUSED) { await TrackPlayer.play(); } else { await TrackPlayer.pause(); } } }; const skipToNext = async () => { try { await TrackPlayer.skipToNext(); } catch (_) {} }; const skipToPrevious = async () => { try { await TrackPlayer.skipToPrevious(); } catch (_) {} }; const changeSelected = (selectedMusic) => { setMusic(prevState => ({ ...prevState, selected: selectedMusic })); TrackPlayer.skip(selectedMusic.id); setModalVisible(false); }; const fetchMusic = async () => { const status = await Permissions.request('storage'); if(status !== "authorized"){ Alert.alert( "We can't access your music", ); } const options = { blured : true, artist : true, genre : true, title : true, cover : true, minimumSongDuration : 10000, fields : ['title','albumTitle','genre','lyrics','artwork','duration'] }; MusicFiles.getAll(options).then(async tracks => { const musicsWithID = tracks.map((elm, index) => { return { ...elm, id: index.toString(), url: elm.path } }); await TrackPlayer.add(musicsWithID); setMusic({...music, list: musicsWithID, changeSelected}); }).catch(error => { console.log("error",error); }) }; const handleModal = () => { setModalVisible(!modalVisible); }; return ( <MusicProvider value={music}> <LinearGradient colors={[color.primary, color.secondary]} style={styles.container} > <View style={styles.content}> <CardMusic/> <SeekBar/> <Controller togglePlayback={togglePlayback} skipToNext={skipToNext} skipToPrevious={skipToPrevious} /> </View> <MusicListModal isModalVisible={modalVisible} closeModal={handleModal}/> </LinearGradient> </MusicProvider> ) }; NowPlaying.navigationOptions = ({ navigation }) => ({ title: "Now Playing", headerTransparent: true, headerLeft: ( <TouchableOpacity onPress={navigation.getParam("handleModal")} hitSlop={{top: 40, bottom: 40, left: 40, right: 40}} > <Image style={{ height: moderateScale(20), width: moderateScale(20)}} source={Hamburger}/> </TouchableOpacity> ), headerRight: ( <TouchableOpacity hitSlop={{top: 40, bottom: 40, left: 40, right: 40}}> <FontAwesome name="heart" size={moderateScale(24)} color="white"/> </TouchableOpacity> ), headerTitleStyle: { textAlign:'center', alignSelf:'center', flex:1, fontFamily: "Avenir-Book", fontSize: moderateScale(20), color: color.white }, headerStyle: { marginLeft: "5%", marginRight: "5%" } }); const styles = StyleSheet.create({ container: { flex: 1, paddingTop: Constants.statusBarHeight + moderateScale(50) }, content: { flex: 1, alignItems: "center", justifyContent: "space-around", } }); export default NowPlaying;
################################################################################ # catimg script by Eduardo San Martin Morote aka Posva # # http://posva.net # # # # Ouput the content of an image to the stdout using the 256 colors of the # # terminal. # # Github: https://github.com/posva/catimg # ################################################################################ function help() { echo "Usage catimg [-h] [-w width] [-c char] img" echo "By default char is \" \" and w is the terminal width" } # VARIABLES COLOR_FILE=$(dirname $0)/colors.png CHAR=" " WIDTH="" IMG="" while getopts qw:c:h opt; do case "$opt" in w) WIDTH="$OPTARG" ;; c) CHAR="$OPTARG" ;; h) help; exit ;; *) help ; exit 1;; esac done while [ "$1" ]; do IMG="$1" shift done if [ "$IMG" = "" -o ! -f "$IMG" ]; then help exit 1 fi if [ ! "$WIDTH" ]; then COLS=$(expr $(tput cols) "/" $(echo -n "$CHAR" | wc -c)) else COLS=$(expr $WIDTH "/" $(echo -n "$CHAR" | wc -c)) fi WIDTH=$(convert "$IMG" -print "%w\n" /dev/null) if [ "$WIDTH" -gt "$COLS" ]; then WIDTH=$COLS fi REMAP="" if convert "$IMG" -resize $COLS\> +dither -remap $COLOR_FILE /dev/null ; then REMAP="-remap $COLOR_FILE" else echo "The version of convert is too old, don't expect good results :(" >&2 #convert "$IMG" -colors 256 PNG8:tmp.png #IMG="tmp.png" fi # Display the image I=0 convert "$IMG" -resize $COLS\> +dither `echo $REMAP` txt:- 2>/dev/null | sed -e 's/.*none.*/NO NO NO/g' -e '1d;s/^.*(\(.*\)[,)].*$/\1/g;y/,/ /' | while read R G B f; do if [ ! "$R" = "NO" ]; then if [ "$R" -eq "$G" -a "$G" -eq "$B" ]; then (( I++, IDX = 232 + R * 23 / 255 )) else (( I++, IDX = 16 + R * 5 / 255 * 36 + G * 5 / 255 * 6 + B * 5 / 255 )) fi #echo "$R,$G,$B: $IDX" echo -ne "\e[48;5;${IDX}m${CHAR}" else (( I++ )) echo -ne "\e[0m${CHAR}" fi # New lines (( $I % $WIDTH )) || echo -e "\e[0m" done
import 'package:flutter/material.dart'; import 'package:flutter_const/src/constant/color.dart'; ThemeData darkTheme = ThemeData( brightness: Brightness.dark, // Colors scaffoldBackgroundColor: FcColor.scaffoldBackgroundDark, backgroundColor: FcColor.backgroundDark, cardColor: FcColor.cardDark, primaryColor: FcColor.primaryDark, bottomAppBarColor: const Color(0xFF35353a), dividerColor: const Color(0x1CFFFFFF), // Themes bottomNavigationBarTheme: const BottomNavigationBarThemeData( backgroundColor: FcColor.cardBackgroundDark, selectedItemColor: FcColor.selectedItemDark, unselectedItemColor: FcColor.unselectedItemDark, ), cardTheme: const CardTheme(color: FcColor.cardBackgroundDark), // AppBarTheme appBarTheme: const AppBarTheme(backgroundColor: FcColor.cardBackgroundDark), textTheme: TextTheme( headline1: const TextStyle(color: FcColor.headingDark, fontWeight: FontWeight.w300), headline2: const TextStyle(color: FcColor.headingDark), headline3: const TextStyle(color: FcColor.headingDark), headline4: const TextStyle(color: FcColor.labelDark), headline5: const TextStyle(color: FcColor.labelDark), headline6: const TextStyle(color: FcColor.labelDark), subtitle1: TextStyle(color: textSwatch.shade200), subtitle2: TextStyle(color: textSwatch.shade300), bodyText1: const TextStyle(color: FcColor.bodyDark), bodyText2: const TextStyle(color: FcColor.bodyDark), button: TextStyle(color: textSwatch.shade400), caption: TextStyle(color: textSwatch.shade400), overline: TextStyle(color: textSwatch.shade400), ), );
using System.IO; using System.Linq; using System.Threading.Tasks; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Lsp.Tests { public class OmniSharpImplementationHandlerFacts : AbstractLanguageServerTestBase { public OmniSharpImplementationHandlerFacts(ITestOutputHelper output) : base(output) { } [Fact] public async Task CanFindImplementationsOfClass() { const string code = @" public class Foo$$Base { } public class FooDerivedA : FooBase { } public class FooDerivedB : FooBase { }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(3, implementations.Count()); } [Fact] public async Task CanFindImplementationsOfInterface() { const string code = @" public interface IF$$oo { } public class FooA : IFoo { } public class FooB : IFoo { }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(2, implementations.Count()); } [Fact] public async Task CanFindImplementationsOfVirtualFunction() { const string code = @" public class FooBase { public virtual int B$$ar() { return 1; } } public class FooDerivedA : FooBase { public override int Bar() { return 2; } } public class FooDerivedB : FooBase { public override int Bar() { return 3; } }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(3, implementations.Count()); } [Fact] public async Task CanFindImplementationsOfAbstractFunction() { const string code = @" public abstract class FooBase { public abstract int B$$ar(); } public class FooDerivedA : FooBase { public override int Bar() { return 2; } } public class FooDerivedB : FooBase { public override int Bar() { return 3; } }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(2, implementations.Count()); } [Fact] public async Task CanFindImplementationsOfVirtualProperty() { const string code = @" public class FooBase { public virtual int B$$ar => 1; } public class FooDerivedA : FooBase { public override int Bar => 2; } public class FooDerivedB : FooBase { public override int Bar => 3; }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(3, implementations.Count()); } [Fact] public async Task CanFindImplementationsOfAbstractProperty() { const string code = @" public abstract class FooBase { public abstract int B$$ar { get; } } public class FooDerivedA : FooBase { public override int Bar => 2; } public class FooDerivedB : FooBase { public override int Bar => 3; }"; var implementations = await FindImplementationsAsync(code); Assert.Equal(2, implementations.Count()); } [Fact] public async Task CannotFindImplementationsWithoutSymbol() { const string code = @" public class Foo { $$ }"; var implementations = await FindImplementationsAsync(code); Assert.Empty(implementations); } [Fact] public async Task CannotFindImplementationsForUnsupportedSymbol() { const string code = @" pub$$lic class Foo { }"; var implementations = await FindImplementationsAsync(code); Assert.Empty(implementations); } [Fact] public async Task CannotFindImplementationsForEmptyFiles() { var response = await Client.TextDocument.RequestImplementation(new ImplementationParams { Position = (0, 0), TextDocument = "notfound.cs" }, CancellationToken); Assert.Empty(response); } private Task<LocationOrLocationLinks> FindImplementationsAsync(string code) { return FindImplementationsAsync(new[] { new TestFile("dummy.cs", code) }); } private async Task<LocationOrLocationLinks> FindImplementationsAsync(TestFile[] testFiles) { OmniSharpTestHost.AddFilesToWorkspace(testFiles .Select(f => new TestFile( ((f.FileName.StartsWith("/") || f.FileName.StartsWith("\\")) ? f.FileName : ("/" + f.FileName)) .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar), f.Content)) .ToArray() ); var file = testFiles.Single(tf => tf.Content.HasPosition); var point = file.Content.GetPointFromPosition(); Client.TextDocument.DidChangeTextDocument(new DidChangeTextDocumentParams { ContentChanges = new Container<TextDocumentContentChangeEvent>(new TextDocumentContentChangeEvent { Text = file.Content.Code }), TextDocument = new VersionedTextDocumentIdentifier { Uri = DocumentUri.From(file.FileName), Version = 1 } }); return await Client.TextDocument.RequestImplementation(new ImplementationParams { Position = new Position(point.Line, point.Offset), TextDocument = new TextDocumentIdentifier(DocumentUri.From(file.FileName)) }, CancellationToken); } } }
#!/bin/bash go get -u github.com/jstemmer/go-junit-report oc login -u ${OCP_CRED_USR} -p ${OCP_CRED_PSW} --server=${OCP_API_URL} --insecure-skip-tls-verify=true go test -timeout 3h -run ${TEST_CASE} -v 2>&1 | tee >($HOME/go/bin/go-junit-report > results.xml) test.log echo "#Testing Completed#" sleep 300
// Copyright 2022 VaultOperator Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v1alpha1 // +kubebuilder:object:generate=false type AnyVaultSecretData interface { GetName() string GetLocation() *VaultSecretLocation GetGenerator() *VaultSecretGenerator GetCollisionStrategy() FieldCollisionStrategy } func (d *VaultSecretData) GetName() string { return d.Name } func (d *VaultSecretData) GetLocation() *VaultSecretLocation { return d.Location } func (d *VaultSecretData) GetGenerator() *VaultSecretGenerator { return d.Generator } func (d *VaultSecretData) GetCollisionStrategy() FieldCollisionStrategy { return ErrorOnCollision } func (d *VaultSecretVariable) GetName() string { return d.Name } func (d *VaultSecretVariable) GetLocation() *VaultSecretLocation { return d.Location } func (d *VaultSecretVariable) GetGenerator() *VaultSecretGenerator { return d.Generator } func (d *VaultSecretVariable) GetCollisionStrategy() FieldCollisionStrategy { return ErrorOnCollision } func (d *VaultSecretDataRef) GetName() string { return d.Path } func (d *VaultSecretDataRef) GetLocation() *VaultSecretLocation { return &VaultSecretLocation{Path: d.Path, Version: d.Version} } func (d *VaultSecretDataRef) GetGenerator() *VaultSecretGenerator { return nil } func (d *VaultSecretDataRef) GetCollisionStrategy() FieldCollisionStrategy { if d.CollisionStrategy != "" { return d.CollisionStrategy } return ErrorOnCollision }
/** @Name:全局配置 @Author:十万马 @Site:http://www.layui.com/admin/ */ layui.define(['laytpl', 'layer', 'element', 'util'], function (exports) { exports('setter', { container: 'LAY_app' //容器ID , base: layui.cache.base //记录layuiAdmin文件夹所在路径 , views: layui.cache.base + 'views/' //视图所在目录 , entry: 'index' //默认视图文件名 , engine: '.html' //视图文件后缀名 , pageTabs: true //是否开启页面选项卡功能。单页版不推荐开启 , name: '东篱下 后台系统' , tableName: 'dlx' //本地存储表名 , MOD_NAME: 'admin' //模块事件名 , debug: false //是否开启调试模式。如开启,接口异常时会抛出异常 URL 等信息 , interceptor: true //是否开启未登入拦截 // 自定义设置全局变量 , admin_set: { domain: '' //接口域名 , table_limit: 15 //数据表,每页显示数量 , table_limits : [10,15,30,50,100,200]//数据表,分页“下拉框”候选项 , editor_config:{ uploadImage: { url: '/admin/upload_file/addImgEditor' //接口url ,type: 'post' //默认post } } , upload_url: '/admin/upload_file/addImg' , upload_url_qiniu: '/admin/qiniu/uploadFile' , upload_size: '4096' } //自定义请求字段 , request: { tokenName: 'access_token' //自动携带 token 的字段名。可设置 false 不携带。 } //自定义响应字段 , response: { statusName: 'code' //数据状态的字段名称 , statusCode: { ok: [0,1] //数据状态一切正常的状态码 , logout: 1001 //登录状态失效的状态码 } , msgName: 'msg' //状态信息的字段名称 , dataName: 'data' //数据详情的字段名称 } //独立页面路由,可随意添加(无需写参数) , indPage: [ '/alone/login' //登入页 , '/alone/reg' //注册页 , '/alone/forget' //找回密码 ] //扩展的第三方模块 , extend: [ 'echarts', //echarts 核心包 'echartsTheme', //echarts 主题 'qiNiu' //js上传七牛云存储 ] }); });
package com.github.cuzfrog.nodejs import scala.scalajs.js import scala.scalajs.js.annotation.JSImport import scala.scalajs.js.| @js.native @JSImport("child_process", JSImport.Namespace) object ChildProcess extends js.Object { def execSync(command: String, options: js.UndefOr[js.Object] = js.undefined): js.Object | String = js.native }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using MusicPrimitives; using RhythmCat; namespace RhythmCatTests { [TestClass] public class TestLarsonExpectedness { [TestMethod] public void TestExpectationVector() { List<Note> notes = new List<Note>(); notes.Add(new Note(1, false, false, new MidiInfo(60, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(62, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(64, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(65, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(67, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(69, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(71, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(72, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(72, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(71, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(69, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(68, Accidental.Flat))); notes.Add(new Note(1, false, false, new MidiInfo(67, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(65, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(64, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(62, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(61, Accidental.Flat))); notes.Add(new Note(1, false, false, new MidiInfo(60, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(59, Accidental.Natural))); notes.Add(new Note(1, false, false, new MidiInfo(60, Accidental.Natural))); Workspace w = new Workspace(-1, false, -1); Rhythm rhythm = new Rhythm(notes); Measure m = new Measure(w, rhythm); Group g = new Group(w); g.AddGroupElement(m); Key cmajor = new Key(0, KeyMode.Major); List<float> larson = g.GetNoteExpectednessLarson(cmajor, Alphabet.GetScaleAlphabet(cmajor)); for (int i = 0; i < notes.Count; i++) { // Test for local min/max. if (i > 0 && i < notes.Count - 1) { if (larson[i - 1] < larson[i] && larson[i + 1] < larson[i]) Console.Write("MAX: "); if (larson[i - 1] > larson[i] && larson[i + 1] > larson[i]) Console.Write("MIN: "); } Console.WriteLine("{0}: {1:0.###}", notes[i].ToString(), larson[i]); } /* List<ScaleDegree> degrees = new List<ScaleDegree>(); degrees.Add(new ScaleDegree(1, Alteration.None)); degrees.Add(new ScaleDegree(4, Alteration.None)); List<Alphabet> result = Alphabet.GetConsistentAlphabetsForScaleDegrees(degrees, KeyMode.Major); Console.WriteLine("Major"); foreach (Alphabet a in result) { Console.WriteLine(a.ToString()); } result = Alphabet.GetConsistentAlphabetsForScaleDegrees(degrees, KeyMode.Minor); Console.WriteLine("Minor"); foreach (Alphabet a in result) { Console.WriteLine(a.ToString()); } */ } } }
require 'safemode' require 'erb' module ActionView module TemplateHandlers class SafeErb < TemplateHandler include Compilable extend SafemodeHandler def self.line_offset 0 end def compile(template) src = template.source filename = template.filename erb_trim_mode = ActionView::TemplateHandlers::ERB.erb_trim_mode erb_code = ::ERB.new("<% __in_erb_template=true %>#{src}", nil, erb_trim_mode, 'self.output_buffer').src # Ruby 1.9 prepends an encoding to the source. However this is # useless because you can only set an encoding on the first line RUBY_VERSION >= '1.9' ? src.sub(/\A#coding:.*\n/, '') : src Safemode::Boxes[filename] = Safemode::Box.new(erb_code, filename, 0) boxed_erb = <<-CODE handler = ActionView::TemplateHandlers::SafeErb assigns = {} handler.valid_assigns(instance_variables).each do |var| assigns[var[1,var.length]] = instance_variable_get(var) end methods = handler.delegate_methods( self.controller.master_helper_module.instance_methods ) box = Safemode::Boxes[#{filename.inspect}] box.eval(self, methods, assigns, local_assigns, &lambda{ |*args| yield(*args) }) CODE # for debugging purposes (or for those curious enough to endure compiled ERB) # puts "ERB CODE OF #{filename}" # puts erb_code # puts "" # puts "JAILED CODE OF #{filename}" # puts Safemode::Boxes[filename].instance_variable_get('@code') boxed_erb end end end end
#!/usr/bin/perl use strict; use warnings; use Benchmark qw( cmpthese timethese ); our $VERSION = '1.00'; my $wanttime = $ARGV[1] || 5; use JSON qw( -support_by_pp -no_export ); # for JSON::PP::Boolean inheritance use JSON::PP (); use JSON::XS (); use utf8; my $pp = JSON::PP->new->utf8; my $xs = JSON::XS->new->utf8; local $/; my $json = <>; my $perl = JSON::XS::decode_json $json; my $result; printf( "JSON::PP %s\n", JSON::PP->VERSION ); printf( "JSON::XS %s\n", JSON::XS->VERSION ); print "-----------------------------------\n"; print "->decode()\n"; print "-----------------------------------\n"; $result = timethese( -$wanttime, { 'JSON::PP' => sub { $pp->decode( $json ) }, 'JSON::XS' => sub { $xs->decode( $json ) }, }, 'none' ); cmpthese( $result ); print "-----------------------------------\n"; __END__ =pod =head1 SYNOPSYS bench_decode.pl json-file # or bench_decode.pl json-file minimum-time =head1 DESCRIPTION L<JSON::PP> and L<JSON::XS> decoding benchmark. =head1 AUTHOR makamaka =head1 LISENCE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
<?php use App\Models\Article; use App\Models\Cart; use App\Models\Client; use App\Models\Commande; use App\Models\Location; use App\Models\Paiement; function cardData($user_id) { $cart_data = Cart::where("client_id", $user_id) ->where("status", false) ->get(); return $cart_data; } function getTotal($user_id) { $cart_data = Cart::where("client_id", $user_id) ->where("status", false) ->get(); $sum = $cart_data->sum(function ($item) { return $item->article->price * $item->quantity; }); return $sum; } function get_locations() { return Location::all(); } function getTotalSells() { $commandes = Commande::where("status", true)->get(); if (count($commandes) == 0) { return 0; } else { return $commandes->sum(function ($commande) { return $commande->articles->sum(function ($item) { return $item->price * $item->pivot->quantity; }); }); } } function getMonthlySells() { $commandes = Commande::where("status", true) ->whereMonth('created_at', date('m')) ->whereYear('created_at', date('Y')) ->get(); return $commandes; } function getSoldArticles() { return count(Commande::where("status", true)->get()); } function allCLients() { return count(Client::all()); } function getMonthlyTotal() { $commandes = Commande::where("status", false) ->whereMonth('created_at', date('m')) ->whereYear('created_at', date('Y')) ->get(); return count($commandes); } function getSuccesCmd($status) { $commandes = Commande::where("status", $status) ->get(); return count($commandes); } function getPaiementStatus($status) { $commandes = Paiement::where("status", $status) ->get(); return count($commandes); } function getNetBenefit() { } function getLocationProducts() { return Location::with('articles')->all(); } function getRoutePath() { $current = Route::currentRouteName(); $link = explode(".", $current); return ucfirst($link[0]); } function getNetProfit() { $commandes = Commande::where("status", true)->get(); $articles = Article::all(); if (count($commandes) == 0) { return 0; } else { $sells = $commandes->sum(function ($commande) { return $commande->articles->sum(function ($item) { return $item->price * $item->pivot->quantity; }); }); $purchases = $articles->sum('price'); return $sells - $purchases; } } function getLocation() { $locations = Location::all(); return $locations[0]; }
import React from "react"; import { Icon, IconProps } from "./index"; import { withKnobs, color, select } from "@storybook/addon-knobs"; import styled from "styled-components"; import { icons } from "../shared/icons"; export default { title: "Components/Icon", component: Icon, decorators: [withKnobs], }; export const knobsIcon = () => ( <Icon icon={select<IconProps["icon"]>( "icons", Object.keys(icons) as IconProps["icon"][], "bookmark" )} color={color("color", "black")} ></Icon> ); const Meta = styled.div` color: #666; font-size: 12px; `; const List = styled.ul` display: flex; flex-flow: row wrap; list-style: none; `; const Item = styled.li` display: inline-flex; flex-direction: row; align-items: center; flex: 0 1 20%; min-width: 120px; padding: 0px 7.5px 20px; svg { margin-right: 10px; width: 24px; height: 24px; } `; export const labels = () => ( <> There are {Object.keys(icons).length} icons <List> {Object.keys(icons).map((key) => ( <Item key={key}> <Icon icon={key as keyof typeof icons} /> <Meta>{key}</Meta> </Item> ))} </List> </> );
import React from "react"; import { Container, Row, Col } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import SignupForm from "./SignupForm"; const HomeSection = () => { return ( <header id="home-section"> <div className="dark-overlay"> <Container> <Row id="home-inner"> <Col lg={8} className="d-none d-lg-block"> <h1 className="display-4"> Build <strong>social profiles</strong> and gain revenue{" "} <strong>profit</strong> </h1> <div className="d-flex"> <div className="p-4 align-self-start"> <FontAwesomeIcon icon={["fas", "check"]} size="lg" /> </div> <div className="p-4 align-self end"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus, labore veniam consequuntur corporis repellat mollitia? </div> </div> <div className="d-flex"> <div className="p-4 align-self-start"> <FontAwesomeIcon icon={["fas", "check"]} size="lg" /> </div> <div className="p-4 align-self end"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus, labore veniam consequuntur corporis repellat mollitia? </div> </div> <div className="d-flex"> <div className="p-4 align-self-start"> <FontAwesomeIcon icon={["fas", "check"]} size="lg" /> </div> <div className="p-4 align-self end"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus, labore veniam consequuntur corporis repellat mollitia? </div> </div> </Col> <Col lg={4}> <SignupForm /> </Col> </Row> </Container> </div> </header> ); }; export default HomeSection;
# framework require "harvesting/version" require "harvesting/enumerable" require "harvesting/errors" require "harvesting/models/base" require "harvesting/models/harvest_record" require "harvesting/models/harvest_record_collection" # harvest records require "harvesting/models/client" require "harvesting/models/user" require "harvesting/models/company" require "harvesting/models/project" require "harvesting/models/invoice" require "harvesting/models/task" require "harvesting/models/task_assignment" require "harvesting/models/time_entry" # harvest record collections require "harvesting/models/clients" require "harvesting/models/tasks" require "harvesting/models/users" require "harvesting/models/contact" require "harvesting/models/time_entries" require "harvesting/models/projects" # API client require "harvesting/client" module Harvesting end
# Returns a comma-seperated list of all binaries with setuid Facter.add(:privileged_commands) do confine :kernel => "Linux" setcode do binaries = Facter::Util::Resolution.exec('find / -xdev -type f -perm -4000 -o -type f -perm -2000 2>/dev/null') binaries && binaries.split().join(',') end end