text
stringlengths 27
775k
|
|---|
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
use JWTAuth;
use App\Comment;
class CommentCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
/*public function with($request) {
$currentUser = JWTAuth::parseToken()->toUser();
$userComment = Comment::where('user_id', $currentUser->id)->where('movie_id', );
return [
'user' => json_encode((new CommentResource($userComment)))
];
}*/
}
|
package com.cheise_proj.data.mapper.user
import com.cheise_proj.data.mapper.base.DataMapper
import com.cheise_proj.data.model.user.ProfileData
import com.cheise_proj.domain.entity.user.ProfileEntity
internal class ProfileDataEntityMapper : DataMapper<ProfileData, ProfileEntity> {
override fun dataToEntity(d: ProfileData): ProfileEntity {
return ProfileEntity(
username = d.username,
semester = d.semester,
section = d.section,
refNo = d.refNo,
guardian = d.guardian,
gender = d.gender,
faculty = d.faculty,
contact = d.contact,
adminDate = d.adminDate,
dob = d.dob,
imageUrl = d.imageUrl,
level = d.level,
name = d.name
)
}
override fun entityToData(e: ProfileEntity): ProfileData {
return ProfileData(
username = e.username,
semester = e.semester,
section = e.section,
refNo = e.refNo,
guardian = e.guardian,
gender = e.gender,
faculty = e.faculty,
contact = e.contact,
adminDate = e.adminDate,
dob = e.dob,
imageUrl = e.imageUrl,
level = e.level,
name = e.name
)
}
}
|
using System;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
namespace Assets.Pixelation.Scripts
{
[Serializable]
[PostProcess(typeof(Pixelationv2Renderer), PostProcessEvent.AfterStack, "Custom/Pixelation")]
public sealed class Pixelationv2 : PostProcessEffectSettings
{
[Range(64.0f, 512.0f)]
public FloatParameter BlockCount = new FloatParameter { value = 128 };
}
public sealed class Pixelationv2Renderer : PostProcessEffectRenderer<Pixelationv2>
{
public override void Render(PostProcessRenderContext context)
{
float k = context.camera.aspect;
var blockCount = settings.BlockCount;
var count = new Vector2(blockCount, blockCount / k);
var size = new Vector2(1.0f / count.x, 1.0f / count.y);
var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/Pixelation"));
sheet.properties.SetVector("BlockCount", count);
sheet.properties.SetVector("BlockSize", size);
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
}
}
|
import MetaInfo from "../config/metainfo.js"
const { NODE_ENV } = process.env
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${MetaInfo.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<meta data-vmid="description" data-vue-meta="true" name="description" content="${
MetaInfo.description
}" />
<link rel="manifest" href="/manifest.json" />
<link rel="icon" href="/images/icons/icon-72x72.png" />
<style>
body {
background-color: #000000;
color: $FFFFFF;
}
</style>
</head>
<body>
<div id="app">oopsreview rendering...</div>
${getScript()}
</body>
</html>`
function getScript() {
const webpackAssets = require("../../internals/webpack-assets.json")
return `
<script src="/build/${
NODE_ENV == "production" ? webpackAssets.vendor.js : "vendor.js"
}"></script>
<script src="/build/${
NODE_ENV == "production" ? webpackAssets.app.js : "app.js"
}"></script>
${
NODE_ENV === "production"
? `
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123389386-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-123389386-1');
</script>
`
: ""
}
`
}
export default (req, res, next) => {
res.writeHead(200, {
"Content-Type": "text/html"
})
res.write(html)
res.end()
}
|
import { Scene } from 'phaser';
import U from '../utils/usefull';
import getConfigKeys from '../utils/getConfigKeys';
import head from '../assets/head.png';
import bip from '../assets/sounds/bip.ogg';
export default class LoadSavedGame extends Scene {
constructor() {
super({ key: 'loadSavedGame' });
}
preload() {
this.load.image('head', head);
this.load.audio('bip', bip);
}
create() {
this.position = [];
this.lastPosition = 0;
this.background = this.add.image(0, 0, 'background')
.setOrigin(0, 0)
.setDisplaySize(U.WIDTH, U.HEIGHT);
if (localStorage.getItem('k438b')) {
this.position = [128, 256, 384];
this.loadGame = this.add.bitmapText(U.WIDTH / 4, this.position[0], 'atomic', ' Load Game ', 48, 1);
this.deleteSavedGame = this.add.bitmapText(U.WIDTH / 4, this.position[2], 'atomic', ' Delete Game ', 48, 1);
} else {
this.position = [128, 256];
this.newGame = this.add.bitmapText(U.WIDTH / 4, this.position[0], 'atomic', ' New Game ', 48, 1);
}
if (!localStorage.getItem('d')) {
localStorage.setItem('d', '0');
}
if (!localStorage.getItem('e')) {
localStorage.setItem('e', '0');
}
const keysOptions = getConfigKeys();
this.keys = this.input.keyboard.addKeys({
up: Phaser.Input.Keyboard.KeyCodes[keysOptions[2]],
down: Phaser.Input.Keyboard.KeyCodes[keysOptions[3]],
fire: Phaser.Input.Keyboard.KeyCodes[keysOptions[4]],
});
this.options = this.add.bitmapText(U.WIDTH / 4, this.position[1], 'atomic', ' Options ', 48, 1);
this.head = this.add.image(U.WIDTH / 4 - 50, this.position[0], 'head')
.setOrigin(0, 0)
.setDisplaySize(50, 50);
this.input.keyboard.on('keydown', (event) => {
if (this.keys.down.isDown && event.key === this.keys.down.originalEvent.key) {
this.sound.play('bip', { volume: 0.2 });
this.choose(1);
} else if (this.keys.up.isDown && event.key === this.keys.up.originalEvent.key) {
this.sound.play('bip', { volume: 0.2 });
this.choose(-1);
} else if (this.keys.fire.isDown && event.key === this.keys.fire.originalEvent.key) {
this.sound.play('bip2', { volume: 0.1 });
this.launch();
}
});
// fading the scene from black
this.cameras.main.fadeIn(500);
}
choose(count) {
if (this.lastPosition === this.position.length - 1 && count > 0) {
this.lastPosition = 0;
} else if (this.lastPosition === 0 && count < 0) {
this.lastPosition = this.position.length - 1;
} else {
this.lastPosition += count;
}
this.head.y = this.position[this.lastPosition];
}
launch() {
if (this.lastPosition === 0 && this.loadGame) {
this.scene.start('playLvl1', { loadSavedGame: true });
this.scene.start('dashBoard');
} else if (this.lastPosition === 0) {
this.scene.start('playLvl1');
this.scene.start('dashBoard');
}
if (this.lastPosition === 1) {
this.scene.start('Options');
}
if (this.lastPosition === 2) {
localStorage.removeItem('k438b');
localStorage.removeItem('d');
localStorage.removeItem('e');
localStorage.removeItem('time');
this.sound.play('bip2', { volume: 0.1 });
window.location.reload(false);
}
}
}
|
@extends('layout')
@section('body')
<div class="well bs-component">
<h3>Section Lists</h3>
<?php
$sections = Section::orderBy('created_at','desc')->simplePaginate() ;
?>
<ul>
@foreach($sections as $section)
<li><a href="{{asset('/section/show/'.$section->id)}}"><strong>{{$section->name}}</strong></a>
<h4>{{$section->about}}</h4>
</li>
@endforeach
</ul>
</div>
@stop
|
require 'mister_bin'
module Kojo
module Commands
# Handle calls to the +kojo file+ command
class FileCmd < CommandBase
using Kojo::Refinements
attr_reader :opts, :outfile, :infile, :import_base
help "Transform a file from a template"
usage "kojo file INFILE [--save FILE --imports DIR --args FILE] [ARGS...]"
usage "kojo file (-h|--help)"
option "-s --save FILE", "Save to file instead of printing"
option "-i --imports DIR", "Specify base directory for @import directives"
option "-a --args FILE", "Load arguments from YAML file"
param "INFILE", "Template to transform"
param "ARGS", "Optional key=value pairs"
example "kojo file main.yml"
example "kojo file main.yml --save out.yml"
example "kojo file main.yml -s out.yml app=lause"
example "kojo file main.yml -s out.yml --args args.yml"
def run
@opts = args['ARGS'].args_to_hash
@outfile = args['--save']
@infile = args['INFILE']
@import_base = args['--imports']
argfile = args['--args']
if argfile
fileopts = YAML.load_file(argfile).symbolize_keys
@opts = fileopts.merge opts
end
run!
end
private
def run!
template = Kojo::Template.new infile
template.import_base = import_base if import_base
output = template.render(opts)
if outfile
save outfile, output
else
puts output
end
end
end
end
end
|
package entity
import (
"crypto/rsa"
)
// RsaKey represents RSA private & public key
type RsaKey struct {
PrivateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
}
|
{-|
Module : Network.Nakadi.Internal.Conversions
Description : Nakadi Client Conversions (Internal)
Copyright : (c) Moritz Clasmeier 2017
License : BSD3
Maintainer : mtesseract@silverratio.net
Stability : experimental
Portability : POSIX
Internal module containing conversions code.
-}
module Network.Nakadi.Internal.Conversions where
import Network.Nakadi.Internal.Prelude
import Control.Lens
import Data.ByteString.Lens
import qualified Data.UUID as UUID
import qualified Network.Nakadi.Internal.Lenses as L
import Network.Nakadi.Types
subscriptionIdToByteString :: SubscriptionId -> ByteString
subscriptionIdToByteString = view (L.id.to UUID.toString.packedChars)
|
aries.samples <- read.csv(file.path(aries.dir, "samplesheet", "samplesheet.csv"), stringsAsFactors=F)
ewas.dat <- sapply(time.points, function(time) {
ewas <- eval.ret(paste("ewas-handed", time, "full", sep="-"))
ewas.dat <- as.data.frame(ewas$design)
ewas.dat <- ewas.dat[,which(colnames(ewas.dat) != "(Intercept)")]
ewas.dat <- ewas.dat[,grep("handed",colnames(ewas.dat),invert=T)]
idx <- match(rownames(ewas.dat), aries.samples$Sample_Name)
if (time %in% child.time.points) {
ewas.dat$sexM <- NULL ## will be contributed by PGS model data
ewas.dat$id <- aries.samples$alnqlet[idx]
}
else {
ewas.dat$id <- aries.samples$aln[idx]
}
ewas.dat
})
|
/// <reference path="../vertx-js/throwable.d.ts" />
/// <reference path="../vertx-js/vertx.d.ts" />
/// <reference path="./template_engine.d.ts" />
/// <reference path="./routing_context.d.ts" />
declare module "vertx-web-js/template_handler" {
export = TemplateHandler;
}
/**
*
* A handler which renders responses using a template engine and where the template name is selected from the URI
* path.
*/
interface TemplateHandler
{
/**
* Something has happened, so handle it.
*/
handle(event: RoutingContext): void;
}
declare var TemplateHandler: {
/**
* Create a handler
*/
create(engine: TemplateEngine): TemplateHandler;
/**
* Create a handler
*/
create(engine: TemplateEngine, templateDirectory: string, contentType: string): TemplateHandler;
}
|
import { MetaComponent } from '@rebelstack-io/metaflux';
import { instanceElement } from '../../utils';
import defaulAvatar from '../../assets/images/user.svg';
import cog from '../../assets/icons/cog-solid.svg';
import searchIcon from '../../assets/icons/search-solid.svg';
import enevelope from '../../assets/icons/envelope-solid.svg';
import closeIcon from '../../assets/icons/times-solid.svg';
import peruFlag from '../../assets/icons/flags/PE.svg'
import './index.css';
class Sidebar extends MetaComponent {
constructor () {
super(global.storage);
}
get searchValue () {
return this.querySelector('.search-input').value;
}
// eslint-disable-next-line class-method-use-this
render () {
const content = instanceElement('div', false, 'sidebar-content');
const close = instanceElement('img', ['mobile-only'], false, false, [{src: closeIcon}]);
const uid = localStorage.getItem('fb-hash');
this.channelList = global.storage.getState().Main.channelList;
this.accessLevel = global.storage.getState().Main.accessLevel;
const urlImg = localStorage.getItem(uid) ? localStorage.getItem(uid) : defaulAvatar;
// where the channels or channel will be deplayed
const chnlBox = instanceElement('div', ['channel-box'], 'channel-t0');
// list of trheads
const thBox = instanceElement('ol', false, 'threads');
// profile img and name
const profile = instanceElement(
'div',
['side-profile'],
false,
`
<img src="${urlImg}" class="profile-img"></img>
<span id="user-name"><span>
`
);
// search input
const search = instanceElement(
'div',
['search-box'],
false,
`<input type="text" class="search-input"></input>
<img src="${searchIcon}"></img>
`
);
content.append(close ,profile, search, chnlBox, thBox);
return content;
}
/**
* add DOM listeners
*/
addListeners () {
// search
this.querySelector('.search-input')
.addEventListener('keydown', () => {
if (this.searchValue === '') {
// full array
const { threads, allThreads } = this.storage.getState().Main;
const selector = document.querySelector('#channel-select')
? document.querySelector('#channel-select').value
: '*';
const currentThread = selector == '0'
? allThreads
: threads;
this.listSelectedThreads(currentThread);
} else {
this.handleSearch();
}
});
// profile image
this.querySelector('.profile-img')
.addEventListener('click', () => {
global.storage.dispatch({ type: 'OPEN-PROFILE' })
document.querySelector('.profile-popup-container-container').classList.remove('hide');
});
//close btn
this.querySelector('.mobile-only').addEventListener('click', () => {
const sideBar = document.querySelector('.loby-side-menu');
const mainContent = document.querySelector('yak-loby > div');
if (sideBar.classList.contains('toggled')) {
sideBar.classList.remove('toggled');
mainContent.classList.remove('toggled');
} else {
sideBar.classList.add('toggled');
mainContent.classList.add('toggled');
}
});
}
/**
* create the view for the client t0-MVP
* @param {Arrya} channelList
*/
createClientView (channelList, domain) {
const sidebar = this.querySelector('#sidebar-content');
const chnlBox = this.querySelector('#channel-t0')
chnlBox.innerHTML = '';
channelList.forEach(chnl => {
const chEl = instanceElement('div', ['collapse'], false,
`<span class="chnl-title">
${chnl.title ? chnl.title : 'add'}
<img src="${cog}"></img>
</span>`
);
chEl.querySelector('img')
.addEventListener('click', () => {
document.querySelector('#channel-popup-container.profile-popup-container').classList.toggle('hide');
global.storage.dispatch({
type: 'CHANNEL-SELECT',
data: {
channel: chnl.title ? chnl.title : '',
domain
}
})
})
chnlBox.appendChild(chEl);
});
sidebar.appendChild(chnlBox);
}
/**
* create the view for the operator
* @param {Object} channelList
*/
createOperatorView (channelList) {
const chnlBox = this.querySelector('#channel-t0');
chnlBox.innerHTML = '';
const selector = instanceElement('select', false, 'channel-select',
`
<option value="0"> All </option>
`
);
Object.keys(channelList).forEach((key) => {
const option = instanceElement('option', false, key,
channelList[key][2] ? channelList[key][2] : 'NOT-SET',
[{value: key}]
);
selector.appendChild(option);
});
selector.addEventListener('change', () => {
if (selector.value != 0) {
const threads = this.storage.getState().Main.channelList[selector.value];
this.storage.dispatch({
type: 'THREAD-SELECTED',
threads: threads[4] ? threads[4] : {},
DID: selector.value
})
document.querySelector('.msg-body').innerHTML = '';
this.listSelectedThreads(threads[4] ? threads[4] : {});
} else {
const { allThreads } = this.storage.getState().Main;
this.listSelectedThreads(allThreads)
}
})
chnlBox.appendChild(selector);
}
/**
* list the selected threads into view
*/
listSelectedThreads(msgObject) {
const sidebar = this.querySelector('#sidebar-content');
const thBox = this.querySelector('#threads');
const { oldThreads } = this.storage.getState().Main;
thBox.innerHTML = '';
Object.keys(msgObject).forEach(uid => {
const random = Math.floor(Math.random()*(999-100+1)+100);
let isNew = false;
if (oldThreads[uid]) {
isNew = JSON.stringify(oldThreads[uid]) !== JSON.stringify(msgObject[uid])
}
const type = msgObject[uid][0] === ''
? `
Visitor
<span class="bottom">
190.234.15.${random} Pisco - Peru
<img class="flag" src="${peruFlag}">
</span>
<img src="${enevelope}" class="${isNew ? '' : 'hide'}"></img>
`
: `
${msgObject[uid][0].split('-')[0]}
<span class="bottom">
${msgObject[uid][0].split('-')[1]}
<img class="flag" src="${peruFlag}">
</span>
<img src="${enevelope}" class="${isNew ? '' : 'hide'}"></img>
`
const li = instanceElement('li', ['thread-item'], 'id-' + uid, type);
li.addEventListener('click', () => {
const envelope = document.querySelector('#id-' + uid + '>img');
if (!envelope.classList.contains('hide')) {
envelope.classList.add('hide');
}
this.storage.dispatch({type: 'CHAT-SELECTED', data: {
clientSelected: type,
messages: msgObject[uid],
visitorId: uid,
chnlId: msgObject[uid].chnlId
}})
})
thBox.appendChild(li);
});
sidebar.appendChild(thBox);
}
/**
* handle search
*/
handleSearch () {
const { threads, allThreads } = this.storage.getState().Main;
const selector = document.querySelector('#channel-select')
? document.querySelector('#channel-select').value
: '*';
const currentThread = selector == '0'
? allThreads
: threads;
let newObject = {};
Object.keys(currentThread).forEach(key => {
const userdata = currentThread[key][0] !== '' ? currentThread[key][0] : 'New User-unknown';
const name = userdata.split('-')[0];
const email = userdata.split('-')[1];
if (name.toUpperCase().startsWith(this.searchValue.toUpperCase()) ||
email.toUpperCase().startsWith(this.searchValue.toUpperCase())
) {
newObject[key] = currentThread[key]
}
});
this.listSelectedThreads(newObject);
}
/**
* handle the storage events
*/
handleStoreEvents () {
return {
'CHANNEL-ARRIVE': (state) => {
const channelList = this.storage.getState().Main.channelList;
const domain = this.storage.getState().Main.domain;
const threads = this.storage.getState().Main.threads;
this.createClientView(channelList,domain);
this.listSelectedThreads(threads);
},
'LOGIN-SUCCESS': () => {
this.querySelector('#user-name').innerHTML = this.storage.getState().Main.displayName;
},
'PROFILE-CHANGED': (state) => {
const { displayName } = state.newState.Main;
this.querySelector('#user-name').innerHTML = displayName;
},
'UPLOAD-SUCCESS': () => {
const {uid} = this.storage.getState().Main;
this.querySelector('.profile-img').src = localStorage.getItem(uid);
},
'OPERATOR-DATA': () => {
const { channelList, chnlUid, allThreads } = this.storage.getState().Main;
this.createOperatorView(channelList);
if (chnlUid !== 0) {
this.listSelectedThreads(channelList[chnlUid][4]);
} else {
this.listSelectedThreads(allThreads);
}
}
}
}
}
window.customElements.define('yak-sidebar', Sidebar);
|
# Set database settings. defaults is like below
# db_url = 'localhost'
# db_port = 27017
# db_name = "crawl"
# db_collection = "crawl_collec"
|
using System;
using NUnit.Framework;
namespace Guards.Tests
{
[TestFixture]
public class Int32ExtensionTests
{
[TestCase(5, 5, true)]
[TestCase(4, 5, false)]
public void should_throw_on_equal_int(int intA, int intB, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(
() => Guard.ThrowIf(nameof(intA), intA).EqualTo(intB));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(intA), intA).EqualTo(intB));
}
}
[TestCase(4, true)]
[TestCase(5, false)]
public void should_throw_if_int_is_even(int int1, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(
() => Guard.ThrowIf(nameof(int1), int1).Even());
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int1), int1).Even());
}
}
[TestCase(5, 5, false)]
[TestCase(5, 4, true)]
public void should_throw_if_int_is_greater_than_value(int int1, int int2, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(int1), int1)
.GreaterThan(int2));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int1), int1).GreaterThan(int2));
}
}
[TestCase(2, 4, false)]
[TestCase(5, 5, false)]
[TestCase(5, 4, true)]
public void should_throw_if_int_is_greater_than_or_equal_to(int int1, int int2, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(int1), int1)
.GreaterThan(int2));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int1), int1).GreaterThan(int2));
}
}
[TestCase(5, 5, false)]
[TestCase(5, 4, true)]
public void should_throw_if_int_is_less_than_value(int int1, int int2, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(int2), int2)
.LessThan(int1));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int2), int2).LessThan(int1));
}
}
[TestCase(5, 6, false)]
[TestCase(5, 5, true)]
[TestCase(5, 4, true)]
public void should_throw_if_int_is_less_than_or_equal_to(int int1, int int2, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(int2), int2)
.LessThanOrEqualTo(int1));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int2), int2).LessThanOrEqualTo(int1));
}
}
[TestCase(5, 5, false)]
[TestCase(4, 5, true)]
public void should_throw_on_unequal_ints(int intA, int intB, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(
() => Guard.ThrowIf(nameof(intA), intA).NotEqualTo(intB));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(intA), intA).NotEqualTo(intB));
}
}
[TestCase(4, false)]
[TestCase(5, true)]
public void should_throw_if_int_is_odd(int int1, bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(
() => Guard.ThrowIf(nameof(int1), int1).Odd());
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(int1), int1).Odd());
}
}
[TestCase(4, 5, 7, true)]
[TestCase(5, 5, 7, false)]
public void should_throw_if_int_is_outside_set(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.Outside(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.Outside(rangeStart, rangeEnd));
}
}
[TestCase(4, 5, 7, true)]
[TestCase(6, 5, 7, false)]
[TestCase(5, 5, 7, true)]
public void should_throw_if_int_is_outside_exclusive_range(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.OutsideExclusiveRange(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.OutsideExclusiveRange(rangeStart, rangeEnd));
}
}
[TestCase(4, 5, 7, true)]
[TestCase(6, 5, 7, false)]
[TestCase(5, 5, 7, false)]
public void should_throw_if_int_is_outside_inclusive_range(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.OutsideInclusiveRange(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.OutsideInclusiveRange(rangeStart, rangeEnd));
}
}
[TestCase(4, 5, 7, false)]
[TestCase(5, 5, 7, true)]
public void should_throw_if_int_is_within_set(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.Within(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.Within(rangeStart, rangeEnd));
}
}
[TestCase(4, 5, 7, false)]
[TestCase(6, 5, 7, true)]
[TestCase(5, 5, 7, false)]
public void should_throw_if_int_is_within_exclusive_range(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.WithinExclusiveRange(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.WithinExclusiveRange(rangeStart, rangeEnd));
}
}
[TestCase(4, 5, 7, false)]
[TestCase(6, 5, 7, true)]
[TestCase(5, 5, 7, true)]
public void should_throw_if_int_is_within_inclusive_range(int target, int rangeStart, int rangeEnd,
bool shouldThrow)
{
if (shouldThrow)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.ThrowIf(nameof(target), target)
.WithinInclusiveRange(rangeStart, rangeEnd));
}
else
{
Assert.DoesNotThrow(() => Guard.ThrowIf(nameof(target), target)
.WithinInclusiveRange(rangeStart, rangeEnd));
}
}
}
}
|
library timeline_tile;
export 'package:timeline_tile/src/tile.dart';
export 'package:timeline_tile/src/style.dart';
export 'package:timeline_tile/src/timeline_divider.dart';
|
import { Routes, RouterModule } from '@angular/router';
//Route for content layout with sidebar, navbar and footer
export const Full_ROUTES: Routes = [
{
path: 'changelog',
loadChildren: () => import('../../portal-changelog/changelog.module').then(m => m.ChangeLogModule)
},
{
path: 'full-layout',
loadChildren: () => import('../../portal-pages/full-layout-page/full-pages.module').then(m => m.FullPagesModule)
}
];
|
require 'citysdk/util.rb'
require 'citysdk/api.rb'
require 'citysdk/file_reader.rb'
require 'citysdk/importer.rb'
module CitySDK
VERSION = "0.1.1.4"
end
|
#!/usr/bin/env bash
set -euo pipefail
mvn clean install package
# Generate the root index.html
DOC_PROJECT_PATH=../tmp
PROJECT_NAME=${PWD##*/}
DESTINATION_PATH=${DOC_PROJECT_PATH}/docs
cp ${DESTINATION_PATH}/${PROJECT_NAME}/index.html ${DESTINATION_PATH}/index.html
HREF_TO_REPLACE="<a href=\".\/"
REPLACE_BY="<a href=\"${PROJECT_NAME}\/"
sed -i "s/${HREF_TO_REPLACE}/${REPLACE_BY}/g" ${DESTINATION_PATH}/index.html
|
import React from 'react';
import { Provider } from 'react-redux';
// Store
import store from '../store/store';
// Components
import Test from './Test';
export default function MasterUI() {
return (
<Provider store={store}>
<Test />
</Provider>
);
}
|
SELECT
user_id
,first_name
,last_name
,email
,password
,tel
,zip
,address
,created_by
,created_at
,updated_by
,updated_at
,deleted_by
,deleted_at
,version
FROM
users
WHERE
deleted_at IS NULL
/*%if user.id != null */
AND user_id = /* user.id */1
/*%end*/
/*%if user.email != null */
AND email = /* user.email */'aaaa@bbbb.com'
/*%end*/
/*%if user.firstName != null */
AND first_name LIKE /* @infix(user.firstName) */'john'
/*%end*/
/*%if user.lastName != null */
AND last_name LIKE /* @infix(user.lastName) */'doe'
/*%end*/
/*%if user.tel != null */
AND tel LIKE /* @prefix(user.tel) */'0901234'
/*%end*/
/*%if user.zip != null */
AND zip LIKE /* @prefix(user.zip) */'10600'
/*%end*/
/*%if user.address != null */
AND address LIKE /* @infix(user.address) */'東京都港区'
/*%end*/
ORDER BY user_id ASC
|
/*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.titus.api.jobmanager.model.job;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.time.Clocks;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.testkit.model.job.JobDescriptorGenerator;
import com.netflix.titus.testkit.model.job.JobGenerator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JobFunctionsTest {
private static final Task REFERENCE_TASK = JobGenerator.batchTasks(JobGenerator.batchJobs(JobDescriptorGenerator.oneTaskBatchJobDescriptor()).getValue()).getValue();
private final Clock clock = Clocks.system();
@Test
public void testGetTimeInStateForCompletedTask() {
TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.Finished).withTimestamp(5000).build();
Task task = REFERENCE_TASK.toBuilder()
.withStatus(checked)
.withStatusHistory(
TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(),
TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build(),
TaskStatus.newBuilder().withState(TaskState.StartInitiated).withTimestamp(200).build(),
TaskStatus.newBuilder().withState(TaskState.Started).withTimestamp(1000).build(),
TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(2000).build()
)
.build();
assertThat(JobFunctions.getTimeInState(task, TaskState.Accepted, clock)).contains(100L);
assertThat(JobFunctions.getTimeInState(task, TaskState.Launched, clock)).contains(100L);
assertThat(JobFunctions.getTimeInState(task, TaskState.StartInitiated, clock)).contains(800L);
assertThat(JobFunctions.getTimeInState(task, TaskState.Started, clock)).contains(1000L);
assertThat(JobFunctions.getTimeInState(task, TaskState.KillInitiated, clock)).contains(3000L);
assertThat(JobFunctions.getTimeInState(task, TaskState.Finished, clock).get()).isGreaterThan(0);
}
@Test
public void testGetTimeInStateForFailedTask() {
TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(1000).build();
Task task = REFERENCE_TASK.toBuilder()
.withStatus(checked)
.withStatusHistory(
TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(),
TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build()
)
.build();
assertThat(JobFunctions.getTimeInState(task, TaskState.Accepted, clock)).contains(100L);
assertThat(JobFunctions.getTimeInState(task, TaskState.Launched, clock)).contains(900L);
assertThat(JobFunctions.getTimeInState(task, TaskState.StartInitiated, clock)).isEmpty();
assertThat(JobFunctions.getTimeInState(task, TaskState.Started, clock)).isEmpty();
assertThat(JobFunctions.getTimeInState(task, TaskState.KillInitiated, clock).get()).isGreaterThan(0);
assertThat(JobFunctions.getTimeInState(task, TaskState.Finished, clock)).isEmpty();
}
@Test
public void testHasTransition() {
TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(1000).build();
Task task = REFERENCE_TASK.toBuilder()
.withStatus(checked)
.withStatusHistory(
TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(),
TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build(),
TaskStatus.newBuilder().withState(TaskState.StartInitiated).withReasonCode("step1").withTimestamp(100).build(),
TaskStatus.newBuilder().withState(TaskState.StartInitiated).withReasonCode("step2").withTimestamp(100).build()
)
.build();
assertThat(JobFunctions.containsExactlyTaskStates(task, TaskState.Accepted, TaskState.Launched, TaskState.StartInitiated, TaskState.KillInitiated)).isTrue();
}
@Test
public void testFindHardConstraint() {
Job<BatchJobExt> job = JobFunctions.appendHardConstraint(JobGenerator.oneBatchJob(), "MyConstraint", "good");
assertThat(JobFunctions.findHardConstraint(job, "myConstraint")).contains("good");
assertThat(JobFunctions.findSoftConstraint(job, "myConstraint")).isEmpty();
}
@Test
public void testFindSoftConstraint() {
Job<BatchJobExt> job = JobFunctions.appendSoftConstraint(JobGenerator.oneBatchJob(), "MyConstraint", "good");
assertThat(JobFunctions.findHardConstraint(job, "myConstraint")).isEmpty();
assertThat(JobFunctions.findSoftConstraint(job, "myConstraint")).contains("good");
}
@Test
public void testGroupTasksByResubmitOrder() {
List<Task> group1 = taskWithReplacements(3);
List<Task> group2 = taskWithReplacements(5);
Task badOne = JobGenerator.oneBatchTask().toBuilder().withOriginalId("missing").build();
List<Task> mixed = CollectionsExt.merge(group1, group2, Collections.singletonList(badOne));
Collections.shuffle(mixed);
Pair<Map<String, List<Task>>, List<Task>> result = JobFunctions.groupTasksByResubmitOrder(mixed);
Map<String, List<Task>> ordered = result.getLeft();
List<Task> rejected = result.getRight();
// Ordered
assertThat(ordered).hasSize(2);
List<Task> firstOrder = ordered.get(group1.get(0).getId());
assertThat(firstOrder).isEqualTo(group1);
List<Task> secondOrder = ordered.get(group2.get(0).getId());
assertThat(secondOrder).isEqualTo(group2);
// Rejected
assertThat(rejected).hasSize(1);
assertThat(rejected.get(0).getId()).isEqualTo(badOne.getId());
}
private static List<Task> taskWithReplacements(int size) {
BatchJobTask first = JobGenerator.oneBatchTask();
List<Task> result = new ArrayList<>();
result.add(first);
Task last = first;
for (int i = 1; i < size; i++) {
BatchJobTask next = JobGenerator.oneBatchTask().toBuilder()
.withJobId(first.getJobId())
.withOriginalId(first.getId())
.withResubmitOf(last.getId())
.build();
result.add(next);
last = next;
}
return result;
}
}
|
---
layout: layout.pug
navigationTitle: Delete the Cluster
title: Delete the Cluster
menuWeight: 90
excerpt: Delete the Kubernetes cluster and/or the bootstrap cluster
beta: false
enterprise: false
---
## Delete the Kubernetes cluster
If you have a need to remove the Kubernetes cluster, such as for environment cleanup, use this command:
1. Delete the provisioned Kubernetes cluster with the command:
```sh
dkp delete cluster --cluster-name=${CLUSTER_NAME}
```
This command may take a few minutes to complete:
## Delete the Kubernetes cluster and cleanup your environment
After you have moved the workload resources back to a bootstrap cluster and deleted the workload cluster, you no longer need the bootstrap cluster. You can safely delete the bootstrap cluster with this command:
1. Delete the `kind` Kubernetes cluster:
```sh
dkp delete bootstrap
```
|
import reacher_env
from puppersim.reacher import reacher_kinematics
import math
import time
import numpy as np
from absl import app
from absl import flags
import copy
flags.DEFINE_bool("run_on_robot", False, "Whether to run on robot or in simulation.")
FLAGS = flags.FLAGS
def run_example():
env = reacher_env.ReacherEnv(run_on_robot=FLAGS.run_on_robot, render=True)
env.reset()
env.setTarget([0.0, 0.0, 0.15])
guess = [0,0,0]
env_step = 0
cumulative_reward = 0
while True:
env_step += 1
time.sleep(0.002)
desired_end_effector_pos = env.target
print("g", guess)
guess = reacher_kinematics.calculate_inverse_kinematics(desired_end_effector_pos, guess)
obs, reward, done, _ = env.step(actions=guess)
cumulative_reward += reward
print("obs: ", obs)
print("reward: ", cumulative_reward)
if env_step > 1000:
cumulative_reward = 0
env_step = 0
env.reset()
def main(_):
run_example()
if __name__ == "__main__":
app.run(main)
|
# StudentCardRecorder
This repository contains a Student Card Recorder Desktop Java Application.

|
@if(\Illuminate\Support\Facades\View::exists("info.".$type.".info"))
@include("info.".$type.".info")
@else
@include("info.Maintainable.info")
@endif
|
package com.paranoia.webfluxreactive.collection.platform;
import com.paranoia.webfluxreactive.collection.BaseDocument;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* @author ZHANGKAI
* @date 2018/10/22
* @description
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Document(collection = "sys_platform_role")
public class SysPlatformRole extends BaseDocument {
@Id
private String id;
@Field("role_code")
private String roleCode;
/**
* 机构编码
*/
@Field("organization_code")
private String organizationCode;
/**
* 平台编码
*/
@Field("platform_code")
private String platformCode;
//todo
private String resource;
}
|
<?php
//---------------------------------------------------------------------------------------------------
// Proyecto: Icasus <https://gestionproyectos.us.es/projects/r2h2-icasus/>
// Archivo: planes/linea_mostrar.php
// Tipo: controlador
// Desarrolladores: Juanan Ruiz (juanan@us.es), Jesus Martin Corredera (jjmc@us.es),
// Joaquín Valonero Zaera (tecnibus1@us.es)
//---------------------------------------------------------------------------------------------------
// Descripcion: Muestra la página principal de una línea estratégica
//---------------------------------------------------------------------------------------------------
global $smarty;
global $plantilla;
global $usuario;
if (filter_has_var(INPUT_GET, 'id_linea'))
{
$id_linea = filter_input(INPUT_GET, 'id_linea', FILTER_SANITIZE_NUMBER_INT);
//Obtenemos los datos de la línea
$linea = new Linea();
if ($linea->load("id = $id_linea"))
{
$smarty->assign('linea', $linea);
}
else
{
$error = ERR_LINEA_MOSTRAR;
header("location:index.php?page=error&error=$error");
}
//Obtener todas las líneas para avanzar o retroceder
$id_plan = $linea->id_plan;
$lineas = $linea->Find("id_plan = $id_plan order by indice");
$smarty->assign("lineas", $lineas);
$cont = 0;
foreach ($lineas as $ln)
{
if ($id_linea == $ln->id)
{
$indice = $cont;
$smarty->assign("indice", $indice);
}
$cont++;
}
//Obtenemos los datos del plan
$plan = new Plan();
$plan->load("id = $id_plan");
$smarty->assign('plan', $plan);
//Obtenemos sus ejecuciones y resultados anuales
$ejecucion = new Ejecucion();
$ejecucion_anual = array();
$resultado_anual = array();
for ($i = $plan->anyo_inicio; $i <= ($plan->anyo_inicio + $plan->duracion - 1); $i++)
{
if ($ejecucion->Load("id_linea=$linea->id AND anyo=$i"))
{
$ejecucion_anual[$i] = $ejecucion->valor;
$resultado_anual[$i] = $ejecucion->resultado;
}
else
{
$ejecucion_anual[$i] = 0;
$resultado_anual[$i] = "";
}
}
$smarty->assign("ejecucion_anual", $ejecucion_anual);
$smarty->assign("resultado_anual", $resultado_anual);
//Objetivos estratégicos
$objest = new ObjetivoEstrategico();
$objests = $objest->Find_joined("id_linea=$id_linea");
$smarty->assign('objests', $objests);
//Objetivos operacionales
$objop = new ObjetivoOperacional();
$objops = array();
$objops_objests = array();
foreach ($objests as $obj)
{
$objops = array_merge($objops, $objop->Find_joined("id_objest=$obj->id"));
$objops_objests[$obj->id] = $objop->Find("id_objest=$obj->id order by indice");
}
$smarty->assign('objops', $objops);
$smarty->assign('objops_objests', $objops_objests);
//Años de ejecución de los objetivos operacionales
$objops_anyos = array();
foreach ($objops as $obj)
{
$objops_anyos[$obj->id] = array();
$ejecuciones = $ejecucion->Find("id_objop=$obj->id order by anyo");
foreach ($ejecuciones as $ejec)
{
if ($ejec->activo)
{
array_push($objops_anyos[$obj->id], $ejec->anyo);
}
}
}
$smarty->assign('objops_anyos', $objops_anyos);
//Unidades de los objetivos operacionales
$objop_unidad = new ObjetivoUnidad();
$objops_unids = array();
foreach ($objops as $obj)
{
$objops_unids[$obj->id] = $objop_unidad->Find("id_objop=$obj->id");
}
$smarty->assign('objops_unids', $objops_unids);
$entidad = new Entidad();
$entidad->load("id = $plan->id_entidad");
$smarty->assign('entidad', $entidad);
$smarty->assign('_javascript', array('linea_mostrar'));
$smarty->assign('_nombre_pagina', FIELD_LINEA . ": " . $linea->indice . ". " . $linea->nombre);
$plantilla = 'planes/linea_mostrar.tpl';
}
else
{
$error = ERR_PARAM;
header("location:index.php?page=error&error=$error");
}
|
using System;
namespace Microsoft.Language.Xml
{
using InternalSyntax;
internal class LastTokenReplacer : InternalSyntax.SyntaxRewriter
{
private readonly Func<SyntaxToken.Green, SyntaxToken.Green> _newItem;
private int _skipCnt;
private LastTokenReplacer(Func<SyntaxToken.Green, SyntaxToken.Green> newItem)
{
_newItem = newItem;
}
internal static TTree Replace<TTree>(TTree root, Func<SyntaxToken.Green, SyntaxToken.Green> newItem) where TTree : GreenNode
{
return (TTree)new LastTokenReplacer(newItem).Visit(root);
}
public override GreenNode Visit(GreenNode node)
{
if (node == null)
{
return null;
}
// node is not interesting until skip count is 0
if (_skipCnt != 0)
{
_skipCnt -= 1;
return node;
} // not interested in trivia
if (!node.IsToken)
{
var allChildrenCnt = 0;
for (int i = 0; i < node.SlotCount; i++)
{
var child = node.GetSlot(i);
if (child == null)
{
continue;
}
if (child.IsList)
{
allChildrenCnt += child.SlotCount;
}
else
{
allChildrenCnt += 1;
}
}
// no children
if (allChildrenCnt == 0)
{
return node;
}
var prevIdx = _skipCnt;
_skipCnt = allChildrenCnt - 1;
GreenNode result;
if (node.IsList)
{
result = VisitList<GreenNode>(new InternalSyntax.SyntaxList<GreenNode>(node)).Node;
}
else
{
result = base.Visit(node);
}
_skipCnt = prevIdx;
return result;
}
else
{
return base.Visit(node);
}
}
public override SyntaxToken.Green VisitSyntaxToken(SyntaxToken.Green token)
{
return _newItem(token);
}
}
}
|
package queue
import "time"
type TaskStatus uint8
const (
TaskStatusCreated TaskStatus = iota // just created, waiting to be processed
TaskStatusProcessing // processing by a worker
TaskStatusFailed // process failed
TaskStatusDone // process completed
)
var (
TaskStatuses []TaskStatus = []TaskStatus{
TaskStatusCreated,
TaskStatusProcessing,
TaskStatusFailed,
TaskStatusDone,
}
)
func (s TaskStatus) Uint32() uint32 {
return uint32(s)
}
func (s TaskStatus) String() string {
switch s {
case TaskStatusCreated:
return "created"
case TaskStatusProcessing:
return "processing"
case TaskStatusFailed:
return "failed"
case TaskStatusDone:
return "done"
default:
return "unknown"
}
}
type Task struct {
ID string
Data []byte
CreationDate time.Time
Status TaskStatus
}
|
//! Miscellaneous utilities.
use std::fmt;
/// Wrapper to force a `&[u8]` to display as nicely-formatted hexadecimal
/// bytes with only the the first line or so of bytes shown.
pub struct BytesFormatter<'a>(pub &'a [u8]);
impl<'a> fmt::Debug for BytesFormatter<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let BytesFormatter(bytes) = *self;
for byte in bytes.iter().take(16) {
write!(f, "{:02x} ", byte)?;
}
write!(f, "({} bytes)", bytes.len())?;
Ok(())
}
}
|
import React from "react";
export const ShipmentTerms = (): JSX.Element => (
<>
<h3>Shipment and delivery.</h3>
<p>
Our products are shipped to any country within the EU. We are usually able
to deliver your product within 14 days of ordering. We'll keep you
up-to-date of your order status through email.
</p>
</>
);
export const WarrantyTerms = (): JSX.Element => (
<>
<h3>Warranty and repairs.</h3>
<p>
You'll have a warranty of at least 1 year on manufacturing defects on
all parts. If damage does occur under normal usage, we'll repair or
replace your product free of charge.
</p>
</>
);
export const WithdrawalTerms = (): JSX.Element => (
<>
<h3>Right of withdrawal.</h3>
<p>
Sometimes, you and your product simply won’t see eye to eye. In this case,
you can send the product back within 14 days after receiving the product
to receive a full refund.
</p>
<p>NB: We accept ‘just because’ as a reason for returning, too.</p>
</>
);
|
# chinese_backend
Backend For Chinese Memory Cards App
# URLs
* Admin - http://learnzh2.cloudapp.net/admin
* Xcode Generated Source Code - http://learnzh2.cloudapp.net/modata/xcode
* Android Generated Source Code - http://learnzh2.cloudapp.net/modata/android
* Data Sample - http://learnzh2.cloudapp.net/modata/data/Topic
# License
MIT (c) Yury Dymov
|
SELECT
gebaeudeadressen_benanntesgebiet.ogc_fid AS t_id,
flaeche AS geometrie,
gebaeudeadressen_benanntesgebiet.gem_bfs,
gebaeudeadressen_benanntesgebiet.los,
gebaeudeadressen_benanntesgebiet.lieferdatum,
text AS name_benanntes_gebiet
FROM
av_avdpool_ng.gebaeudeadressen_benanntesgebiet
LEFT JOIN av_avdpool_ng.gebaeudeadressen_lokalisation
ON gebaeudeadressen_benanntesgebiet.benanntesgebiet_von = gebaeudeadressen_lokalisation.tid
LEFT JOIN av_avdpool_ng.gebaeudeadressen_lokalisationsname
ON gebaeudeadressen_lokalisationsname.benannte = gebaeudeadressen_lokalisation.tid
WHERE
art = 0
;
|
const router = require('express').Router();
const Task = require('../models/Task');
module.exports = router
.post('/', (req, res, next) => {
Task.create(req.body)
.then(task => res.json(task))
.catch(next);
});
|
#include <chili/cont.h>
#if CBY_BACKEND_CYCLES_ENABLED
#include "../bytecode/opcodes.h"
#include "../instrument/append.h"
#include "../instrument/count.h"
#include "../instrument/cycles.h"
INSTRUMENT_APPEND(countcycles, count, cycles)
void insnStats(CbyInterpreter*, const countData*, const cyclesData*);
CHI_INL void _countcyclesDestroy(CbyInterpreter* interp, countcyclesData* data) {
insnStats(interp, &data->a, &data->b);
countcyclesDestroy(interp, data);
}
#define countcyclesDestroy _countcyclesDestroy
// we use switch since this leads to smaller code being generated
#define INTERP_DISPATCH switch
#define INSTRUMENT_NAME countcycles
#define INTERP_NAME cycles
#include "interpreter.h"
#endif
|
import React from 'react';
import StoryElement from './StoryElement';
const StoryList = ({storiesList, history, loggedIn, deleteFn, editFn}) => (
<div>
{storiesList.map((story, i) =>
<div key={i}>
<StoryElement story={story} history={history} loggedIn={loggedIn} deleteFn={deleteFn} editFn={editFn} />
</div>
)}
</div>
);
export default StoryList;
|
# Logging
* [How to use](HowToUse.md)
* [Sub-categories](SubCategories.md)
|
C$Procedure ET2LST ( ET to Local Solar Time )
SUBROUTINE ET2LST ( ET, BODY, LONG, TYPE, HR, MN, SC, TIME, AMPM )
C$ Abstract
C
C Given an ephemeris epoch ET, compute the local solar time for
C an object on the surface of a body at a specified longitude.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C TIME
C
C$ Keywords
C
C TIME
C
C$ Declarations
IMPLICIT NONE
DOUBLE PRECISION ET
INTEGER BODY
DOUBLE PRECISION LONG
CHARACTER*(*) TYPE
INTEGER HR
INTEGER MN
INTEGER SC
CHARACTER*(*) TIME
CHARACTER*(*) AMPM
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C ET I Epoch in seconds past J2000 epoch
C BODY I ID-code of the body of interest
C LONG I Longitude of surface point (RADIANS)
C TYPE I Type of longitude 'PLANETOCENTRIC', etc.
C HR O Local hour on a "24 hour" clock
C MN O Minutes past the hour
C SC O Seconds past the minute
C TIME O String giving local time on 24 hour clock
C AMPM O String giving time on A.M./ P.M. scale
C
C$ Detailed_Input
C
C ET is the epoch expressed in TDB seconds past
C the J2000 epoch at which a local time is desired.
C
C BODY is the NAIF ID-code of a body on which local
C time is to be measured.
C
C LONG is the longitude (either planetocentric or
C planetographic) in radians of the site on the
C surface of body for which local time should be
C computed.
C
C TYPE is the form of longitude supplied by the variable
C LONG. Allowed values are 'PLANETOCENTRIC' and
C 'PLANETOGRAPHIC'. Note the case of the letters
C in TYPE is insignificant. Both 'PLANETOCENTRIC'
C and 'planetocentric' are recognized.
C
C$ Detailed_Output
C
C HR is the local "hour" of the site specified at the
C epoch ET. Note that an "hour" of local time does not
C have the same duration as an hour measured by
C conventional clocks. It is simply a representation
C of an angle. See the "Particulars" section for a more
C complete discussion of the meaning of local time.
C
C MN is the number of "minutes" past the hour of the
C local time of the site at the epoch ET. Again note
C that a "local minute" is not the same as a minute
C you would measure with conventional clocks.
C
C SC is the number of "seconds" past the minute of the
C local time of the site at the epoch ET. Again note
C that a "local second" is not the same as a second
C you would measure with conventional clocks.
C
C TIME is a string expressing the local time
C on a "24 hour" local clock.
C
C AMPM is a string expressing the local time on a "12 hour"
C local clock together with the traditional AM/PM
C label to indicate whether the sun has crossed
C the local zenith meridian.
C
C$ Parameters
C
C None.
C
C$ Exceptions
C
C 1) This routine defines local solar time for any point on the
C surface of the Sun to be 12:00:00 noon.
C
C 2) If the TYPE of the coordinates is not recognized, the
C error 'SPICE(UNKNOWNSYSTEM)' will be signaled.
C
C 3) If the body-fixed frame to associate with BODY cannot be
C determined, the error 'SPICE(CANTFINDFRAME)' is signaled.
C
C 4) If insufficient data is available to compute the
C location of the sun in body-fixed coordinates, the
C error will be diagnosed by a routine called by this one.
C
C 5) If the BODY#_PM keyword required to determine the body
C rotation sense is not found in the POOL or if it is found but
C is not a numeric keyword with at least two elements, the error
C 'SPICE(CANTGETROTATIONTYPE)' is signaled.
C
C$ Files
C
C Suitable SPK and PCK files must be loaded prior to calling this
C routine so that the body-fixed position of the sun relative to
C BODY can be computed. The PCK files must contain the standard
C BODY#_PM keyword need by this routine to determine the body
C rotation sense.
C
C When the input longitude is planetographic, the default
C interpretation of this value can be overridden using the optional
C kernel variable
C
C BODY<body ID>_PGR_POSITIVE_LON
C
C which is normally defined via loading a text kernel.
C
C$ Particulars
C
C This routine returns the local solar time at a user
C specified location on a user specified body.
C
C Let SUNLNG be the planetocentric longitude (in degrees) of
C the sun as viewed from the center of the body of interest.
C
C Let SITLNG be the planetocentric longitude (in degrees) of
C the site for which local time is desired.
C
C We define local time to be 12 + (SITLNG - SUNLNG)/15
C
C (where appropriate care is taken to map ( SITLNG - SUNLNG )
C into the range from -180 to 180).
C
C Using this definition, we see that from the point of view
C of this routine, local solar time is simply a measure of angles
C between meridians on the surface of a body. Consequently,
C this routine is not appropriate for computing "local times"
C in the sense of Pacific Standard Time. For computing times
C relative to standard time zones on earth, see the routines
C TIMOUT and STR2ET.
C
C
C Regarding planetographic longitude
C ----------------------------------
C
C In the planetographic coordinate system, longitude is defined
C using the spin sense of the body. Longitude is positive to the
C west if the spin is prograde and positive to the east if the spin
C is retrograde. The spin sense is given by the sign of the first
C degree term of the time-dependent polynomial for the body's prime
C meridian Euler angle "W": the spin is retrograde if this term is
C negative and prograde otherwise. For the sun, planets, most
C natural satellites, and selected asteroids, the polynomial
C expression for W may be found in a SPICE PCK kernel.
C
C The earth, moon, and sun are exceptions: planetographic longitude
C is measured positive east for these bodies.
C
C If you wish to override the default sense of positive
C planetographic longitude for a particular body, you can do so by
C defining the kernel variable
C
C BODY<body ID>_PGR_POSITIVE_LON
C
C where <body ID> represents the NAIF ID code of the body. This
C variable may be assigned either of the values
C
C 'WEST'
C 'EAST'
C
C For example, you can have this routine treat the longitude
C of the earth as increasing to the west using the kernel
C variable assignment
C
C BODY399_PGR_POSITIVE_LON = 'WEST'
C
C Normally such assignments are made by placing them in a text
C kernel and loading that kernel via FURNSH.
C
C
C$ Examples
C
C The following code fragment illustrates how you
C could print the local time at a site on Mars with
C planetographic longitude 326.17 deg E at epoch ET.
C
C (This example assumes all required SPK and PCK files have
C been loaded).
C
C Convert the longitude to radians, set the type of the longitude
C and make up a mnemonic for Mars' ID-code.
C
C LONG = 326.17 * RPD()
C TYPE = 'PLANETOGRAPHIC'
C MARS = 499
C
C CALL ET2LST ( ET, MARS, LONG, TYPE, HR, MN, SC, TIME, AMPM )
C
C WRITE (*,*) 'The local time at Mars 326.17 degrees E '
C WRITE (*,*) 'planetographic longitude is: ', AMPM
C
C$ Restrictions
C
C This routine relies on being able to determine the name
C of the body-fixed frame associated with BODY through the
C frames subsystem. If the BODY specified is NOT one of the
C nine planets or their satellites, you will need to load
C an appropriate frame definition kernel that contains
C the relationship between the body id and the body-fixed frame
C name. See the FRAMES required reading for more details
C on specifying this relationship.
C
C The routine determines the body rotation sense using the PCK
C keyword BODY#_PM. Therefore, you will need to a text PCK file
C defining the complete set of the standard PCK body rotation
C keywords for the body of interest. The text PCK file must be
C loaded independently of whether a binary PCK file providing
C rotation data for the same body is loaded or not.
C
C Although it is not currently the case for any of the Solar System
C bodies, it is possible that the retrograde rotation rate of a
C body would be slower than the orbital rate of the body rotation
C around the Sun. The routine does not account for such cases; for
C them it will compute incorrect the local time progressing
C backwards.
C
C$ Literature_References
C
C None.
C
C$ Author_and_Institution
C
C W.L. Taber (JPL)
C
C$ Version
C
C- SPICELIB Version 3.0.2, 18-APR-2014 (BVS)
C
C Minor edits to long error messages.
C
C- SPICELIB Version 3.0.1, 09-SEP-2009 (EDW)
C
C Header edits: deleted a spurious C$ marker from the
C "Detailed_Output" section. The existence of the marker
C caused a failure in the HTML documentation creation script.
C
C Deleted the "Revisions" section as it contained several
C identical entries from the "Version" section.
C
C Corrected order of header sections.
C
C- SPICELIB Version 3.0.0, 28-OCT-2006 (BVS)
C
C Bug fix: incorrect computation of the local time for the
C bodies with the retrograde rotation causing the local time to
C flow backwards has been fixed. The local time for all types of
C bodies now progresses as expected -- midnight, increasing AM
C hours, noon, increasing PM hours, next midnight, and so on.
C
C- SPICELIB Version 2.0.0, 03-NOV-2005 (NJB)
C
C Bug fix: treatment of planetographic longitude has been
C updated to be consistent with the SPICE planetographic/
C rectangular coordinate conversion routines. The effect of
C this change is that the default sense of positive longitude
C for the moon is now east; also, the default sense of positive
C planetographic longitude now may be overridden for any body
C (see Particulars above).
C
C Updated to remove non-standard use of duplicate arguments
C in RMAIND calls.
C
C- SPICELIB Version 1.1.0, 24-MAR-1998 (WLT)
C
C The integer variable SUN was never initialized in the
C previous version of the routine. Now it is set to
C the proper value of 10.
C
C- SPICELIB Version 1.0.0, 9-JUL-1997 (WLT)
C
C
C-&
C$ Index_Entries
C
C Compute the local time for a point on a body.
C
C-&
C
C SPICELIB Functions
C
DOUBLE PRECISION BRCKTD
DOUBLE PRECISION PI
DOUBLE PRECISION TWOPI
LOGICAL RETURN
C
C Local parameters
C
C
INTEGER BDNMLN
PARAMETER ( BDNMLN = 36 )
INTEGER SUN
PARAMETER ( SUN = 10 )
INTEGER WDSIZE
PARAMETER ( WDSIZE = 32 )
C
C Local Variables
C
CHARACTER*(4) AMORPM
CHARACTER*(BDNMLN) BODNAM
CHARACTER*(WDSIZE) FRAME
CHARACTER*(2) H
CHARACTER*(WDSIZE) BPMKWD
CHARACTER*(2) M
CHARACTER*(WDSIZE) MYTYPE
CHARACTER*(2) S
CHARACTER*(1) KWTYPE
DOUBLE PRECISION ANGLE
DOUBLE PRECISION HOURS
DOUBLE PRECISION LAT
DOUBLE PRECISION LT
DOUBLE PRECISION MINS
DOUBLE PRECISION MYLONG
DOUBLE PRECISION RANGE
DOUBLE PRECISION RATE
DOUBLE PRECISION Q
DOUBLE PRECISION SECNDS
DOUBLE PRECISION SLAT
DOUBLE PRECISION SLONG
DOUBLE PRECISION SPOINT ( 3 )
DOUBLE PRECISION STATE ( 6 )
DOUBLE PRECISION TMPANG
DOUBLE PRECISION TMPSEC
INTEGER FRCODE
INTEGER HRAMPM
INTEGER N
LOGICAL FOUND
C
C Standard SPICE error handling.
C
IF ( RETURN() ) THEN
RETURN
END IF
CALL CHKIN ( 'ET2LST')
CALL LJUST ( TYPE, MYTYPE )
CALL UCASE ( MYTYPE, MYTYPE )
IF ( MYTYPE .EQ. 'PLANETOGRAPHIC' ) THEN
C
C Find planetocentric longitude corresponding to the input
C longitude. We first represent in rectangular coordinates
C a surface point having zero latitude, zero altitude, and
C the input planetographic longitude. We then find the
C planetocentric longitude of this point.
C
C Since PGRREC accepts a body name, map the input code to
C a name, if possible. Otherwise, just convert the input code
C to a string.
C
CALL BODC2N ( BODY, BODNAM, FOUND )
IF ( .NOT. FOUND ) THEN
CALL INTSTR ( BODY, BODNAM )
END IF
C
C Convert planetographic coordinates to rectangular coordinates.
C All we care about here is longitude. Set the other inputs
C as follows:
C
C Latitude = 0
C Altitude = 0
C Equatorial radius = 1
C Flattening factor = 0
C
CALL PGRREC ( BODNAM, LONG, 0.D0, 0.D0, 1.D0, 0.D0, SPOINT )
C
C The output MYLONG is planetocentric longitude. The other
C outputs are not used. Note that the variable RANGE appears
C later in another RECLAT call; it's not used after that.
C
CALL RECLAT ( SPOINT, RANGE, MYLONG, LAT )
ELSE IF ( MYTYPE .EQ. 'PLANETOCENTRIC' ) THEN
MYLONG = LONG
ELSE
CALL SETMSG ( 'The coordinate system ''#'' is not a '
. // 'recognized system of longitude. The '
. // 'recognized systems are '
. // '''PLANETOCENTRIC'' and '
. // '''PLANETOGRAPHIC''. ' )
CALL ERRCH ( '#', TYPE )
CALL SIGERR ( 'SPICE(UNKNOWNSYSTEM)' )
CALL CHKOUT ( 'ET2LST' )
RETURN
END IF
C
C It's always noon on the surface of the sun.
C
IF ( BODY .EQ. 10 ) THEN
HR = 12
MN = 0
SC = 0
TIME = '12:00:00'
AMPM = '12:00:00 P.M.'
CALL CHKOUT ( 'ET2LST' )
RETURN
END IF
C
C Get the body-fixed position of the sun.
C
CALL CIDFRM ( BODY, FRCODE, FRAME, FOUND )
IF ( .NOT. FOUND ) THEN
CALL SETMSG ( 'The body-fixed frame associated with '
. // 'body # could not be determined. This '
. // 'information needs to be "loaded" via a '
. // 'frames definition kernel. See '
. // 'frames.req for more details. ' )
CALL ERRINT ( '#', BODY )
CALL SIGERR ( 'SPICE(CANTFINDFRAME)' )
CALL CHKOUT ( 'ET2LST' )
RETURN
END IF
CALL SPKEZ ( SUN, ET, FRAME, 'LT+S', BODY, STATE, LT )
CALL RECLAT ( STATE, RANGE, SLONG, SLAT )
ANGLE = MYLONG - SLONG
C
C Force the angle into the region from -PI to PI
C
CALL RMAIND ( ANGLE, TWOPI(), Q, TMPANG )
ANGLE = TMPANG
IF ( ANGLE .GT. PI() ) THEN
ANGLE = ANGLE - TWOPI()
END IF
C
C Get the rotation sense of the body and invert the angle if the
C rotation sense is retrograde. Use the BODY#_PM PCK keyword to
C determine the sense of the body rotation.
C
BPMKWD = 'BODY#_PM'
CALL REPMI ( BPMKWD, '#', BODY, BPMKWD )
CALL DTPOOL ( BPMKWD, FOUND, N, KWTYPE )
IF ( .NOT. FOUND
. .OR. KWTYPE .NE. 'N'
. .OR. N .LT. 2 ) THEN
CALL SETMSG ( 'The rotation type for the body # could '
. // 'not be determined because the # keyword '
. // 'was either not found in the POOL or '
. // 'or it was not of the expected type and/or '
. // 'dimension. This keyword is usually '
. // 'provided via a planetary constants '
. // 'kernel. See pck.req for more details. ')
CALL ERRINT ( '#', BODY )
CALL ERRCH ( '#', BPMKWD )
CALL SIGERR ( 'SPICE(CANTGETROTATIONTYPE)' )
CALL CHKOUT ( 'ET2LST' )
RETURN
ELSE
C
C If the rotation rate is negative, invert the angle.
C
CALL GDPOOL ( BPMKWD, 2, 1, N, RATE, FOUND )
IF ( RATE .LT. 0.D0 ) THEN
ANGLE = - ANGLE
END IF
END IF
C
C Convert the angle to "angle seconds" before or after local noon.
C
SECNDS = 86400.0D0 * ANGLE / TWOPI()
SECNDS = BRCKTD ( SECNDS, -43200.0D0, 43200.0D0 )
C
C Get the hour, and minutes components of the local time.
C
CALL RMAIND ( SECNDS, 3600.0D0, HOURS, TMPSEC )
CALL RMAIND ( TMPSEC, 60.0D0, MINS, SECNDS )
C
C Construct the integer components of the local time.
C
HR = 12 + INT(HOURS)
MN = INT(MINS)
SC = INT(SECNDS)
C
C Set the A.M./P.M. components of local time.
C
IF ( HR .EQ. 24 ) THEN
HR = 0
HRAMPM = 12
AMORPM = 'A.M.'
ELSE IF ( HR .GT. 12 ) THEN
HRAMPM = HR - 12
AMORPM = 'P.M.'
ELSE IF ( HR .EQ. 12 ) THEN
HRAMPM = 12
AMORPM = 'P.M.'
ELSE IF ( HR .EQ. 0 ) THEN
HRAMPM = 12
AMORPM = 'A.M.'
ELSE
HRAMPM = HR
AMORPM = 'A.M.'
END IF
C
C Now construct the two strings we need.
C
HOURS = DBLE(HR)
MINS = DBLE(MN)
SECNDS = DBLE(SC)
CALL DPFMT ( HOURS, '0x', H )
CALL DPFMT ( MINS, '0x', M )
CALL DPFMT ( SECNDS, '0x', S )
TIME = H // ':' // M // ':' // S
HOURS = DBLE(HRAMPM)
CALL DPFMT ( HOURS, '0x', H )
AMPM = H // ':' // M // ':' // S // ' ' // AMORPM
CALL CHKOUT ( 'ET2LST' )
RETURN
END
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package event_test
import (
"context"
"io"
"testing"
"golang.org/x/exp/event"
"golang.org/x/exp/event/adapter/logfmt"
"golang.org/x/exp/event/eventtest"
"golang.org/x/exp/event/severity"
)
var (
eventLog = eventtest.Hooks{
AStart: func(ctx context.Context, a int) context.Context {
severity.Info.Log(ctx, eventtest.A.Msg, event.Int64(eventtest.A.Name, int64(a)))
return ctx
},
AEnd: func(ctx context.Context) {},
BStart: func(ctx context.Context, b string) context.Context {
severity.Info.Log(ctx, eventtest.B.Msg, event.String(eventtest.B.Name, b))
return ctx
},
BEnd: func(ctx context.Context) {},
}
eventLogf = eventtest.Hooks{
AStart: func(ctx context.Context, a int) context.Context {
severity.Info.Logf(ctx, eventtest.A.Msgf, a)
return ctx
},
AEnd: func(ctx context.Context) {},
BStart: func(ctx context.Context, b string) context.Context {
severity.Info.Logf(ctx, eventtest.B.Msgf, b)
return ctx
},
BEnd: func(ctx context.Context) {},
}
eventTrace = eventtest.Hooks{
AStart: func(ctx context.Context, a int) context.Context {
ctx = event.Start(ctx, eventtest.A.Msg, event.Int64(eventtest.A.Name, int64(a)))
return ctx
},
AEnd: func(ctx context.Context) {
event.End(ctx)
},
BStart: func(ctx context.Context, b string) context.Context {
ctx = event.Start(ctx, eventtest.B.Msg, event.String(eventtest.B.Name, b))
return ctx
},
BEnd: func(ctx context.Context) {
event.End(ctx)
},
}
eventMetric = eventtest.Hooks{
AStart: func(ctx context.Context, a int) context.Context {
gauge.Record(ctx, 1, event.Int64("aValue", int64(a)))
gauge.Record(ctx, 1, event.Int64("aCount", 1))
return ctx
},
AEnd: func(ctx context.Context) {},
BStart: func(ctx context.Context, b string) context.Context {
gauge.Record(ctx, 1, event.Int64("BLen", int64(len(b))))
gauge.Record(ctx, 1, event.Int64("B", 1))
return ctx
},
BEnd: func(ctx context.Context) {},
}
)
func eventNoExporter() context.Context {
return event.WithExporter(context.Background(), nil)
}
func eventNoop() context.Context {
return event.WithExporter(context.Background(), event.NewExporter(nopHandler{}, eventtest.ExporterOptions()))
}
func eventPrint(w io.Writer) context.Context {
return event.WithExporter(context.Background(), event.NewExporter(logfmt.NewHandler(w), eventtest.ExporterOptions()))
}
func eventPrintSource(w io.Writer) context.Context {
opts := eventtest.ExporterOptions()
opts.EnableNamespaces = true
return event.WithExporter(context.Background(), event.NewExporter(logfmt.NewHandler(w), opts))
}
type nopHandler struct{}
func (nopHandler) Event(ctx context.Context, _ *event.Event) context.Context { return ctx }
func BenchmarkEventLogNoExporter(b *testing.B) {
eventtest.RunBenchmark(b, eventNoExporter(), eventLog)
}
func BenchmarkEventLogNoop(b *testing.B) {
eventtest.RunBenchmark(b, eventNoop(), eventLog)
}
func BenchmarkEventLogDiscard(b *testing.B) {
eventtest.RunBenchmark(b, eventPrint(io.Discard), eventLog)
}
func BenchmarkEventLogSourceDiscard(b *testing.B) {
eventtest.RunBenchmark(b, eventPrintSource(io.Discard), eventLog)
}
func BenchmarkEventLogfDiscard(b *testing.B) {
eventtest.RunBenchmark(b, eventPrint(io.Discard), eventLogf)
}
func BenchmarkEventTraceNoop(b *testing.B) {
eventtest.RunBenchmark(b, eventNoop(), eventTrace)
}
func BenchmarkEventTraceDiscard(b *testing.B) {
eventtest.RunBenchmark(b, eventPrint(io.Discard), eventTrace)
}
func BenchmarkEventMetricNoop(b *testing.B) {
eventtest.RunBenchmark(b, eventNoop(), eventMetric)
}
func BenchmarkEventMetricDiscard(b *testing.B) {
eventtest.RunBenchmark(b, eventPrint(io.Discard), eventMetric)
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Decharge ;
use App\Facture;
use App\Devis;
class DechargeController extends Controller
{
public function index(){
$decharges = Devis::where('date_decharge','<>',null)->orderBy('id' , 'DESC')->with('client')->get();
//$mesures = $client->mesures() ;
return response()->json($decharges) ;
}
public function store(Request $request)
{
// return $request ;
$request->validate([
'name' => 'required|max:255',
'numero' => 'required|max:255',
'numero_facture' => 'required|max:255',
'vendeur' => 'required|max:255',
]);
$decharge = new Decharge() ;
$decharge->name=request('name') ;
$decharge->numero=request('numero') ;
$decharge->numero_facture=request('numero_facture') ;
$decharge->vendeur = request('vendeur') ; // \Auth::user()->nv ;
$decharge->respo=\Auth::user()->name ;
$decharge->save() ;
// return response()->json($decharge);
if($decharge){
return $this->refresh() ;
}
}
private function refresh(){
$decharges = Decharge::orderBy('created_at' , 'DESC')->get();
return response()->json($decharges);
}
}
|
// Copyright 2015-2021 Swim Inc.
//
// 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.
use std::time::Duration;
use tokio::sync::mpsc;
use super::*;
use crate::router::tests::{FakeConnections, MockRemoteRouterTask};
use crate::router::TopLevelClientRouterFactory;
use swim_model::path::AbsolutePath;
use swim_runtime::error::RouterError;
use swim_runtime::routing::CloseSender;
use swim_utilities::future::retryable::Quantity;
use swim_warp::envelope::Envelope;
async fn create_connection_pool(
fake_connections: FakeConnections,
) -> (SwimConnPool<AbsolutePath>, CloseSender) {
let (client_tx, client_rx) = mpsc::channel(32);
let (conn_request_tx, _conn_request_rx) = mpsc::channel(32);
let (close_tx, close_rx) = promise::promise();
let remote_tx = MockRemoteRouterTask::build(fake_connections);
let delegate_fac = TopLevelClientRouterFactory::new(client_tx.clone(), remote_tx);
let client_router_fac = ClientRouterFactory::new(conn_request_tx, delegate_fac);
let (connection_pool, pool_task) = SwimConnPool::new(
DownlinkConnectionsConfig::default(),
(client_tx, client_rx),
client_router_fac,
close_rx,
);
tokio::task::spawn(pool_task.run());
(connection_pool, close_tx)
}
#[tokio::test]
async fn test_connection_pool_send_single_message_single_connection() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("Hello")
.done();
let mut fake_conns = FakeConnections::new();
let (_remote_tx, mut remote_rx) = fake_conns.add_connection(host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
let (mut connection_sender, _connection_receiver) = connection_pool
.request_connection(path, ConnectionType::Outgoing)
.await
.unwrap()
.unwrap();
// When
connection_sender.send_item(envelope.clone()).await.unwrap();
// Then
assert_eq!(
remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(0), envelope)
);
}
#[tokio::test]
async fn test_connection_pool_send_multiple_messages_single_connection() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let first_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("First_Text")
.done();
let second_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("Second_Text")
.done();
let mut fake_conns = FakeConnections::new();
let (_remote_tx, mut remote_rx) = fake_conns.add_connection(host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
let (mut connection_sender, _connection_receiver) = connection_pool
.request_connection(path.clone(), ConnectionType::Outgoing)
.await
.unwrap()
.unwrap();
// When
connection_sender
.send_item(first_envelope.clone())
.await
.unwrap();
connection_sender
.send_item(second_envelope.clone())
.await
.unwrap();
// Then
assert_eq!(
remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(0), first_envelope)
);
assert_eq!(
remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(0), second_envelope)
);
}
#[tokio::test]
async fn test_connection_pool_send_multiple_messages_multiple_connections() {
// Given
let first_host_url = url::Url::parse("ws://127.0.0.1:9001").unwrap();
let second_host_url = url::Url::parse("ws://127.0.0.2:9001/").unwrap();
let third_host_url = url::Url::parse("ws://127.0.0.3:9001/").unwrap();
let first_path = AbsolutePath::new(first_host_url.clone(), "/foo", "/bar");
let second_path = AbsolutePath::new(second_host_url.clone(), "/foo", "/bar");
let third_path = AbsolutePath::new(third_host_url.clone(), "/foo", "/bar");
let first_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("First_Text")
.done();
let second_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("Second_Text")
.done();
let third_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("Third_Text")
.done();
let mut fake_conns = FakeConnections::new();
let (_first_remote_tx, mut first_remote_rx) = fake_conns.add_connection(first_host_url);
let (_second_remote_tx, mut second_remote_rx) = fake_conns.add_connection(second_host_url);
let (_third_remote_tx, mut third_remote_rx) = fake_conns.add_connection(third_host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
let (mut first_connection_sender, _first_connection_receiver) = connection_pool
.request_connection(first_path, ConnectionType::Outgoing)
.await
.unwrap()
.unwrap();
let (mut second_connection_sender, _second_connection_receiver) = connection_pool
.request_connection(second_path, ConnectionType::Outgoing)
.await
.unwrap()
.unwrap();
let (mut third_connection_sender, _third_connection_receiver) = connection_pool
.request_connection(third_path, ConnectionType::Outgoing)
.await
.unwrap()
.unwrap();
// When
first_connection_sender
.send_item(first_envelope.clone())
.await
.unwrap();
second_connection_sender
.send_item(second_envelope.clone())
.await
.unwrap();
third_connection_sender
.send_item(third_envelope.clone())
.await
.unwrap();
// Then
assert_eq!(
first_remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(0), first_envelope)
);
assert_eq!(
second_remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(1), second_envelope)
);
assert_eq!(
third_remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(2), third_envelope)
);
}
#[tokio::test]
async fn test_connection_pool_receive_single_message_single_connection() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("Hello")
.done();
let mut fake_conns = FakeConnections::new();
let (remote_tx, _remote_rx) = fake_conns.add_connection(host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
// When
let (_connection_sender, connection_receiver) = connection_pool
.request_connection(path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
remote_tx
.send(TaggedEnvelope(RoutingAddr::remote(0), envelope.clone()))
.await
.unwrap();
// Then
let pool_message = connection_receiver.unwrap().recv().await.unwrap();
assert_eq!(
pool_message,
RouterEvent::Message(envelope.into_response().unwrap())
);
}
#[tokio::test]
async fn test_connection_pool_receive_multiple_messages_single_connection() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let first_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("first_message")
.done();
let second_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("second_message")
.done();
let third_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("third_message")
.done();
let mut fake_conns = FakeConnections::new();
let (remote_tx, _remote_rx) = fake_conns.add_connection(host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
// When
let (_connection_sender, connection_receiver) = connection_pool
.request_connection(path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
let mut connection_receiver = connection_receiver.unwrap();
remote_tx
.send(TaggedEnvelope(
RoutingAddr::remote(0),
first_envelope.clone(),
))
.await
.unwrap();
remote_tx
.send(TaggedEnvelope(
RoutingAddr::remote(0),
second_envelope.clone(),
))
.await
.unwrap();
remote_tx
.send(TaggedEnvelope(
RoutingAddr::remote(0),
third_envelope.clone(),
))
.await
.unwrap();
// Then
let first_pool_message = connection_receiver.recv().await.unwrap();
let second_pool_message = connection_receiver.recv().await.unwrap();
let third_pool_message = connection_receiver.recv().await.unwrap();
assert_eq!(
first_pool_message,
RouterEvent::Message(first_envelope.into_response().unwrap())
);
assert_eq!(
second_pool_message,
RouterEvent::Message(second_envelope.into_response().unwrap())
);
assert_eq!(
third_pool_message,
RouterEvent::Message(third_envelope.into_response().unwrap())
);
}
#[tokio::test]
async fn test_connection_pool_receive_multiple_messages_multiple_connections() {
// Given
let first_host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let second_host_url = url::Url::parse("ws://127.0.0.2:9001/").unwrap();
let third_host_url = url::Url::parse("ws://127.0.0.3:9001//").unwrap();
let first_path = AbsolutePath::new(first_host_url.clone(), "/foo", "/bar");
let second_path = AbsolutePath::new(second_host_url.clone(), "/foo", "/bar");
let third_path = AbsolutePath::new(third_host_url.clone(), "/foo", "/bar");
let first_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("first_message")
.done();
let second_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("second_message")
.done();
let third_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("third_message")
.done();
let mut fake_conns = FakeConnections::new();
let (first_reader_tx, _) = fake_conns.add_connection(first_host_url);
let (second_reader_tx, _) = fake_conns.add_connection(second_host_url);
let (third_reader_tx, _) = fake_conns.add_connection(third_host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
// When
let (_first_sender, mut first_receiver) = connection_pool
.request_connection(first_path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
let (_second_sender, mut second_receiver) = connection_pool
.request_connection(second_path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
let (_third_sender, mut third_receiver) = connection_pool
.request_connection(third_path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
first_reader_tx
.send(TaggedEnvelope(
RoutingAddr::remote(0),
first_envelope.clone(),
))
.await
.unwrap();
second_reader_tx
.send(TaggedEnvelope(
RoutingAddr::remote(1),
second_envelope.clone(),
))
.await
.unwrap();
third_reader_tx
.send(TaggedEnvelope(
RoutingAddr::remote(2),
third_envelope.clone(),
))
.await
.unwrap();
// Then
let first_pool_message = first_receiver.take().unwrap().recv().await.unwrap();
let second_pool_message = second_receiver.take().unwrap().recv().await.unwrap();
let third_pool_message = third_receiver.take().unwrap().recv().await.unwrap();
assert_eq!(
first_pool_message,
RouterEvent::Message(first_envelope.into_response().unwrap())
);
assert_eq!(
second_pool_message,
RouterEvent::Message(second_envelope.into_response().unwrap())
);
assert_eq!(
third_pool_message,
RouterEvent::Message(third_envelope.into_response().unwrap())
);
}
#[tokio::test]
async fn test_connection_pool_send_and_receive_messages() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let incoming_envelope = Envelope::event()
.node_uri("/foo")
.lane_uri("/bar")
.body("recv_baz")
.done();
let outgoing_envelope = Envelope::command()
.node_uri("/foo")
.lane_uri("/bar")
.body("send_bar")
.done();
let mut fake_conns = FakeConnections::new();
let (remote_tx, mut remote_rx) = fake_conns.add_connection(host_url);
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
let (mut connection_sender, connection_receiver) = connection_pool
.request_connection(path, ConnectionType::Full)
.await
.unwrap()
.unwrap();
// When
connection_sender
.send_item(outgoing_envelope.clone())
.await
.unwrap();
remote_tx
.send(TaggedEnvelope(
RoutingAddr::remote(0),
incoming_envelope.clone(),
))
.await
.unwrap();
// Then
let pool_message = connection_receiver.unwrap().recv().await.unwrap();
assert_eq!(
pool_message,
RouterEvent::Message(incoming_envelope.into_response().unwrap())
);
assert_eq!(
remote_rx.recv().await.unwrap(),
TaggedEnvelope(RoutingAddr::client(0), outgoing_envelope)
);
}
#[tokio::test]
async fn test_connection_pool_connection_error() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let path = AbsolutePath::new(host_url.clone(), "/foo", "/bar");
let fake_conns = FakeConnections::new();
let (mut connection_pool, _close_tx) = create_connection_pool(fake_conns).await;
// When
let connection = connection_pool
.request_connection(path, ConnectionType::Full)
.await
.unwrap();
// Then
assert!(connection.is_err());
}
#[tokio::test]
async fn test_connection_pool_close() {
// Given
let host_url = url::Url::parse("ws://127.0.0.1:9001/").unwrap();
let mut fake_conns = FakeConnections::new();
let (remote_tx, mut remote_rx) = fake_conns.add_connection(host_url);
let (_connection_pool, close_tx) = create_connection_pool(fake_conns).await;
let (response_tx, mut response_rx) = mpsc::channel(8);
// When
assert!(close_tx.provide(response_tx).is_ok());
// Then
assert!(response_rx.recv().await.is_none());
assert!(remote_rx.recv().await.is_none());
assert!(remote_tx.is_closed());
}
#[tokio::test]
async fn test_retry_open_connection_cancel() {
// Given
let target = RegistrationTarget::Local(String::from("/foo"));
let retry_strategy = RetryStrategy::interval(Duration::from_secs(10), Quantity::Infinite);
let (request_tx, _request_rx) = mpsc::channel(8);
let client_router_fac = ClientRouterFactory::new(request_tx, MockRouterFactory);
let mut client_router: ClientRouter<AbsolutePath, MockRouter> =
client_router_fac.create_for(RoutingAddr::client(0));
let (close_tx, close_rx) = promise::promise();
let (response_tx, _response_rx) = mpsc::channel(8);
// When
close_tx.provide(response_tx).unwrap();
let result = open_connection(target, retry_strategy, &mut client_router, close_rx).await;
// Then
assert!(result.is_err());
}
struct MockRouterFactory;
impl RouterFactory for MockRouterFactory {
type Router = MockRouter;
fn create_for(&self, _addr: RoutingAddr) -> Self::Router {
MockRouter
}
}
struct MockRouter;
impl Router for MockRouter {
fn resolve_sender(&mut self, _addr: RoutingAddr) -> BoxFuture<Result<Route, ResolutionError>> {
unimplemented!()
}
fn lookup(
&mut self,
_host: Option<Url>,
_route: RelativeUri,
) -> BoxFuture<Result<RoutingAddr, RouterError>> {
async {
Err(RouterError::ConnectionFailure(
ConnectionError::WriteTimeout(Duration::from_secs(10)),
))
}
.boxed()
}
}
impl BidirectionalRouter for MockRouter {
fn resolve_bidirectional(
&mut self,
_host: Url,
) -> BoxFuture<Result<BidirectionalRoute, ResolutionError>> {
unimplemented!()
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Serilog;
namespace PostSharp.Samples.Logging.ElmahIo.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public string Result
{
get;
set;
}
[BindProperty]
public string NumberOfKgs
{
get;
set;
}
public void OnPost()
{
this.WriteInterestingFacts();
}
public void OnGet()
{
this.WriteInterestingFacts();
}
private void WriteInterestingFacts()
{
try
{
float kgs = this.GetKilograms(this.NumberOfKgs);
this.Result =
"You weigh " + kgs + " kilograms.\n" +
"You would sell for " + WorthInGold(kgs) + " if you were made of gold.\n" +
"You would explode as " + Explosion(kgs) + " atomic bombs if you were turned into pure energy.\n" +
"You would fall for " + EiffelFall(kgs) + " seconds if you fell from the Eiffel Tower.";
}
catch (Exception)
{
this.Result = "I can't tell you anything about your body.";
}
}
private string EiffelFall(in float kgs) // Ha ha, your mass doesn't actually matter ^^
{
int distance = 300; // m
// distance = acceleration * time squared
// time = square root of (distance / acceleration)
float time = MathF.Sqrt((float) distance / 9.81f);
return time.ToString("F2");
}
private string Explosion(in float kgs)
{
// e = m * c * c
BigInteger c = 299792458;
BigInteger cc = c * c;
BigInteger eTimes1000 = (cc) * new BigInteger((int) (kgs * 1000)); // reasonable accuracy
BigInteger e = eTimes1000 / 1000;
BigInteger atomicEnergy = new BigInteger(100) * 1000 * 1000 * 1000 * 1000;
BigInteger bombs = e / atomicEnergy;
return bombs.ToString();
}
private string WorthInGold(in float kgs)
{
float costOfKgOfGold = 61612; // USD as of September 22, 2020
return "$" + (kgs * costOfKgOfGold);
}
private float GetKilograms(string numberOfStars)
{
return float.Parse(numberOfStars, this.GetUserCulture());
}
private CultureInfo GetUserCulture()
{
var locale = this.Request.HttpContext.Features.Get<IRequestCultureFeature>();
return locale.RequestCulture.Culture;
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cofoundry.Web
{
public class ErrorsRouteRegistration : IOrderedRouteRegistration, IRunAfterRouteRegistration
{
public int Ordering => (int)RouteRegistrationOrdering.Early;
public ICollection<Type> RunAfter => new Type[] { typeof(AssetsRouteRegistration) };
public void RegisterRoutes(IEndpointRouteBuilder routeBuilder)
{
routeBuilder.MapControllerRoute(
"Cofoundry_ErrorCode",
"cofoundryerror/errorcode/{statusCode}",
new { controller = "CofoundryError", action = "ErrorCode" },
new { statusCode = @"\d+" });
routeBuilder.MapControllerRoute(
"Cofoundry_Exception",
"cofoundryerror/exception/",
new { controller = "CofoundryError", action = "Exception" });
}
}
}
|
MODULE efstr_I
INTERFACE
!...Generated by Pacific-Sierra Research 77to90 4.4G 10:47:10 03/09/06
SUBROUTINE efstr (XPARAM, FUNCT, IHESS, NTIME, ILOOP, IGTHES, MXSTEP&
, IRECLC, IUPD, DMAX, DDMAX, DMIN, TOL2, TIME1, TIME2, NVAR, SCF1, LUPD&
, LDUMP, LOG, RRSCAL, DONR, GNMIN, HESS, BMAT, PMAT)
USE vast_kind_param,ONLY: DOUBLE
real(DOUBLE), DIMENSION(*) :: XPARAM
real(DOUBLE) :: FUNCT
integer, INTENT(OUT) :: IHESS
integer, INTENT(OUT) :: NTIME
integer, INTENT(OUT) :: ILOOP
integer, INTENT(INOUT) :: IGTHES
integer, INTENT(OUT) :: MXSTEP
integer, INTENT(OUT) :: IRECLC
integer, INTENT(INOUT) :: IUPD
real(DOUBLE), INTENT(OUT) :: DMAX
real(DOUBLE), INTENT(OUT) :: DDMAX
real(DOUBLE), INTENT(OUT) :: DMIN
real(DOUBLE), INTENT(OUT) :: TOL2
real(DOUBLE), INTENT(OUT) :: TIME1
real(DOUBLE), INTENT(OUT) :: TIME2
integer, INTENT(INOUT) :: NVAR
logical, INTENT(OUT) :: SCF1
logical, INTENT(OUT) :: LUPD
integer, INTENT(OUT) :: LDUMP
logical, INTENT(OUT) :: LOG
logical, INTENT(OUT) :: RRSCAL
logical, INTENT(OUT) :: DONR
logical, INTENT(OUT) :: GNMIN
real(DOUBLE), DIMENSION(NVAR,NVAR) :: HESS
real(DOUBLE), DIMENSION(NVAR,NVAR) :: BMAT
real(DOUBLE), DIMENSION(NVAR,NVAR) :: PMAT
END SUBROUTINE
END INTERFACE
END MODULE
|
//
// Created by Yohsuke Murase on 2021/10/17.
//
#include <iostream>
#include <vector>
#include <array>
#include <cassert>
#include "mpi.h"
#ifndef CPP_SCALAPACK_HPP
#define CPP_SCALAPACK_HPP
extern "C" {
void sl_init_(int *icontext, int *nprow, int *npcolumn);
// SL_INIT initializes an NPROW x NPCOL process grid using a row-major ordering
// of the processes. This routine retrieves a default system context which will
// include all available processes. (out) ictxt, (in) nprow, npcolumn
void blacs_gridinfo_(int *icontext, int *nprow, int *npcolumn, int *myrow,
int *mycolumn);
// (in) icontext: BLACS context
// (out) nprow, npcolumn: the numbers of rows and columns in this process grid
// (out) myrow, mycolumn: the process grid row- and column-index
void blacs_exit_(int *cont);
// (in) continue: if 0, all the resources are released. If nonzero, MPI
// resources are not released.
void blacs_gridexit_(int *icontext);
// (in) icontext: BLACS context
void descinit_(int *desc, int *m, int *n, int *mb, int *nb, int *irsrc,
int *icsrc, int *icontext, int *lld, int *info);
// (out) descriptor for the global matrix. `desc` must be an array of int of
// length 9. int[9]
// (in) m, n: rows and columns of the matrix (in) mb, nb: row,
// column block sizes
// (in) irsrc, icsrc: the process row (column) over which the
// first row of the global matrix is distributed.
// (in) icontext: BLACS context
// (in) lld: leading dimension of the local array
// (out) info: 0 => completed successfully
void dgesd2d_(int *icontext, int *m, int *n, double *A, int *lda, int *r_dest,
int *c_dest);
// Takes a general rectangular matrix and sends it to the destination process.
// (in) icontext: BLACS context
// (in) m,n: matrix sizes
// (in) A: matrix
// (in) lda: leading dimension (m)
// (in) r_dest, c_dest: the process corrdinate of the process to send the
// message to
void dgerv2d_(int *icontext, int *m, int *n, double *A, int *lda, int *row_src,
int *col_src);
// Receives a message from the process into the general rectangular matrix.
// (in) icontext: BLACS context
// (in) m,n,lda: sizes of the matrix
// (out) A: matrix
// (in) row_src, col_src: the process coordinate of the source of the message
void pdgesv_(int *n, int *nrhs, double *A, int *ia, int *ja, int desc_a[9],
int *ipvt, double *B, int *ib, int *jb, int desc_b[9], int *info);
// These subroutines solve the following systems of equations for multiple
// right-hand sides: AX = B
// (in) n: order of the submatrix = the number of rows of B
// (in) nrhs: the number of columns of B
// (in/out) A: the local part of the global general matrix A.
// (in) ia, ja: the row and the column indices of the
// global matrix A, identifying the first row and column of the submatrix A.
// (in) desc_a: descriptor of A matrix
// (out) ipvt: the local part of the global vector ipvt, containing the pivot
// indices.
// (in/out) B: the local part of the global general matrix B,
// containing the right-hand sides of the system.
// (in) ib, jb: the row and the column indices of the global matrix B,
// identifying the first row and column of the submatrix B.
// (in) desc_b: descriptor of B matrix (out) info: error code
void pdgemm_( char *TRANSA, char *TRANSB,
int *M, int *N, int *K,
double *ALPHA,
double *A, int *IA, int *JA, int DESCA[9],
double *B, int *IB, int *JB, int DESCB[9],
double *BETA,
double *C, int *IC, int *JC, int DESCC[9] );
// calculate alpha*AB + beta*C
// A: M x K, B: K x N, C: M x N
// (in) TRANSA, TRANSB: 'n' or 't' (normal or transpose)
// (in) M, N, K: sizes of the matrix
// (in) ALPHA, BETA: coefficient
// (in) A,B,C: input matrix
// (out) C: output matrix
}
class Scalapack {
public:
static int ICTXT, NPROW, NPCOL, MYROW, MYCOL;
static void Initialize(const std::array<int,2>& proc_grid_size) {
NPROW = proc_grid_size[0];
NPCOL = proc_grid_size[1];
int num_proc;
MPI_Comm_size(MPI_COMM_WORLD, &num_proc);
if (num_proc != NPROW * NPCOL) {
std::cerr << "Error: invalid number of procs" << std::endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
sl_init_(&ICTXT, &NPROW, &NPCOL);
blacs_gridinfo_(&ICTXT, &NPROW, &NPCOL, &MYROW, &MYCOL);
}
static void Finalize() {
blacs_gridexit_(&ICTXT);
int blacs_exitcode = 0;
blacs_exit_(&blacs_exitcode);
}
// global matrix
class GMatrix {
public:
GMatrix(size_t N, size_t M) : N(N), M(M) {
A.resize(N * M, 0.0);
}
size_t N, M;
std::vector<double> A;
double At(size_t I, size_t J) const { return A.at(I*M+J); }
void Set(size_t I, size_t J, double val) { A[I*M+J] = val; }
double* Data() { return A.data(); }
size_t Size() { return A.size(); }
friend std::ostream& operator<<(std::ostream& os, const GMatrix& gm) {
for (size_t i = 0; i < gm.N; i++) {
for (size_t j = 0; j < gm.M; j++) {
os << gm.At(i, j) << ' ';
}
os << "\n";
}
return os;
}
void BcastFrom(int root_rank) {
int my_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
std::array<uint64_t,2> sizes = {N, M};
MPI_Bcast(sizes.data(), 2, MPI_UINT64_T, root_rank, MPI_COMM_WORLD);
if (my_rank != root_rank) { A.resize(N*M); }
MPI_Bcast(A.data(), N*M, MPI_DOUBLE, root_rank, MPI_COMM_WORLD);
}
};
// local matrix for scalapack
class LMatrix {
public:
LMatrix(int N, int M, int NB, int MB) : N(N), M(M), NB(NB), MB(MB) { // matrix N x M with block NB x MB
SUB_ROWS = (N / (NB * NPROW)) * NB + std::min(N % (NB * NPROW), NB);
SUB_COLS = (M / (MB * NPCOL)) * MB + std::min(M % (MB * NPCOL), MB);
int RSRC = 0, CSRC = 0, INFO;
descinit_(DESC, &N, &M, &NB, &MB, &RSRC, &CSRC, &ICTXT, &SUB_ROWS, &INFO);
assert(INFO == 0);
SUB.resize(SUB_ROWS * SUB_COLS, 0.0);
}
LMatrix(const GMatrix& gm, int NB, int MB) : N(gm.N), M(gm.M), NB(NB), MB(MB) {
SUB_ROWS = (N / (NB * NPROW)) * NB + std::min(N % (NB * NPROW), NB);
SUB_COLS = (M / (MB * NPCOL)) * MB + std::min(M % (MB * NPCOL), MB);
int RSRC = 0, CSRC = 0, INFO;
descinit_(DESC, &N, &M, &NB, &MB, &RSRC, &CSRC, &ICTXT, &SUB_ROWS, &INFO);
assert(INFO == 0);
SUB.resize(SUB_ROWS * SUB_COLS, 0.0);
for (int i = 0; i < SUB_ROWS; i++) {
for (int j = 0; j < SUB_COLS; j++) {
auto IJ = ToGlobalCoordinate(i, j);
size_t I = IJ[0], J = IJ[1];
if (I < N && J < M) {
Set(i, j, gm.At(I, J));
}
}
}
};
int N, M; // size of the global matrix
int NB, MB; // block sizes
int SUB_ROWS, SUB_COLS; // size of the local matrix
int DESC[9];
std::vector<double> SUB;
// convert submatrix index (i,j) at process (p_row, p_col) into global coordinate (I,J)
std::array<size_t,2> ToGlobalCoordinate(size_t i, size_t j, int p_row = MYROW, int p_col = MYCOL) const {
// block coordinate (bi, bj)
size_t bi = i / NB;
size_t bj = j / MB;
// local coordinate inside the block
size_t ii = i % NB;
size_t jj = j % MB;
// calculate global coordinate
size_t I = bi * (NB * NPROW) + p_row * NB + ii;
size_t J = bj * (MB * NPCOL) + p_col * MB + jj;
return {I, J};
}
// convert global matrix index (I,J) to local coordinate (i,j),(p_row,p_col)
std::pair<std::array<size_t,2>, std::array<int,2>> ToLocalCoordinate(size_t I, size_t J) const {
// global block coordinate (BI, BJ)
size_t BI = I / NB;
size_t BJ = J / MB;
// process coordinate (bi, bj)
int p_row = BI % NPROW;
int p_col = BJ % NPCOL;
// local block coordinate (bi, bj)
size_t bi = BI / NPROW;
size_t bj = BJ / NPCOL;
// local coordinate inside the block
size_t ii = I % NB;
size_t jj = J % MB;
// calculate global coordinate
size_t i = bi * NB + ii;
size_t j = bj * MB + jj;
return {{i, j}, {p_row, p_col}};
}
double At(size_t i, size_t j) const { // get an element at SUB[ (i,j) ]
return SUB[i + j * SUB_ROWS];
}
void Set(size_t i, size_t j, double val) {
SUB[i + j * SUB_ROWS] = val;
}
void SetByGlobalCoordinate(size_t I, size_t J, double val) {
auto local_pos = ToLocalCoordinate(I, J);
auto ij = local_pos.first;
auto proc_grid = local_pos.second;
if (proc_grid[0] == MYROW && proc_grid[1] == MYCOL) {
Set(ij[0], ij[1], val);
}
}
void SetAll(double val) {
for (size_t i = 0; i < SUB_ROWS; i++) {
for (size_t j = 0; j < SUB_COLS; j++) {
auto IJ = ToGlobalCoordinate(i, j);
if (IJ[0] < N && IJ[1] < M) Set(i, j, val);
}
}
}
double* Data() { return SUB.data(); }
friend std::ostream& operator<<(std::ostream& os, const LMatrix& lm) {
for (size_t i = 0; i < lm.SUB_ROWS; i++) {
for (size_t j = 0; j < lm.SUB_COLS; j++) {
os << lm.At(i, j) << ' ';
}
os << "\n";
}
return os;
}
GMatrix ConstructGlobalMatrix() const {
GMatrix A(N, M);
for (size_t i = 0; i < SUB_ROWS; i++) {
for (size_t j = 0; j < SUB_COLS; j++) {
auto IJ = ToGlobalCoordinate(i, j);
size_t I = IJ[0], J = IJ[1];
if (I < N && J < M) {
A.Set(I, J, At(i, j));
}
}
}
GMatrix AA(N, M);
MPI_Allreduce(A.Data(), AA.Data(), N*M, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
return AA;
}
void DebugPrintAtRoot(std::ostream& out) const {
MPI_Barrier(MPI_COMM_WORLD);
GMatrix g = ConstructGlobalMatrix();
if (Scalapack::MYROW == 0 && Scalapack::MYCOL == 0) {
out << g;
}
MPI_Barrier(MPI_COMM_WORLD);
}
static LMatrix Identity(int N, int M, int NB, int MB) {
LMatrix lm(N, M, NB, MB);
for (size_t i = 0; i < lm.SUB_ROWS; i++) {
for (size_t j = 0; j < lm.SUB_COLS; j++) {
auto IJ = lm.ToGlobalCoordinate(i, j);
if (IJ[0] < N && IJ[1] < M && IJ[0] == IJ[1]) lm.Set(i, j, 1.0);
}
}
return lm;
}
};
// call PDGESV routine of Scalapack
// The solution is stored in B
static void CallPDGESV(LMatrix& A, LMatrix& B) {
assert(A.N == A.M);
assert(A.N == B.N);
int IA = 1;
int JA = 1;
int IB = 1;
int JB = 1;
int INFO = 0;
std::vector<int> IPIV(A.N + A.NB, 0);
// std::cerr << A << B;
pdgesv_(&A.N, &B.M, A.Data(), &IA, &JA, A.DESC, IPIV.data(),
B.Data(), &IB, &JB, B.DESC, &INFO);
if (INFO != 0) {
std::cerr << "Error: INFO of PDGESV is not zero but " << INFO << std::endl;
MPI_Abort(MPI_COMM_WORLD, 2);
}
assert(INFO == 0);
}
// computes AB+C
// the results are stored in C
static void CallPDGEMM(double alpha, LMatrix& A, LMatrix& B, double beta, LMatrix& C) {
assert(A.N == C.N);
assert(A.M == B.N);
assert(B.M == C.M);
int IA = 1, JA = 1, IB = 1, JB = 1, IC = 1, JC = 1;
char trans = 'n';
pdgemm_(&trans, &trans, &C.N, &C.M, &A.M,
&alpha,
A.Data(), &IA, &JA, A.DESC,
B.Data(), &IB, &JB, B.DESC,
&beta,
C.Data(), &IC, &JC, C.DESC);
}
};
#endif //CPP_SCALAPACK_HPP
|
package com.socion.backend.service;
import com.socion.backend.dto.AppUpdateDto;
public interface AppUpdateService {
AppUpdateDto appupdate(String appVersion, String appName, String appType);
}
|
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dolittle.CodeAnalysis.ExceptionDescriptionShouldFollowStandard
{
[TestClass]
public class UnitTests : CodeFixVerifier
{
[TestMethod]
public void WithDescriptionFollowingStandard()
{
const string content = @"
using System;
namespace MyNamespace
{
/// <summary>
/// Exception that gets thrown when
/// </summary>
public class SomethingWentWrong : Exception
{
}
}
";
VerifyCSharpDiagnostic(content);
}
[TestMethod]
public void WithoutDescriptionFollowingStandard()
{
const string content = @"
using System;
namespace MyNamespace
{
/// <summary>
/// Some kinda exception
/// </summary>
public class SomethingWentWrong : Exception
{
}
}
";
var expected = new DiagnosticResult
{
Id = Analyzer.Rule.Id,
Message = (string)Analyzer.Rule.MessageFormat,
Severity = Analyzer.Rule.DefaultSeverity,
Locations = new[]
{
new DiagnosticResultLocation("Test0.cs", 7, 24)
}
};
VerifyCSharpDiagnostic(content, expected);
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new Analyzer();
}
}
}
|
import { Context, Next } from "koa";
import { Provide } from "../../../decorator/provide.decorator";
import { IMiddleware } from "../../../types/http";
import { Inject } from "../../../decorator/inject.decorator";
import { Application } from "../../../Application";
import fs from "fs";
import path from "path";
interface IStaticConfig {
static: string;
index?: string;
}
@Provide<Static>("core.http.middleware.static", "single", "initialize")
class Static implements IMiddleware {
@Inject("#application")
private app!: Application;
private staticPath = "./";
private index = "index.html";
public initialize() {
const config = this.app.getConfig("http") as IStaticConfig;
this.staticPath = path.resolve(this.app.getContextPath(), config.static);
if (config.index) {
this.index = config.index;
}
}
public exec(ctx: Context, next: Next) {
if (ctx.method === "GET") {
const { path: urlPath } = ctx;
let filename = path.resolve(this.staticPath, `.${urlPath}`);
if (!fs.existsSync(filename) || !fs.statSync(filename).isFile()) {
const _path = path.resolve(filename, `${this.index}`);
if (fs.existsSync(_path) && fs.statSync(_path).isFile()) {
filename = _path;
}
}
if (fs.existsSync(filename) && fs.statSync(filename).isFile()) {
ctx.body = fs.readFileSync(filename, { encoding: "utf-8" });
}
}
return next();
}
public getStaticPath() {
return this.staticPath;
}
}
export default Static;
|
'use strict';
/* Controllers */
angular.module('sampleApp.controllers')
.controller('MainController', [ '$scope', 'messageService', 'language',
function ($scope, messages, language) {
$scope.language = language;
$scope.user = {username:"daniel"};
$scope.addMsg = function(transl8Key, level, showContactInfo) {
messages.add(transl8Key, level, showContactInfo);
}
$scope.searchPathFunction = function(q){return 'some-search-path?q=' + q}
}
]);
|
<?php
namespace Hris\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gist\CoreBundle\Template\Entity\HasGeneratedID;
use Gist\CoreBundle\Template\Entity\HasName;
use Gist\CoreBundle\Template\Entity\HasCode;
use Gist\CoreBundle\Template\Entity\HasNotes;
use Gist\CoreBundle\Template\Entity\TrackCreate;
use stdClass;
/**
* @ORM\Entity
* @ORM\Table(name="hr_job_title")
*/
class JobTitle
{
const TYPE_RANK = "Rank";
const TYPE_MANAGEMENT = "Management";
use HasGeneratedID;
use HasName;
use HasNotes;
use TrackCreate;
/** @ORM\Column(type="string", length=80) */
protected $type;
/**
* @ORM\ManyToOne(targetEntity="Hris\AdminBundle\Entity\Department")
* @ORM\JoinColumn(name="dept_id", referencedColumnName="id")
*/
protected $department;
/**
* @ORM\ManyToOne(targetEntity="JobTitle", inversedBy="subordinates")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
**/
protected $parent;
/** @ORM\OneToMany(targetEntity="JobTitle", mappedBy="parent") */
protected $subordinates;
public function __construct()
{
$this->initTrackCreate();
$this->initHasName();
$this->initHasNotes();
$this->type = self::TYPE_RANK;
$this->parent = null;
$this->subordinates = new ArrayCollection();
}
public function setType($type)
{
$this->type = $type;
return $this;
}
public function getType()
{
return $this;
}
public function setDepartment(\Hris\AdminBundle\Entity\Department $department = null)
{
$this->department = $department;
return $this;
}
public function getDepartment()
{
return $this->department;
}
public function setParent(JobTitle $jobTitle)
{
$this->parent = $jobTitle;
return $this;
}
public function getParent()
{
return $this->parent;
}
public function addSubordinate(JobTitle $jobTitle)
{
$jobTitle->setParent($this);
$this->subordinates->add($jobTitle);
return $this;
}
public function getSubordinates()
{
return $this->subordinates;
}
public function toData()
{
$data = new \stdClass();
$this->dataHasGeneratedID($data);
$this->dataTrackCreate($data);
$this->dataHasName($data);
$this->dataHasNotes($data);
return $data;
}
}
|
package uk.jixun.project.Exceptions;
public class LabelNotFoundException extends Exception {
public LabelNotFoundException() {
super();
}
public LabelNotFoundException(String s) {
super(s);
}
static public LabelNotFoundException fromLabel(String l) {
return new LabelNotFoundException("From label '" + l + "'");
}
}
|
/*
+----------------------------------------------------------------------+
| Copyright (c) 1997-2019 Derick Rethans |
+----------------------------------------------------------------------+
| This source file is subject to the 2-Clause BSD license which is |
| available through the LICENSE file, or online at |
| http://opensource.org/licenses/bsd-license.php |
+----------------------------------------------------------------------+
| Authors: Derick Rethans <derick@derickrethans.nl> |
+----------------------------------------------------------------------+
*/
/* $Id: php_vld.h,v 1.9 2009-03-30 18:22:15 derick Exp $ */
#ifndef PHP_VLD_H
#define PHP_VLD_H
#include "php.h"
extern zend_module_entry vld_module_entry;
#define phpext_vld_ptr &vld_module_entry
#ifdef PHP_WIN32
#define PHP_VLD_API __declspec(dllexport)
#else
#define PHP_VLD_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
PHP_MINIT_FUNCTION(vld);
PHP_MSHUTDOWN_FUNCTION(vld);
PHP_RINIT_FUNCTION(vld);
PHP_RSHUTDOWN_FUNCTION(vld);
PHP_MINFO_FUNCTION(vld);
ZEND_BEGIN_MODULE_GLOBALS(vld)
int active;
int skip_prepend;
int skip_append;
int execute;
int verbosity;
int format;
char *col_sep;
int save_paths;
char *save_dir;
FILE *path_dump_file;
int dump_paths;
ZEND_END_MODULE_GLOBALS(vld)
int vld_printf(FILE *stream, const char* fmt, ...);
#ifdef ZTS
#define VLD_G(v) TSRMG(vld_globals_id, zend_vld_globals *, v)
#else
#define VLD_G(v) (vld_globals.v)
#endif
#define VLD_PRINT(v,args) if (VLD_G(verbosity) >= (v)) { vld_printf(stderr, args); }
#define VLD_PRINT1(v,args,x) if (VLD_G(verbosity) >= (v)) { vld_printf(stderr, args, (x)); }
#define VLD_PRINT2(v,args,x,y) if (VLD_G(verbosity) >= (v)) { vld_printf(stderr, args, (x), (y)); }
#if PHP_VERSION_ID >= 70000
# define ZHASHKEYSTR(k) ((k)->key->val)
# define ZHASHKEYLEN(k) ((k)->key->len)
# define PHP_URLENCODE_NEW_LEN(v)
# define ZVAL_VALUE_TYPE zend_value
# define ZVAL_VALUE_STRING_TYPE zend_string
# define ZVAL_STRING_VALUE(s) (s.str)->val
# define ZVAL_STRING_LEN(s) (s.str)->len
# define ZSTRING_VALUE(s) (s ? (s)->val : NULL)
# define OPARRAY_VAR_NAME(v) (v)->val
#else
# define ZHASHKEYSTR(k) ((k)->arKey)
# define ZHASHKEYLEN(k) ((k)->nKeyLength - 1)
# define PHP_URLENCODE_NEW_LEN(v) , &(v)
# define ZVAL_VALUE_TYPE zvalue_value
# define ZVAL_VALUE_STRING_TYPE char
# define ZVAL_STRING_VALUE(s) (s.str.val)
# define ZVAL_STRING_LEN(s) (s.str.len)
# define ZSTRING_VALUE(s) (s)
# define OPARRAY_VAR_NAME(v) (v).name
#endif
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
|
/*
Copyright 2018 The Crossplane 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 bucket
import (
"context"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
corev1alpha1 "github.com/crossplaneio/crossplane/pkg/apis/core/v1alpha1"
"github.com/crossplaneio/crossplane/pkg/apis/gcp"
"github.com/crossplaneio/crossplane/pkg/apis/gcp/storage/v1alpha1"
storagev1alpha1 "github.com/crossplaneio/crossplane/pkg/apis/storage/v1alpha1"
"github.com/crossplaneio/crossplane/pkg/test"
)
const (
ns = "default"
name = "testBucket"
)
var (
meta = metav1.ObjectMeta{
Namespace: ns,
Name: name,
}
)
func init() {
_ = gcp.AddToScheme(scheme.Scheme)
}
func TestGCSBucketHandler_Find(t *testing.T) {
nn := types.NamespacedName{Namespace: ns, Name: name}
type args struct {
n types.NamespacedName
c client.Client
}
type want struct {
err error
res corev1alpha1.Resource
}
tests := []struct {
name string
args args
want want
}{
{
name: "ErrorRetrieving",
args: args{
n: nn,
c: &test.MockClient{
MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error {
return errors.New("test-get-error")
},
},
},
want: want{
err: errors.Wrapf(errors.New("test-get-error"),
"cannot find gcs bucket instance %s", nn),
},
},
{
name: "Success",
args: args{
n: nn,
c: fake.NewFakeClient(&v1alpha1.Bucket{ObjectMeta: meta}),
},
want: want{
res: corev1alpha1.Resource(&v1alpha1.Bucket{ObjectMeta: meta}),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &GCSBucketHandler{}
got, err := h.Find(tt.args.n, tt.args.c)
if diff := cmp.Diff(err, tt.want.err, test.EquateErrors()); diff != "" {
t.Errorf("GCSBucketHandler.Find() error = %v, wantErr %v\n%s", err, tt.want.err, diff)
}
if diff := cmp.Diff(got, tt.want.res); diff != "" {
t.Errorf("GCSBucketHandler.Find() = %v, want %v\n%s", got, tt.want.res, diff)
}
})
}
}
func TestGCSBucketHandler_Provision(t *testing.T) {
meta := metav1.ObjectMeta{
Namespace: ns,
Name: name,
UID: types.UID("test-uid"),
}
class := &corev1alpha1.ResourceClass{
ObjectMeta: meta,
}
claim := &storagev1alpha1.Bucket{
ObjectMeta: meta,
}
type args struct {
class *corev1alpha1.ResourceClass
claim corev1alpha1.ResourceClaim
c client.Client
}
type want struct {
err error
res corev1alpha1.Resource
}
tests := []struct {
name string
args args
want want
}{
{
name: "CreateSuccessful",
args: args{
class: class,
claim: claim,
c: test.NewMockClient(),
},
want: want{
res: &v1alpha1.Bucket{
TypeMeta: metav1.TypeMeta{
APIVersion: v1alpha1.APIVersion,
Kind: v1alpha1.BucketKind,
},
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: fmt.Sprintf("gcs-%s", claim.GetUID()),
OwnerReferences: []metav1.OwnerReference{claim.OwnerReference()},
},
Spec: v1alpha1.BucketSpec{
ClassRef: class.ObjectReference(),
ClaimRef: claim.ObjectReference(),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &GCSBucketHandler{}
got, err := h.Provision(tt.args.class, tt.args.claim, tt.args.c)
if diff := cmp.Diff(err, tt.want.err, test.EquateErrors()); diff != "" {
t.Errorf("GCSBucketHandler.Provision() error = %v, wantErr %v\n%s", err, tt.want.err, diff)
return
}
if diff := cmp.Diff(got, tt.want.res); diff != "" {
t.Errorf("GCSBucketHandler.Provision() = \n%+v, want \n%+v\n%s", got, tt.want.res, diff)
}
})
}
}
func TestGCSBucketHandler_SetBindStatus(t *testing.T) {
nn := types.NamespacedName{Namespace: ns, Name: name}
type args struct {
n types.NamespacedName
c client.Client
bound bool
}
tests := []struct {
name string
args args
wantErr error
}{
{
name: "GetErrorNotFoundAndNotBound",
args: args{
n: nn,
c: fake.NewFakeClient(),
bound: false,
},
},
{
name: "GetErrorNotFoundAndBound",
args: args{
n: nn,
c: fake.NewFakeClient(),
bound: true,
},
wantErr: errors.Wrapf(errors.New("buckets.storage.gcp.crossplane.io \"testBucket\" not found"),
"cannot get bucket default/testBucket"),
},
{
name: "UpdateError",
args: args{
n: nn,
c: &test.MockClient{
MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error {
return nil
},
MockUpdate: func(ctx context.Context, obj runtime.Object) error {
return errors.New("test-update-error")
},
},
bound: true,
},
wantErr: errors.Wrapf(errors.New("test-update-error"),
"cannot update bucket %s", nn),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &GCSBucketHandler{}
err := h.SetBindStatus(tt.args.n, tt.args.c, tt.args.bound)
if diff := cmp.Diff(err, tt.wantErr, test.EquateErrors()); diff != "" {
t.Errorf("GCSBucketHandler.SetBindStatus() error = %v, wantErr %v\n%s", err, tt.wantErr, diff)
}
})
}
}
|
---
layout: page
title: grep
docs: https://www.man7.org/linux/man-pages/man1/grep.1p.html
---
Find and print lines containing `hello` in file `./file.txt`
```bash
grep hello file.txt
```
Find and print lines containing `hello` in files in directory `./files` and it's subdirectories
```bash
grep -r hello files
```
Find and print lines containing `hello` in file `./file.txt` ignoring case
```bash
grep -i hello file.txt
```
Find and print lines containing `hello` as a seperate word in file `./file.txt`
```bash
grep -w hello file.txt
```
Find and print lines not containing `hello` in file `./file.txt`
```bash
grep -v hello file.txt
```
|
/**
# 2D Rayleigh-Bernard convection in a periodic square.
Setting $Ra = 10^6$ and $Pr = 1$ results in a periodic-in-time
pattern.

*/
#define NOSLIP_TOP (1)
#define NOSLIP_BOTTOM (1)
#include "nsf4t.h"
scalar zeros[], b[], * tracers = {b};
b[bottom] = dirichlet_vert_bottom(0.5);
b[top] = dirichlet_vert_top(-0.5);
int main() {
periodic (left);
const scalar diff[] = 1e-3;
kappa = nu = diff;
a.x = zeros;
a.y = b;
run();
}
event init (t = 0) {
TOLERANCE = 1e-5;
foreach_vert()
b[] = noise()/100;
boundary ({b});
}
event mov (t += 0.1)
output_ppm (b, file = "b.mp4", n = 300, min = -0.55, max = 0.55);
event stop (t = 100);
|
import React from "react";
import cn from "classnames";
import { LinkCommonProps } from "src/components/Link";
import { overrideTw } from "src/util/site";
type LinkButtonProps = {
color?: "default";
};
export type ButtonLinkProps = LinkCommonProps & LinkButtonProps;
export const buttonStyles = {
default: `
bg-transparent
text-rust-5
font-bold
py-2 px-4
border border-rust-5
rounded
focus:outline-none
active:outline-none
dark:text-rust-6 dark:active:text-rust-6
dark:border-rust-6
`,
};
export function ButtonLink({
children,
color = "default",
className = "",
...otherProps
}: ButtonLinkProps) {
const buttonStyle = buttonStyles[color];
return (
<a
{...otherProps}
className={overrideTw(
cn("inline-block cursor-pointer underline-effect-button", buttonStyle),
className
)}
>
{children}
</a>
);
}
|
---
title: Frameset.Delete Method (Word)
keywords: vbawd10.chm165806131
f1_keywords:
- vbawd10.chm165806131
ms.prod: word
api_name:
- Word.Frameset.Delete
ms.assetid: 21290f22-9881-02a9-278c-055c0b8d1051
ms.date: 06/08/2017
---
# Frameset.Delete Method (Word)
Deletes the specified **Frameset** object.
## Syntax
_expression_. `Delete`
_expression_ Required. A variable that represents a '[Frameset](Word.Frameset.md)' object.
## See also
[Frameset Object](Word.Frameset.md)
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 ohos.devtools.views.applicationtrace.analysis;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.util.ui.JBUI;
import net.miginfocom.swing.MigLayout;
import ohos.devtools.views.applicationtrace.AllData;
import ohos.devtools.views.applicationtrace.bean.Func;
import ohos.devtools.views.perftrace.PerfData;
import ohos.devtools.views.perftrace.bean.PrefFunc;
import ohos.devtools.views.trace.EventDispatcher;
/**
* The OtherFunctionPanel
*
* @since 2021/04/22 12:25
*/
public class OtherFunctionPanel extends JBPanel {
private JBTabbedPane otherFunctionTab;
private TopBottomPanel topBottomPanel;
private TopBottomPanel bottomUpPanel;
private FlameSearchChart flameSearchChart;
/**
* structure
*/
public OtherFunctionPanel() {
setLayout(new MigLayout("inset 0", "[grow,fill]", "[grow,fill]"));
otherFunctionTab = new JBTabbedPane();
otherFunctionTab.setBackground(JBColor.background().darker());
setBorder(JBUI.Borders.empty(5, 8));
topBottomPanel = new TopBottomPanel();
bottomUpPanel = new TopBottomPanel();
flameSearchChart = new FlameSearchChart();
otherFunctionTab.addTab("Summary", new OtherFunctionSummaryPanel());
otherFunctionTab.addTab("Top Down", topBottomPanel);
otherFunctionTab.addTab("Flame Chart", flameSearchChart);
otherFunctionTab.addTab("Bottom Up", bottomUpPanel);
add(otherFunctionTab);
EventDispatcher.addClickListener(node -> {
if (node instanceof Func) {
Func func = (Func) node;
topBottomPanel.freshTreeData(AllData.getFuncTreeByFuncTopDown(func));
bottomUpPanel.freshTreeData(AllData.getFuncTreeByFuncBottomUp(func));
flameSearchChart.freshData(AllData.getFuncTreeFlameChart(func), func.getDur());
} else {
if (node instanceof PrefFunc) {
PrefFunc func = (PrefFunc) node;
topBottomPanel.freshTreeData(PerfData.getFuncTreeByFuncTopDown(func));
bottomUpPanel.freshTreeData(PerfData.getFuncTreeByFuncBottomUp(func));
flameSearchChart.freshData(PerfData.getFuncTreeFlameChart(func), func.getDur());
}
}
});
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
class Member extends Model
{
//
use Notifiable;
//creating uuid for user model
/**
* @var mixed
*/
public $incrementing = false;
protected static function boot()
{
parent::boot();
static::creating(function($model){
$model->id = Str::uuid();
});
}
protected $fillable = ['id', 'first_name', 'middle_name', 'last_name', 'staff_no', 'residential_address',
'office_location', 'department', 'designation', 'gender', 'state_of_origin', 'lga',
'town', 'nok_fname', 'nok_mname', 'nok_lname', 'nok_address', 'nok_phone_number',
'nok_email', 'nok_relationship', 'user_id', 'email', 'referee_one', 'referee_two',
'certification', 'multiple_loan_permission', 'permission_count', 'approval_status',
'approval_count', 'membership_status','member_id',
];
public function users()
{
return $this->belongsTo(User::class,'user_id')->withTrashed();
}
public function applications()
{
return $this->belongsTo('App\Application');
}
}
|
import 'reflect-metadata'
import { ButtonComponent, Discord, Slash, SlashChoice, SlashOption } from 'discordx'
import { fetchData } from '../Cache'
import { ButtonInteraction, Client, CommandInteraction, InteractionReplyOptions, MessageActionRow } from 'discord.js'
import { Location } from '../lib/game/Location'
import { DATABASE_LOCATION, handleCommandInteraction, THEmbed, translation } from '../Lib'
import { MapImageData, MapImage, Maps } from '../types/Maps'
import { realTimeToTarkovTime } from '../helpers/MapTimeResolver'
const mapImages = fetchData<MapImageData>('maps')
const mapUrlPrefix = `${DATABASE_LOCATION}/images/map_icons`
const factoryTime = ['15:28:00', '03:28:00']
@Discord()
export abstract class MapCommand {
@Slash('map', {
description: 'Returns information and maps of a certain location'
})
async map(
@SlashChoice('Lighthouse', 'lighthouse')
@SlashChoice('Labs', 'thelab')
@SlashChoice('Interchange', 'interchange')
@SlashChoice('Woods', 'woods')
@SlashChoice('Customs', 'customs')
@SlashChoice('Factory', 'factory')
@SlashChoice('Reserve', 'reserve')
@SlashChoice('Shoreline', 'shoreline')
@SlashOption('map', {
description: 'What location to use'
})
mapName: string,
interaction: CommandInteraction,
client: Client,
{ serverData: { Language } }: GuardData
) {
handleCommandInteraction(interaction, Language, MapCommand.message(mapName, Language))
}
static message(mapName: string, language: Languages): Promise<InteractionReplyOptions> {
return new Promise((respond, error) => {
const t = translation(language)
const map = new Location(mapName as Maps, language)
let mapTime: string[] = ['', '']
if (mapName === 'factory') {
mapTime = factoryTime
} else if (mapName !== 'thelab') {
mapTime = [realTimeToTarkovTime(new Date(), 'left'), realTimeToTarkovTime(new Date(), 'right')]
}
respond({
embeds: [
new THEmbed()
.setTitle(`${map.name} ${mapTime !== ['', ''] ? '-' : ''} ${mapTime[0]} | ${mapTime[1]}`)
.setThumbnail(`${mapUrlPrefix}/${map.name.toLowerCase()}.png`)
.setDescription(map.description)
.setImage(mapImages[mapName.toLowerCase()][0].link)
.setFooter({ text: t('Click the buttons below to view maps') })
.setFields(
{
name: t('Raid Time'),
value: t('{0} minutes', map.raidTime),
inline: true
},
{
name: t('Player Count'),
value: `${map.playerCount.min} - ${map.playerCount.max}`,
inline: true
},
{
name: t('Has Insurance?'),
value: map.hasInsurance ? t('yes') : t('no'),
inline: true
}
)
],
components: [new MessageActionRow().addComponents(map.mapButtons)]
})
})
}
@ButtonComponent(/^map__/)
mapButton(interaction: ButtonInteraction) {
const [, l, m, type] = interaction.customId.split('__')
const map = m as Maps
const language = l as Languages
const t = translation(language)
const imageData = mapImages[map.toLowerCase()].find((t) => t.name == type) as MapImage
interaction.reply({
embeds: [
new THEmbed()
.setImage(imageData.link)
.setTitle(t('{0} {1} Map', map, type))
.setFooter({ text: t('Map created by: {0}', imageData.author) })
],
ephemeral: true
})
}
}
|
import React from "react"
import { Global, css } from "@emotion/react"
import Header from "./Header"
import "normalize.css"
import "@fontsource/poppins/300.css"
import "@fontsource/poppins/400.css"
import "@fontsource/poppins/600.css"
import "@fontsource/poppins/700.css"
import "@fontsource/raleway/900.css"
const Layout: React.FC<{}> = ({ children }) => {
return (
<div>
<Global
styles={css`
* {
box-sizing: border-box;
font-family: "Poppins", sans-serif;
::selection {
background-color: rgba(var(--color-accent-rgb), 0.7);
}
}
body {
margin-top: 60px;
color: #fff;
background-color: #000;
overflow-x: hidden;
}
p {
font-family: Poppins;
font-size: 24px;
font-style: normal;
font-weight: 400;
line-height: 36px;
letter-spacing: 0em;
text-align: left;
}
:root {
--color-primary: #477fec;
--color-accent: #edcf30;
--color-accent-rgb: 237, 207, 48;
--gradient-heading: linear-gradient(
102.19deg,
#182f82 16.27%,
#5789eb 48.5%,
#182f82 81.4%
);
--gradient-container: linear-gradient(
203.95deg,
#2d62df 0%,
#4ebff0 97.48%
);
--screen-xl: 1180px;
--screen-lg: 960px;
--screen-md: 768px;
--screen-sm: 540px;
--screen-xs: 320px;
}
.grecaptcha-badge {
visibility: hidden;
}
`}
/>
<Header />
{children}
</div>
)
}
export default Layout
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreBookRequest;
use Image;
use App\Models\Book;
use App\Models\Author;
use App\Models\Publisher;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class BookController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$books = Book::all();
return view('pages.book.index-book', compact('books'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$book = New Book();
$authors = Author::all();
$publishers = Publisher::all();
return view('pages.book.createOrUpdate-book', compact('book', 'authors', 'publishers'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreBookRequest $request)
{
$img = $request->file('cover');
$nameImg = $img->hashName();
$img = Image::make($img)->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save('storage/books/' . $nameImg);
$book = Book::create([
'cover_path' => $nameImg,
'name' => $request->title,
'slug' => Str::slug($request->title),
'ISBN' => $request->isbn,
'public_price' => floatval($request->publicPrice),
'student_price' => floatval($request->studentPrice),
'editings_details' => $request->publishingDetails,
'required' => $request->required === 'oui' ? 1 : 0,
'publisher_id' => $request->publisher,
]);
foreach ($request->authors as $author) {
$authorId = (Author::where('name', $author)->first())->id;
$book->authors()->attach($authorId);
}
return redirect('books');
}
/**
* Display the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function show(Book $book)
{
$book->load('authors', 'publisher');
$randomBooks = Book::all()->shuffle()->random(5);
return view('pages.book.show-book', compact('book', 'randomBooks'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function edit(Book $book)
{
$authors = Author::all();
$publishers = Publisher::all();
return view('pages.book.createOrUpdate-book', compact('book', 'authors', 'publishers'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Book $book)
{
if($request->hasFile('cover')){
$img = $request->file('cover');
$nameImg = $img->hashName();
$img = Image::make($img)->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save('storage/books/' . $nameImg);
$book->update([
'cover_path' => $nameImg,
]);
}
if($request->title){
$book->update([
'name' => $request->title,
]);
$book->update([
'slug' => Str::slug($request->title),
]);
}
if($request->isbn){
$book->update([
'isbn' => $request->isbn
]);
}
if($request->required){
$book->update([
'required' => $request->required === 'oui' ? 1 : 0
]);
}
if($request->publicPrice){
$book->update([
'public_price' => $request->publicPrice,
]);
}
if($request->studentPrice){
$book->update([
'student_price' => $request->studentPrice
]);
}
if($request->publisher){
$book->update([
'publisher_id' => $request->publisher
]);
}
if($request->authors){
foreach ($request->authors as $author) {
$book->authors()->sync((Author::where('name', $author)->first()->id));
}
}
if($request->publishingDetails){
$book->update([
'editing_details' => $request->publishingDetails
]);
}
return Redirect::route('book.edit', $book->slug);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Book $book
* @return \Illuminate\Http\Response
*/
public function destroy(Book $book)
{
Book::destroy($book->id);
return redirect('books');
}
}
|
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgxCarousel } from 'ngx-carousel';
//import { NgxHmCarouselModule } from 'ngx-hm-carousel';
import { AuthenticationService, UserDetails } from '../authentication.service';
import { Router } from '@angular/router';
@Component({
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
imageUrls = [
{ url: 'assets/img/bg1.png' },
{ url: 'assets/img/bg22.png' },
{ url: 'assets/img/bg2.png' },
{ url: 'assets/img/bg4.png' },
{ url: 'assets/img/bg55.png' }//,
// { url: 'assets/img/bg22.png' }
];
backgroundSize: string = '86%';
height: string = '480px';
imgags: string[];
isFirst = false;
@ViewChild('slideshow') slideshow: any;
public carouselBannerItems: Array<any> = [];
public carouselBanner: NgxCarousel;
constructor(
private auth: AuthenticationService,
private router: Router
) {
if (auth.isLoggedIn()) {
// digital_sign
router.navigate(['landing']);
}
}
ngOnInit() {
// this.slideshow.goToSlide(0);
let ele = document.querySelector('.arrow.prev') as HTMLElement;
ele.classList.remove('arrow')
ele.classList.remove('left');
ele.style.fontSize = '175px';
ele.style.fontStyle = 'normal';
ele.style.position = 'absolute';
ele.style.color = '#b59848';
ele.style.top = '25%';
ele.style.left = '10%';
ele.innerHTML = '<img src="../../assets/img/arrowleft.png">';
ele.style.fontStyle = 'normal';
ele = document.querySelector('.arrow.next') as HTMLElement;
ele.classList.remove('arrow');
ele.classList.remove('right');
ele.style.fontSize = '175px';
ele.style.fontStyle = 'normal';
ele.style.color = '#b59848';
ele.style.position = 'absolute';
ele.style.top = '25%';
ele.style.right = '10%';
ele.innerHTML = '<img src="../../assets/img/arrowright.png">';
}
setcarouselimage(image) {
console.log("-->", image)
if (image == 0 && this.isFirst == false) { }
else if (image == 0 && this.isFirst == true) {
this.slideshow.goToSlide(1);
this.slideshow.goToSlide(2);
this.slideshow.goToSlide(3);
this.slideshow.goToSlide(4);
this.slideshow.goToSlide(0);
} else {
this.isFirst=true;
this.slideshow.goToSlide(1);
this.slideshow.goToSlide(2);
this.slideshow.goToSlide(3);
this.slideshow.goToSlide(4);
this.slideshow.goToSlide(image);
}
}
}
|
using Cars.WebAPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Cars.WebAPI.Controllers
{
[ApiVersionNeutral]
[Route("[controller]")]
public class ApiController : ControllerBase
{
/// <summary>
/// Reset API
/// </summary>
/// <response code="200">Ok</response>
/// <response code="500">Internal Server Error</response>
[HttpPost()]
[AllowAnonymous]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(500)]
public async Task<ActionResult<string>> ResetAPI()
{
CarRepository.SetDefault();
return await Task.FromResult<ActionResult>(this.Ok("The WebAPI has been reset."));
}
}
}
|
{-# LANGUAGE DuplicateRecordFields #-}
module GpoM.Types.CSE.Common where
import Data.List.NonEmpty
import Data.Text (Text)
import Data.Word (Word8)
class FromXml a where
fromXml :: Text -> a
data Outer = Outer {clsid :: !Text
,disabled :: !(Maybe Bool)
}
deriving (Eq, Show)
mkOuter :: Text -> Outer
mkOuter clsid = Outer clsid Nothing
data Inner = Inner {clsid :: !Text
,image :: !(Maybe Word8)
,bypassErrors :: !(Maybe Bool)
,userContext :: !(Maybe Bool)
,removePolicy :: !(Maybe Bool)
,desc :: !(Maybe Text)
,changed :: !(Maybe Text)
,uid :: !Text
,name :: !Text
,status :: !(Maybe Text)
}
deriving (Eq, Show)
mkInner :: Text -> Text -> Text -> Inner
mkInner clsid uid name = Inner clsid Nothing Nothing Nothing Nothing Nothing Nothing uid name Nothing
data CseXml = CseXml {outer :: Outer
,inner :: NonEmpty Inner}
deriving Show
instance FromXml CseXml where
fromXml _ = CseXml {outer = o, inner = i :| [i2]}
where o = mkOuter "outerClsid"
i = mkInner "innerClsid" "innerUid" "innerName"
i2 = mkInner "inner2Clsid" "inner2Uid" "inner2Name"
data EnvironmentVariableProperties =
EnvironmentVariableProperties{action :: !(Maybe String)
,name :: !Text
,value :: !Text
,user :: !(Maybe Bool)
,partial :: !(Maybe Bool)
,disabled :: !(Maybe Bool)
} deriving (Eq, Show)
data EnvironmentVariable =
EnvironmentVariable{clsid :: !Text
,name :: !Text
,image :: !(Maybe Word8)
,changed :: !(Maybe Text)
,uid :: !Text
,desc :: !(Maybe Text)
,bypassErrors :: !(Maybe Bool)
,userContext :: !(Maybe Bool)
,removePolicy :: !(Maybe Bool)
,properties :: !EnvironmentVariableProperties
} deriving (Eq, Show)
data EnvironmentVariables =
EnvironmentVariables{clsid :: !Text
,disabled :: !(Maybe Bool)
,environmentVariables :: [EnvironmentVariable]
} deriving (Eq, Show)
|
package test;
fun main() {
console.log("Testing math...")
console.log("1+1:", 1 + 1)
console.log("30/2:", 30 / 2)
console.log("10-(20-10)+100:", 10 - (20 - 10) + 100)
console.log("JSTest: ", "11" - 2)
console.log("JSTest №2: ", "1" + 1)
}
|
package digraph_test
import (
"testing"
. "github.com/DmitryBogomolov/algorithms/graph/digraph"
"github.com/DmitryBogomolov/algorithms/graph/internal/tests"
"github.com/stretchr/testify/assert"
)
func TestReverseDigraph(t *testing.T) {
gr := tests.NewTestDigraph(4,
0, 1,
0, 2,
2, 1,
1, 3,
2, 3,
)
ret := ReverseDigraph(gr)
assert.Equal(t, 4, ret.NumVertices(), "vertices")
assert.Equal(t, 5, ret.NumEdges(), "edges")
assert.Equal(t, []int(nil), ret.AdjacentVertices(0), "vertex 0 adjacency")
assert.Equal(t, []int{0, 2}, ret.AdjacentVertices(1), "vertex 1 adjacency")
assert.Equal(t, []int{0}, ret.AdjacentVertices(2), "vertex 2 adjacency")
assert.Equal(t, []int{1, 2}, ret.AdjacentVertices(3), "vertex 3 adjacency")
}
func TestReverseReversedDigraph(t *testing.T) {
gr := tests.NewTestDigraph(4,
0, 1,
0, 2,
2, 1,
1, 3,
2, 3,
)
ret, ok := ReverseDigraph(gr).(ReversibleDigraph)
assert.Equal(t, true, ok, "reversible")
assert.Equal(t, gr, ret.Reverse(), "reverse to original")
assert.Equal(t, gr, ReverseDigraph(ret), "reverse to original")
}
|
package io.github.warriorzz.ktify.model.auth
enum class Scope(val value: String) {
NONE("none"),
UGC_IMAGE_UPLOAD("ugc-image-upload"),
USER_READ_RECENTLY_PLAYER("user-read-recently-played"),
USER_TOP_READ("user-top-read"),
USER_READ_PLAYBACK_POSITION("user-read-playback-position"),
USER_READ_PLAYBACK_STATE("user-read-playback-state"),
USER_MODIFY_PLAYBACK_STATE("user-modify-playback-state"),
USER_READ_CURRENTLY_PLAYING("user-read-currently-playing"),
APP_REMOTE_CONTROL("app-remote-control"),
STREAMING("streaming"),
PLAYLIST_MODIFY_PUBLIC("playlist-modify-public"),
PLAYLIST_MODIFY_PRIVATE("playlist-modify-private"),
PLAYLIST_READ_PRIVATE("playlist-read-private"),
PLAYLIST_READ_COLLABORATIVE("playlist-read-collaborative"),
USER_FOLLOW_MODIFY("user-follow-modify"),
USER_FOLLOW_READ("user-follow-read"),
USER_LIBRARY_MODIFY("user-library-modify"),
USER_LIBRARY_READ("user-library-read"),
USER_READ_EMAIL("user-read-email"),
USER_READ_PRIVATE("user-read-private"),
}
|
<?php
// Call Zend_View_Helper_DeclareVarsTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
define("PHPUnit_MAIN_METHOD", "Zend_View_Helper_DeclareVarsTest::main");
}
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/TestHelper.php';
require_once "PHPUnit/Framework/TestCase.php";
require_once "PHPUnit/Framework/TestSuite.php";
require_once 'Zend/View.php';
require_once 'Zend/View/Helper/DeclareVars.php';
class Zend_View_Helper_DeclareVarsTest extends PHPUnit_Framework_TestCase
{
/**
* Runs the test methods of this class.
*
* @access public
* @static
*/
public static function main()
{
require_once "PHPUnit/TextUI/TestRunner.php";
$suite = new PHPUnit_Framework_TestSuite("Zend_View_Helper_DeclareVarsTest");
$result = PHPUnit_TextUI_TestRunner::run($suite);
}
public function setUp()
{
$view = new Zend_View();
$base = str_replace('/', DIRECTORY_SEPARATOR, '/../_templates');
$view->setScriptPath(dirname(__FILE__) . $base);
$view->strictVars(true);
$this->view = $view;
}
public function tearDown()
{
unset($this->view);
}
protected function _declareVars()
{
$this->view->declareVars(
'varName1',
'varName2',
array(
'varName3' => 'defaultValue',
'varName4' => array()
)
);
}
public function testDeclareUndeclaredVars()
{
$this->_declareVars();
$this->assertTrue(isset($this->view->varName1));
$this->assertTrue(isset($this->view->varName2));
$this->assertTrue(isset($this->view->varName3));
$this->assertTrue(isset($this->view->varName4));
$this->assertEquals('defaultValue', $this->view->varName3);
$this->assertEquals(array(), $this->view->varName4);
}
public function testDeclareDeclaredVars()
{
$this->view->varName2 = 'alreadySet';
$this->view->varName3 = 'myValue';
$this->view->varName5 = 'additionalValue';
$this->_declareVars();
$this->assertTrue(isset($this->view->varName1));
$this->assertTrue(isset($this->view->varName2));
$this->assertTrue(isset($this->view->varName3));
$this->assertTrue(isset($this->view->varName4));
$this->assertTrue(isset($this->view->varName5));
$this->assertEquals('alreadySet', $this->view->varName2);
$this->assertEquals('myValue', $this->view->varName3);
$this->assertEquals('additionalValue', $this->view->varName5);
}
}
// Call Zend_View_Helper_DeclareVarsTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_View_Helper_DeclareVarsTest::main") {
Zend_View_Helper_DeclareVarsTest::main();
}
|
/*
* *
* * Created by Sina Dalvand on 12/22/20 19:20 PM
* * Copyright (c) 2020 . All rights reserved.
* * Last modified 12/22/20 19:20 PM
*
*/
package ir.sinadalvand.projects.bazaarproject.contracts
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import ir.sinadalvand.projects.bazaarproject.contracts.interfaces.ViewLayoutBinding
abstract class Xfragment : Fragment(), ViewLayoutBinding {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return getPreparedView(inflater, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
overrideBackButton()
}
/**
* parse every input for fragment to view and don't care it's Res id or View
* @param inflater LayoutInflater
* @param container ViewGroup?
* @return View
*/
private fun getPreparedView(inflater: LayoutInflater, container: ViewGroup?): View {
return when (val layout = layoutView()) {
is Int -> inflater.inflate(layout, container, false)
is View -> return layout
else -> throw IllegalArgumentException("You should Set @resLayout Int or View")
}
}
/**
* override back press button in fragments
* @return Boolean consume back press button if yes return true
*/
open fun backPressButton(): Boolean {
return false
}
// we should override back button to be able return to previous category
private fun overrideBackButton() {
view?.isFocusableInTouchMode = true;
view?.requestFocus();
view?.setOnKeyListener(object : View.OnKeyListener {
override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event?.action != KeyEvent.ACTION_DOWN) {
return backPressButton()
}
return false
}
})
}
}
|
package com.tomcz.ellipse.internal.util
import com.tomcz.ellipse.PartialState
import kotlinx.coroutines.flow.MutableStateFlow
fun <T : PartialState<K>, K : Any> MutableStateFlow<K>.reduceAndSet(intent: T) {
value = intent.reduce(value)
}
|
// PROBLEM: none
open class A {
<caret>internal fun foo() {}
fun bar() {
O.foo()
}
}
object O : A()
|
package 四法
trait P1Num1
case class P1Num1S(tail: P1Num1) extends P1Num1
case object P1Num1T extends P1Num1
trait P1Num2 {
def method1(num1: P1Num1): P1Num1
}
case class P1Num2S(tail: P1Num2) extends P1Num2 {
override def method1(num1: P1Num1): P1Num1 = P1Num1S(tail.method1(num1))
}
case object P1Num2T extends P1Num2 {
override def method1(num1: P1Num1): P1Num1 = num1
}
|
<?php
namespace PgFramework;
use PgFramework\Auth\UserInterface;
interface Auth
{
/**
*
* @return UserInterface|null
*/
public function getUser(): ?UserInterface;
/**
*
* @param UserInterface $user
* @return Auth
*/
public function setUser(UserInterface $user): self;
}
|
// Read a sequence of double values into a vector.
// Think of each value as the distance between two cities along a given route.
// 1. Compute and print the total distance.
// 2. Find the smallest and the greatest distance between two neighbor cities.
// 3. Find and print the mean distance between cities.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
double sum(std::vector<double> values)
{
double total = 0.0;
for (double v: values)
{
total += v;
}
return total;
}
double max(std::vector<double> values)
{
double max_dist = std::numeric_limits<double>::min();
for (double i: values)
{
if (i > max_dist)
{
max_dist = i;
}
}
return max_dist;
}
double min(std::vector<double> values)
{
double min_dist = std::numeric_limits<double>::max();
for (double i: values)
{
if (i < min_dist)
{
min_dist = i;
}
}
return min_dist;
}
double mean(std::vector<double> values)
{
return sum(values) / values.size();
}
int main()
{
std::cout << "Give me some distances!\n";
std::vector<double> values;
for (double value; std::cin >> value; )
{
values.push_back(value);
}
std::cout << "\nSum dist along route is: \t" << sum(values);
std::cout << "\nMax dist is: \t" << max(values);
std::cout << "\nMin dist is: \t" << min(values);
std::cout << "\nMean dist is: \t" << mean(values);
}
|
INSERT INTO COUNTRIES(ID, NAME, CODE) VALUES
(1, 'Australia', 'au'),
(2, 'Great Britain (UK)', 'gb'),
(3, 'United States of America', 'us');
INSERT INTO CITIES(ID, COUNTRY_ID, LATITUDE, LONGITUDE, NAME) VALUES
(1, 1, -33.88333300, 151.21666700, 'Sydney'),
(2, 1, -37.81666700, 144.96666700, 'Melbourne'),
(3, 1, -27.50000000, 153.01666700, 'Brisbane'),
(4, 1, -34.93333300, 138.60000000, 'Adelaide'),
(5, 2, 51.50020000, -0.12620000, 'London'),
(6, 2, 53.41666700, -3.00000000, 'Liverpool'),
(7, 2, 53.50000000, -2.21666700, 'Manchester'),
(8, 2, 52.20000000, 0.11666700, 'Cambridge'),
(9, 3, 30.83833330, -87.20083330, 'New York'),
(10, 3, 34.39583330, -106.83861110, 'San Francisco'),
(11, 3, 42.58611110, -87.82472220, 'Chicago'),
(12, 3, 34.05222220, -118.24277780, 'Los Angeles');
|
<h5 class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span id="user-email">{{ $text }}</span><span class="caret"></span>
</h5>
|
package bsaber.tools.bsaber_scrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class BeatSaverParser {
private static final Logger cvLogger = LogManager.getLogger(BeatSaverParser.class);
// Jsonkeys
private static final String KEY = "key";
private static final String SONG_NAME = "songName";
private static final String SONG_SUB_NAME = "songSubname";
private static final String LEVEL_AUTHOR_NAME = "levelAuthorName";
private static final String SONG_AUTHOR_NAME = "songAuthorName";
private static final String DOWNLOAD_URL = "downloadURL";
private static final String BPM = "bpm";
private static final String DOWN_VOTES = "downVotes";
private static final String UP_VOTES = "upVotes";
private static final String RATING = "rating";
private static final String HEAT = "heat";
private static final String DIFFICULTIES = "difficulties";
private static final String COVER_URL = "coverURL";
private static final String DIRECT_DOWNLOAD = "directDownload";
// Exclude
private static final String CHARACTERISTICS = "characteristics";
// Json Membernames
private static final String DOCS = "docs";
public static List<SongEntry> parse(String aJsonString) {
List<SongEntry> songEntries = new ArrayList<>();
Gson gson = new GsonBuilder().create();
JsonElement fromJson = gson.fromJson(aJsonString, JsonElement.class);
if (fromJson instanceof JsonObject) {
JsonObject jsonObject = fromJson.getAsJsonObject();
// Multiple entries
if (jsonObject.has(DOCS)) {
JsonArray asJsonArray = jsonObject.getAsJsonArray(DOCS);
for (JsonElement jsonElement : asJsonArray) {
songEntries.add(new SongEntry(parse(jsonElement, new SongMetaData())));
}
}
// Single entry
else {
songEntries.add(new SongEntry(parse(fromJson, new SongMetaData())));
}
}
return songEntries;
}
private static SongMetaData parse(JsonElement aJsonElement, SongMetaData aMetaData) {
if (!(aJsonElement instanceof JsonPrimitive) && !(aJsonElement instanceof JsonNull)) {
if (aJsonElement instanceof JsonArray) {
for (JsonElement jsonElement : aJsonElement.getAsJsonArray()) {
aMetaData = parse(jsonElement, aMetaData);
}
} else {
JsonObject jsonObject = (JsonObject) aJsonElement;
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if (!CHARACTERISTICS.equals(key)) {
if (KEY.equals(key)) {
aMetaData.setKey(value.getAsString());
} else if (SONG_NAME.equals(key)) {
aMetaData.setSongName(value.getAsString());
} else if (SONG_SUB_NAME.equals(key)) {
aMetaData.setSongSubName(value.getAsString());
} else if (LEVEL_AUTHOR_NAME.equals(key)) {
aMetaData.setLevelAuthorName(value.getAsString());
} else if (SONG_AUTHOR_NAME.equals(key)) {
aMetaData.setSongAuthorName(value.getAsString());
} else if (DOWNLOAD_URL.equals(key)) {
aMetaData.setDownloadURL(Constants.BEATSAVER_BASE_URL + value.getAsString());
} else if (BPM.equals(key)) {
aMetaData.setBpm(value.getAsInt());
} else if (DOWN_VOTES.equals(key)) {
aMetaData.setDownVotes(value.getAsInt());
} else if (UP_VOTES.equals(key)) {
aMetaData.setUpVotes(value.getAsInt());
} else if (RATING.equals(key)) {
aMetaData.setRating(value.getAsFloat());
} else if (HEAT.equals(key)) {
aMetaData.setHeat(value.getAsFloat());
} else if (DIRECT_DOWNLOAD.equals(key)) {
aMetaData.setDirectDownload(value.getAsString());
} else if (COVER_URL.equals(key)) {
aMetaData.setCoverUrl(value.getAsString());
} else if (DIFFICULTIES.equals(key)) {
JsonObject difficulties = value.getAsJsonObject();
for (Entry<String, JsonElement> difficultEntry : difficulties.entrySet()) {
aMetaData.addDifficulty(difficultEntry.getKey());
}
} else {
aMetaData = parse(value, aMetaData);
}
}
}
}
}
return aMetaData;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
class LoginController extends Controller
{
//登陆展示
public function login(){
return view("login.login");
}
public function loginDo(){
// echo 11;
\request()->validate([
"admin_name"=>"required",
"admin_pwd"=>"required",
],[
"admin_name.required"=>"账号不能为空",
"admin_pwd.required"=>"密码不能为空",
]);
$data=\request()->except("_token");
// dd($data["admin_name"]);
$res=Admin::where("admin_name",$data["admin_name"])->first();
if($res){
if(decrypt($res["admin_pwd"])==$data["admin_pwd"]){
// dd($res);
Cookie::queue("admin_user",$res["admin_name"]);
Cookie::queue("admin_leven",$res["admin_leven"]);
// dd($admin);die;
return redirect("/admin");
}
}else{
return redirect("/login/login")->with("msg","账号或密码错误");
}
// dd($res);
}
public function index(){
// $admin=\request()->cookie("admin_user");
// dd($admin);
return view("login.index");
}
//退出
public function quit(){
if(\request()->session()->flush()===null){
return redirect("login/login");
}
}
}
|
// export const APP_SERVE_URL = 'http://88.128.18.193:8080/';
// export const FILE_SERVE_URL = 'http://88.128.18.144:3333/';
/*----------------------------------------后台Api地址----------------------------------------*/
export const APP_SERVE_URL = 'http://192.168.0.225:55555/'; // 'http://119.7.14.131:8099/';
/*----------------------------------------文件服务器地址----------------------------------------*/
export const FILE_SERVE_URL = APP_SERVE_URL; // 文件服务:测试环境
/*----------------------------------------app版本升级服务地址----------------------------------------*/
export const APP_VERSION_SERVE_URL = APP_SERVE_URL; // app版本升级服务;测试环境,查询app最新版本号,更新日志等信息.
export const UPLOAD_PATH = {
"hrImg": "images/hr/",
"hr": "Attach/hr/",
"work": "Attach/flow/work/",
"mail": "Attach/portal/yj/",
"announcement": "Attach/portal/gg/",
};
export const IS_DEBUG = true; // 是否开发(调试)模式
export const DEFAULT_AVATAR = './assets/img/avatar.png'; // 用户默认头像
export const PAGE_SIZE = 5; // 默认分页大小
export const IMAGE_SIZE = 1024; // 拍照/从相册选择照片压缩大小
export const QUALITY_SIZE = 94; // 图像压缩质量,范围为0 - 100
export const REQUEST_TIMEOUT = 20000; // 请求超时时间,单位为毫秒
export const ENABLE_FUNDEBUG = true; // 是否启用fundebug日志监控
export const FUNDEBUG_API_KEY =
'ec3cba8712b00e9db075ee9debf73fdfb2233c748b737d71f69ed7fe04b9ead4'; // 去https://fundebug.com/申请key
export const APK_DOWNLOAD = 'http://omzo595hi.bkt.clouddn.com/ionic2_tabs.apk'; // android apk下载完整地址,用于android本地升级
export const APP_DOWNLOAD = 'http://omzo595hi.bkt.clouddn.com/download.html'; // app网页下载地址,用于ios升级或android本地升级失败
// code push 部署key
export const CODE_PUSH_DEPLOYMENT_KEY = {
'android': {
'Production': 'i0LgJRugiIfjVYTgmXs9go45Xc7g26690215-d954-4697-a879-90e0c4612b59',
'Staging': 'WY29_Zyq_hg0eB3TSTGaKRSKPE6k26690215-d954-4697-a879-90e0c4612b59'
},
'ios': {
'Production': 'kn3VJ28z0hB_zQYnW-KnblldnBzN26690215-d954-4697-a879-90e0c4612b59',
'Staging': 'SRoxClVMoed8SgwIRxeVCPWx26Fk26690215-d954-4697-a879-90e0c4612b59'
}
};
|
using StyleCop;
using StyleCopCmd.Reader;
namespace StyleCopCmd.Core
{
public abstract class StyleCopIssueReporter
{
public virtual void Report(string message)
{
}
public virtual void ProjectAdded(CsProject project)
{
}
public virtual void Started()
{
}
public virtual void Result(ViolationEventArgs @event)
{
}
public virtual void Completed(ExecutionResult result, string tempFileName)
{
this.Completed(result);
}
public virtual void Completed(ExecutionResult result)
{
}
}
}
|
from tkbuilder.widgets.widget_wrappers.button import Button
from tkbuilder.widgets.widget_wrappers.canvas import Canvas
from tkbuilder.widgets.widget_wrappers.combobox import Combobox
from tkbuilder.widgets.widget_wrappers.scale import Scale
from tkbuilder.widgets.widget_wrappers.label import Label
from tkbuilder.widgets.widget_wrappers.labelFrame import LabelFrame
from tkbuilder.widgets.widget_wrappers.entry import Entry
from tkbuilder.widgets.widget_wrappers.text import Text
from tkbuilder.widgets.widget_wrappers.spinbox import Spinbox
from tkbuilder.widgets.widget_wrappers.radiobutton import RadioButton
from tkbuilder.widgets.widget_wrappers.checkbutton import CheckButton
|
class App < ApplicationRecord
has_one :graylog_stream, dependent: :destroy
NAME_FORMAT = /\A[a-z0-9\-]+\Z/.freeze
attr_accessor :validate_stream
validates :name, uniqueness: true, presence: true, format: { with: NAME_FORMAT }
validates :image_source, inclusion: { in: %w[dockerhub ecr] }
validates :repository_name, presence: true
validates :job_spec, presence: true
validates_with GraylogValidator, if: :validate_stream
def to_param
name
end
def trigger_auto_deploy(notification)
return unless auto_deploy? &&
auto_deploy_branch == notification.branch &&
notification.finished? &&
notification.success?
AppDeployment.new(self, "build-#{notification.build_number}").deploy!
end
end
|
## Cryptocoin Price Indicator
<a href="https://github.com/tortuvshin/indicator/issues">
<img src="https://img.shields.io/github/issues/tortuvshin/indicator.svg"
alt="Issues"></a>
<a href="https://github.com/tortuvshin/indicator/fork">
<img src="https://img.shields.io/github/forks/tortuvshin/indicator.svg?style=social&label=Fork"
alt="Forks"></a>
<a href="https://github.com/tortuvshin/indicator/stargazers">
<img src="https://img.shields.io/github/stars/tortuvshin/indicator.svg?style=social&label=Stars"
alt="Stars"></a>
<a href="https://github.com/tortuvshin/">
<img src="https://img.shields.io/github/followers/tortuvshin.svg?style=social&label=Follow"
alt="Followers"></a>
<a href="https://raw.githubusercontent.com/tortuvshin/indicator/master/LICENSE">
<img src="https://img.shields.io/badge/license-MIT-blue.svg"
alt="LICENSE"></a>
<a href="https://twitter.com/intent/tweet?text=Wow:&url=%5Bobject%20Object%5D">
<img src="https://img.shields.io/twitter/url/https/github.com/tortuvshin/indicator.svg?style=social"
alt="Tweet"></a>
</p>
An Ubuntu desktop indicator (top bar widget) that displays prices of Cryptocoin as on the COINBASE API.
### Screen
Ubuntu 17.10 Screen shot


### Installation
```
git clone https://github.com/tortuvshin/indicator.git
cd indicator
sudo apt-get install python-gi
sudo apt-get install python-requests
sudo apt-get install gir1.2-appindicator3-0.1
python indicator.py
```
### Or
```
make install
make run
```
### Contributing
See <a href="https://github.com/tortuvshin/indicator/issues">
<img src="https://img.shields.io/github/issues/tortuvshin/indicator.svg"
alt="Issues"></a>
.
- If you found any problems, please report on issues page.
- If you made any change, send me pull request.
### License
<a href="https://raw.githubusercontent.com/tortuvshin/indicator/master/LICENSE">
<img src="https://img.shields.io/badge/license-MIT-blue.svg"
alt="LICENSE"></a>
|
# frozen_string_literal: true
require "ferrum/frame"
module Ferrum
class Page
module Frames
attr_reader :main_frame
def frames
@frames.values
end
def frame_by(id: nil, name: nil)
if id
@frames[id]
elsif name
frames.find { |f| f.name == name }
else
raise ArgumentError
end
end
def frames_subscribe
on("Page.frameAttached") do |params|
parent_frame_id, frame_id = params.values_at("parentFrameId", "frameId")
@frames[frame_id] = Frame.new(frame_id, self, parent_frame_id)
end
on("Page.frameStartedLoading") do |params|
frame = @frames[params["frameId"]]
frame.state = :started_loading
@event.reset
end
on("Page.frameNavigated") do |params|
frame_id, name = params["frame"]&.values_at("id", "name")
frame = @frames[frame_id]
frame.state = :navigated
frame.name = name unless name.to_s.empty?
end
on("Page.frameStoppedLoading") do |params|
# `DOM.performSearch` doesn't work without getting #document node first.
# It returns node with nodeId 1 and nodeType 9 from which descend the
# tree and we save it in a variable because if we call that again root
# node will change the id and all subsequent nodes have to change id too.
if @main_frame.id == params["frameId"]
@event.set if idling?
get_document_id
end
frame = @frames[params["frameId"]]
frame.state = :stopped_loading
@event.set if idling?
end
on("Page.navigatedWithinDocument") do
@event.set if idling?
end
on("Network.requestWillBeSent") do |params|
if params["frameId"] == @main_frame.id
# Possible types:
# Document, Stylesheet, Image, Media, Font, Script, TextTrack, XHR,
# Fetch, EventSource, WebSocket, Manifest, SignedExchange, Ping,
# CSPViolationReport, Other
@event.reset if params["type"] == "Document"
end
end
on("Runtime.executionContextCreated") do |params|
context_id = params.dig("context", "id")
frame_id = params.dig("context", "auxData", "frameId")
frame = @frames[frame_id] || Frame.new(frame_id, self)
frame.execution_id = context_id
@main_frame ||= frame
@frames[frame_id] ||= frame
end
on("Runtime.executionContextDestroyed") do |params|
execution_id = params["executionContextId"]
frame = frames.find { |f| f.execution_id?(execution_id) }
frame.execution_id = nil
end
on("Runtime.executionContextsCleared") do
@frames.delete_if { |_, f| !f.main? }
end
end
private
def idling?
@frames.all? { |_, f| f.state == :stopped_loading }
end
end
end
end
|
/*
* Copyright (C) 2004-2016 L2J DataPack
*
* This file is part of L2J DataPack.
*
* L2J DataPack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J DataPack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package instances.SanctumOftheLordsOfDawn;
import instances.AbstractInstance;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import quests.Q00195_SevenSignsSecretRitualOfThePriests.Q00195_SevenSignsSecretRitualOfThePriests;
import com.l2jserver.gameserver.instancemanager.InstanceManager;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.Location;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.holders.SkillHolder;
import com.l2jserver.gameserver.model.instancezone.InstanceWorld;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.network.NpcStringId;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.clientpackets.Say2;
import com.l2jserver.gameserver.network.serverpackets.MagicSkillUse;
/**
* Sanctum of the Lords of Dawn instance zone.
* @author Adry_85
*/
public final class SanctumOftheLordsOfDawn extends AbstractInstance
{
protected static final class HSWorld extends InstanceWorld
{
protected int doorst = 0;
protected final static Map<Integer, List<L2Npc>> _save_point = new HashMap<>();
public static Map<Integer, List<L2Npc>> getMonsters()
{
return _save_point;
}
}
// NPCs
private static final int GUARDS_OF_THE_DAWN = 18834;
private static final int GUARDS_OF_THE_DAWN_2 = 18835;
private static final int GUARDS_OF_THE_DAWN_3 = 27351;
private static final int LIGHT_OF_DAWN = 32575;
private static final int PASSWORD_ENTRY_DEVICE = 32577;
private static final int IDENTITY_CONFIRM_DEVICE = 32578;
private static final int DARKNESS_OF_DAWN = 32579;
private static final int SHELF = 32580;
// Item
private static final int IDENTITY_CARD = 13822;
// Skill
private static SkillHolder GUARD_SKILL = new SkillHolder(5978, 1);
// Locations
private static final Location ENTER = new Location(-76161, 213401, -7120, 0, 0);
private static final Location EXIT = new Location(-12585, 122305, -2989, 0, 0);
// Misc
private static final int TEMPLATE_ID = 111;
private static int DOOR_ONE = 17240001;
private static int DOOR_TWO = 17240003;
private static int DOOR_THREE = 17240005;
private static final Location[] SAVE_POINT = new Location[]
{
new Location(-75775, 213415, -7120),
new Location(-74959, 209240, -7472),
new Location(-77699, 208905, -7640),
new Location(-79939, 205857, -7888),
};
public SanctumOftheLordsOfDawn()
{
super(SanctumOftheLordsOfDawn.class.getSimpleName());
addStartNpc(LIGHT_OF_DAWN);
addTalkId(LIGHT_OF_DAWN, IDENTITY_CONFIRM_DEVICE, PASSWORD_ENTRY_DEVICE, DARKNESS_OF_DAWN, SHELF);
addAggroRangeEnterId(GUARDS_OF_THE_DAWN, GUARDS_OF_THE_DAWN_2, GUARDS_OF_THE_DAWN_3);
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
switch (event)
{
case "spawn":
{
final InstanceWorld tmpworld = InstanceManager.getInstance().getPlayerWorld(player);
if (tmpworld instanceof HSWorld)
{
final HSWorld world = (HSWorld) tmpworld;
spawnGroup("high_priest_of_dawn", world.getInstanceId());
player.sendPacket(SystemMessageId.BY_USING_THE_SKILL_OF_EINHASAD_S_HOLY_SWORD_DEFEAT_THE_EVIL_LILIMS);
}
break;
}
case "teleportPlayer":
{
switch (npc.getId())
{
case GUARDS_OF_THE_DAWN:
{
broadcastNpcSay(npc, Say2.NPC_ALL, NpcStringId.INTRUDER_PROTECT_THE_PRIESTS_OF_DAWN);
break;
}
case GUARDS_OF_THE_DAWN_2:
{
broadcastNpcSay(npc, Say2.NPC_ALL, NpcStringId.HOW_DARE_YOU_INTRUDE_WITH_THAT_TRANSFORMATION_GET_LOST);
break;
}
case GUARDS_OF_THE_DAWN_3:
{
broadcastNpcSay(npc, Say2.NPC_ALL, NpcStringId.WHO_ARE_YOU_A_NEW_FACE_LIKE_YOU_CAN_T_APPROACH_THIS_PLACE);
break;
}
}
OUTTER: for (Entry<Integer, List<L2Npc>> entry : HSWorld._save_point.entrySet())
{
for (L2Npc monster : entry.getValue())
{
if (monster.getObjectId() == npc.getObjectId())
{
player.teleToLocation(SAVE_POINT[entry.getKey()]);
break OUTTER;
}
}
}
}
}
return super.onAdvEvent(event, npc, player);
}
@Override
public void onEnterInstance(L2PcInstance player, InstanceWorld world, boolean firstEntrance)
{
if (firstEntrance)
{
world.addAllowed(player.getObjectId());
final Map<Integer, List<L2Npc>> save_point = HSWorld.getMonsters();
save_point.put(0, spawnGroup("save_point1", world.getInstanceId()));
save_point.put(1, spawnGroup("save_point2", world.getInstanceId()));
save_point.put(2, spawnGroup("save_point3", world.getInstanceId()));
save_point.put(3, spawnGroup("save_point4", world.getInstanceId()));
}
teleportPlayer(player, ENTER, world.getInstanceId());
}
@Override
public String onTalk(L2Npc npc, L2PcInstance talker)
{
switch (npc.getId())
{
case LIGHT_OF_DAWN:
{
final QuestState qs = talker.getQuestState(Q00195_SevenSignsSecretRitualOfThePriests.class.getSimpleName());
if ((qs != null) && qs.isCond(3) && hasQuestItems(talker, IDENTITY_CARD) && (talker.getTransformationId() == 113))
{
enterInstance(talker, new HSWorld(), "SanctumoftheLordsofDawn.xml", TEMPLATE_ID);
return "32575-01.html";
}
return "32575-02.html";
}
case IDENTITY_CONFIRM_DEVICE:
{
final InstanceWorld tmpworld = InstanceManager.getInstance().getWorld(npc.getInstanceId());
if (tmpworld instanceof HSWorld)
{
if (hasQuestItems(talker, IDENTITY_CARD) && (talker.getTransformationId() == 113))
{
final HSWorld world = (HSWorld) tmpworld;
if (world.doorst == 0)
{
openDoor(DOOR_ONE, world.getInstanceId());
talker.sendPacket(SystemMessageId.SNEAK_INTO_DAWNS_DOCUMENT_STORAGE);
talker.sendPacket(SystemMessageId.MALE_GUARDS_CAN_DETECT_FEMALES_DONT);
talker.sendPacket(SystemMessageId.FEMALE_GUARDS_NOTICE_BETTER_THAN_MALE);
world.doorst++;
npc.decayMe();
}
else if (world.doorst == 1)
{
openDoor(DOOR_TWO, world.getInstanceId());
world.doorst++;
npc.decayMe();
for (int objId : world.getAllowed())
{
final L2PcInstance pl = L2World.getInstance().getPlayer(objId);
if (pl != null)
{
pl.showQuestMovie(11);
startQuestTimer("spawn", 35000, null, talker);
}
}
}
return "32578-01.html";
}
return "32578-02.html";
}
break;
}
case PASSWORD_ENTRY_DEVICE:
{
final InstanceWorld tmworld = InstanceManager.getInstance().getWorld(npc.getInstanceId());
if (tmworld instanceof HSWorld)
{
final HSWorld world = (HSWorld) tmworld;
openDoor(DOOR_THREE, world.getInstanceId());
return "32577-01.html";
}
break;
}
case DARKNESS_OF_DAWN:
{
final InstanceWorld world = InstanceManager.getInstance().getPlayerWorld(talker);
world.removeAllowed(talker.getObjectId());
talker.teleToLocation(EXIT, 0);
return "32579-01.html";
}
case SHELF:
{
final InstanceWorld world = InstanceManager.getInstance().getWorld(npc.getInstanceId());
InstanceManager.getInstance().getInstance(world.getInstanceId()).setDuration(300000);
talker.teleToLocation(-75925, 213399, -7128);
return "32580-01.html";
}
}
return "";
}
@Override
public String onAggroRangeEnter(L2Npc npc, L2PcInstance player, boolean isSummon)
{
npc.broadcastPacket(new MagicSkillUse(npc, player, GUARD_SKILL.getSkillId(), 1, 2000, 1));
startQuestTimer("teleportPlayer", 2000, npc, player);
return super.onAggroRangeEnter(npc, player, isSummon);
}
}
|
<?php
declare(strict_types=1);
namespace __Vendor__\__Package__;
class __Package__
{
}
|
docker build -t `
scth/mssql-server-windows-2019-developer:10.0.17763.1397 `
--no-cache `
.
docker rmi $(docker images -f "dangling=true" -q) -f
docker tag scth/mssql-server-windows-2019-developer:10.0.17763.1397 scth/mssql-server-windows-2019-developer:latest
|
package com.nikitamaslov.domain.interactor.preferences
import com.nikitamaslov.domain.model.Temperature
import com.nikitamaslov.domain.repository.PreferencesRepository
interface SetTemperatureUnitUseCase {
suspend operator fun invoke(temperatureUnit: Temperature.Unit)
}
internal class SetTemperatureUnitUseCaseImpl(
private val preferencesRepository: PreferencesRepository,
private val getCurrentTemperatureUnit: GetCurrentTemperatureUnitUseCase
) : SetTemperatureUnitUseCase {
override suspend fun invoke(temperatureUnit: Temperature.Unit) {
if (getCurrentTemperatureUnit() != temperatureUnit) {
setTemperatureUnit(temperatureUnit)
}
}
private suspend fun setTemperatureUnit(temperatureUnit: Temperature.Unit) {
preferencesRepository.setTemperatureUnit(temperatureUnit)
}
}
|
// 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Size and EventState manager
use super::Pending;
use crate::draw::DrawShared;
use crate::event::EventState;
use crate::geom::{Rect, Size, Vec2};
use crate::layout::{Align, AlignHints};
use crate::text::TextApi;
use crate::theme::{Feature, SizeMgr, TextClass, ThemeSize};
use crate::{TkAction, Widget, WidgetExt, WidgetId};
use std::ops::{Deref, DerefMut};
#[allow(unused)]
use crate::{event::Event, Layout};
/// Manager available to [`Layout::set_rect`] and [`Widget::configure`]
///
/// This type is functionally a superset of [`SizeMgr`] and subset of
/// [`crate::theme::DrawMgr`], with support for the appropriate conversions.
///
/// `SetRectMgr` supports [`Deref`] and [`DerefMut`] with target [`EventState`].
#[must_use]
pub struct SetRectMgr<'a> {
sh: &'a dyn ThemeSize,
ds: &'a mut dyn DrawShared,
pub(crate) ev: &'a mut EventState,
}
impl<'a> SetRectMgr<'a> {
/// Construct
#[cfg_attr(not(feature = "internal_doc"), doc(hidden))]
#[cfg_attr(doc_cfg, doc(cfg(internal_doc)))]
pub fn new(sh: &'a dyn ThemeSize, ds: &'a mut dyn DrawShared, ev: &'a mut EventState) -> Self {
SetRectMgr { sh, ds, ev }
}
/// Access a [`SizeMgr`]
///
/// Warning: sizes are calculated using the window's current scale factor.
/// This may change, even without user action, since some platforms
/// always initialize windows with scale factor 1.
/// See also notes on [`Widget::configure`].
pub fn size_mgr(&self) -> SizeMgr<'a> {
SizeMgr::new(self.sh)
}
/// Access [`DrawShared`]
pub fn draw_shared(&mut self) -> &mut dyn DrawShared {
self.ds
}
/// Access [`EventState`]
pub fn ev_state(&mut self) -> &mut EventState {
self.ev
}
/// Configure a widget
///
/// All widgets must be configured after construction (see
/// [`Widget::configure`]). This method may be used to configure a new
/// child widget without requiring the whole window to be reconfigured.
///
/// Pass the `id` to assign to the widget: this should be constructed from
/// the parent's id via [`WidgetId::make_child`].
#[inline]
pub fn configure(&mut self, id: WidgetId, widget: &mut dyn Widget) {
widget.pre_configure(self, id);
for index in 0..widget.num_children() {
let id = widget.make_child_id(index);
if let Some(widget) = widget.get_child_mut(index) {
self.configure(id, widget);
}
}
widget.configure(self);
}
/// Align a feature's rect
///
/// In case the input `rect` is larger than desired on either axis, it is
/// reduced in size and offset within the original `rect` as is preferred.
#[inline]
pub fn align_feature(&self, feature: Feature, rect: Rect, hints: AlignHints) -> Rect {
self.sh.align_feature(feature, rect, hints)
}
/// Update a text object, setting font properties and wrap size
///
/// Returns required size.
#[inline]
pub fn text_set_size(
&self,
text: &mut dyn TextApi,
class: TextClass,
size: Size,
align: (Align, Align),
) -> Vec2 {
self.sh.text_set_size(text, class, size, align)
}
/// Advance the keyboard navigation focus
///
/// If some widget currently has nav focus, this will give focus to the next
/// (or previous) widget under `widget` where [`Widget::key_nav`]
/// returns true; otherwise this will give focus to the first (or last)
/// such widget.
///
/// Returns true on success, false if there are no navigable widgets or
/// some error occurred.
///
/// The target widget will receive [`Event::NavFocus`] with `key_focus` as
/// the payload. This boolean should be true if focussing in response to
/// keyboard input, false if reacting to mouse or touch input.
pub fn next_nav_focus(
&mut self,
mut widget: &mut dyn Widget,
reverse: bool,
key_focus: bool,
) -> bool {
if let Some(id) = self.popups.last().map(|(_, p, _)| p.id.clone()) {
if let Some(w) = widget.find_widget_mut(&id) {
widget = w;
} else {
// This is a corner-case. Do nothing.
return false;
}
}
// We redraw in all cases. Since this is not part of widget event
// processing, we can push directly to self.action.
self.send_action(TkAction::REDRAW);
let old_nav_focus = self.nav_focus.take();
fn nav(
mgr: &mut SetRectMgr,
widget: &mut dyn Widget,
focus: Option<&WidgetId>,
rev: bool,
) -> Option<WidgetId> {
if mgr.ev_state().is_disabled(widget.id_ref()) {
return None;
}
let mut child = focus.and_then(|id| widget.find_child_index(id));
if !rev {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
} else if !widget.eq_id(focus) && widget.key_nav() {
return Some(widget.id());
}
loop {
if let Some(index) = widget.spatial_nav(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return None;
}
}
} else {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
}
loop {
if let Some(index) = widget.spatial_nav(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return if !widget.eq_id(focus) && widget.key_nav() {
Some(widget.id())
} else {
None
};
}
}
}
}
// Whether to restart from the beginning on failure
let restart = self.nav_focus.is_some();
let mut opt_id = nav(self, widget, old_nav_focus.as_ref(), reverse);
if restart && opt_id.is_none() {
opt_id = nav(self, widget, None, reverse);
}
log::trace!("EventMgr: nav_focus = {:?}", opt_id);
self.nav_focus = opt_id.clone();
if opt_id == old_nav_focus {
return opt_id.is_some();
}
if let Some(id) = old_nav_focus {
self.pending.push_back(Pending::LostNavFocus(id));
}
if let Some(id) = opt_id {
if id != self.sel_focus {
self.clear_char_focus();
}
self.pending.push_back(Pending::SetNavFocus(id, key_focus));
true
} else {
// Most likely an error occurred
self.clear_char_focus();
false
}
}
}
impl<'a> std::ops::BitOrAssign<TkAction> for SetRectMgr<'a> {
#[inline]
fn bitor_assign(&mut self, action: TkAction) {
self.ev.send_action(action);
}
}
impl<'a> Deref for SetRectMgr<'a> {
type Target = EventState;
fn deref(&self) -> &EventState {
self.ev
}
}
impl<'a> DerefMut for SetRectMgr<'a> {
fn deref_mut(&mut self) -> &mut EventState {
self.ev
}
}
|
from test_util import build_parquet_data, verify_datasets
import sys
official_application = sys.argv[1]
official_files_location = sys.argv[2]
cmdline_params = ["-p",
"PriceUpdate-for-test",
"-o",
"1003",
official_files_location + "/20190104/221500/224.0.66.193_21193.pcap.gz",
official_files_location + "/20190104/170000/224.0.64.200_11200.pcap.gz",
official_files_location + "/20190104/084500/224.0.67.193_21193.pcap.gz"]
print("Building PriceUpdate")
build_parquet_data(official_application, cmdline_params)
print("Checking PriceUpdate")
verify_datasets(official_files_location + "/Official-PriceUpdate", "PriceUpdate-for-test-price-update.parquet", {
"MDSeqNum": "mkt_data_seq_num",
"RebroadcastIndicator": "rebroadcast_indicator",
"EMM": "emm",
"EventTime": "event_time",
"PriceType": "mkt_data_price_type",
"SymbolIndex": "symbol_index",
"Price": "price",
"Quantity": "quantity",
"ImbalanceQty": "imbalance_quantity",
"ImbalanceQtySide": "imbalance_qty_side"
})
|
(function () {
var global = typeof window !== 'undefined' ? window : this || Function('return this')();
var nx = global.nx || require('@jswork/next');
//@thanks to: https://github.com/gr0uch/promise-compose/blob/master/index.js
//@thanks to: https://itnext.io/roll-your-own-async-compose-pipe-functions-658cafe4c46f
nx.promiseCompose = function () {
var fns = nx.slice(arguments);
return function (value) {
var initial = Promise.resolve(value);
try {
return fns.reduce(function (chain, fn) {
return chain.then(fn);
}, initial);
} catch (err) {
return Promise.reject(err);
}
};
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = nx.promiseCompose;
}
})();
|
<?php
namespace App\MsAccess\Traitements;
use App\MsAccess\Database\DatabaseAccess;
use App\Entity\EmDenom;
use App\Entity\EmDenomV2;
//use Doctrine\ORM\EntityManagerInterface;
/**
* Description of TrtBaseEM
*
* @author Frannou
*/
class TrtBaseEM {
private $em;
function __construct($em)
{
$this->em = $em;
}
// public function test()
// {
// echo "ça marche !!!";
// }
// public function DBaccess()
// {
// $ObjAccess = new DatabaseAccess();
// $ReqAccess=$ObjAccess->RqOccurrenceEm();
//// foreach ($ReqAccess as $value) {
//// var_dump(utf8_encode($value["produit"]));
//// var_dump($value["Nbr"]);
//// }
//// var_dump($ReqAccess[2]);
// dump($ReqAccess[2]["produit"]);
//// die();
//
//// $pdo = DatabaseAccess::getPdoAccess();
//// dump($pdo);
// }
// public function ExtractionAccessOccEM()
// {
// $ObjAccess = new DatabaseAccess();
//// $ReqAccess=$ObjAccess->RqOccurrenceEm();
// $ReqAccess=$ObjAccess->RqOccurrenceEmLimit30();
// dump(count($ReqAccess));
// }
public function importBaseEM()
{
$NbEnregParLot = 1000;
$iCptEnreg = 0;
$iCptLot = 0;
$listeInsert = array();
$this->effaceEmDenomV2();
$ObjAccess = new DatabaseAccess();
// $ReqAccess=$ObjAccess->RqOccurrenceEmLimit30();
$ReqAccess=$ObjAccess->RqOccurrenceEm();
foreach($ReqAccess as $row)
{
$iCptEnreg++;
$produit = $row['produit'];
$produit = str_replace(CHR(13).CHR(10),"",$produit);
$produit = str_replace(CHR(34),CHR(39),$produit);
// $listeInsert[] = '("'.(str_replace(CHR(13).CHR(10),"",$row['produit'])).'", '.$row['Nbr'].')';
$listeInsert[] = '("'.$produit.'", '.$row['Nbr'].')';
if ($iCptEnreg > $NbEnregParLot) {
$iCptLot++;
// dump($iCptLot);
$sql = "INSERT INTO em_denom_v2 (denomination, nbr) VALUES ".implode(',', $listeInsert);
// dump($sql);
$stmt = $this->em->getConnection()->prepare(utf8_encode ($sql));
$stmt->execute([]);
$iCptEnreg = 0;
$listeInsert = array();
}
}
// dd();
// $sql = "INSERT INTO em_denom_v2 (denomination, nbr) VALUES ".implode(',', $listeInsert);
// $stmt = $this->em->getConnection()->prepare(utf8_encode ($sql));
// $stmt->execute([]);
}
public function effaceEmDenomV2(): void
{
$sql = "TRUNCATE em_denom_v2";
$stmt = $this->em->getConnection()->prepare($sql);
$stmt->execute([]);
}
}
|
#!/usr/bin/env sh
# Sets up a new Aniseed plugin project within the current directory.
# Warning: Only run in new empty directories, it will replace your
# `.gitignore`, `Makefile` and other such files!
# Warning: Requires `make` as part of the workflow.
# Usage: curl -fL https://raw.githubusercontent.com/Olical/aniseed/master/scripts/seed.sh | sh
mkdir -p scripts
printf "$(tput bold)Downloading Aniseed dependency manager script...\n\n"
curl -fL https://raw.githubusercontent.com/Olical/aniseed/master/scripts/dep.sh -o scripts/dep.sh 2>/dev/null;
chmod +x scripts/dep.sh
printf "Fetching Aniseed...\n\n"
scripts/dep.sh Olical aniseed origin/master 2>/dev/null;
printf "Creating your new plugin...\n\n"
cp -r deps/aniseed/seed/* .
cp deps/aniseed/seed/.gitignore .
plug_name=${PWD##*/}
mv ./fnl/example ./fnl/$plug_name
mv ./test/fnl/example ./test/fnl/$plug_name
mv ./plugin/example.vim ./plugin/$plug_name.vim
sed -i -e "s/example/$plug_name/g" ./test/fnl/$plug_name/main-test.fnl
sed -i -e "s/example/$plug_name/g" ./fnl/$plug_name/main.fnl
sed -i -e "s/example/$plug_name/g" ./plugin/$plug_name.vim
sed -i -e "s/example/$plug_name/g" ./Makefile
printf "$(tput bold)Running Makefile...$(tput sgr0)\n\n"
make -s &
wait
printf "\nDone, $(tput bold)Happy dev.\n\n"
if command -v tree &> /dev/null
then
tree -I 'aniseed'
fi
|
import { addons } from "@storybook/addons";
import flatTheme from "./flat-theme";
addons.setConfig({
theme: flatTheme,
});
|
package p26_1
func removeDuplicates(nums []int) int {
if len(nums) < 2 {
return len(nums)
}
target, source := 1, 1
for source < len(nums) {
if nums[source] == nums[target-1] {
source++
} else {
nums[target] = nums[source]
source++
target++
}
}
return target
}
|
## 函数
1.函数使用def关键字定义,不需要指定函数参数或返回值类型。
2.python中每一个对象都有一个关联的真值,表示这个对象计算为True或者False
> 如果计算为0、值None、空窜或者一个空的内置数据结构,则为False。其它为True
>
> 可以向bool函数传递任何对象来确定它是True还是False。任何非空数据结构都计算为True
3.使用函数注解来提供参数和返回说明
```python
# str 注解说明希望word参数类型是字符串,->set 说明函数将返回一个set
# 注解添加与否,解释器同样不会对输入和返回进行检验
def search_for_vowels_by_ann(word: str) -> set:
"""Display any vowels found in an supplied word."""
vowels = set('aeiou')
return vowels.intersection(set(word))
```
4.""" show Display""" 三重引号可以添加多行注释
5.任何参数都可以指定一个默认值
```python
def search_for_vowels_by_ann(phrase: str,letters:str='aeiou') -> set:
""" 参数指定默认值"""
return set(letters).intersection(set(phrase))
```
6.python支持位置赋值的同时还支持**关键字赋值**
```python
def search (phrase:str,letters:str='aeiou') -> set:
return set(letters).intersection(set(phrase))
#位置赋值:严格按照参数顺序
search('galaxy','xyz')
#关键字赋值:指定关键字之后,可以不按照参数顺序
search(letters='xyz',phrase='galaxy')
```
7.使用setuptool安装模块到site-packages中
第一步:创建一个发布描述:至少为模块创建两个描述文件:setup.py和README.txt
```python
from setuptools import setup
setup(
name='vsearch',#指定发布包。按照模块命名发布包
version='1.0',
description='The Head First Python Search Tools',
author='head',
author_email='head@gmail.com',
url='yinhaijun.com',
py_modules=['vsearch'],#指定需要包含的.py文件列表
)
```
第二步:生成一个发布文件,在包路径下执行命令
```shell
python3 setup.py sdist
```
成功会在当前目录下生成 dist文件夹 里面的vsearch-1.0.tar.gz 就是可安装文件
第三步:使用安装发布文件:在dist文件夹目录下执行命令:
```shell
python3 -m pip install vsearch-1.0.tar.gz
```
8.python的函数参数语义即支持**按值调用**也支持**按引用调用**。
1.如果变量指示一个**可变的**值,就会应用**按引用调用**语义
2.如果数据是**不可变**的,则会应用**按值调用**语义
列表、字典、集合(都是可变的)总是会按引用传入函数,字符串、整数和元组(不可变)总是会按值传入参数
9.使用pytest和检查代码PEP8兼容性
1.安装pytest和 pytest-pep8
```shell
pip3 install pytest
pip3 install pytest-pep8
```
2.检查代码兼容性:
```shell
py.test --pep8 vsearch.py
```
|
# Copyright 2020 Self Group Ltd. All Rights Reserved.
# frozen_string_literal: true
require 'httparty'
module SelfSDK
class RestClient
attr_reader :self_url, :jwt, :env
# RestClient initializer
#
# @param url [string] self-messaging url
# @param token [string] jwt token identifying the authenticated user
def initialize(url, app_id, app_key, env)
SelfSDK.logger.info "client setup with #{url}"
@self_url = url
@env = env
@jwt = SelfSDK::JwtService.new(app_id, app_key)
end
# Get identity details
#
# @param id [string] identity self_id.
def identity(id)
get_identity "/v1/identities/#{id}"
end
# Get app details
#
# @param id [string] app self_id.
def app(id)
get_identity "/v1/apps/#{id}"
end
# Get app/identity details
#
# @param id [string] app/identity self_id.
def entity(id)
#TODO : Consider a better check for this conditional
if id.length == 11
return identity(id)
else
return app(id)
end
end
# Lists all devices assigned to the given identity
#
# @param id [string] identity id
def devices(id)
res = get "/v1/identities/#{id}/devices"
body = JSON.parse(res.body, symbolize_names: true)
if res.code != 200
SelfSDK.logger.error "identity response : #{body[:message]}"
raise "you need connection permissions"
end
body
end
# Lists all public keys stored on self for the given ID
#
# @param id [string] identity id
# DEPRECATED
def public_keys(id)
i = entity(id)
i[:public_keys]
end
def post(endpoint, body)
res = nil
loop do
res = HTTParty.post("#{@self_url}#{endpoint}",
headers: {
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{@jwt.auth_token}"
},
body: body)
break if res.code != 503
sleep 2
end
return res
end
def get(endpoint)
res = nil
loop do
res = HTTParty.get("#{@self_url}#{endpoint}", headers: {
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{@jwt.auth_token}"
})
break if res.code != 503
sleep 2
end
return res
end
# Lists all public keys stored on self for the given ID
#
# @param id [string] identity id
def public_key(id, kid)
i = entity(id)
sg = SelfSDK::SignatureGraph.new(i[:history])
sg.key_by_id(kid)
end
# Get the active public key for a device
#
# @param id [string] identity id
def device_public_key(id, did)
i = entity(id)
sg = SelfSDK::SignatureGraph.new(i[:history])
sg.key_by_device(did)
end
private
def get_identity(endpoint)
res = get endpoint
body = JSON.parse(res.body, symbolize_names: true)
if res.code != 200
SelfSDK.logger.error "app response : #{body[:message]}"
raise body[:message]
end
body
end
end
end
|
import 'package:flutter/material.dart';
import 'user.dart';
///页面路由角色
abstract class IYimPageRouterRole {
///允许访问页面的角色
List<IYimRouterRole> visitsRouterRoles(BuildContext context);
}
///页面
abstract class YimPage implements Widget, IYimPageRouterRole {}
class EmptyYimPage extends StatelessWidget implements YimPage {
@override
Widget build(BuildContext context) => Container(color: Colors.red);
@override
List<IYimRouterRole> visitsRouterRoles(BuildContext context) => [YimRouterRoleAnonymous()];
}
|
package com.zys.my.shop.persistence;
import com.zys.my.shop.dto.BaseResult;
import java.util.List;
/**
* @program: my-shop
* @description: 树形结构业务逻辑层标准
* @author: Leo
* @create: 2019-06-13 14:23
**/
public interface BaseTreeService<T extends BaseEntity> {
/**
* @Description: 查询所有信息
* @Author: Leo
*/
public List<T> selectAll();
/**
* @Description: 插入一条信息
* @Param: [tbUser]
* @Author: Leo
*/
public BaseResult save(T entity);
/**
* @Description: 删除
* @Param: [id]
* @Author: Leo
*/
public void delete(long id);
/**
* @Description: 通过id查询信息
* @Param: [id]
* @Author: Leo
*/
public T getById(long id);
/**
* @Description: 更新信息
* @Param: [entity]
* @Author: Leo
*/
public void update(T entity);
/**
* @Description: 根据父节点查询所有子节点
* @Param: [parentId]
* @Author: Leo
*/
List<T> selectByPid(Long parentId);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.