text
stringlengths 27
775k
|
---|
use bevy::prelude::*;
#[derive(Component)]
pub struct DeckContainer;
#[derive(Component)]
pub struct CardInDeck(pub usize);
pub fn create_container(parent: &mut ChildBuilder) {
parent
.spawn_bundle(NodeBundle {
style: Style {
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
size: Size::new(Val::Px(229.), Val::Px(229.)),
..Default::default()
},
color: Color::rgba_u8(0, 0, 0, 0).into(),
..Default::default()
})
.insert(DeckContainer);
}
pub fn spawn_card(parent: &mut ChildBuilder, asset_server: &Res<AssetServer>, index: usize) {
let card_back: Handle<Image> = asset_server.load("textures/cards/cardderpback1.png");
parent
.spawn_bundle(NodeBundle {
style: Style {
position_type: PositionType::Absolute,
position: Rect {
left: if index < 5 {
Val::Px(20. + (10. * index as f32))
} else {
Val::Px(60.)
},
..Default::default()
},
size: Size::new(Val::Px(153.), Val::Px(200.)),
..Default::default()
},
image: card_back.into(),
..Default::default()
})
.insert(CardInDeck(index));
}
|
package com.jn.kikukt.utils
import android.app.Activity
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.jn.kikukt.R
import com.jn.kikukt.common.utils.statusbar.setColorNoTranslucent
import org.greenrobot.eventbus.EventBus
/**
* Author:Stevie.Chen Time:2019/9/11
* Class Comment:
*/
fun Activity.initEventBus() {
EventBus.getDefault().register(this)
}
fun Activity.unregisterEventBus() {
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this)
}
fun Activity.setStatusBar(@ColorRes id: Int = R.color.colorPrimary) {
setColorNoTranslucent(ContextCompat.getColor(applicationContext, id))
} |
#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#set -x
usage() {
printf "Usage: %s [vhd file in secondary storage] [template directory in secondary storage] [template local dir] \n" $(basename $0)
}
options='tcp,soft,timeo=133,retrans=1'
cleanup()
{
if [ ! -z $snapshotdir ]; then
umount $snapshotdir
if [ $? -eq 0 ]; then
rmdir $snapshotdir
fi
fi
if [ ! -z $templatedir ]; then
umount $templatedir
if [ $? -eq 0 ]; then
rmdir $templatedir
fi
fi
}
if [ -z $1 ]; then
usage
echo "2#no vhd file path"
exit 0
else
snapshoturl=${1%/*}
vhdfilename=${1##*/}
fi
if [ -z $2 ]; then
usage
echo "3#no template path"
exit 0
else
templateurl=$2
fi
if [ -z $3 ]; then
usage
echo "3#no template local dir"
exit 0
else
tmpltLocalDir=$3
fi
snapshotdir=/var/run/cloud_mount/$(uuidgen -r)
mkdir -p $snapshotdir
if [ $? -ne 0 ]; then
echo "4#cann't make dir $snapshotdir"
exit 0
fi
mount -o $options $snapshoturl $snapshotdir
if [ $? -ne 0 ]; then
rmdir $snapshotdir
echo "5#can not mount $snapshoturl to $snapshotdir"
exit 0
fi
templatedir=/var/run/cloud_mount/$tmpltLocalDir
mkdir -p $templatedir
if [ $? -ne 0 ]; then
templatedir=""
cleanup
echo "6#cann't make dir $templatedir"
exit 0
fi
mount -o $options $templateurl $templatedir
if [ $? -ne 0 ]; then
rmdir $templatedir
templatedir=""
cleanup
echo "7#can not mount $templateurl to $templatedir"
exit 0
fi
VHDUTIL="/opt/cloud/bin/vhd-util"
copyvhd()
{
local desvhd=$1
local srcvhd=$2
local parent=
parent=`$VHDUTIL query -p -n $srcvhd`
if [ $? -ne 0 ]; then
echo "30#failed to query $srcvhd"
cleanup
exit 0
fi
if [[ "${parent}" =~ " no parent" ]]; then
dd if=$srcvhd of=$desvhd bs=2M
if [ $? -ne 0 ]; then
echo "31#failed to dd $srcvhd to $desvhd"
cleanup
exit 0
fi
else
copyvhd $desvhd $parent
$VHDUTIL coalesce -p $desvhd -n $srcvhd
if [ $? -ne 0 ]; then
echo "32#failed to coalesce $desvhd to $srcvhd"
cleanup
exit 0
fi
fi
}
templateuuid=$(uuidgen -r)
desvhd=$templatedir/$templateuuid.vhd
srcvhd=$snapshotdir/$vhdfilename
copyvhd $desvhd $srcvhd
virtualSize=`$VHDUTIL query -v -n $desvhd`
physicalSize=`ls -l $desvhd | awk '{print $5}'`
cleanup
echo "0#$templateuuid#$physicalSize#$virtualSize"
exit 0
|
require "sinatra"
require 'json'
get '/login/:id/:password' do |id, password|
content_type :json
if id == "1" && password == '1234'
{ success: true }.to_json
else
{ success: false }.to_json
end
end
|
<?php
namespace App;
use Chumper\Zipper\Facades\Zipper;
use Illuminate\Support\Facades\Storage;
class BinderPackage
{
var $storage_path;
public function generate(Binder $binder)
{
$this->storage_path = 'public/packages/binders/' . $binder->id;
// Delete old package
Storage::deleteDirectory($this->storage_path);
$this->generateBinderJson($binder);
$zip = $this->zipPackage();
return $zip;
}
protected function generateBinderJson(Binder $binder)
{
$binder = Binder::with('days')->find($binder->id);
$binder->update_url = url('/api/binders/' . $binder->id . '/download');
$binder_json = $binder->toJson();
Storage::put($this->storage_path . '/binder.json', $binder_json);
$days_json = $binder->days()->orderBy('date')->get()->toJson();
Storage::put($this->storage_path . '/days.json', $days_json);
foreach ($binder->days as $day)
{
$this->generateDayJson($day);
foreach ($day->events as $event) {
$this->generateEventJson($event);
}
}
$this->generateDocumentsJson($binder);
foreach ($binder->documents as $document)
{
$this->generateDocumentJson($document);
}
$this->generateArticlesJson($binder);
foreach ($binder->articles as $article)
{
$this->generateArticleJson($article);
}
$this->generatePeopleJson($binder);
foreach ($binder->people as $person)
{
$this->generatePersonJson($person);
}
}
protected function generateDayJson(Day $day)
{
$json = Day::with('events', 'events.contacts', 'events.participants')->find($day->id)->toJson();
Storage::put($this->storage_path . '/days/' . $day->id . '.json', $json);
}
protected function generateDocumentsJson(Binder $binder)
{
$documents = $binder->documents->sortBy('name', SORT_NATURAL)->groupBy('document_type');
Storage::put($this->storage_path . '/documents.json', $documents->toJson());
}
protected function generateDocumentJson(Document $document)
{
$json = $document->toJson();
Storage::put($this->storage_path . '/documents/' . $document->id . '.json', $json);
Storage::copy('public/' . $document->file, $this->storage_path . '/assets/' . $document->file);
}
protected function generateEventJson(Event $event)
{
$json = Event::with('contacts', 'participants', 'documents')->find($event->id)->toJson();
Storage::put($this->storage_path . '/events/' . $event->id . '.json', $json);
}
protected function generateArticlesJson(Binder $binder)
{
$json = $binder->articles->toJson();
Storage::put($this->storage_path . '/articles.json', $json);
}
protected function generateArticleJson(Article $article)
{
$json = Article::with('documents')->find($article->id)->toJson();
Storage::put($this->storage_path . '/articles/' . $article->id . '.json', $json);
}
protected function generatePeopleJson(Binder $binder)
{
$json = $binder->people->toJson();
Storage::put($this->storage_path . '/people.json', $json);
}
protected function generatePersonJson(Person $person)
{
$json = $person->toJson();
Storage::put($this->storage_path . '/people/' . $person->id . '.json', $json);
if ($person->image) {
Storage::copy('public/' . $person->image, $this->storage_path . '/assets/' . $person->image);
}
}
protected function zipPackage()
{
$files = glob(storage_path('app/' . $this->storage_path));
$zip = storage_path('app/' . $this->storage_path . '/') . 'package.zip';
Zipper::make($zip)->add($files)->close();
return $zip;
}
} |
#!/bin/bash
##
## Copyright (c) 2019-2021, ETH Zurich. All rights reserved.
##
## Please, refer to the LICENSE file in the root directory.
## SPDX-License-Identifier: BSD-3-Clause
##
while true; do
echo "use mysql;" | mysql -u root
# continue if succesful
if [ "$?" == 0 ]; then
break
fi
sleep 1
done
echo "127.0.0.1 cluster" >> /etc/hosts
echo "CREATE USER slurmdb@localhost IDENTIFIED BY 'slurmdbpass';" | mysql -u root
echo "CREATE DATABASE slurmdb; GRANT ALL PRIVILEGES ON slurmdb.* TO slurmdb;" | mysql -u root
/usr/sbin/slurmdbd -D
|
package goyave
import (
"fmt"
"net/http"
"strings"
"goyave.dev/goyave/v3/validation"
)
// Route stores information for matching and serving.
type Route struct {
name string
uri string
methods []string
parent *Router
handler Handler
validationRules *validation.Rules
middlewareHolder
parameterizable
}
var _ routeMatcher = (*Route)(nil) // implements routeMatcher
// newRoute create a new route without any settings except its handler.
// This is used to generate a fake route for the Method Not Allowed and Not Found handlers.
// This route has the core middleware enabled and can be used without a parent router.
// Thus, custom status handlers can use language and body.
func newRoute(handler Handler) *Route {
return &Route{
handler: handler,
middlewareHolder: middlewareHolder{
middleware: []Middleware{recoveryMiddleware, parseRequestMiddleware, languageMiddleware},
},
}
}
func (r *Route) match(req *http.Request, match *routeMatch) bool {
if params := r.parameterizable.regex.FindStringSubmatch(match.currentPath); params != nil {
if r.checkMethod(req.Method) {
if len(params) > 1 {
match.mergeParams(r.makeParameters(params))
}
match.route = r
return true
}
match.err = errMatchMethodNotAllowed
return false
}
if match.err == nil {
// Don't override error if already set.
// Not nil error means it's either already errMatchNotFound
// or it's errMatchMethodNotAllowed, implying that a route has
// already been matched but with wrong method.
match.err = errMatchNotFound
}
return false
}
func (r *Route) checkMethod(method string) bool {
for _, m := range r.methods {
if m == method {
return true
}
}
return false
}
func (r *Route) makeParameters(match []string) map[string]string {
return r.parameterizable.makeParameters(match, r.parameters)
}
// Name set the name of the route.
// Panics if a route with the same name already exists.
// Returns itself.
func (r *Route) Name(name string) *Route {
if r.name != "" {
panic(fmt.Errorf("Route name is already set"))
}
if _, ok := r.parent.namedRoutes[name]; ok {
panic(fmt.Errorf("Route %q already exists", name))
}
r.name = name
r.parent.namedRoutes[name] = r
return r
}
// Validate adds validation rules to this route. If the user-submitted data
// doesn't pass validation, the user will receive an error and messages explaining
// what is wrong.
//
// Returns itself.
func (r *Route) Validate(validationRules validation.Ruler) *Route {
r.validationRules = validationRules.AsRules()
return r
}
// Middleware register middleware for this route only.
//
// Returns itself.
func (r *Route) Middleware(middleware ...Middleware) *Route {
r.middleware = middleware
return r
}
// BuildURL build a full URL pointing to this route.
// Panics if the amount of parameters doesn't match the amount of
// actual parameters for this route.
func (r *Route) BuildURL(parameters ...string) string {
return BaseURL() + r.BuildURI(parameters...)
}
// BuildURI build a full URI pointing to this route. The returned
// string doesn't include the protocol and domain. (e.g. "/user/login")
// Panics if the amount of parameters doesn't match the amount of
// actual parameters for this route.
func (r *Route) BuildURI(parameters ...string) string {
fullURI, fullParameters := r.GetFullURIAndParameters()
if len(parameters) != len(fullParameters) {
panic(fmt.Errorf("BuildURI: route has %d parameters, %d given", len(fullParameters), len(parameters)))
}
var builder strings.Builder
builder.Grow(len(fullURI))
idxs, _ := r.braceIndices(fullURI)
length := len(idxs)
end := 0
currentParam := 0
for i := 0; i < length; i += 2 {
raw := fullURI[end:idxs[i]]
end = idxs[i+1]
builder.WriteString(raw)
builder.WriteString(parameters[currentParam])
currentParam++
end++ // Skip closing braces
}
builder.WriteString(fullURI[end:])
return builder.String()
}
// GetName get the name of this route.
func (r *Route) GetName() string {
return r.name
}
// GetURI get the URI of this route.
// The returned URI is relative to the parent router of this route, it is NOT
// the full path to this route.
//
// Note that this URI may contain route parameters in their définition format.
// Use the request's URI if you want to see the URI as it was requested by the client.
func (r *Route) GetURI() string {
return r.uri
}
// GetFullURI get the full URI of this route.
//
// Note that this URI may contain route parameters in their définition format.
// Use the request's URI if you want to see the URI as it was requested by the client.
func (r *Route) GetFullURI() string {
router := r.parent
segments := make([]string, 0, 3)
segments = append(segments, r.uri)
for router != nil {
segments = append(segments, router.prefix)
router = router.parent
}
// Revert segements
for i := len(segments)/2 - 1; i >= 0; i-- {
opp := len(segments) - 1 - i
segments[i], segments[opp] = segments[opp], segments[i]
}
return strings.Join(segments, "")
}
// GetMethods returns the methods the route matches against.
func (r *Route) GetMethods() []string {
cpy := make([]string, len(r.methods))
copy(cpy, r.methods)
return cpy
}
// GetHandler returns the Handler associated with this route.
func (r *Route) GetHandler() Handler {
return r.handler
}
// GetValidationRules returns the validation rules associated with this route.
func (r *Route) GetValidationRules() *validation.Rules {
return r.validationRules
}
// GetFullURIAndParameters get the full uri and parameters for this route and all its parent routers.
func (r *Route) GetFullURIAndParameters() (string, []string) {
router := r.parent
segments := make([]string, 0, 3)
segments = append(segments, r.uri)
parameters := make([]string, 0, len(r.parameters))
for i := len(r.parameters) - 1; i >= 0; i-- {
parameters = append(parameters, r.parameters[i])
}
for router != nil {
segments = append(segments, router.prefix)
for i := len(router.parameters) - 1; i >= 0; i-- {
parameters = append(parameters, router.parameters[i])
}
router = router.parent
}
// Revert segements
for i := len(segments)/2 - 1; i >= 0; i-- {
opp := len(segments) - 1 - i
segments[i], segments[opp] = segments[opp], segments[i]
}
// Revert parameters
for i := len(parameters)/2 - 1; i >= 0; i-- {
opp := len(parameters) - 1 - i
parameters[i], parameters[opp] = parameters[opp], parameters[i]
}
return strings.Join(segments, ""), parameters
}
|
object Form1: TForm1
Left = 0
Top = 0
Caption = 'CL.mORMot REST test'
ClientHeight = 469
ClientWidth = 1174
Color = clBtnFace
Constraints.MinHeight = 205
Constraints.MinWidth = 815
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnCreate = FormCreate
OnDestroy = FormDestroy
DesignSize = (
1174
469)
PixelsPerInch = 96
TextHeight = 13
object LabelAuthenticationMode: TLabel
Left = 37
Top = 38
Width = 74
Height = 13
Caption = 'Authentication:'
end
object LabelProtocol: TLabel
Left = 68
Top = 11
Width = 43
Height = 13
Caption = 'Protocol:'
end
object Label1: TLabel
Left = 799
Top = 11
Width = 80
Height = 13
Anchors = [akTop, akRight]
Caption = 'Server and port:'
end
object Label2: TLabel
Left = 780
Top = 38
Width = 99
Height = 13
Anchors = [akTop, akRight]
Caption = 'Login and password:'
end
object EditServerAdress: TEdit
Left = 885
Top = 8
Width = 99
Height = 21
Anchors = [akTop, akRight]
TabOrder = 0
Text = '127.0.0.1'
TextHint = 'Server adress (IP or HostName)'
end
object EditServerPort: TEdit
Left = 990
Top = 8
Width = 65
Height = 21
Anchors = [akTop, akRight]
TabOrder = 1
Text = '777'
TextHint = 'Port'
end
object ButtonStartStop: TButton
Left = 1061
Top = 16
Width = 105
Height = 33
Anchors = [akTop, akRight]
Caption = 'Start client'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 2
OnClick = ButtonStartStopClick
end
object GroupBoxIRestMethods: TGroupBox
Left = 8
Top = 75
Width = 720
Height = 54
Caption = 'IRestMethods (InstanceImplementation = sicSingle)'
TabOrder = 3
object ButtonMethHelloWorld: TButton
Left = 8
Top = 19
Width = 81
Height = 23
Caption = 'HelloWorld'
TabOrder = 0
OnClick = ButtonMethHelloWorldClick
end
object ButtonMethSum: TButton
Left = 95
Top = 19
Width = 50
Height = 23
Caption = 'Sum'
TabOrder = 1
OnClick = ButtonMethSumClick
end
object ButtonGetCustomRecord: TButton
Left = 151
Top = 19
Width = 137
Height = 23
Caption = 'GetCustomRecord'
TabOrder = 2
OnClick = ButtonGetCustomRecordClick
end
object ButtonMethSendCustomRecord: TButton
Left = 294
Top = 19
Width = 115
Height = 23
Caption = 'SendCustomRecord'
TabOrder = 3
OnClick = ButtonMethSendCustomRecordClick
end
object ButtonMethSendMultipleCustomRecords: TButton
Left = 415
Top = 19
Width = 154
Height = 23
Caption = 'SendMultipleCustomRecords'
TabOrder = 4
OnClick = ButtonMethSendMultipleCustomRecordsClick
end
object ButtonMethGetMethodCustomResult: TButton
Left = 572
Top = 19
Width = 141
Height = 23
Caption = 'GetMethodCustomResult'
TabOrder = 5
OnClick = ButtonMethGetMethodCustomResultClick
end
end
object ComboBoxAuthentication: TComboBox
Left = 117
Top = 35
Width = 388
Height = 21
Style = csDropDownList
ItemIndex = 1
TabOrder = 4
Text = 'Default'
OnChange = ComboBoxAuthenticationChange
Items.Strings = (
'No authentication'
'Default'
'None'
'HttpBasic'
'SSPI')
end
object MemoLog: TMemo
Left = 8
Top = 135
Width = 1158
Height = 298
Anchors = [akLeft, akTop, akRight, akBottom]
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Consolas'
Font.Style = []
ParentFont = False
ScrollBars = ssVertical
TabOrder = 5
end
object ButtonCLS: TButton
Left = 10
Top = 439
Width = 38
Height = 22
Anchors = [akLeft, akBottom]
Caption = 'CLS'
TabOrder = 6
OnClick = ButtonCLSClick
end
object CheckBoxAutoScroll: TCheckBox
Left = 57
Top = 441
Width = 69
Height = 17
Anchors = [akLeft, akBottom]
Caption = 'auto scroll'
Checked = True
State = cbChecked
TabOrder = 7
end
object CheckBoxDisableLog: TCheckBox
Left = 133
Top = 441
Width = 203
Height = 17
Anchors = [akLeft, akBottom]
Caption = 'disable log (for max performance test)'
TabOrder = 8
OnClick = CheckBoxDisableLogClick
end
object ComboBoxProtocol: TComboBox
Left = 117
Top = 8
Width = 388
Height = 21
Style = csDropDownList
ItemIndex = 7
TabOrder = 9
Text = ' '#8250' WebSocket ( bidirectional, binary + AES-CFB 256)'
OnChange = ComboBoxProtocolChange
Items.Strings = (
'HTTP ( socket )'
' '#8250' HTTP ( fast http.sys )'
' '#8250#8250' HTTPS ( fast http.sys + SSL )'
' '#8250#8250' HTTP ( fast http.sys + AES-CFB 256 )'
'HTTP ( web socket )'
' '#8250' WebSocket ( bidirectional, JSON )'
' '#8250' WebSocket ( bidirectional, binary )'
' '#8250' WebSocket ( bidirectional, binary + AES-CFB 256)'
'Named pipe')
end
object EditUserLogin: TEdit
Left = 885
Top = 35
Width = 99
Height = 21
Anchors = [akTop, akRight]
TabOrder = 10
Text = 'George'
TextHint = 'Login'
end
object EditUserPassword: TEdit
Left = 990
Top = 35
Width = 65
Height = 21
Anchors = [akTop, akRight]
TabOrder = 11
Text = '123'
TextHint = 'Password'
end
object TimerRefreshLogMemo: TTimer
OnTimer = TimerRefreshLogMemoTimer
Left = 56
Top = 144
end
end
|
---
uid: crmscript_ref_NSContact_SetDirectPhone
title: SetDirectPhone(String directPhone)
intellisense: NSContact.SetDirectPhone
keywords: NSContact, GetDirectPhone
so.topic: reference
---
# SetDirectPhone(String directPhone)
The contacts phone
**Parameter:**
- **directPhone** String
```crmscript
NSContact thing;
String directPhone;
thing.SetDirectPhone(directPhone);
```
|
package no.group3.springQuiz.quiz.api
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import no.group3.springQuiz.quiz.model.dto.*
import no.group3.springQuiz.quiz.model.entity.Question
import no.group3.springQuiz.quiz.model.entity.Quiz
import no.group3.springQuiz.quiz.model.repository.CategoryRepository
import no.group3.springQuiz.quiz.model.repository.QuestionRepository
import no.group3.springQuiz.quiz.model.repository.QuizRepository
import org.springframework.amqp.core.FanoutExchange
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.security.Principal
import javax.validation.ConstraintViolationException
/**
* Created by josoder on 03.11.17.
*/
@Api(value = "/quizzes", description = "API for quizzes.")
@RequestMapping(
path = arrayOf("/quizzes"),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)
)
@RestController
@Validated
class QuizController {
@Autowired
lateinit var questionRepository : QuestionRepository
@Autowired
lateinit var quizRepository : QuizRepository
@Autowired
lateinit var categoryRepository : CategoryRepository
@Autowired
private lateinit var template: RabbitTemplate
@Autowired
private lateinit var fanout: FanoutExchange
@ApiOperation("Retrieve all quizzes, apply '?category={categoryname}' to get quizzes from one specific category")
@GetMapping
fun get(@ApiParam("Category")
@RequestParam(value="category", required = false)
category: String?
): ResponseEntity<List<QuizDto>> {
val list = if(category.isNullOrBlank()) {
quizRepository.findAll()
} else {
quizRepository.findByCategory(category!!)
}
if(list!=null){
return ResponseEntity.ok(QuizConverter.transform(list))
}
return ResponseEntity.ok().build()
}
@ApiOperation("Delete quiz with the given id")
@DeleteMapping(path = arrayOf("/{id}"))
fun deleteQuestion(@ApiParam("id of the quiz to delete")
@PathVariable("id")
pId: String?): ResponseEntity<Any> {
val id: Long
try {
id = pId!!.toLong()
} catch (e: Exception) {
return ResponseEntity.status(400).build()
}
if(!quizRepository.exists(id)) {
return ResponseEntity.status(404).build()
}
val q = quizRepository.findOne(id)
quizRepository.delete(id)
return ResponseEntity.status(204).build()
}
@ApiOperation("Create a quiz")
@PostMapping(consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
@ApiResponse(code = 201, message = "The id of created quiz")
fun createQuiz(
@ApiParam("Name of the quiz to create.")
@RequestBody
dto: QuizDto): ResponseEntity<Long> {
// don't want the id from the client
if (dto.quizId != null || dto.category==null) {
return ResponseEntity.status(400).build()
}
val cat = categoryRepository.findByName(dto.category!!)
if(cat==null && dto.category != "mixed"){
return ResponseEntity.status(400).build()
}
// need to get the question from the db before creating the quiz entity
val qList: MutableList<Question> = ArrayList()
// make sure all questions exists(if any)
if(dto.questions != null && !(dto.questions!!.isEmpty())){
var valid = true
dto.questions!!.forEach {
if(!questionRepository.exists(it.id)) {
valid = false
return@forEach
}
qList.add(questionRepository.findOne(it.id))
}
if (!valid) return ResponseEntity.status(400).build()
}
var quiz : Quiz
try {
quiz = quizRepository.save(Quiz(questions = qList, difficulty = dto.difficulty, category = dto.category))
} catch (e: ConstraintViolationException) {
return ResponseEntity.status(400).build()
}
return ResponseEntity.status(201).body(quiz.id)
}
@ApiOperation("Get a single quiz by id")
@GetMapping(path = arrayOf("/{id}"))
fun getById(@ApiParam("The id of the quiz")
@PathVariable("id")
pId: String?): ResponseEntity<QuizDto> {
val id: Long
try {
id = pId!!.toLong()
} catch (e: Exception) {
return ResponseEntity.status(404).build()
}
val quiz = quizRepository.findOne(id) ?: return ResponseEntity.status(404).build()
return ResponseEntity.ok(QuizConverter.transform(quiz))
}
@ApiOperation("Get all questions of the quiz with the given id")
@GetMapping(path = arrayOf("/{id}/questions"))
fun getAllQuestionsById(@ApiParam("The id of the quiz")
@PathVariable("id")
pId: String?): ResponseEntity<List<QuestionDto>> {
val id: Long
try {
id = pId!!.toLong()
} catch (e: Exception) {
return ResponseEntity.status(404).build()
}
val quiz = quizRepository.findOne(id) ?: return ResponseEntity.status(404).build()
return ResponseEntity.ok(QuestionConverter.transform(quiz.questions!!))
}
/**
* This one is a bit tricky, it will create a new message added to the amqp
*/
@ApiOperation("Check answer from the playing user")
@PostMapping(path = arrayOf("/{id}/check"), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
@ApiResponse(code = 201, message = "answers are submitted")
fun checkAnswers(@ApiParam("the id of the quiz to submit answers to")
@PathVariable("id")
pId: String?,
@RequestBody
@ApiParam("json representation of the answers")
dto: AnswersDto): ResponseEntity<ScoreDto> {
val id: Long
try {
id = pId!!.toLong()
} catch (e: Exception) {
return ResponseEntity.status(404).build()
}
val quiz = quizRepository.findOne(id)
var correctAnswers = 0
if(quiz==null){
return ResponseEntity.status(403).build()
}
if(!dto.answers!!.isNotEmpty() || quiz.questions!=null) {
if(quiz.questions!!.size != dto.answers!!.size){
return ResponseEntity.status(400).build()
}
var i = 0
dto!!.answers!!.forEach {
if(quiz.questions!![i].correctAnswers == it){
correctAnswers++
}
i++
}
}
val scoreDto = ScoreDto(score = correctAnswers*quiz.difficulty!!, username = dto.username)
template.convertAndSend(fanout.name, "", scoreDto)
return ResponseEntity.status(201).body(scoreDto)
}
} |
export const ROUTER = {
user: '/user',
login: '/user/login',
register: '/user/register',
home: '/',
forgotPassword: '/user/forgot-password',
memberPrice: '/',
createNewQuiz: '/',
takeQuiz: '/',
takeExam: '/',
helpCenter: '/',
};
|
import config from '../node_modules/esri-leaflet/profiles/base.js';
config.input = 'src/EsriLeafletRelated.js';
config.output.name = 'L.esri.Related';
config.output.sourcemap = true;
export default config;
|
module PricingRules
# fully discounts one of items for each x items,
# where x is the quantity defined in rule item
class BuyXGetOneFree < BaseRule
private
def calculate_items(items)
rule_item = find_rule_item(items.first.code)
return items unless rule_item
eligible_qty = eligible_items_qty(items, rule_item)
return items unless eligible_qty.positive?
items.map.with_index do |item, ix|
next item unless ix < eligible_qty
Checkout::ItemStruct.new(item.to_h.merge(discount: item.price))
end
end
def eligible_items_qty(items, rule_item)
items.size / rule_item['quantity']
end
end
end |
import type { Font } from '@/hooks/use-font/lib/types'
export const SETTINGS = {
defaultFont: <Font>'open-sans', // change CSS roots in "source/styles/_variables.scss" if you change this value
}
|
"use strict";
var spApplication = spApplication || {};
spApplication.options = {};
/**
* Установки модального окна задачи
*/
spApplication.options.task = {
element: "#modal-task",
height: 470,
width: 600,
title: "Редактирование задачи",
server_addr: "edit-task"
};
/**
* Установки модального окна статуса
*/
spApplication.options.status = {
element: "#modal-status",
height: 200,
width: 390,
title: "Редактирование статуса",
server_addr: "edit-status"
};
/**
* Установки модального окна тега
*/
spApplication.options.tags = {
element: "#modal-tags",
height: 200,
width: 390,
title: "Редактирование тега",
server_addr: "edit-tag"
}; |
package com.github.j5ik2o.plantuml.application
import com.github.j5ik2o.plantuml.domain.classDiagram.{ Fields, Methods, Package, Type, Types }
import com.github.j5ik2o.plantuml.domain._
class PlantUmlBuilder(content: String = "") {
import PlantUmlBuilder._
private val sb = new StringBuilder(content)
private val stereotypesRender = new StereotypesRender(sb)
def start: PlantUmlBuilder =
new PlantUmlBuilder(
sb.append(StartUml).append(NewLine).append(NewLine).toString()
)
def end: PlantUmlBuilder =
new PlantUmlBuilder(sb.append(NewLine).append(EndUml).toString())
private def escape(value: String): String = Quote + value + Quote
private def writeClazzDefinition(clazz: Type): Unit = {
sb.append(clazz.tpe.entryName)
.append(Space)
.append(escape(clazz.name.value))
}
private def writeLink(link: Option[Link]): Unit = {
link.foreach { l =>
sb.append(Space)
.append(l.asString)
}
}
private def writeBackgroundColor(color: Option[Color]): Unit = {
color.foreach { c =>
sb.append(Space)
.append(Hashtag)
.append(c.asString)
}
}
private def writeMethods(methods: Methods, offset: Int): Unit = {
methods.foreach { m =>
writeOffset(offset)
sb.append(Tab)
m.modifier.foreach { modifier =>
sb.append(modifier.entryName)
}
sb.append(m.name.value)
sb.append(BracketOpen)
if (m.parameters.nonEmpty) {
sb.append(m.parameters.toStrings.map {
case (k, v) => s"$k${Comma}${Space}$v"
})
}
sb.append(BracketClose)
sb.append(Semicolon).append(Space).append(m.typeName.value)
writeLink(m.link)
sb.append(NewLine)
}
}
private def writeOffset(offset: Int): Unit = {
if (offset > 0)
sb.append(Space * offset)
}
private def writeFields(fields: Fields, offset: Int): Unit = {
fields.foreach { f =>
writeOffset(offset)
sb.append(Tab)
f.modifier.foreach { modifier =>
sb.append(modifier.entryName)
}
sb.append(f.name.value)
sb.append(Space).append(Semicolon).append(Space).append(f.typeName.value)
writeLink(f.link)
sb.append(NewLine)
}
}
def addPackage(pkg: Package, types: Type*): PlantUmlBuilder = {
addPackage(pkg, Types(types: _*))
}
def addPackage(pkg: Package, types: Types): PlantUmlBuilder = {
sb.append("package").append(Space)
sb.append(pkg.name).append(Space)
pkg.tpe.foreach { t =>
sb.append(StereotypeOpen).append(t.entryName).append(StereotypeClose)
}
pkg.color.foreach { c =>
sb.append(Space).append(Hashtag).append(c.asString)
}
sb.append(BraceOpen).append(NewLine)
types.foreach { c =>
addType(c, 2)
}
sb.append(BraceClose).append(NewLine).append(NewLine)
new PlantUmlBuilder(sb.result())
}
def addType(clazz: Type): PlantUmlBuilder =
addType(clazz, 0)
private def addType(clazz: Type, offset: Int = 0): PlantUmlBuilder = {
writeOffset(offset)
writeClazzDefinition(clazz)
stereotypesRender.render(clazz.stereotypes)
writeLink(clazz.link)
writeBackgroundColor(clazz.backgroundColor)
if (clazz.hasContent) {
sb.append(Space).append(BraceOpen).append(NewLine)
writeFields(clazz.fields, offset)
writeMethods(clazz.methods, offset)
writeOffset(offset)
sb.append(BraceClose)
}
sb.append(NewLine)
new PlantUmlBuilder(sb.result())
}
def addAssociation(association: Association): PlantUmlBuilder = {
sb.append(escape(association.from.name.value))
if (Cardinality.None != association.from.cardinality) {
sb.append(Space)
.append(Quote)
.append(association.from.cardinality.entryName)
.append(Quote)
}
sb.append(Space).append(association.tpe.entryName).append(Space)
if (Cardinality.None != association.to.cardinality) {
sb.append(Space)
.append(Quote)
.append(association.to.cardinality.entryName)
.append(Quote)
}
sb.append(escape(association.to.name.value))
association.label.foreach { l =>
sb.append(Space).append(Semicolon).append(Space).append(l)
}
sb.append(NewLine)
new PlantUmlBuilder(sb.result())
}
def build: String = sb.result()
}
object PlantUmlBuilder {
val StartUml = "@startuml"
val EndUml = "@enduml"
val Quote = "\""
val Space = " "
val StereotypeOpen = "<<"
val StereotypeClose = ">>"
val BraceOpen = "{"
val BraceClose = "}"
val BracketOpen = "("
val BracketClose = ")"
val Semicolon = ":"
val Comma = ","
val Hashtag = "#"
val Tab = Space + Space
val NewLine = System.getProperty("line.separator")
}
|
using System;
namespace HostInvoker.HostOperations
{
class DownloadFileOperation : HostOperation
{
protected override void Run()
{
Console.WriteLine("File has been downloaded");
}
}
}
|
package com.epicknife.modules.tcplistener;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Samuel "MrOverkill" Meyers
* License : BSD
* Date of Creation : 01 / 23 / 2015
*/
public class MetaHandler
{
public MetaHandler()
{
}
public void readMeta(InputStream in)
{
}
public void writeMeta(OutputStream out)
{
}
} |
var assert = require('assert');
var Headers = require('../headers');
var Parser = require('../parser');
var h = Headers({
'Content-Type': 'text/plain',
'Content-Length': 7
});
var normal = h.toString();
assert.equal(normal.split('\r\n').length, 4);
assert.equal(normal.indexOf('\r\n\r\n'), normal.length-4);
var noLastLine = h.toString({
emptyLastLine: false
});
assert.equal(noLastLine.split('\r\n').length, 3);
assert.equal(noLastLine.indexOf('\r\n\r\n'), -1);
var firstLine = h.toString({
firstLine: 'test'
});
assert.equal(firstLine.indexOf('test'), 0);
var delimiter = h.toString({
delimiter: '~~'
});
assert.equal(delimiter.split('~~').length, 4);
var parser = new Parser();
var gotHeaders = false;
parser.on('headers', function(headers, leftover) {
gotHeaders = true;
assert.equal(headers.length, 2);
});
parser.parse(new Buffer(h.toString({})));
process.on('exit', function() {
assert.ok(gotHeaders);
});
|
### operator
#### explain
- 使用迭代器进行编程有时需要为简单表达式创建小函数。有时,这些可以作为lambda函数实现,但对于某些操作,根本不需要新函数。该operator模块定义了与算术,比较和与标准对象API相对应的其他操作的内置操作相对应的函数。 |
import {Instruction, RuntimeContext} from '../Types';
export default (instruction: Instruction, context: RuntimeContext): void => {
context.next++;
};
|
#include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <unordered_set>
#include <future>
// The following was inspired by XtremePrime's vlc-title-grabber, be sure
// to check him out https://github.com/XtremePrime/
// NOTE:
// This program uses std::async because of reasons. In this particular
// use case it most likely just adds needless overhead if the implementation
// actually does create new threads. So consider removing the async code if
// you do plan to use this for anything.
std::string GetActiveWindowTitle()
{
HWND hwnd = GetForegroundWindow();
size_t title_length = GetWindowTextLength(hwnd);
if (title_length < 1) { return "[Empty Title]"; }
auto window_text = std::unique_ptr<char>{ new char[title_length + 1] };
GetWindowText(hwnd, window_text.get(), title_length + 1);
return window_text.get();
}
std::unordered_set<std::string> LoadTitleSet()
{
std::ifstream in("titles.txt");
if (!in.is_open()) { return std::unordered_set<std::string>(); }
std::unordered_set<std::string> title_set;
for (std::string title; std::getline(in, title);)
{
title_set.insert(title);
}
in.close();
return title_set;
}
int main()
{
using namespace std::chrono_literals;
std::string title;
std::unordered_set<std::string> title_set = LoadTitleSet();
std::ofstream out;
std::future<void> fut;
while (true)
{
title = GetActiveWindowTitle();
if (title_set.find(title) == title_set.end())
{
if (fut.valid()) { fut.get(); }
fut = std::async(std::launch::async, [&] {
out.open("titles.txt", std::ios::app);
out << title << std::endl;
title_set.insert(title);
out.close();
});
}
std::this_thread::sleep_for(100ms);
}
return 0;
} |
import {Component, OnInit, ElementRef, Renderer, Self} from '@angular/core';
import {NgModel, NgClass} from '@angular/common';
import {Pagination} from './pagination.component';
const pagerConfig = {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
};
const PAGER_TEMPLATE = `
<ul class="pager">
<li [class.disabled]="noPrevious()" [class.previous]="align" [ngClass]="{'pull-right': align}">
<a href (click)="selectPage(page - 1, $event)">{{getText('previous')}}</a>
</li>
<li [class.disabled]="noNext()" [class.next]="align" [ngClass]="{'pull-right': align}">
<a href (click)="selectPage(page + 1, $event)">{{getText('next')}}</a>
</li>
</ul>
`;
@Component({
moduleId: module.id,
selector: 'pager[ngModel]',
template: PAGER_TEMPLATE,
directives: [NgClass],
inputs: [
'align',
'totalItems', 'itemsPerPage',
'previousText', 'nextText',
]
})
export class Pager extends Pagination implements OnInit {
public config = pagerConfig;
constructor(@Self() cd:NgModel, renderer:Renderer, elementRef:ElementRef) {
super(cd, renderer, elementRef);
}
} |
--+ holdcas on;
--alter_table_change_type_strict
--change the type of a numeric column to bigint
create class coo(
col1 numeric(13),
col2 numeric(19),
col3 numeric(19),
col4 numeric(22),
col5 numeric(23),
col6 numeric(13, 3),
col7 numeric(25, 4),
col8 numeric(25, 4)
);
insert numerico coo
values(7382234738923, 1234523456837297104, -2112354321738293654, 5167890739284328473254, -66034383829127482934271, 8463457655.123, 654321829354847311223.1234, -736283562934489013542.5342);
show columns in coo;
--numeric -> bigint, old prec < 19, scale=0
alter table coo change col1 col1 bigint;
select * from coo order by 1;
--numeric -> bigint, old prec >= 19, scal=0, numeric < max(bigint)
alter table coo change col2 col2 bigint;
--numeric -> bigint, old prec >= 19, scal=0, numeric > min(bigint)
alter table coo change col3 col3 bigint;
select * from coo order by 1;
--numeric -> bigint, old prec >= 19, scal=0, numeric > max(bigint)
set system parameters 'alter_table_change_type_strict=yes';
alter table coo change col4 col4 bigint;
set system parameters 'alter_table_change_type_strict=no';
alter table coo change col4 col4 bigint;
select * from coo order by 1;
--numeric -> bigint, old prec >= 19, scal=0, numeric < min(bigint)
set system parameters 'alter_table_change_type_strict=yes';
alter table coo change col5 col5 bigint;
set system parameters 'alter_table_change_type_strict=no';
alter table coo change col5 col5 bigint;
select * from coo order by 1;
--numeric -> bigint, scal > 0, min(bigint) < numeric < max(bigint)
set system parameters 'alter_table_change_type_strict=yes';
alter table coo change col6 col6 bigint;
set system parameters 'alter_table_change_type_strict=no';
alter table coo change col6 col6 bigint;
select * from coo order by 1;
--numeric -> bigint, scal > 0, numeric > max(bigint)
set system parameters 'alter_table_change_type_strict=yes';
alter table coo change col7 col7 bigint;
set system parameters 'alter_table_change_type_strict=no';
alter table coo change col7 col7 bigint;
select * from coo order by 1;
--numeric -> bigint, scal > 0, numeric < min(bigint)
set system parameters 'alter_table_change_type_strict=yes';
alter table coo change col8 col8 bigint;
set system parameters 'alter_table_change_type_strict=no';
alter table coo change col8 col8 bigint;
select * from coo order by 1;
show columns in coo;
drop table coo;
commit;
--+ holdcas off;
|
using System;
using System.Collections.Generic;
using System.Linq;
using LHGames.Helper;
using LHGames.Navigation;
using LHGames.Navigation.Pathfinding;
namespace LHGames.Bot.Behaviours
{
public class MiningBehaviour : Behaviour
{
public MiningBehaviour(BehaviourExecuter executer) : base(executer)
{
}
public override bool Evaluate()
{
return true;
}
public override string Execute()
{
var playerPos = _executer.PlayerInfo.Position;
if (_executer.PlayerInfo.CarriedResources >= _executer.PlayerInfo.CarryingCapacity)
{
// Go home you're ~drunk~ full
var returnHomePath = _executer.Map.PathBetween(playerPos, _executer.PlayerInfo.HouseLocation);
return MoveTo(returnHomePath[1].Tile.Position - playerPos);
}
else
{
var adjacentMine = _executer.Map.HasTileOfTypeAdjacentTo(TileContent.Resource, playerPos);
if (adjacentMine != null)
{
// if we're next to a mine, mine
return AIHelper.CreateCollectAction(adjacentMine.Position - playerPos);
}
else
{
// Go to mine
var resource = _executer.Map.GetClosestTileOfType(TileContent.Resource, playerPos);
var minePath = _executer.Map.ShortestPathNextTo(resource.Position, playerPos);
return MoveTo(minePath[1].Tile.Position - playerPos);
}
}
}
private string MoveTo(Point direction)
{
var tileToGo = _executer.Map.TileAt(direction + _executer.PlayerInfo.Position);
if (tileToGo.TileType == TileContent.Wall)
{
return AIHelper.CreateMeleeAttackAction(direction);
}
else
{
return AIHelper.CreateMoveAction(direction);
}
}
}
} |
@extends('master')
@section('content')
<div class="container">
<h1>
{{trans('models.depots.singular')}} {{$depot->number}}
@include('depots.partials.show-buttons')
</h1>
<h2>
Administrado por
<a href="{{route('users.show', $depot->owner->name)}}">
{{$depot->owner->name}},
</a>
{!! Html::mailto($depot->owner->email) !!}
</h2>
<h3>
Anaquel {{$depot->rack}}, Alacena {{$depot->shelf}}
</h3>
@include('depots.partials.items')
@include('partials.admins.show-basic-audit', [
'model' => $depot,
'created' => trans('models.depots.singular') . ' creado',
'updated' => trans('models.depots.singular') . ' actualizado',
])
</div>
@stop
|
if (Test-Path 'dist') {
Get-ChildItem 'dist' | Remove-Item -Recurse -Force
}
# npm install -g @po-ui/theme-cli -f
Write-Host 'Building solution...' -ForegroundColor Yellow
npm run build
cp .\README.md .\dist\
cd .\dist
Write-Host 'Publishing NPM package...' -ForegroundColor Yellow
npm publish
Write-Host "`r`Done" -ForegroundColor Green
Pause
|
#!/usr/bin/env python
####################
# Required Modules #
####################
# Generic/Built-in
import os
from pathlib import Path
# Libs
# Custom
##################
# Configurations #
##################
SRC_DIR = Path(__file__).parent.absolute()
API_VERSION = "0.2.0"
##############################################
# Synergos UI Container Local Configurations #
##############################################
""" General parameters & constants """
# State static directory
STATIC_DIR = os.path.join(SRC_DIR, "static")
# State image directory
IMAGE_DIR = os.path.join(STATIC_DIR, "images")
# State styling directory
STYLES_DIR = os.path.join(STATIC_DIR, "styles")
# Temporary directory to track user access
TMP_DIR = os.path.join(SRC_DIR, "tmp")
# State docker alias address for SynUI-Tracker
TRACKER_HOST = os.environ['TRACK_HOST']
TRACKER_PORT = os.environ['TRACK_PORT']
################################################
# Synergos UI Container Service Configurations #
################################################
""" Custom settings for components """
SUPPORTED_COMPONENTS = {
'logs': {
'name': "Synergos Logger",
'command': 'Logs'
},
'mlops': {
'name': "Synergos MLOps",
'command': "MLOps"
},
'mq': {
"name": "Synergos MQ",
'command': "MQ"
}
}
DEFAULT_DEPLOYMENTS = {
'Synergos Basic': [],
'Synergos Plus': [
SUPPORTED_COMPONENTS['logs']['name'],
SUPPORTED_COMPONENTS['mlops']['name']
],
'Synergos Cluster': [
SUPPORTED_COMPONENTS['logs']['name'],
SUPPORTED_COMPONENTS['mlops']['name'],
SUPPORTED_COMPONENTS['mq']['name']
]
} |
package generators
import crypto.EncryptedValue
import models._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Gen}
import java.time.LocalDate
trait Generators {
implicit lazy val arbitrarySalesChannels: Arbitrary[SalesChannels] =
Arbitrary {
Gen.oneOf(SalesChannels.values)
}
implicit lazy val arbitraryNiPresence: Arbitrary[NiPresence] =
Arbitrary {
Gen.oneOf(
Gen.const(PrincipalPlaceOfBusinessInNi),
Gen.const(FixedEstablishmentInNi),
arbitrary[SalesChannels].map(NoPresence(_))
)
}
implicit lazy val arbitraryBic: Arbitrary[Bic] = {
val asciiCodeForA = 65
val asciiCodeForN = 78
val asciiCodeForP = 80
val asciiCodeForZ = 90
Arbitrary {
for {
firstChars <- Gen.listOfN(6, Gen.alphaUpperChar).map(_.mkString)
char7 <- Gen.oneOf(Gen.alphaUpperChar, Gen.choose(2, 9))
char8 <- Gen.oneOf(
Gen.choose(asciiCodeForA, asciiCodeForN).map(_.toChar),
Gen.choose(asciiCodeForP, asciiCodeForZ).map(_.toChar),
Gen.choose(0, 9)
)
lastChars <- Gen.option(Gen.listOfN(3, Gen.oneOf(Gen.alphaUpperChar, Gen.numChar)).map(_.mkString))
} yield Bic(s"$firstChars$char7$char8${lastChars.getOrElse("")}").get
}
}
implicit lazy val arbitraryIban: Arbitrary[Iban] =
Arbitrary {
Gen.oneOf(
"GB94BARC10201530093459",
"GB33BUKB20201555555555",
"DE29100100100987654321",
"GB24BKEN10000031510604",
"GB27BOFI90212729823529",
"GB17BOFS80055100813796",
"GB92BARC20005275849855",
"GB66CITI18500812098709",
"GB15CLYD82663220400952",
"GB26MIDL40051512345674",
"GB76LOYD30949301273801",
"GB25NWBK60080600724890",
"GB60NAIA07011610909132",
"GB29RBOS83040210126939",
"GB79ABBY09012603367219",
"GB21SCBL60910417068859",
"GB42CPBK08005470328725"
).map(v => Iban(v).right.get)
}
implicit lazy val arbitraryEncryptedCountry: Arbitrary[EncryptedCountry] =
Arbitrary {
for {
code <- arbitrary[EncryptedValue]
name <- arbitrary[EncryptedValue]
} yield EncryptedCountry(code, name)
}
implicit lazy val arbitraryEncryptedValue: Arbitrary[EncryptedValue] =
Arbitrary {
for {
value <- Gen.listOfN(50, Gen.alphaNumChar).map(_.mkString)
nonce <- Gen.listOfN(50, Gen.alphaNumChar).map(_.mkString)
} yield EncryptedValue(value, nonce)
}
implicit lazy val arbitraryVatDetails: Arbitrary[VatDetails] =
Arbitrary {
for {
registrationDate <- arbitrary[Int].map(n => LocalDate.ofEpochDay(n))
address <- arbitrary[Address]
partOfVatGroup <- arbitrary[Boolean]
source <- arbitrary[VatDetailSource]
} yield VatDetails(registrationDate, address, partOfVatGroup, source)
}
implicit val arbitraryVatDetailSource: Arbitrary[VatDetailSource] =
Arbitrary(
Gen.oneOf(VatDetailSource.values)
)
implicit lazy val arbitraryPreviousRegistration: Arbitrary[PreviousRegistration] =
Arbitrary {
for {
country <- arbitrary[Country]
vatNumber <- Gen.listOfN(11, Gen.alphaChar).map(_.mkString)
} yield PreviousRegistration(country, vatNumber)
}
implicit lazy val arbitraryEuTaxRegistration: Arbitrary[EuTaxRegistration] =
Arbitrary {
Gen.oneOf(arbitrary[EuVatRegistration], arbitrary[RegistrationWithFixedEstablishment])
}
implicit lazy val arbitraryEuVatRegistration: Arbitrary[EuVatRegistration] =
Arbitrary {
for {
country <- arbitrary[Country]
vatNumber <- Gen.listOfN(9, Gen.numChar).map(_.mkString)
} yield EuVatRegistration(country, vatNumber)
}
implicit lazy val arbitraryRegistrationWithFixedEstablishment: Arbitrary[RegistrationWithFixedEstablishment] =
Arbitrary {
for {
country <- arbitrary[Country]
taxIdentifier <- arbitrary[EuTaxIdentifier]
fixedEstablishment <- arbitrary[FixedEstablishment]
} yield RegistrationWithFixedEstablishment(country, taxIdentifier, fixedEstablishment)
}
implicit lazy val arbitraryRegistrationWithoutFixedEstablistment: Arbitrary[RegistrationWithoutFixedEstablishment] =
Arbitrary {
arbitrary[Country].map(c => RegistrationWithoutFixedEstablishment(c))
}
implicit lazy val arbitraryUkAddress: Arbitrary[UkAddress] =
Arbitrary {
for {
line1 <- arbitrary[String]
line2 <- Gen.option(arbitrary[String])
townOrCity <- arbitrary[String]
county <- Gen.option(arbitrary[String])
postCode <- arbitrary[String]
} yield UkAddress(line1, line2, townOrCity, county, postCode)
}
implicit val arbitraryAddress: Arbitrary[Address] =
Arbitrary {
Gen.oneOf(
arbitrary[UkAddress],
arbitrary[InternationalAddress],
arbitrary[DesAddress]
)
}
implicit lazy val arbitraryInternationalAddress: Arbitrary[InternationalAddress] =
Arbitrary {
for {
line1 <- arbitrary[String]
line2 <- Gen.option(arbitrary[String])
townOrCity <- arbitrary[String]
stateOrRegion <- Gen.option(arbitrary[String])
postCode <- Gen.option(arbitrary[String])
country <- arbitrary[Country]
} yield InternationalAddress(line1, line2, townOrCity, stateOrRegion, postCode, country)
}
implicit lazy val arbitraryDesAddress: Arbitrary[DesAddress] =
Arbitrary {
for {
line1 <- arbitrary[String]
line2 <- Gen.option(arbitrary[String])
line3 <- Gen.option(arbitrary[String])
line4 <- Gen.option(arbitrary[String])
line5 <- Gen.option(arbitrary[String])
postCode <- Gen.option(arbitrary[String])
countryCode <- Gen.listOfN(2, Gen.alphaChar).map(_.mkString)
} yield DesAddress(line1, line2, line3, line4, line5, postCode, countryCode)
}
implicit lazy val arbitraryBankDetails: Arbitrary[BankDetails] =
Arbitrary {
for {
accountName <- arbitrary[String]
bic <- Gen.option(arbitrary[Bic])
iban <- arbitrary[Iban]
} yield BankDetails(accountName, bic, iban)
}
implicit val arbitraryEuTaxIdentifierType: Arbitrary[EuTaxIdentifierType] =
Arbitrary {
Gen.oneOf(EuTaxIdentifierType.values)
}
implicit val arbitraryEuTaxIdentifier: Arbitrary[EuTaxIdentifier] =
Arbitrary {
for {
identifierType <- arbitrary[EuTaxIdentifierType]
value <- arbitrary[Int].map(_.toString)
} yield EuTaxIdentifier(identifierType, value)
}
implicit lazy val arbitraryFixedEstablishment: Arbitrary[FixedEstablishment] =
Arbitrary {
for {
tradingName <- arbitrary[String]
address <- arbitrary[InternationalAddress]
} yield FixedEstablishment(tradingName, address)
}
implicit lazy val arbitraryCountry: Arbitrary[Country] =
Arbitrary {
for {
char1 <- Gen.alphaUpperChar
char2 <- Gen.alphaUpperChar
name <- arbitrary[String]
} yield Country(s"$char1$char2", name)
}
implicit lazy val arbitraryBusinessContactDetails: Arbitrary[ContactDetails] =
Arbitrary {
for {
fullName <- arbitrary[String]
telephoneNumber <- arbitrary[String]
emailAddress <- arbitrary[String]
} yield ContactDetails(fullName, telephoneNumber, emailAddress)
}
}
|
#!/bin/sh
rm $0
"./trabalho"
echo "
------------------
(program exited with code: $?)"
echo "Press return to continue"
#to be more compatible with shells like dash
dummy_var=""
read dummy_var
|
using System;
namespace ManagedLua.Environment.Types {
/// <summary>
/// Description of VMCommand.
/// </summary>
public enum VMCommand {
CO_CREATE, CO_RESUME, CO_YIELD, CO_RUNNING, PCALL, ERROR
}
}
|
<?php
namespace App\Http\Controllers\AdminControllers;
use App\Http\Controllers\Controller;
use App\Models\Admin\DoctorFaq;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class DoctorFaqController extends Controller
{
public function doctor_faqs($doctor_id)
{
$faqs = DoctorFaq::where('doctor_id',$doctor_id)->get();
return view('adminpanel.doctorfaqs.index',compact('faqs','doctor_id'));
}
public function store_faqs(Request $request)
{
$validator = Validator::make($request->all(), [
'question' => 'required',
'answer' => 'required',
'is_active' => 'nullable',
]);
if ($validator->fails()) {
session()->flash('error', 'Please Fill out all the Fields');
return back();
}
$answer = $request->answer;
$question = $request->question;
$is_active = $request->is_active;
$store = DB::table('doctor_faqs')->insert([
'doctor_id' => $request->doctor_id,
'question' => $question,
'answer' => $answer,
'is_active' => $is_active,
'created_by' => Auth::user()->id,
]);
if ($store) {
session()->flash('success', 'FAQs saved Successfully!');
return back();
} else {
session()->flash('error', 'Could not Save!');
return back();
}
}
public function edit($id)
{
$faq = DoctorFaq::where('id',$id)->first();
return view('adminpanel.doctorfaqs.edit',compact('faq'));
}
public function update(Request $request ,$id)
{
// dd($request->all());
$faq = DoctorFaq::where('id',$id)->first();
if ($faq) {
$update = DB::table('doctor_faqs')->where('id',$id)->update([
'question' => $request->question,
'answer' => $request->answer,
'is_active' => isset($request->is_active) ? $request->is_active : 0,
'updated_by' => Auth::user()->id,
'updated_at' => Carbon::now()->toDateTimeString(),
]);
session()->flash('success', 'FAQs Updated Successfully!');
return redirect()->route('doctor_faqs',$faq->doctor_id);
} else {
session()->flash('error', 'FAQs Updated Successfully!');
return back();
}
}
public function delete_faqs(Request $request,$id)
{
$delete = DoctorFaq::where('id',$request->id)->delete();
if ($delete) {
return response()->json(["data" =>"Deleted"]);
} else {
abort(403);
}
}
}
|
"""Standard experiments for ICRA 2021"""
from milp_sim.risk.classes.child_mespp import MyInputs2
from milp_sim.risk.src import base_fun as bf, risk_sim as sr
def specs_basic():
"""Set specs that won't change"""
# initialize default inputs
specs = MyInputs2()
# ------------------------
# graph number -- SS-2: 8
specs.set_graph(8)
# solver parameter: central x distributed
specs.set_solver_type('distributed')
# solver timeout (in seconds)
specs.set_timeout(10)
# ------------------------
# time stuff: deadline mission (tau), planning horizon (h), re-plan frequency (theta)
specs.set_horizon(14)
specs.set_deadline(100)
specs.set_theta(1)
# ------------------------
# searchers' detection: capture range and false negatives
m = 3
v0 = [1, 1, 1]
specs.set_size_team(m)
specs.set_start_searchers(v0)
specs.set_capture_range(0)
specs.set_zeta(None)
# ------------------------
# target motion
specs.set_target_motion('static')
specs.set_start_target_vertex(None)
# ------------------------
# pseudorandom
# repetitions for each configuration
specs.set_number_of_runs(1000)
# set random seeds
specs.set_start_seeds(2000, 6000)
return specs
def specs_danger_common():
"""Set common danger specs
"""
specs = specs_basic()
# danger files
base_name = 'danger_map_NCF_freq_'
# true danger file
true_file = base_name + '100'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating danger with 5% images
# ----------------------------------------
per = 5
estimated_file = base_name + str(per).zfill(2)
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.95, 0.95, 0.95]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'point'
specs.set_danger_perception(perception)
# Apply prob kill (true/false)
# hybrid prob (op 3)
default_prob = 3
specs.use_kill(True, default_prob)
specs.set_mva_conservative(True)
specs.set_use_fov(True)
specs.set_true_estimate(False)
return specs
# ------------------------------------------
def specs_true_priori():
specs = specs_danger_common()
# set perfect a priori knowledge
specs.set_true_know(True)
# and estimate
specs.set_true_estimate(True)
return specs
def specs_no_danger():
specs = specs_danger_common()
specs.use_kill(False)
specs.use_danger_constraints(False)
return specs
def specs_no_constraints():
specs = specs_danger_common()
specs.use_kill(True, 3)
specs.use_danger_constraints(False)
return specs
def specs_no_fov():
specs = specs_danger_common()
specs.set_use_fov(False)
return specs
def specs_100_img():
specs = specs_danger_common()
# danger files
base_name = 'danger_map_NCF_freq_'
# true danger file
true_file = base_name + '100'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating only with 5% images
# ----------------------------------------
per = 100
estimated_file = base_name + str(per).zfill(2)
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
return specs
def specs_335():
specs = specs_danger_common()
kappa = [3, 3, 5]
specs.set_threshold(kappa, 'kappa')
return specs
def specs_333():
specs = specs_danger_common()
kappa = [3, 3, 3]
specs.set_threshold(kappa, 'kappa')
return specs
# ------------------------------------------
def specs_prob():
specs = specs_danger_common()
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.6, 0.4, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'prob'
specs.set_danger_perception(perception)
return specs
def specs_true_priori_prob():
specs = specs_prob()
# set perfect a priori knowledge
specs.set_true_know(True)
# and estimate
specs.set_true_estimate(True)
return specs
def specs_no_fov_prob():
specs = specs_prob()
specs.set_use_fov(False)
return specs
def specs_100_img_prob():
specs = specs_prob()
# danger files
base_name = 'danger_map_NCF_freq_'
# true danger file
true_file = base_name + '100'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating only with 5% images
# ----------------------------------------
per = 100
estimated_file = base_name + str(per).zfill(2)
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
return specs
def specs_335_prob():
specs = specs_prob()
kappa = [3, 3, 5]
alpha = [0.6, 0.6, 0.1]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
return specs
def specs_NFF_both():
specs = specs_basic()
# danger files
# true danger file
true_file = 'gt_danger_NFF'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating danger with 5% images
# ----------------------------------------
per = 5
estimated_file = 'estimate_danger_both_des_NFF_freq_05'
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
specs.set_gt(True)
specs.set_all_descriptions(True)
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.6, 0.4, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'point'
specs.set_danger_perception(perception)
# Apply prob kill (true/false)
# hybrid prob (op 3)
default_prob = 3
specs.use_kill(True, default_prob)
specs.set_mva_conservative(True)
specs.set_use_fov(True)
specs.set_true_estimate(False)
return specs
def specs_NFF_both_est():
specs = specs_basic()
# danger files
# true danger file
true_file = 'estimate_danger_both_des_NFF_freq_100'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating danger with 5% images
# ----------------------------------------
per = 5
estimated_file = 'estimate_danger_both_des_NFF_freq_05'
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
specs.set_gt(False)
specs.set_all_descriptions(True)
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.6, 0.4, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'point'
specs.set_danger_perception(perception)
# Apply prob kill (true/false)
# hybrid prob (op 3)
default_prob = 3
specs.use_kill(True, default_prob)
specs.set_mva_conservative(True)
specs.set_use_fov(True)
specs.set_true_estimate(False)
return specs
def specs_NFF_fire():
specs = specs_basic()
# danger files
# true danger file
true_file = 'gt_danger_NFF'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating danger with 5% images
# ----------------------------------------
per = 5
estimated_file = 'estimate_danger_fire_des_NFF_freq_05'
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
specs.set_gt(True)
specs.set_all_descriptions(False)
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.6, 0.4, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'point'
specs.set_danger_perception(perception)
# Apply prob kill (true/false)
# hybrid prob (op 3)
default_prob = 3
specs.use_kill(True, default_prob)
specs.set_mva_conservative(True)
specs.set_use_fov(True)
specs.set_true_estimate(False)
return specs
def specs_NFF_fire_est():
specs = specs_basic()
# danger files
# true danger file
true_file = 'estimate_danger_fire_des_NFF_freq_100'
specs.set_danger_file(true_file, 'true')
# ----------------------------------------
# estimating danger with 5% images
# ----------------------------------------
per = 5
estimated_file = 'estimate_danger_fire_des_NFF_freq_05'
# estimated danger file
specs.set_danger_file(estimated_file, 'hat')
specs.set_gt(False)
specs.set_all_descriptions(False)
# threshold of searchers
kappa = [3, 4, 5]
alpha = [0.6, 0.4, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
# danger perception
perception = 'point'
specs.set_danger_perception(perception)
# Apply prob kill (true/false)
# hybrid prob (op 3)
default_prob = 3
specs.use_kill(True, default_prob)
specs.set_mva_conservative(True)
specs.set_use_fov(True)
specs.set_true_estimate(False)
return specs
def specs_new_true_335():
specs = specs_NFF_both()
# threshold of searchers
kappa = [3, 3, 5]
alpha = [0.6, 0.6, 0.4]
specs.set_threshold(kappa, 'kappa')
specs.set_threshold(alpha, 'alpha')
def get_believes():
specs = specs_basic()
for turn in specs.list_turns:
# set seed according to run #
specs.set_seeds(turn)
# set new belief
n = 46
b0 = MyInputs2.pick_random_belief(n, specs.target_seed)
# print(b0)
if turn > 30:
break
# ------------------------------------------
def num_sim(specs):
# loop for number of repetitions
for turn in specs.list_turns:
specs.prep_next_turn(turn)
# try:
# run simulator
belief, target, team, solver_data, danger, mission = sr.run_simulator(specs)
# save everything as a pickle file
bf.save_sim_data(belief, target, team, solver_data, danger, specs, mission)
# iterate run #
specs.update_run_number()
# delete things
del belief, target, team, solver_data, danger, mission
#except:
# print('Error on instance %d! Jumping to next instance.' % turn)
# iterate run #
# specs.update_run_number()
# pass
print("----------------------------------------------------------------------------------------------------")
print("----------------------------------------------------------------------------------------------------")
|
<?php
namespace App\Http\Controllers\Cad;
use App\Http\Controllers\Controller;
use App\Http\Requests\Cad\PessoaTelefoneRequest;
use App\Http\Resources\Cad\PessoaTelefoneColletionResource;
use App\Http\Resources\Cad\PessoaTelefoneResource;
use App\Models\Cad\Pessoa;
use App\Models\Cad\PessoaTelefone;
use Illuminate\Http\Request;
class PessoaTelefoneController extends Controller
{
public function index()
{
return PessoaTelefoneResource::collection(PessoaTelefone::all());
}
public function store(PessoaTelefoneRequest $request)
{
$pessoatelefone = PessoaTelefone::create($request->all());
$pessoatelefone->refresh(); // devido ao default active para atualizar quando não e passado
return new PessoaTelefoneResource($pessoatelefone);
}
public function show(PessoaTelefone $pessoatelefone)
{
return new PessoaTelefoneResource($pessoatelefone);
}
public function update(PessoaTelefoneRequest $request, PessoaTelefone $pessoatelefone)
{
$pessoatelefone->fill($request->all());
$pessoatelefone->save();
return new PessoaTelefoneResource($pessoatelefone);
}
public function destroy(PessoaTelefone $pessoatelefone)
{
$pessoatelefone->delete();
return response()->json([], 204);
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Pays extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pays', function (Blueprint $table) {
$table->collation = 'utf8_persian_ci';
$table->id();
$table->string('terminalId', 250);
$table->integer('amount');
$table->string('localDate', 250);
$table->string('localTime_', 250);
$table->text('additionalData')->nullable();
$table->text('callBackUrl');
$table->string('payerId', 250);
$table->string('orderId', 250);
$table->string('saleOrderId', 250)->nullable();
$table->string('saleReferenceId', 250)->nullable();
$table->string('subServiceId', 250)->nullable();
$table->text('CardHolderInfo')->nullable();
$table->integer('userId')->nullable();
$table->string('RefId', 250)->nullable();
$table->string('ResCode', 250)->nullable();
$table->string('action', 250)->nullable();
$table->boolean('status')->nullable()->default(0);
$table->boolean('verify')->nullable()->default(0);
$table->boolean('reverse')->default(0);
$table->boolean('settle')->default(0);
$table->integer('time')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pays');
}
}
|
-- *CA APPROVALS
-- *Specified as primary user
-- *Specified as secondary user
--
-- Usage:
/*
select * from udf_GetEditAccessOrdersForLogin('bazemore')
*/
-- =============================================
CREATE FUNCTION udf_GetEditAccessRecentOrdersForLogin
(
-- Add the parameters for the function here
@LoginId varchar(50),
@Cutoff datetime
)
RETURNS
@EditAccessOrders TABLE
(
id int,
orderid int,
accessuserid varchar(10),
isadmin bit,
accesslevel char(2)
)
AS
BEGIN
INSERT INTO @EditAccessOrders
select ROW_NUMBER() over (order by orderid) id, *
from (
-- regular permissions
select distinct o.id orderid
, case when ap.userid is null then wp.userid
when ap.userid is not null and ouser.isaway = 1 then wp.userid
else ap.userid
end accessuserid
, 0 isadmin
, ap.orderstatuscodeid accesslevel
from orders o
inner join orderstatuscodes osc on o.orderstatuscodeid = osc.id
left outer join approvals ap on o.id = ap.orderid
inner join orderstatuscodes aposc on ap.OrderStatusCodeId = aposc.id
left outer join workgrouppermissions wp on o.workgroupid = wp.workgroupid and ap.orderstatuscodeid = wp.roleid
left outer join users ouser on ouser.id = ap.userid
where
case when ap.userid is null then wp.userid
when ap.userid is not null and ouser.isaway = 1 then wp.userid
else ap.userid
end = @LoginId
and ap.Completed = 0
and osc.iscomplete = 0
and aposc.level = osc.Level
and o.DateLastAction > @Cutoff
and (
wp.isadmin = 0
or
(
wp.isadmin = 1 and wp.isfullfeatured = 1
)
)
and (
ap.userid in ( select userid from workgrouppermissions where workgroupid = o.workgroupid )
or
ap.userid is null
)
union
-- ad hoc permissons
select distinct o.id orderid
, ap.userid accessuserid
, 0 isadmin
, ap.orderstatuscodeid accesslevel
from orders o
inner join orderstatuscodes osc on o.orderstatuscodeid = osc.id
left outer join approvals ap on o.id = ap.orderid
inner join orderstatuscodes aposc on ap.OrderStatusCodeId = aposc.id
where
ap.userid = @LoginId
and ap.Completed = 0
and osc.iscomplete = 0
and aposc.level = osc.level
and ap.userid not in ( select userid from workgrouppermissions where workgroupid = o.workgroupid )
and o.DateLastAction > @Cutoff
union
-- override, provides admin permissions
select o.id orderid, userid, isadmin, wp.roleid
from orders o
inner join workgrouppermissions wp on o.workgroupid = wp.workgroupid and o.OrderStatusCodeId = wp.roleid
where
wp.userid = @LoginId
and wp.isadmin = 1
and wp.IsFullFeatured = 0
and o.DateLastAction > @Cutoff
union
-- secondary Conditional Approval
select ap.OrderId, ap.SecondaryUserId accessuserid, cast(0 as bit) isadmin, ap.OrderStatusCodeId
from approvals ap
inner join orders o on ap.OrderId = o.id
inner join OrderStatusCodes aposc on ap.OrderStatusCodeId = aposc.id
inner join OrderStatusCodes oosc on o.orderstatuscodeid = oosc.id
where
ap.SecondaryUserId = @LoginId
and ap.OrderStatusCodeId = 'CA'
and ap.SecondaryUserId is not null
and aposc.level = oosc.level
and ap.Completed = 0
and o.DateLastAction > @Cutoff
union
-- Primary Conditional Approval
select ap.OrderId, ap.UserId accessuserid, cast(0 as bit) isadmin, ap.OrderStatusCodeId
from approvals ap
inner join orders o on ap.OrderId = o.id
inner join OrderStatusCodes aposc on ap.OrderStatusCodeId = aposc.id
inner join OrderStatusCodes oosc on o.orderstatuscodeid = oosc.id
where
ap.UserId = @LoginId
and ap.OrderStatusCodeId = 'CA'
and aposc.level = oosc.level
and ap.Completed = 0
and o.DateLastAction > @Cutoff
) veditaccess
where accessuserid is not null
RETURN
END |
import { unwrapNodesByType } from 'common/transforms';
import { ListType } from 'elements/list/types';
import { Editor } from 'slate';
export const unwrapList = (
editor: Editor,
{
typeUl = ListType.UL,
typeOl = ListType.OL,
typeLi = ListType.LI,
}: { typeUl?: string; typeOl?: string; typeLi?: string } = {}
) => {
unwrapNodesByType(editor, typeLi);
unwrapNodesByType(editor, [typeUl, typeOl], { split: true });
};
|
const knex = require('../../db');
var fs = require('fs');
const EthUtil=require('ethereumjs-util');
async function getAllRequests(email) {
let xfiles= await knex('requests').select().where('recipient',email)
.orderBy('fileId', 'desc') ;
return xfiles;
}
async function getAllSentRequests(id) {
let xfiles= await knex('requests').select().where('issuerId',id)
.orderBy('fileId', 'desc') ;
return xfiles;
}
async function getUser(id) {
const [user] = await knex('users')
.where('id', id)
.select('name', 'public_key','b_address');
return user;
}
async function update_request_status(fileId,hash){
//console.log("Updating file with :\n",fileId)
const [request] = await knex('requests')
.where({ 'fileId':fileId })
.update({
status:'signed',
hash:hash,
})
.returning(['fileId','status']);
return request;
}
async function signFile(private_key, filePath, userId,filename,description,public_key) {
let fileToSign ={}
fileToSign=fs.readFileSync(filePath)
console.log("fileToSign",fileToSign)
const keccak256hash = EthUtil.keccak256(fileToSign);
console.log("keccak256hash",keccak256hash)
const messageHash = keccak256hash.toString('hex');
const privateKey=private_key;
const ecSignature = EthUtil.ecsign(keccak256hash, new Buffer(privateKey, 'hex') )
console.log("signature 2", ecSignature)
let v = EthUtil.bufferToHex(ecSignature.v);
let r = EthUtil.bufferToHex(ecSignature.r);
let s = EthUtil.bufferToHex(ecSignature.s);
console.log("v ",v,ecSignature.v)
console.log("r ",r)
console.log("s ",s)
const aggregatedSignature= r+s.substring(2)+v.substring(2);
const qrUrl= {'hash':messageHash, 'signature':aggregatedSignature,'publicKey':public_key};
let objJsonStr = JSON.stringify(qrUrl);
let base64Qr = Buffer.from(objJsonStr).toString("base64");
const [file] = await knex('files')
.insert({
owner_id:userId,
file_name:filename||'file',
signature:aggregatedSignature,
hash: messageHash,
signed_at:new Date(),
type:'signed',
description:description,
path:filePath,
qrcode:base64Qr,
})
.returning(['file_name', 'signature','hash','qrcode']);
return file;
}
async function createfile(fileName_,issuer_,recipient_,issuerId_,message_,path_) {
const [request] = await knex('requests')
.insert({
fileName:fileName_,
issuer:issuer_,
recipient: recipient_,
description: message_,
issuerId: issuerId_,
status:"En attente",
path:path_,
})
.returning(['fileName', 'recipient']);
return request;
}
async function getPrivateKey(id) {
const [pkey] = await knex('users')
.where('id', id)
.select('private_key');
return pkey;
}
module.exports = {
createfile,
getAllRequests,
getUser,
signFile,
getPrivateKey,
update_request_status,
getAllSentRequests,
};
|
#!/usr/bin/env bash
set -ex
docker network create web
touch /opt/traefik/acme.json
chmod 600 /opt/traefik/acme.json
|
@extends("auth.plantillaLogForm")
@section("htmlheader_title")
Notas Meritos
@endsection
@section("infoGeneral")
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="card mt-5">
<!---cabeza-->
<div class="card-header text-white">
<h2>Postulante: {{Auth::user()->name}} {{Auth::user()->lastname}}</h2>
<h2>Auxiliatura: {{Auth::user()->requerimientos->first()->nombre_auxiliatura}}</h2>
<h2>Nota Meritos: {{$postulante}}</h2>
@if(isset($calf))
@if($calf->publicado=="si")
<h2>Nota Conocimiento: {{$calf->score}}</h2>
<h2>Nota Final: {{$calf->score + $postulante}}</h2>
@endif
@endif
</div>
</div>
</div>
</div>
</div>
@endsection |
# running convert makes Rake to create all File tasks for Thumbs
desc 'convert to thumbs'
task :convert => THUMBS
file "final.png" => THUMBS do
sh "convert #{THUMBS} -append final.png"
end
desc 'merge thumbs to one'
task :merge => "final.png"
|
import 'dart:convert';
import 'package:test/test.dart';
import '../../lib/src/errors/ApplicationException.dart';
//import '../../lib/src/data/StringValueMap.dart';
void main() {
group('ApplicationException', () {
ApplicationException _appEx;
Exception _ex;
var Category = 'category';
var CorrelationId = 'correlationId';
var Code = 'code';
var Message = 'message';
setUp(() {
_ex = Exception('Cause exception');
_appEx = ApplicationException(Category, CorrelationId, Code, Message);
});
test('With Cause', () {
_appEx.withCause(_ex);
expect(_appEx.cause, equals(_ex.toString()));
});
test('Check Parameters', () {
expect(_appEx.category, equals(Category));
expect(_appEx.correlation_id, equals(CorrelationId));
expect(_appEx.code, equals(Code));
expect(_appEx.message, equals(Message));
});
test('With Code', () {
var newCode = 'newCode';
var appEx = _appEx.withCode(newCode);
expect(appEx, equals(_appEx));
expect(appEx.code, equals(newCode));
});
test('With CorrelationId', () {
var newCorrelationId = 'newCorrelationId';
var appEx = _appEx.withCorrelationId(newCorrelationId);
expect(appEx, equals(_appEx));
expect(appEx.correlation_id, equals(newCorrelationId));
});
test('With Status', () {
var newStatus = 777;
var appEx = _appEx.withStatus(newStatus);
expect(appEx, equals(_appEx));
expect(appEx.status, equals(newStatus));
});
test('With Details', () {
var key = 'key';
var obj = {};
var appEx = _appEx.withDetails(key, obj);
//var newObj = appEx.details.getAsObject(key);
expect(appEx, equals(_appEx));
});
test('With Stack Trace', () {
var newTrace = 'newTrace';
var appEx = _appEx.withStackTrace(newTrace);
expect(appEx, equals(_appEx));
expect(appEx.stack_trace, equals(newTrace));
});
test('JSON serialization', () {
var key = 'key';
var details = 'details';
_appEx.category = 'category';
_appEx.correlation_id = 'correlationId';
_appEx.code = 'code';
_appEx.message = 'message';
_appEx.status = 777;
_appEx.cause = 'cause';
_appEx.stack_trace = 'stackTrace';
_appEx.withDetails(key, details);
var json = jsonEncode(_appEx);
var appEx2 = ApplicationException.fromJson(jsonDecode(json));
expect(appEx2, isNotNull);
expect(appEx2.category, equals(_appEx.category));
expect(appEx2.correlation_id, equals(_appEx.correlation_id));
expect(appEx2.code, equals(_appEx.code));
expect(appEx2.message, equals(_appEx.message));
expect(appEx2.status, equals(_appEx.status));
expect(appEx2.cause, equals(_appEx.cause));
expect(appEx2.stack_trace, equals(_appEx.stack_trace));
expect(appEx2.details, equals(_appEx.details.getValue()));
});
});
}
|
#!/bin/sh
docker run --user 4000 \
--security-opt=no-new-privileges \
--cap-drop ALL \
--read-only \
--tmpfs /tmp \
--volume "$(pwd)"/www:/var/www/localhost/htdocs \
--publish 80:1337 funcgi:"$1"
|
l = @latexify dummyfunc(x; y=1, z=3) = x^2/y + z
@test l == raw"$\mathrm{dummyfunc}\left( x; y = 1, z = 3 \right) = \frac{x^{2}}{y} + z$"
@test_throws UndefVarError dummyfunc(1.)
l2 = @latexrun dummyfunc2(x; y=1, z=3) = x^2/y + z
@test l2 == raw"$\mathrm{dummyfunc2}\left( x; y = 1, z = 3 \right) = \frac{x^{2}}{y} + z$"
@test dummyfunc2(1.) == 4
l3 = @latexify dummyfunc2(x::Number; y=1, z=3) = x^2/y + z
@test l3 == raw"$\mathrm{dummyfunc2}\left( x::Number; y = 1, z = 3 \right) = \frac{x^{2}}{y} + z$"
l4 = @latexify dummyfunc2(::Number; y=1, z=3) = x^2/y + z
@test l4 == raw"$\mathrm{dummyfunc2}\left( ::Number; y = 1, z = 3 \right) = \frac{x^{2}}{y} + z$"
|
namespace FORCEBuild.Net.RPC.Interface
{
/// <summary>
/// 服务工厂,远程客户端调用以创建服务
/// </summary>
public interface IServiceFactory
{
T CreateService<T>();
}
} |
class CreateAssignmentQuestionnaires < ActiveRecord::Migration
def self.up
begin
drop_table :assignments_questionnaires
rescue
end
create_table :assignment_questionnaires do |t|
t.column :assignment_id, :integer, :null => true
t.column :questionnaire_id, :integer, :null => true
t.column :user_id, :integer, :null => true
t.column :notification_limit, :integer, :null => false, :default => 15
t.column :questionnaire_weight, :integer, :null => false, :default => 0
end
execute 'ALTER TABLE `assignment_questionnaires`
ADD CONSTRAINT fk_aq_user_id
FOREIGN KEY (user_id) REFERENCES users(id)'
execute 'ALTER TABLE `assignment_questionnaires`
ADD CONSTRAINT fk_aq_assignments_id
FOREIGN KEY (assignment_id) REFERENCES assignments(id)'
execute 'ALTER TABLE `assignment_questionnaires`
ADD CONSTRAINT fk_aq_questionnaire_id
FOREIGN KEY (questionnaire_id) REFERENCES questionnaires(id)'
Assignment.find_each{
| assignment |
make_association('ReviewQuestionnaire', assignment, assignment.review_questionnaire_id)
make_association('MetareviewQuestionnaire', assignment, assignment.review_of_review_questionnaire_id)
make_association('AuthorFeedbackQuestionnaire', assignment, assignment.author_feedback_questionnaire_id)
make_association('TeammateReviewQuestionnaire', assignment, assignment.teammate_review_questionnaire_id)
}
l_records = ActiveRecord::Base.connection.select_all("select * from notification_limits")
l_records.each{
|l|
begin
association = AssignmentQuestionnaire.create(:user_id => l['user_id'], :notification_limit => l['limit'])
rescue
puts $!
end
}
drop_table :questionnaire_weights
drop_table :notification_limits
end
def self.make_association(model, assignment, questionnaire_id)
begin
q = Object.const_get(model).find(questionnaire_id)
association = AssignmentQuestionnaire.create(:assignment_id => assignment.id, :questionnaire_id => q.id)
l_records = ActiveRecord::Base.connection.select_all("select * from notification_limits where assignment_id = #{assignment.id} and questionnaire_id = #{q.id}")
w_records = ActiveRecord::Base.connection.select_all("select * from questionnaire_weights where assignment_id = #{assignment.id} and questionnaire_id = #{q.id}")
if l_records.length > 0
association.update_attribute("user_id",l_records[0]['user_id'])
association.update_attribute("notification_limit",l_records[0]['limit'])
execute "delete from notification_limits where assignment_id = #{assignment.id} and questionnaire_id = #{q.id}"
end
if w_records.length > 0
association.update_attribute("questionnaire_weight",w_records[0]['weight'])
execute "delete from questionnaire_weights where assignment_id = #{assignment.id} and questionnaire_id = #{q.id}"
end
if association.user_id.nil?
association.update_attribute("user_id",assignment.instructor_id)
end
rescue
puts "Assignment: #{assignment.id}"
puts " "+$!
end
end
def self.down
drop_table :assignment_questionnaires
end
end
|
class WatchList::DSL::Context::Monitor
class Keyword < HTTP
def result
[:KeywordType, :KeywordValue].each do |key|
raise %!Monitor `#{@monitor_name}`: "#{key.to_s.downcase}" is required! unless @result[key]
end
super
end
def keywordtype(value)
if value.kind_of?(Integer)
type = value
else
type = WatchList::Monitor::KeywordType[value.to_s]
end
unless WatchList::Monitor::KeywordType.values.include?(type)
raise %!Monitor `#{@monitor_name}`: "keywordtype" is invalid: #{value.inspect}!
end
@result[:KeywordType] = type
end
def keywordvalue(value)
raise %!Monitor `#{@monitor_name}`: "keywordvalue" is invalid: #{value.inspect}! if value.nil?
@result[:KeywordValue] = WatchList::Secure.decrypt_if_possible(value).to_s
end
end
end
|
#pragma once
// Header file for neighGraphPipe class - see neighGraphPipe.cpp for descriptions
#include <map>
#include "basePipe.hpp"
template<typename nodeType>
class neighGraphPipe : public basePipe<nodeType> {
private:
double epsilon;
int dim;
public:
neighGraphPipe();
void runPipe(pipePacket<nodeType>&);
void outputData(pipePacket<nodeType>&);
bool configPipe(std::map<std::string, std::string>&);
};
|
class AdminMailer < ApplicationMailer
include SettingsHelper
def new_user(user)
@user = user
mail to: admin_auth_email, subject: "[#{competition_name}] New User"
end
end
|
docker service create --name demo-app --network demo-app-net \
--publish 80:80 \
--constraint 'node.hostname == swarm-mgr' \
demo-app-img
|
part of 'mocktail.dart';
/// {@template real_call}
/// A real invocation on a mock.
/// {@endtemplate}
class RealCall {
/// {@macro real_call}
RealCall(this.mock, this.invocation) : timeStamp = _timer.now();
/// The mock instance.
final Mock mock;
/// The invocation.
final Invocation invocation;
/// When the invocation occurred.
final DateTime timeStamp;
/// Whether it was verified.
bool verified = false;
@override
String toString() {
var verifiedText = verified ? '[VERIFIED] ' : '';
return '$verifiedText$mock.${invocation.toPrettyString()}';
}
}
/// {@template real_call_with_captured_args}
/// A simple struct for storing a [RealCall] and any [capturedArgs] stored
/// during `InvocationMatcher.match`.
/// {@endtemplate}
class RealCallWithCapturedArgs {
/// {@macro real_call_with_captured_args}
const RealCallWithCapturedArgs(this.realCall, this.capturedArgs);
/// The [RealCall] instance.
final RealCall realCall;
/// Any captured arguments.
final List<Object?> capturedArgs;
}
extension on Invocation {
/// Returns a pretty String representing a method (or getter or setter) call
/// including its arguments, separating elements with newlines when it should
/// improve readability.
String toPrettyString() {
String argString;
var args = positionalArguments.map((dynamic v) => '$v');
if (args.any((arg) => arg.contains('\n'))) {
// As one or more arg contains newlines, put each on its own line, and
// indent each, for better readability.
argString =
'''\n${args.map((arg) => arg.splitMapJoin('\n', onNonMatch: (m) => ' $m')).join(',\n')}''';
} else {
// A compact String should be perfect.
argString = args.join(', ');
}
if (namedArguments.isNotEmpty) {
if (argString.isNotEmpty) argString += ', ';
var namedArgs = namedArguments.keys
.map((key) => '${_symbolToString(key)}: ${namedArguments[key]}');
if (namedArgs.any((arg) => arg.contains('\n'))) {
// As one or more arg contains newlines, put each on its own line, and
// indent each, for better readability.
namedArgs = namedArgs
.map((arg) => arg.splitMapJoin('\n', onNonMatch: (m) => ' $m'));
argString += '{\n${namedArgs.join(',\n')}}';
} else {
// A compact String should be perfect.
argString += '{${namedArgs.join(', ')}}';
}
}
var method = _symbolToString(memberName);
if (isMethod) {
method = '$method($argString)';
} else if (isGetter) {
method = '$method';
} else if (isSetter) {
method = '$method=$argString';
} else {
throw StateError('Invocation should be getter, setter or a method call.');
}
return method;
}
}
// Converts a [Symbol] to a meaningful [String].
String _symbolToString(Symbol symbol) => symbol.toString().split('"')[1];
|
/*
* Copyright 2021 The Android Open Source Project
*
* 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 androidx.appsearch.observer;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.ObjectsCompat;
import androidx.core.util.Preconditions;
/**
* Contains information about an individual change detected by an {@link AppSearchObserverCallback}.
*
* <p>This class reports information about document changes, i.e. when documents were added, updated
* or removed.
*
* <p>Changes are grouped by package, database, schema type and namespace. Each unique
* combination of these items will generate a unique {@link DocumentChangeInfo}.
*
* <p>Note that document changes that happen during schema migration from calling
* {@link androidx.appsearch.app.AppSearchSession#setSchema} are not reported via this class.
* Such changes are reported through {@link SchemaChangeInfo}.
*/
public final class DocumentChangeInfo {
private final String mPackageName;
private final String mDatabase;
private final String mNamespace;
private final String mSchemaName;
// TODO(b/193494000): Add the set of changed document IDs to this class
/**
* Constructs a new {@link DocumentChangeInfo}.
*
* @param packageName The package name of the app which owns the documents that changed.
* @param database The database in which the documents that changed reside.
* @param namespace The namespace in which the documents that changed reside.
* @param schemaName The name of the schema type that contains the changed documents.
*/
public DocumentChangeInfo(
@NonNull String packageName,
@NonNull String database,
@NonNull String namespace,
@NonNull String schemaName) {
mPackageName = Preconditions.checkNotNull(packageName);
mDatabase = Preconditions.checkNotNull(database);
mNamespace = Preconditions.checkNotNull(namespace);
mSchemaName = Preconditions.checkNotNull(schemaName);
}
/** Returns the package name of the app which owns the documents that changed. */
@NonNull
public String getPackageName() {
return mPackageName;
}
/** Returns the database in which the documents that was changed reside. */
@NonNull
public String getDatabaseName() {
return mDatabase;
}
/** Returns the namespace of the documents that changed. */
@NonNull
public String getNamespace() {
return mNamespace;
}
/** Returns the name of the schema type that contains the changed documents. */
@NonNull
public String getSchemaName() {
return mSchemaName;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) return true;
if (!(o instanceof DocumentChangeInfo)) return false;
DocumentChangeInfo that = (DocumentChangeInfo) o;
return mPackageName.equals(that.mPackageName)
&& mDatabase.equals(that.mDatabase)
&& mNamespace.equals(that.mNamespace)
&& mSchemaName.equals(that.mSchemaName);
}
@Override
public int hashCode() {
return ObjectsCompat.hash(mPackageName, mDatabase, mNamespace, mSchemaName);
}
@NonNull
@Override
public String toString() {
return "DocumentChangeInfo{"
+ "packageName='" + mPackageName + '\''
+ ", database='" + mDatabase + '\''
+ ", namespace='" + mNamespace + '\''
+ ", schemaName='" + mSchemaName + '\''
+ '}';
}
}
|
export type OutgoingMessage =
| PortInformationRequestOutgoingMessage
| PortModeInformationRequestOutgoingMessage
| PortInputFormatSetupOutgoingMessage
| PortOutputCommandOutgoingMessage;
/**
* https://lego.github.io/lego-ble-wireless-protocol-docs/index.html#port-information-request
*/
export interface PortInformationRequestOutgoingMessage {
readonly messageType: 'PortInformationRequest'; // 0x21
readonly portId: number;
readonly portInformationRequestType: 'PortValue' | 'ModeInfo';
}
/**
* https://lego.github.io/lego-ble-wireless-protocol-docs/index.html#port-mode-information-request
*/
export interface PortModeInformationRequestOutgoingMessage {
readonly messageType: 'PortModeInformationRequest'; // 0x22
readonly portId: number;
readonly modeId: number;
readonly portModeInformationRequestType: PortModeInformationRequestType;
}
export type PortModeInformationRequestType =
| 'Name'
| 'Raw'
| 'Pct'
| 'Si'
| 'Symbol'
| 'ValueFormat';
/**
* https://lego.github.io/lego-ble-wireless-protocol-docs/index.html#port-input-format-setup-single
*/
export interface PortInputFormatSetupOutgoingMessage {
readonly messageType: 'PortInputFormatSetup'; // 0x41
readonly portId: number;
readonly modeId: number;
readonly deltaInterval: number;
readonly notificationsEnabled: boolean;
}
/**
* https://lego.github.io/lego-ble-wireless-protocol-docs/index.html#port-output-command
*/
export interface PortOutputCommandOutgoingMessage {
readonly messageType: 'PortOutputCommand'; // 0x81
readonly portId: number;
readonly portOutputSubCommandData: ArrayBuffer;
}
|
# stdx-dev – the missing development batteries of Rust
New to Rust development and don't know how to improve your development?
stdx-dev [has the best tools](#about-stdx-dev).
First, you're going to want to write Rust code using your favorite editor or
IDE, whether that's [emacs], [vi] or [sublime text], [Eclipse] or [IntelliJ],
[Atom] or [VSCode] – or something else entirely. Most tools seem to coalesce
around [racer] and the nascent [RLS] (Rust Language Server). See
[Are we IDE yet?](https://areweideyet.com/) for further information.
[emacs]: https://github.com/rust-lang/rust-mode
[vi]: https://github.com/rust-lang/rust.vim
[sublime Text]: https://github.com/rust-lang/sublime-rust
[Eclipse]: https://rustdt.github.io/
[IntelliJ]: https://plugins.jetbrains.com/idea/plugin/8182-rust
[Atom]: https://github.com/vertexclique/tokamak
[VSCode]: https://github.com/saviorisdead/RustyCode
[racer]: https://github.com/phildawes/racer
[RLS]: https://github.com/jonathandturner/rls
### A Note About Nightly
Some tools require a nightly Rust compiler to work. This is usually not a
problem, because it's easy enough to run different Rust versions side by side
thanks to [rustup], and most of those tools are only needed while developing
software and either don't factor into or can easily be removed from the final
build. Nevertheless, not everyone wants to maintain a nightly Rust version for
tooling, so we'll mark the respective crates with a <kbd>⚠ nightly only</kbd>
label.
If you want to have a nightly version, and already have rustup, just type
`rustup install nightly` into your console. To update to the newest version,
use `rustup update nightly`.
[rustup]: https://rustup.rs
With that out of the way, here are the goods:
|feature |crate |
|------------------------|-------------------------|
|code style / correctness|[clippy](#clippy) |
|formatting |[rustfmt](#rustfmt) |
|random testing |[quickcheck](#quickcheck)|
|benchmarks |[bencher](#bencher) |
|profiling |[flame](#flame) |
|dependency management |[cargo-edit](#cargo-edit)|
|dependency management |[cargo-outdated](#cargo-outdated)|
|dependency author listing|[cargo-authors](#cargo-authors)|
# Clippy
[Crate](https://crates.io/crates/clippy) |
[Repository](https://github.com/Manishearth/rust-clippy) |
[Docs](https://github.com/Manishearth/rust-clippy/wiki) |
[MPL-2.0] | <kbd>⚠ nightly only</kbd>
More than 180 lints (at the time of this writing) catch bugs and unfortunate
patterns and give helpful suggestions.
Install and run clippy with:
```sh
cargo +nightly install clippy # install clippy, add "-f" to upgrade existing
cargo +nightly clippy # runs clippy on the current project
```
This will likely give you a list of warnings and suggestions. While there
remain some false positives (and negatives), the overall quality is quite good,
and having worked extensively with clippy, I can attest that it sharpens the
newcomer's intuition about what rustic code makes.
Many IDEs can use clippy within their workflow. Also there's an experimental
[rustfix](https://github.com/killercup/rustfix) tool to auto-apply some of the
suggestions (Warning: Will eat your code).
# RustFMT
[Crate](https://crates.io/crates/rustfmt) |
[Repository](https://github.com/rust-lang-nursery/rustfmt) |
[Docs](https://github.com/rust-lang-nursery/rustfmt/blob/master/README.md) |
[MIT] / [Apache-2.0]
This program will format your code according to some "default" style. It is
highly configurable and will only occasionally eat your laundry.
Install with `cargo install rustfmt` (add `-f` to update an existing
installation) and run with `cargo fmt` for a whole project or `rustfmt <file>`
to format a single file. There are multiple modes of operation, e.g. output as
diff. Check out the documentation for further assistance.
# Quickcheck
[Crate](https://crates.io/crates/quickcheck) |
[Repository](https://github.com/burntsushi/quickcheck) |
[Docs](http://burntsushi.net/rustdoc/quickcheck/) |
[MIT] / [Unlicense]
This is a crate you can use to generate a series of random inputs for your
tests and *reduce* the input in case of test failure.
If you have [cargo-edit], you can type `cargo add --dev quickcheck` into a
command line in your crate root. Otherwise, add the following to your
`Cargo.toml` manually:
```toml
[dev-dependencies]
quickcheck = "0.4"
```
Now you can use quickcheck in your tests! The easiest way is:
```rust
#[macro_use] extern crate quickcheck;
quickcheck! {
// any predicate of any type that has an `Arbitrary` implementation
// most default types already have one
fn check_it(a: usize, b: usize) -> bool {
a == b || a != b
}
}
```
# Bencher
[Crate](https://crates.io/crates/bencher) |
[Repository](https://github.com/bluss/bencher) |
[Docs](https://docs.rs/bencher) |
[MIT] / [Apache-2.0]
Rust has an internal benchmarking tool, but it's only available on nightly
behind a feature gate. This package makes benchmarks available on stable.
You'll need the following incantations in your `Cargo.toml`:
```toml
[dev-dependencies]
bencher = "0.1"
# and for each file:
[[bench]]
name = "bench_something"
harness = false
```
Now we can add `src/bench_something.rs`:
```Rust
#[macro_use] extern crate bencher;
fn bench_mul(b: &mut bencher::Bencher) {
let i = 1;
b.iter(|| i * i);
}
// set up the benchmarks group
benchmark_group!(bench, bench_mul); // <- can add more benchmarks here
// and run it
benchmark_main!(bench);
```
This can be run with the usual `cargo bench`.
# Flame
[Crate](https://crates.io/crates/flame) |
[Repository](https://github.com/TyOverby/flame) |
[Docs](https://docs.rs/flame) |
[MIT] / [Apache-2.0]
Flame is a library that allows you to stopwatch your code and see the result
rendered as a flame graph. There is also the (<kbd>⚠ nightly only</kbd>)
[flamer] plugin that lets you annotate your crates/modules/items to insert
flame trace points.
[flamer]: https://github.com/llogiq/flamer
Code augmented by `flame` can look like the following:
```Rust
extern crate flame;
fn foo() {
flame::start("foo");
let result = ...;
flame::end("foo");
return result;
}
fn main() {
flame::start("main");
let foo = foo();
...
flame::end("main");
}
```
The resulting flame graph can look like this:
https://raw.githubusercontent.com/TyOverby/flame/master/resources/screenshot.png
# cargo-edit
[Crate](https://crates.io/crates/cargo-edit) |
[Repository](https://github.com/killercup/cargo-edit) |
[Docs](https://github.com/killercup/cargo-edit/blob/master/README.md) |
[MIT] / [Apache-2.0]
This crate gives you the `cargo add`, `cargo rm` and `cargo list` subcommands,
allowing for easy dependency management from the command line. Refer to the
docs for further information.
# cargo-outdated
[Crate](https://crates.io/crates/cargo-outdated) |
[Repository](https://github.com/kbknapp/cargo-outdated) |
[Docs](https://github.com/kbknapp/cargo-outdated/blob/master/README.md) |
[MIT]
This crate gives you the `cargo outdated` subcommand which displays when
dependencies have newer versions available.
# cargo-authors
[Crate](https://crates.io/crates/cargo-authors) |
[Repository](https://github.com/Henning-K/cargo-authors) |
[Docs](https://github.com/Henning-K/cargo-authors/blob/master/README.md) |
[MIT] / [Apache-2.0]
This crate gives you the `cargo authors` subcommand which lists all the
authors of all the dependencies of the crate in your current working directory.
----
# About stdx-dev
The [stdx](https://github.com/brson/stdx) curated list of crates has some great
crates that you can build on, but it lacks all kinds of crates that make
*development* with Rust even more awesome.
So I'm going to try and list them here. If you find any crate I've missed, file
an issue or a PR. Thank you!
The contents of this repository are licensed under [MIT] / [Apache-2.0], at
your discretion.
[Apache-2.0]: http://www.apache.org/licenses/LICENSE-2.0
[MIT]: http://opensource.org/licenses/MIT
[MPL-2.0]: https://www.mozilla.org/MPL/2.0/
[Unlicense]: http://unlicense.org/
|
module Data.Format.NetCDF.LowLevel.Variable(
module Data.Format.NetCDF.LowLevel.Variable.Internal
) where
import Data.Format.NetCDF.LowLevel.Variable.Internal hiding (mkSomeNCVariable)
|
const uuid = require('uuid');
module.exports.createData = {
taskId: uuid.v1(),
datePosted: Date.now(),
status: "Incomplete",
task: "My task."
}
module.exports.updateData = {
datePosted: Date.now(),
status: "Complete",
task: "My task. Has been finished!"
}
|
const fs = require('fs');
const pathToHTML = './build/index.html';
if (!fs.existsSync(pathToHTML)) {
throw new Error("index.html file doesn't exist");
}
const fontsPrefix = '/static/media/';
const pathToFonts = './build' + fontsPrefix;
if (!fs.existsSync(pathToFonts)) {
throw new Error("Fonts directory doesn't exist");
}
const files = fs.readdirSync(pathToFonts);
const fontBundles = new RegExp(/[-a-z0-9_]+\.[a-z0-9]+\.woff2$/gi);
const preloadLinks = files
.filter(f => fontBundles.test(f))
.map(
f =>
`<link rel="preload" href="${fontsPrefix}${f}" as="font" type="font/woff2" crossorigin>`
);
if (!preloadLinks.length) {
throw new Error('Fonts for preload are not found');
}
fs.readFile(pathToHTML, (err, data) => {
if (err) {
throw err;
}
const parts = data.toString().split('</title>');
fs.writeFile(
pathToHTML,
[parts[0], '</title>', ...preloadLinks, parts[1]].join(''),
err => {
if (err) {
throw err;
}
console.log('Saved preload tags to index.html');
}
);
});
|
// Copyright 2018, Goomba project Authors. All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with this
// work for additional information regarding copyright ownership. The ASF
// licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
/*
Package gossiper implements a gossip network protocol. It is intended only for
fun and learning.
Gossip protocols are network protocols where each machine, each peer, does not
have a complete list of all peers. Instead, it knows only a subset of them. In
order to spread a message to all the peers, every gossiper transmits the
message to all the peers it knows, in turn, each transmits it to all the peers
it knows and so on. As long as the set of peers is connected, the message will
eventually reach everyone.
The best-known examples of gossip protocols are the Network News (RFC-1036) and
BGP (RFC 4271).
An important part of a gossip protocol is the history: peers must remember
which messages they sent, to avoid wasting time (or, worse, creating endless
loops) with peers which already know the message.
Note that a successful gossip protocol does not require every pair of peers to
communicate by the same means (Network News is a good example: not everyone
uses NNTP). But, in this simple example, the protocol between two peers is
fixed. Every peer has an ID, set at startup. The "server" (the peer which
replied to the connection) sends its ID followed by a comma. The "client" (the
peer which initiated the connection) sends its ID followed by a comma and by
the message (one line only). In this implementation, for each peer, only a
tuple (IP address, port) is used to connect but it is not imposed by the
protocol (machines are identified by the ID, not by the IP address).
Peers remember the messages they have seen (in the global history) and the
messages they sent to each peer (in a per-peer history).
This package is still in R&D, so there is no code yet available.
*/
package gossiper
|
package sdk.guru.common;
import io.reactivex.annotations.Nullable;
public class Optional<T> {
private final T optional;
public Optional() {
this(null);
}
public Optional(@Nullable T optional) {
this.optional = optional;
}
public boolean isEmpty() {
return this.optional == null;
}
public T get() {
return optional;
}
public static <T> Optional<T> empty() {
return new Optional<>();
}
public static <T> Optional<T> with(T value) {
return new Optional<>(value);
}
}
|
using System;
namespace Interface1
{
interface IinterfaceOne
{
//string stringFieldOne = "stringFieldOne";
//public string stringPropertyOne { get; set; } = "stringPropertyOne";
//public string stringPropertyOne { get; set; }
//IinterfaceOne() { }
//void MethodOne()
//{
// Console.WriteLine("MethodOne");
//}
void MethodNoBody();
}
class ClassOne : IinterfaceOne
{
public void MethodNoBody()
{
Console.WriteLine("ClassOne : IinterfaceOne");
}
}
class Program
{
static void Main(string[] args)
{
//interface IinterfaceOne { }
ClassOne classOne = new ClassOne();
classOne.MethodNoBody();
}
}
}
|
package io.github.erikjhordanrey.cleanarchitecture.ui;
import io.github.erikjhordanrey.cleanarchitecture.RxAndroidRule;
import io.github.erikjhordanrey.cleanarchitecture.domain.usecase.GetTeamsUseCase;
import io.github.erikjhordanrey.cleanarchitecture.fake.FakeTeamLocalAPI;
import io.github.erikjhordanrey.cleanarchitecture.view.model.mapper.TeamToTeamUiMapper;
import io.github.erikjhordanrey.cleanarchitecture.view.presenter.TeamsPresenter;
import io.reactivex.rxjava3.core.Observable;
import java.util.Collections;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import static org.mockito.BDDMockito.given;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class TeamsPresenterTest {
@ClassRule public static RxAndroidRule blockingRxAndroidTestRule = new RxAndroidRule();
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock private TeamsPresenter.View view;
@Mock private GetTeamsUseCase getTeamsUseCase;
@Mock private TeamToTeamUiMapper teamToTeamUiMapper;
private TeamsPresenter teamsPresenter;
@Before
public void setUp() {
teamsPresenter = new TeamsPresenter(getTeamsUseCase, teamToTeamUiMapper);
teamsPresenter.setView(view);
}
@Test
public void showTeamsWhenRetrieveTeamsSuccessfully() {
given(getTeamsUseCase.getTeamList()).willReturn(Observable.just(FakeTeamLocalAPI.getFakeTeamList()));
teamsPresenter.initialize();
InOrder order = Mockito.inOrder(view);
order.verify(view).showLoading();
order.verify(view).showEuroTeams(Collections.emptyList());
order.verify(view).hideLoading();
verifyNoMoreInteractions(view);
}
@Test
public void showErrorWhenRetrieveTeamsFails() {
given(getTeamsUseCase.getTeamList()).willReturn(Observable.error(new Throwable("Error getting teams")));
teamsPresenter.initialize();
InOrder order = Mockito.inOrder(view);
order.verify(view).showLoading();
order.verify(view).hideLoading();
verifyNoMoreInteractions(view);
}
}
|
package def
import (
"masterserver/data"
"masterserver/database"
"masterserver/server"
"share/rpc"
"github.com/jmoiron/sqlx"
)
var ServerConfig = &Config{}
var ServerSettings = &Settings{}
var RPCHandler = &rpc.Server{}
var LoginDatabase = &sqlx.DB{}
var ServerManager = &server.ServerManager{}
var DatabaseManager = &database.DatabaseManager{}
var DataLoader = &data.Loader{}
|
from IMLearn.utils import split_train_test
from IMLearn.learners.regressors import LinearRegression
from typing import NoReturn
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
data = pd.read_csv(filename).dropna()
data.drop(data[(data["id"] == 0)].index, inplace=True)
features = ["bedrooms", "bathrooms", "sqft_living", "sqft_lot",
"waterfront", "view", "condition", "grade", "sqft_above",
"sqft_basement"]
floors = pd.get_dummies(data["floors"])
house_age = data["yr_built"] - pd.to_numeric(data["date"].astype(
str).apply(lambda x: x[:4]))
years_from_renovation = data["yr_renovated"] - pd.to_numeric(data[
"date"].astype(str).apply(lambda x: x[:4]))
last_renovation_or_built_year = pd.concat([house_age,
years_from_renovation],
axis=1).max(axis=1)
data["zipcode"] = (data["zipcode"] / 10).astype(int)
zipcodes = pd.get_dummies(data["zipcode"], prefix="zipcode-")
x = pd.concat([floors, data[features], zipcodes], axis=1)
x.insert(0, "house_age", house_age)
x.insert(0, "last_renovation_or_built_year", last_renovation_or_built_year)
return (x, data["price"])
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str =
".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- Plot saved under given folder with file name including feature name
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Design matrix of regression problem
y : array-like of shape (n_samples, )
Response vector to evaluate against
output_path: str (default ".")
Path to folder in which plots are saved
"""
for col in X.columns:
feature = X[col]
pearson_correlation = np.cov(feature, y)[0, 1] / (np.sqrt(np.var(
feature) * np.var(y)))
layout = go.Layout(title=f"Pearson Correlation between {col} and "
f"response: {pearson_correlation}",
xaxis={"title": f"x - {col} values"},
yaxis={"title": "y - response values"})
fig = go.Figure([go.Scatter(x=feature, y=y, mode="markers")],
layout=layout)
fig.show()
fig.write_image(f"{output_path}{col}.png", format="png")
if __name__ == '__main__':
np.random.seed(0)
# Question 1 - Load and preprocessing of housing prices dataset
x, y = load_data("C:\\Users\\rotem\\IML.HUJI\\datasets\\house_prices.csv")
# Question 2 - Feature evaluation with respect to response
feature_evaluation(x, y, "../")
# Question 3 - Split samples into training- and testing sets.
train_x, train_y, test_x, test_y = split_train_test(x, y, 0.75)
# Question 4 - Fit model over increasing percentages of the overall
# training data
# For every percentage p in 10%, 11%, ..., 100%, repeat the following 10
# times:
# 1) Sample p% of the overall training data
# 2) Fit linear model (including intercept) over sampled set
# 3) Test fitted model over test set
# 4) Store average and variance of loss over test set
# Then plot average loss as function of training size with error ribbon of
# size (mean-2*std, mean+2*std)
precentage_range = np.arange(10, 101, 1)
std_vals = []
mean_vals = []
linearregression = LinearRegression()
for p in precentage_range:
losses = []
for i in range(10):
p_train_x, p_train_y, p_test_x, p_test_y = split_train_test(x, y,
(p / 100))
linearregression.fit(p_train_x.to_numpy(), p_train_y.to_numpy())
losses.append(
linearregression.loss(test_x.to_numpy(), test_y.to_numpy()))
mean_vals.append(np.mean(losses))
std_vals.append(np.std(losses))
mean_vals = np.array(mean_vals)
std_vals = np.array(std_vals)
fig = go.Figure(
[go.Scatter(x=precentage_range, y=mean_vals, mode="markers+lines",
name="Mean Prediction", line=dict(dash="dash"),
marker=dict(color="red", opacity=.7)),
go.Scatter(x=precentage_range, y=mean_vals - 2 * std_vals,
fill=None, mode="lines",
line=dict(color="lightgrey"),
showlegend=False),
go.Scatter(x=precentage_range, y=mean_vals + 2 * std_vals,
fill='tonexty', mode="lines",
line=dict(color="lightgrey"),
showlegend=False), ],
layout=go.Layout(
title=r"$\text{The mean loss as function of p%}$",
xaxis_title="$\\text{percentage}$",
yaxis_title="$\\text{mean loss}$"))
fig.show() |
module Bitcoin
module Message
# Base message class
class Base
include Bitcoin::HexConverter
include Bitcoin::Util
extend Bitcoin::Util
# generate message header (binary format)
# https://bitcoin.org/en/developer-reference#message-headers
def to_pkt
payload = to_payload
magic = Bitcoin.chain_params.magic_head.htb
command_name = self.class.const_get(:COMMAND, false).ljust(12, "\x00")
payload_size = [payload.bytesize].pack('V')
checksum = Bitcoin.double_sha256(payload)[0...4]
magic << command_name << payload_size << checksum << payload
end
# abstract method
def to_payload
raise 'to_payload must be implemented in a child class.'
end
end
end
end
|
model-import-export
===================
Imports and Exports django model to excel and csv
Requirement
-----------
python >= 3
Django 1.11.5, >= 2.11
Installation
------------
pip install model-import-export
Usage
-----
**Creating resources**
In your `example_app/resources.py`
```python
from model_import_export.resources import ModelResource, ForeignKeyResource, ManyToManyResource
from dashboard.models import *
class UserResource(ModelResource):
class Meta:
model = User
fields = '__all__'
```
**Exporting model**
```python
from .resources import UserResource
queryset = User.objects.all()
resource = UserResource(queryset)
resource.to_excel('users.xlsx')
```
**Importing model**
```python
resource = UserResource()
resource.from_excel('users.xlsx')
```
## Model Import/Export Example

|
package ao.httpstatuscode.romavicdosanjoskc.ui
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.ContentLoadingProgressBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ao.httpstatuscode.romavicdosanjos.statusCode.*
import ao.httpstatuscode.romavicdosanjoskc.R
import ao.httpstatuscode.romavicdosanjoskc.network.api.ApiClient.apiClient
import ao.httpstatuscode.romavicdosanjoskc.network.api.ApiEndPoints
import ao.httpstatuscode.romavicdosanjoskc.network.model.PostsModel
import ao.httpstatuscode.romavicdosanjoskc.ui.adapters.PostsAdapter
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private var recyclerMain: RecyclerView? = null
private var postsAdapter: PostsAdapter? = null
private var progressMain: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerMain = findViewById(R.id.recyclerMain)
progressMain = findViewById(R.id.progressMain)
recyclerMain?.layoutManager = LinearLayoutManager(this)
recyclerMain?.setHasFixedSize(true)
val apiEndPoints = apiClient!!.create(ApiEndPoints::class.java)
val call = apiEndPoints.posts
call.enqueue(object : Callback<List<PostsModel>> {
override fun onResponse(
call: Call<List<PostsModel>>,
response: Response<List<PostsModel>>
) {
when {
response.code() == Successful.Ok -> {
postsAdapter = PostsAdapter(this@MainActivity, response.body()!!)
recyclerMain?.adapter = postsAdapter
progressMain?.visibility = View.GONE
}
response.code() == Informational.Continue -> {
Toast.makeText(this@MainActivity, "Please wait...", Toast.LENGTH_SHORT).show()
progressMain?.visibility = View.VISIBLE
}
response.code() == ClientError.BadRequest -> {
progressMain?.visibility = View.GONE
Toast.makeText(
this@MainActivity,
"The request could not be delivered due to incorrect syntax.",
Toast.LENGTH_SHORT
).show()
}
response.code() == Redirection.Found -> {
progressMain?.visibility = View.GONE
Toast.makeText(this@MainActivity, "The request was found.", Toast.LENGTH_SHORT).show()
}
response.code() == ServerError.BadGateway -> {
progressMain?.visibility = View.GONE
Toast.makeText(this@MainActivity, "Bad Gateway.", Toast.LENGTH_SHORT).show()
}
}
}
override fun onFailure(call: Call<List<PostsModel>>, t: Throwable) {
Log.i("Error", t.message.toString())
progressMain?.visibility = View.GONE
}
})
}
}
|
// Sample Text
var Datamatrix = require('./lib/datamatrix').Datamatrix;
var dm = new Datamatrix();
var ascii = dm.getDigit('http://tualo.de',false);
console.log(ascii);
|
WITH
store_sales AS (SELECT * FROM deltas3."$path$"."s3://tpc-datasets/tpcds_1000_dat_delta/store_sales" ),
date_dim AS (SELECT * FROM deltas3."$path$"."s3://tpc-datasets/tpcds_1000_dat_delta/date_dim" )
SELECT * FROM store_sales
JOIN date_dim ON ss_sold_date_sk = d_date_sk
WHERE d_year=1998 AND d_moy=7 AND d_dom=5
;
|
package com.senior.cyber.sftps.web.gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
public class CertificationSignRequestAdaptor extends TypeAdapter<PKCS10CertificationRequest> {
@Override
public void write(JsonWriter out, PKCS10CertificationRequest csr) throws IOException {
if (csr == null) {
out.nullValue();
} else {
StringWriter pem = new StringWriter();
try (JcaPEMWriter writer = new JcaPEMWriter(pem)) {
writer.writeObject(csr);
}
out.value(pem.toString());
}
}
@Override
public PKCS10CertificationRequest read(JsonReader in) throws IOException {
String pem = in.nextString();
StringReader reader = new StringReader(pem);
try (PEMParser pemParser = new PEMParser(reader)) {
Object o = pemParser.readObject();
return (PKCS10CertificationRequest) o;
}
}
}
|
package io.horrorshow.soulhub.ui.views;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.*;
import io.horrorshow.soulhub.ui.MainLayout;
import io.horrorshow.soulhub.ui.UIConst;
import io.horrorshow.soulhub.ui.components.SOULPatchReadOnlyDialog;
import io.horrorshow.soulhub.ui.components.SOULPatchesGrid;
import io.horrorshow.soulhub.ui.components.SOULPatchesGridHeader;
import io.horrorshow.soulhub.ui.components.SPFileReadOnlyDialog;
import io.horrorshow.soulhub.ui.presenter.SOULPatchesPresenter;
import org.springframework.beans.factory.annotation.Autowired;
@Route(value = UIConst.ROUTE_SOULPATCHES, layout = MainLayout.class)
@RouteAlias(value = UIConst.ROUTE_EMPTY, layout = MainLayout.class)
@PageTitle(UIConst.TITLE_SOULPATCHES)
public class SOULPatchesView extends Div
implements HasUrlParameter<String> {
private static final long serialVersionUID = 6587633236690463135L;
private final SOULPatchesGrid grid = new SOULPatchesGrid();
private final SOULPatchesGridHeader filter = new SOULPatchesGridHeader();
private final SPFileReadOnlyDialog spFileReadOnlyDialog = new SPFileReadOnlyDialog();
private final SOULPatchReadOnlyDialog soulPatchReadOnlyDialog = new SOULPatchReadOnlyDialog();
private final SOULPatchesPresenter soulPatchesPresenter;
public SOULPatchesView(@Autowired SOULPatchesPresenter soulPatchesPresenter) {
this.soulPatchesPresenter = soulPatchesPresenter;
soulPatchesPresenter.init(this);
layoutComponents();
}
public SOULPatchesGrid getGrid() {
return this.grid;
}
public SOULPatchesGridHeader getHeader() {
return this.filter;
}
public SPFileReadOnlyDialog getSpFileReadOnlyDialog() {
return spFileReadOnlyDialog;
}
public SOULPatchReadOnlyDialog getSoulPatchReadOnlyDialog() {
return soulPatchReadOnlyDialog;
}
private void layoutComponents() {
grid.setHeightByRows(true);
filter.setWidthFull();
VerticalLayout layout = new VerticalLayout();
layout.add(filter);
layout.add(grid);
add(layout);
}
@Override
public void setParameter(BeforeEvent event, @OptionalParameter String parameter) {
var parameterMap = event.getLocation().getQueryParameters().getParameters();
soulPatchesPresenter.onNavigation(parameter, parameterMap);
}
}
|
<?php
declare(strict_types=1);
namespace Phpcq\Runner\Repository;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\VersionParser;
use Generator;
use Phpcq\Runner\Exception\PluginVersionNotFoundException;
use Phpcq\Runner\Exception\ToolVersionNotFoundException;
use Phpcq\Runner\Platform\PlatformRequirementCheckerInterface;
use Phpcq\RepositoryDefinition\Plugin\Plugin;
use Phpcq\RepositoryDefinition\Plugin\PluginVersionInterface;
use Phpcq\RepositoryDefinition\Repository as DecoratedRepository;
use Phpcq\RepositoryDefinition\RepositoryInterface as DefinitionRepositoryInterface;
use Phpcq\RepositoryDefinition\Tool\Tool;
use Phpcq\RepositoryDefinition\Tool\ToolVersionInterface;
use Phpcq\RepositoryDefinition\VersionRequirementList;
use Traversable;
use function array_shift;
use function count;
use function krsort;
use const SORT_NATURAL;
/**
* Represents a JSON contained repository.
*/
class Repository implements RepositoryInterface
{
use RepositoryHasToolVersionTrait;
use RepositoryHasPluginVersionTrait;
/**
* @var DefinitionRepositoryInterface
*/
private $repository;
/**
* @var VersionParser
*/
private $parser;
/**
* @var PlatformRequirementCheckerInterface|null
*/
private $requirementChecker;
/**
* Repository constructor.
*
* @param PlatformRequirementCheckerInterface|null $requirementChecker
* @param DefinitionRepositoryInterface|null $repository
*/
public function __construct(
?PlatformRequirementCheckerInterface $requirementChecker = null,
?DefinitionRepositoryInterface $repository = null
) {
$this->repository = $repository ?: new DecoratedRepository();
$this->requirementChecker = $requirementChecker;
$this->parser = new VersionParser();
}
public function addPluginVersion(PluginVersionInterface $pluginVersion): void
{
if (! $this->repository->hasPlugin($pluginVersion->getName())) {
$this->repository->addPlugin(new Plugin($pluginVersion->getName()));
}
$this->repository->getPlugin($pluginVersion->getName())->addVersion($pluginVersion);
}
public function getPluginVersion(string $name, string $versionConstraint): PluginVersionInterface
{
if ($this->repository->hasPlugin($name)) {
$candidates = $this->findMatchingPluginVersions($name, $versionConstraint);
if (count($candidates) > 0) {
return array_shift($candidates);
}
}
throw new PluginVersionNotFoundException($name, $versionConstraint);
}
public function iteratePluginVersions(): Generator
{
foreach ($this->repository->iteratePlugins() as $plugin) {
foreach ($plugin as $pluginVersion) {
yield $pluginVersion;
}
}
}
public function addToolVersion(ToolVersionInterface $toolVersion): void
{
if (! $this->repository->hasTool($toolVersion->getName())) {
$this->repository->addTool(new Tool($toolVersion->getName()));
}
$this->repository->getTool($toolVersion->getName())->addVersion($toolVersion);
}
public function getToolVersion(string $name, string $versionConstraint): ToolVersionInterface
{
// No tool specified, exit out.
if ($this->repository->hasTool($name)) {
$candidates = $this->findMatchingToolVersions($name, $versionConstraint);
if (count($candidates) > 0) {
return array_shift($candidates);
}
}
throw new ToolVersionNotFoundException($name, $versionConstraint);
}
/**
* @return Traversable<int, ToolVersionInterface>
*
* @psalm-return \Generator<int, ToolVersionInterface, mixed, void>
*/
public function iterateToolVersions(): Generator
{
foreach ($this->repository->iterateTools() as $tool) {
foreach ($tool as $version) {
yield $version;
}
}
}
/**
* @return PluginVersionInterface[]
*
* @psalm-return array<string, PluginVersionInterface>
*/
private function findMatchingPluginVersions(string $name, string $versionConstraint): array
{
$constraint = $this->parser->parseConstraints($versionConstraint);
$results = [];
foreach ($this->repository->getPlugin($name) as $versionHunk) {
$version = $versionHunk->getVersion();
$normalized = $this->parser->normalize($version);
if (!$constraint->matches(new Constraint('=', $normalized))) {
continue;
}
if (!$this->matchesPlatformRequirements($versionHunk->getRequirements()->getPhpRequirements())) {
continue;
}
$results[$normalized] = $versionHunk;
}
krsort($results);
return $results;
}
/**
* @return ToolVersionInterface[]
*
* @psalm-return array<string, ToolVersionInterface>
*/
private function findMatchingToolVersions(string $name, string $versionConstraint): array
{
$constraint = $this->parser->parseConstraints($versionConstraint);
$results = [];
foreach ($this->repository->getTool($name) as $versionHunk) {
$version = $versionHunk->getVersion();
$normalized = $this->parser->normalize($version);
if (!$constraint->matches(new Constraint('=', $normalized))) {
continue;
}
if (!$this->matchesPlatformRequirements($versionHunk->getRequirements()->getPhpRequirements())) {
continue;
}
$results[$normalized] = $versionHunk;
}
krsort($results, SORT_NATURAL);
return $results;
}
private function matchesPlatformRequirements(VersionRequirementList $requirements): bool
{
if (null === $this->requirementChecker) {
return true;
}
foreach ($requirements as $requirement) {
if (!$this->requirementChecker->isFulfilled($requirement->getName(), $requirement->getConstraint())) {
return false;
}
}
return true;
}
}
|
/**
* Creates fixed period which does not depend on time instance.
*
* @param {number} quantity number of fixed intervals.
* @param {number} duration length of s fixed interval in milliseconds.
* @constructor
* @class Represents general period.
* @extends Period
*/
FixedPeriod = function(quantity, duration) {
this._super(quantity);
/**
* @private
* @type {number}
*/
this._duration = duration * quantity;
};
/**
* Returns fixed duration.
*
* @param {number} instant not used.
* @returns {number} fixed duration.
*/
FixedPeriod.prototype.duration = function(instant) {
return this._duration;
};
/**
* Represents period in milliseconds.
*
* @constructor
* @extends FixedPeriod
*/
Millis = function(quantity) {
this._super(quantity, 1);
};
/**
* Represents period in seconds.
*
* @constructor
* @extends FixedPeriod
*/
Seconds = function(quantity) {
this._super(quantity, Chronology.MILLIS_PER_SECOND);
};
/**
* Represents period in minutes.
*
* @constructor
* @extends FixedPeriod
*/
Minutes = function(quantity) {
this._super(quantity, Chronology.MILLIS_PER_MINUTE);
};
/**
* Represents period in hours.
*
* @constructor
* @extends FixedPeriod
*/
Hours = function(quantity) {
this._super(quantity, Chronology.MILLIS_PER_HOUR);
};
inherits(FixedPeriod, Period);
inherits(Millis, FixedPeriod);
inherits(Seconds, FixedPeriod);
inherits(Minutes, FixedPeriod);
inherits(Hours, FixedPeriod); |
const Koa = require('koa')
const Router = require('koa-router')
const Session = require('koa-session')
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')
const app = new Koa()
const testRouter = new Router()
// 创建session配置
const session = Session({
'key': 'sessionid',
maxAge: 10 * 1000,
signed: true // 是否使用加密签名
}, app)
app.keys = ["aaaaaa"] // 加密加盐
app.use(session)
// 登陆接口,登陆成功返回cookie
testRouter.get('/login', async (ctx, next) => {
// 服务端对应的是毫秒
ctx.cookies.set('name', 'lilei', {
'maxAge': 30 * 1000,
})
ctx.body = "test-login"
await next()
})
testRouter.get('/demo', async (ctx, next) => {
// 读取cookie
const name = ctx.cookies.get('name')
console.log('读取到的cookie', name)
ctx.body = "当前的cookie是" + name
})
testRouter.get('/getSession', async (ctx, next) => {
// 读取cookie
console.log('读取到的cookie', ctx.session.user)
ctx.body = "当前的cookie是" + ctx.session.user.name
})
testRouter.get('/session', async (ctx, next) => {
// 登陆成功设置session
const id = 10
const name = 'coderhub'
ctx.session.user = { id, name }
ctx.body = "session" + name
})
const SECRET_KEY = 'abcsba1234'
const PRIVATE_KEY = fs.readFileSync(path.resolve(__dirname, './keys/private.key'))
const PUBLIC_KEY = fs.readFileSync(path.resolve(__dirname, './keys/public.key'))
testRouter.get('/getToken', async (ctx, next) => {
const user = { id: 10, name: 'coderhub' }
// 使用私钥颁发签名
const token = jwt.sign(user, PRIVATE_KEY, {
expiresIn: 10 * 1000,
algorithm: "RS256" // 指定使用的非对称加密的算法
})
ctx.body = token
})
testRouter.get('/decodeToken', async (ctx, next) => {
const authorization = ctx.headers.authorization
const token = authorization.replace('Bearer ', '')
try {
const result = jwt.verify(token, PUBLIC_KEY, {
algorithms: ["RS256"]
})
console.log('token解密出来的结果!', result)
ctx.body = result
} catch (error) {
ctx.body = 'token是无效的'
}
})
app.use(testRouter.routes())
app.use(testRouter.allowedMethods())
app.listen(8000, () => {
console.log("服务:8000启动成功!")
}) |
package moe.pizza.eveapi.endpoints
import moe.pizza.eveapi.ApiRequest
import moe.pizza.eveapi.generated.map
import org.http4s.client.Client
import scalaz.concurrent.Task
class Map(baseurl: String)(implicit c: Client) {
def Sovereignty(): Task[Seq[map.Sovereignty.Row]] = {
new ApiRequest[map.Sovereignty.Eveapi](baseurl, "Map/Sovereignty.xml.aspx")(
map.Sovereignty.SovereigntyEveapiFormat).apply().map(_.result.rowset.row)
}
def FacWarSystems(): Task[Seq[map.FacWarSystems.Row]] = {
new ApiRequest[map.FacWarSystems.Eveapi](baseurl, "Map/FacWarSystems.xml.aspx")(
map.FacWarSystems.FacWarSystemsEveapiFormat).apply().map(_.result.rowset.row)
}
def Kills(): Task[Seq[map.Kills.Row]] = {
new ApiRequest[map.Kills.Eveapi](baseurl, "Map/Kills.xml.aspx")(map.Kills.KillsEveapiFormat)
.apply()
.map(_.result.rowset.row)
}
def Jumps(): Task[Seq[map.Jumps.Row]] = {
new ApiRequest[map.Jumps.Eveapi](baseurl, "Map/Jumps.xml.aspx")(map.Jumps.JumpsEveapiFormat)
.apply()
.map(_.result.rowset.row)
}
}
|
package com.socrata.eurybates
object SessionMode {
sealed trait SessionMode
case object Transacted extends SessionMode
case object None extends SessionMode
}
|
/**
* Convenient helper code for applications that use Dalma engine.
*/
package dalma.helpers; |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimal-ui">
<title>SSA INFRA - User Forget Password</title>
<meta content="Admin Dashboard" name="description">
<meta content="Mannatthemes" name="author">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="shortcut icon" href="{{ asset('images/ssa.png') }}">
<link href="{{ asset('panel') }}/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="{{ asset('panel') }}/assets/css/icons.css" rel="stylesheet" type="text/css">
<link href="{{ asset('panel') }}/assets/css/style.css" rel="stylesheet" type="text/css">
</head>
<body class="fixed-left">
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="card">
<div class="card-body">
<h3 class="text-center mt-0 m-b-15">
<a href="/" class="logo logo-admin"><b>
<h2>SSA INFRA</h2>
</b></a>
</h3>
<div class="p-3">
<form class="form-horizontal" action="{{ route('updatepassword') }}" method="POST">
@csrf
<input type="hidden" name="password_token" value="{{ $token }}" />
<div class="form-group row">
<div class="col-12"><input class="form-control" type="email"
value="{{ $email }}" name="email" placeholder="Email"></div>
</div>
<div class="form-group row">
<div class="col-12"><input class="form-control" type="password" name="password"
placeholder="New Password"></div>
</div>
<div class="form-group row">
<div class="col-12"><input class="form-control" type="password" name="c_password"
placeholder="Confirm Password"></div>
</div>
<div class="form-group text-center row m-t-20">
<div class="col-12"><button
class="btn btn-danger btn-block waves-effect waves-light"
type="submit">Reset</button></div>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="{{ asset('panel') }}/assets/js/jquery.min.js"></script>
<script src="{{ asset('panel') }}/assets/js/popper.min.js"></script>
<script src="{{ asset('panel') }}/assets/js/bootstrap.min.js"></script>
<script src="{{ asset('panel') }}/assets/js/modernizr.min.js"></script>
<script src="{{ asset('panel') }}/assets/js/detect.js"></script>
<script src="{{ asset('panel') }}/assets/js/fastclick.js"></script>
<script src="{{ asset('panel') }}/assets/js/jquery.slimscroll.js"></script>
<script src="{{ asset('panel') }}/assets/js/jquery.blockUI.js"></script>
<script src="{{ asset('panel') }}/assets/js/waves.js"></script>
<script src="{{ asset('panel') }}/assets/js/jquery.nicescroll.js"></script>
<script src="{{ asset('panel') }}/assets/js/jquery.scrollTo.min.js"></script>
<script src="{{ asset('panel') }}/assets/js/app.js"></script>
</body>
</html>
|
package com.ijinshan.sjk.config;
public class AppConfig {
public static final int BATCH_SIZE = 30;
public static final int BATCH_SIZE_OF_TRANC = BATCH_SIZE * 10;
private String tmpFullDir = "/data/appsdata/sjk-market/tmp/";
private String tmpUploadDir = "/data/apps/static-web/sjk/app/market/tmp/img/";
private String tmpUploadBaseurl = "http://app.sjk.ijinshan.com/market/tmp/img/";
private String destUploadDir = "/data/apps/static-web/sjk/market/img/";
private String destUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/";
private String destTagUploadDir = "/data/apps/static-web/sjk/market/img/tag/";
private String destTagUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/tag/";
private String destMobileTagUploadDir = "/data/apps/static-web/sjk/app/market/img/mobile/tag/";
private String destMobileTagUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/mobile/tag/";
private String destMobileFeaturedUploadDir = "/data/apps/static-web/sjk/app/market/img/mobile/featured/";
private String destMobileFeaturedUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/mobile/featured/";
private String destMomixFeaturedUploadDir = "/data/apps/static-web/sjk/app/market/img/momix/featured/";
private String destMomixFeaturedUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/momix/featured/";
private String destBigGameUploadDir = "/data/apps/static-web/sjk/app/market/img/biggame/";
private String destBigGameUploadBaseurl = "http://app.sjk.ijinshan.com/market/img/biggame/";
private boolean updateAudit = false;
private boolean deleteUploadImageFile = false;
public String getTmpFullDir() {
return tmpFullDir;
}
public void setTmpFullDir(String tmpFullDir) {
this.tmpFullDir = tmpFullDir;
}
public String getTmpUploadDir() {
return tmpUploadDir;
}
public void setTmpUploadDir(String tmpUploadDir) {
this.tmpUploadDir = tmpUploadDir;
}
public String getDestUploadDir() {
return destUploadDir;
}
public void setDestUploadDir(String destUploadDir) {
this.destUploadDir = destUploadDir;
}
public String getDestUploadBaseurl() {
return destUploadBaseurl;
}
public void setDestUploadBaseurl(String destUploadBaseurl) {
this.destUploadBaseurl = destUploadBaseurl;
}
public String getTmpUploadBaseurl() {
return tmpUploadBaseurl;
}
public void setTmpUploadBaseurl(String tmpUploadBaseurl) {
this.tmpUploadBaseurl = tmpUploadBaseurl;
}
public String getDestTagUploadDir() {
return destTagUploadDir;
}
public void setDestTagUploadDir(String destTagUploadDir) {
this.destTagUploadDir = destTagUploadDir;
}
public String getDestTagUploadBaseurl() {
return destTagUploadBaseurl;
}
public void setDestTagUploadBaseurl(String destTagUploadBaseurl) {
this.destTagUploadBaseurl = destTagUploadBaseurl;
}
public String getDestMobileTagUploadDir() {
return destMobileTagUploadDir;
}
public void setDestMobileTagUploadDir(String destMobileTagUploadDir) {
this.destMobileTagUploadDir = destMobileTagUploadDir;
}
public String getDestMobileTagUploadBaseurl() {
return destMobileTagUploadBaseurl;
}
public void setDestMobileTagUploadBaseurl(String destMobileTagUploadBaseurl) {
this.destMobileTagUploadBaseurl = destMobileTagUploadBaseurl;
}
public String getDestMobileFeaturedUploadDir() {
return destMobileFeaturedUploadDir;
}
public void setDestMobileFeaturedUploadDir(String destMobileFeaturedUploadDir) {
this.destMobileFeaturedUploadDir = destMobileFeaturedUploadDir;
}
public String getDestMobileFeaturedUploadBaseurl() {
return destMobileFeaturedUploadBaseurl;
}
public void setDestMobileFeaturedUploadBaseurl(String destMobileFeaturedUploadBaseurl) {
this.destMobileFeaturedUploadBaseurl = destMobileFeaturedUploadBaseurl;
}
public String getDestBigGameUploadDir() {
return destBigGameUploadDir;
}
public void setDestBigGameUploadDir(String destBigGameUploadDir) {
this.destBigGameUploadDir = destBigGameUploadDir;
}
public String getDestBigGameUploadBaseurl() {
return destBigGameUploadBaseurl;
}
public void setDestBigGameUploadBaseurl(String destBigGameUploadBaseurl) {
this.destBigGameUploadBaseurl = destBigGameUploadBaseurl;
}
public String getDestMomixFeaturedUploadDir() {
return destMomixFeaturedUploadDir;
}
public void setDestMomixFeaturedUploadDir(String destMomixFeaturedUploadDir) {
this.destMomixFeaturedUploadDir = destMomixFeaturedUploadDir;
}
public String getDestMomixFeaturedUploadBaseurl() {
return destMomixFeaturedUploadBaseurl;
}
public void setDestMomixFeaturedUploadBaseurl(String destMomixFeaturedUploadBaseurl) {
this.destMomixFeaturedUploadBaseurl = destMomixFeaturedUploadBaseurl;
}
public boolean isDeleteUploadImageFile() {
return deleteUploadImageFile;
}
public void setDeleteUploadImageFile(boolean deleteUploadImageFile) {
this.deleteUploadImageFile = deleteUploadImageFile;
}
public boolean isUpdateAudit() {
return updateAudit;
}
public void setUpdateAudit(boolean updateAudit) {
this.updateAudit = updateAudit;
}
public static int getBatchSize() {
return BATCH_SIZE;
}
public static int getBatchSizeOfTranc() {
return BATCH_SIZE_OF_TRANC;
}
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Complexity, type: :model do
subject do
described_class.new(level: "high",
reason: "Lorem ipsum")
end
it 'validates the presence of level, reason' do
expect(subject).to be_valid :level
expect(subject).to be_valid :reason
end
it "is not valid without a level" do
subject.level = nil
expect(subject).not_to be_valid
end
it "is not valid without a reason" do
subject.reason = nil
expect(subject).not_to be_valid
expect(subject.errors.messages).to eq(reason: ["Enter the reason why the level has changed"])
end
end
|
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
namespace SLStudio.Core.Menus
{
public class MenuItemConverter : MarkupExtension, IValueConverter
{
private static MenuItemConverter instance;
public override object ProvideValue(IServiceProvider serviceProvider)
=> instance ??= new MenuItemConverter();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter is not MenuItemTypes menuType)
return false;
return menuType switch
{
MenuItemTypes.Separator => value is IMenuSeparatorItem,
MenuItemTypes.Toggle => value is IMenuToggleItem,
MenuItemTypes.Normal => value is IMenuItem,
_ => false
};
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
public enum MenuItemTypes
{
Normal,
Toggle,
Separator
}
} |
// Defining the Supplier Map Login table
module.exports = (sequelize, DataTypes) => {
const SupplierMapLogin = sequelize.define(
'supplier_map_login',
{
login_email: {
type: DataTypes.STRING,
allowNull: false
},
supplier_number: {
type: DataTypes.INTEGER,
allowNull: false
}
},
{
underscored: true
}
);
// Associating Order & Supplier tables to Supplier Map Login table
SupplierMapLogin.associate = (models) => {
SupplierMapLogin.hasMany(models.order);
SupplierMapLogin.belongsTo(models.supplier);
};
return SupplierMapLogin;
};
|
pip install -r requirements.txt
git clone https://www.github.com/nvidia/apex && cd apex && rm -rf build && python setup.py install --cuda_ext --cpp_ext |
## A simple GO program example for kubernetes using minikube
#### NOTE: This doesn't work as it exists today, things are clearly missing :)
|
export const IMAGES = {
truckIcon: require("./assests/images/icons/truck-icon.svg"),
sofaIcon: require("./assests/images/icons/sofa-icon.svg"),
treeIcon: require("./assests/images/icons/tree-icon.svg"),
customer1: require("assests/images/customers/customer-1.jpg"),
customer2: require("assests/images/customers/customer-2.jpg"),
customer3: require("assests/images/customers/customer-3.jpg"),
}
|
import asyncio
import asyncssh
from datetime import datetime
from riegocloud.db import get_db
from logging import getLogger
_log = getLogger(__name__)
_instance = None
def get_ssh():
global _instance
return _instance
def setup_ssh(app, options=None, db=None):
global _instance
if _instance is not None:
del _instance
_instance = Ssh(app, options, db)
return _instance
class Ssh:
def __init__(self, app, db, options):
global _instance
if _instance is None:
_instance = self
self._server = None
app.cleanup_ctx.append(self._sshd_engine)
# asyncssh.set_log_level(logging.DEBUG)
# asyncssh.set_debug_level(3)
async def _sshd_engine(self, app):
task = asyncio.create_task(self._start_server(app))
yield
await self._shutdown_server(app, task)
async def _start_server(self, app):
self._server = await asyncssh.listen(
app['options'].ssh_server_bind_address,
app['options'].ssh_server_bind_port,
server_host_keys=app['options'].ssh_host_key,
process_factory=self._handle_client,
server_factory=MySSHServer)
async def _shutdown_server(self, app, task):
MySSHServer._shutdown_all()
if self._server is not None:
self._server.close()
await self._server.wait_closed()
def _handle_client(self, process):
process.stdout.write('Welcome to my SSH server, %s!\n' %
process.get_extra_info('username'))
process.exit(0)
def get_clients(self):
return MySSHServer.get_clients()
class MySSHServer(asyncssh.SSHServer):
_conn_list = []
@classmethod
def _shutdown_all(cls):
for conn in cls._conn_list:
conn.close()
@classmethod
def get_clients(cls):
ret = []
for conn in cls._conn_list:
ret.append({
'client_id': conn.get_extra_info('client_id'),
'timestamp': conn.get_extra_info('timestamp'),
'cloud_identifier': conn.get_extra_info('username'),
'listen_port': conn.get_extra_info('listen_port'),
'ip': conn.get_extra_info('peername')[0],
'port': conn.get_extra_info('peername')[1]
})
return ret
def __init__(self):
self._conn = None
async def server_requested(self, listen_host, listen_port):
if (listen_host != 'localhost' or
listen_port != self._conn.get_extra_info('listen_port')):
_log.error('unallowed TCP forarding requested from: {}'.format(
self._conn.get_extra_info('username')))
await asyncio.sleep(3)
return False
_log.debug(f'Port forwarding established: {listen_host}:{listen_port}')
# TODO Write log-information to database: timestamp,
return True
def connection_made(self, conn):
self._conn = conn
_log.debug('SSH connection received from {}'.format(
conn.get_extra_info('peername')[0]))
MySSHServer._conn_list.append(conn)
def connection_lost(self, exc):
if exc:
_log.debug(f'SSH connection error: {exc}')
else:
_log.debug('SSH connection closed.')
MySSHServer._conn_list.remove(self._conn)
self._conn = None
async def begin_auth(self, username):
cursor = get_db().conn.cursor()
cursor.execute("""SELECT *
FROM clients
WHERE cloud_identifier = %s""", (username,))
client = cursor.fetchone()
if client is None or client['is_disabled']:
await asyncio.sleep(3)
return True
self._conn.set_extra_info(listen_port=client['ssh_server_listen_port'])
self._conn.set_extra_info(client_id=client['id'])
self._conn.set_extra_info(timestamp=datetime.now())
key = asyncssh.import_authorized_keys(
client['public_user_key'])
self._conn.set_authorized_keys(key)
return True
def public_key_auth_supported(self):
return True
def validate_public_key(self, username, key):
return True
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class C_Home extends CI_Controller {
function __construct() {
parent::__construct();
// Load url helper
$this->load->helper('url');
}
public function index()
{
$data['judul'] = 'Ruang Guru';
$this->load->view('templates/header');
$this->load->view('V_Home');
$this->load->view('templates/footer');
}
public function Register()
{
$data['judul'] = 'Register';
$this->load->view('templates/header');
$this->load->view('V_Register');
$this->load->view('templates/footer');
}
public function formRegister()
{
$data['judul'] = 'Form Register';
$this->load->view('templates/header');
$this->load->view('V_FormRegister');
$this->load->view('templates/footer');
}
}
|
require 'rails_helper'
describe InterventionsChartsService do
let(:ics) { InterventionsChartsService.new([], 0) }
describe "#by_city" do
subject { ics.by_city }
it { expect(subject.options[:title][:text]).to match(/ville/) }
it { expect(subject.series_data.size).to eq 1 }
end
describe "#by_vehicle" do
subject { ics.by_vehicle }
it { expect(subject.options[:title][:text]).to match(/véhicule/) }
it { expect(subject.series_data.size).to eq 1 }
end
describe "#by_hour" do
subject { ics.by_hour }
it { expect(subject.options[:title][:text]).to match(/heure/) }
it { expect(subject.series_data.size).to eq 1 }
end
describe "#by_month" do
subject { ics.by_month }
it { expect(subject.options[:title][:text]).to match(/mois/) }
it { expect(subject.series_data.size).to eq 1 }
end
describe "#by_subkind" do
subject { ics.by_subkind }
it { expect(subject.options[:title][:text]).to match(/sous-type/) }
it { expect(subject.series_data.size).to eq 1 }
end
describe "#by_type" do
subject { ics.by_type }
it { expect(subject.options[:title][:text]).to match(/type/) }
it { expect(subject.series_data.size).to eq 1 }
end
end
|
# -*- encoding : utf-8 -*-
FactoryGirl.define do
# factory :user do
#
# end
#
# factory :debt do
#
# end
end
|
import React from 'react'
import X from '.'
import { shallow } from 'enzyme'
describe('Component xxx', () => {
it('render the X', () => {
const result = shallow(<X />).contains(<p>X</p>)
expect(result).toBeTruthy()
})
})
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ddt import data, ddt
from django.test import TransactionTestCase
from django.urls import reverse
from django.utils import timezone
from freezegun import freeze_time
from mock_django import mock_signal_receiver
from rest_framework import status, test
from waldur_core.core.tests.helpers import override_waldur_core_settings
from waldur_core.quotas.tests import factories as quota_factories
from waldur_core.structure import signals
from waldur_core.structure.models import Customer, CustomerRole, ProjectRole
from waldur_core.structure.tests import factories, fixtures
class UrlResolverMixin(object):
def _get_customer_url(self, customer):
return 'http://testserver' + reverse('customer-detail', kwargs={'uuid': customer.uuid})
def _get_project_url(self, project):
return 'http://testserver' + reverse('project-detail', kwargs={'uuid': project.uuid})
def _get_user_url(self, user):
return 'http://testserver' + reverse('user-detail', kwargs={'uuid': user.uuid})
@freeze_time('2017-11-01 00:00:00')
class CustomerTest(TransactionTestCase):
def setUp(self):
self.customer = factories.CustomerFactory()
self.user = factories.UserFactory()
self.created_by = factories.UserFactory()
def test_add_user_returns_created_if_grant_didnt_exist_before(self):
_, created = self.customer.add_user(self.user, CustomerRole.OWNER)
self.assertTrue(created, 'Customer permission should have been reported as created')
def test_add_user_returns_not_created_if_grant_existed_before(self):
self.customer.add_user(self.user, CustomerRole.OWNER)
_, created = self.customer.add_user(self.user, CustomerRole.OWNER)
self.assertFalse(created, 'Customer permission should have been reported as not created')
def test_add_user_returns_membership(self):
membership, _ = self.customer.add_user(self.user, CustomerRole.OWNER)
self.assertEqual(membership.user, self.user)
self.assertEqual(membership.customer, self.customer)
def test_add_user_returns_same_membership_for_consequent_calls_with_same_arguments(self):
membership1, _ = self.customer.add_user(self.user, CustomerRole.OWNER)
membership2, _ = self.customer.add_user(self.user, CustomerRole.OWNER)
self.assertEqual(membership1, membership2)
def test_add_user_emits_structure_role_granted_if_grant_didnt_exist_before(self):
with mock_signal_receiver(signals.structure_role_granted) as receiver:
self.customer.add_user(self.user, CustomerRole.OWNER, self.created_by)
receiver.assert_called_once_with(
structure=self.customer,
user=self.user,
role=CustomerRole.OWNER,
sender=Customer,
signal=signals.structure_role_granted,
created_by=self.created_by
)
def test_add_user_doesnt_emit_structure_role_granted_if_grant_existed_before(self):
self.customer.add_user(self.user, CustomerRole.OWNER)
with mock_signal_receiver(signals.structure_role_granted) as receiver:
self.customer.add_user(self.user, CustomerRole.OWNER)
self.assertFalse(receiver.called, 'structure_role_granted should not be emitted')
def test_remove_user_emits_structure_role_revoked_for_each_role_user_had_in_customer(self):
self.customer.add_user(self.user, CustomerRole.OWNER)
with mock_signal_receiver(signals.structure_role_revoked) as receiver:
self.customer.remove_user(self.user, removed_by=self.created_by)
receiver.assert_called_once_with(
structure=self.customer,
user=self.user,
role=CustomerRole.OWNER,
removed_by=self.created_by,
sender=Customer,
signal=signals.structure_role_revoked,
)
def test_remove_user_emits_structure_role_revoked_if_grant_existed_before(self):
self.customer.add_user(self.user, CustomerRole.OWNER)
with mock_signal_receiver(signals.structure_role_revoked) as receiver:
self.customer.remove_user(self.user, CustomerRole.OWNER, self.created_by)
receiver.assert_called_once_with(
structure=self.customer,
user=self.user,
role=CustomerRole.OWNER,
removed_by=self.created_by,
sender=Customer,
signal=signals.structure_role_revoked,
)
def test_remove_user_doesnt_emit_structure_role_revoked_if_grant_didnt_exist_before(self):
with mock_signal_receiver(signals.structure_role_revoked) as receiver:
self.customer.remove_user(self.user, CustomerRole.OWNER)
self.assertFalse(receiver.called, 'structure_role_remove should not be emitted')
class CustomerRoleTest(TransactionTestCase):
def setUp(self):
self.customer = factories.CustomerFactory()
def test_get_owners_returns_empty_list(self):
self.assertEqual(0, self.customer.get_owners().count())
@ddt
class CustomerApiPermissionTest(UrlResolverMixin, test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.ProjectFixture()
# List filtration tests
@data('staff', 'global_support', 'owner', 'customer_support', 'admin', 'manager', 'project_support')
def test_user_can_list_customers(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
self._check_user_list_access_customers(self.fixture.customer, 'assertIn')
@data('user', 'admin', 'manager', 'project_support')
def test_user_cannot_list_other_customer(self, user):
customer = factories.CustomerFactory()
self.client.force_authenticate(user=getattr(self.fixture, user))
self._check_customer_in_list(customer, False)
# Nested objects filtration tests
@data('admin', 'manager', 'project_support')
def test_user_can_see_project_he_has_a_role_in_within_customer(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
response = self.client.get(self._get_customer_url(self.fixture.customer))
self.assertEqual(response.status_code, status.HTTP_200_OK)
project_urls = set([project['url'] for project in response.data['projects']])
self.assertIn(
self._get_project_url(self.fixture.project), project_urls,
'User should see project',
)
@data('admin', 'manager', 'project_support')
def test_user_cannot_see_project_he_has_no_role_in_within_customer(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
non_seen_project = factories.ProjectFactory(customer=self.fixture.customer)
response = self.client.get(self._get_customer_url(self.fixture.customer))
self.assertEqual(response.status_code, status.HTTP_200_OK)
project_urls = set([project['url'] for project in response.data['projects']])
self.assertNotIn(
self._get_project_url(non_seen_project), project_urls,
'User should not see project',
)
# Direct instance access tests
@data(('owner', 'owners'), ('customer_support', 'support_users'))
def test_user_can_see_its_owner_membership_in_a_service_he_is_owner_of(self, user_data):
user, response_field = user_data
self.client.force_authenticate(user=getattr(self.fixture, user))
response = self.client.get(self._get_customer_url(self.fixture.customer))
users = set(c['url'] for c in response.data[response_field])
user_url = self._get_user_url(getattr(self.fixture, user))
self.assertEqual([user_url], list(users))
@data('staff', 'global_support')
def test_user_can_access_all_customers_if_he_is_staff(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
self._check_user_direct_access_customer(self.fixture.customer, status.HTTP_200_OK)
customer = factories.CustomerFactory()
self._check_user_direct_access_customer(customer, status.HTTP_200_OK)
# Helper methods
def _check_user_list_access_customers(self, customer, test_function):
response = self.client.get(reverse('customer-list'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
urls = set([instance['url'] for instance in response.data])
url = self._get_customer_url(customer)
getattr(self, test_function)(url, urls)
def _check_customer_in_list(self, customer, positive=True):
response = self.client.get(reverse('customer-list'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
urls = set([instance['url'] for instance in response.data])
customer_url = self._get_customer_url(customer)
if positive:
self.assertIn(customer_url, urls)
else:
self.assertNotIn(customer_url, urls)
def _check_user_direct_access_customer(self, customer, status_code):
response = self.client.get(self._get_customer_url(customer))
self.assertEqual(response.status_code, status_code)
@ddt
class CustomerApiManipulationTest(UrlResolverMixin, test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.ProjectFixture()
# Deletion tests
@data('owner', 'admin', 'manager', 'global_support', 'customer_support', 'project_support')
def test_user_cannot_delete_customer(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
response = self.client.delete(self._get_customer_url(self.fixture.customer))
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_user_cannot_delete_customer_with_associated_projects_if_he_is_staff(self):
self.client.force_authenticate(user=self.fixture.staff)
factories.ProjectFactory(customer=self.fixture.customer)
response = self.client.delete(self._get_customer_url(self.fixture.customer))
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
self.assertDictContainsSubset({'detail': 'Cannot delete organization with existing projects'},
response.data)
# Creation tests
@data('user', 'global_support')
def test_user_can_not_create_customer_if_he_is_not_staff(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
response = self.client.post(factories.CustomerFactory.get_list_url(), self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
@override_waldur_core_settings(CREATE_DEFAULT_PROJECT_ON_ORGANIZATION_CREATION=True)
def test_default_project_is_created_if_configured(self):
self.client.force_authenticate(user=self.fixture.staff)
response = self.client.post(factories.CustomerFactory.get_list_url(), self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
customer = Customer.objects.get(uuid=response.data['uuid'])
self.assertEqual(customer.projects.count(), 1)
self.assertEqual(customer.projects.first().name, 'First project')
self.assertEqual(customer.projects.first().description, 'First project we have created for you')
@override_waldur_core_settings(CREATE_DEFAULT_PROJECT_ON_ORGANIZATION_CREATION=False)
def test_default_project_is_not_created_if_configured(self):
self.client.force_authenticate(user=self.fixture.staff)
response = self.client.post(factories.CustomerFactory.get_list_url(), self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
customer = Customer.objects.get(uuid=response.data['uuid'])
self.assertEqual(customer.projects.count(), 0)
@override_waldur_core_settings(OWNER_CAN_MANAGE_CUSTOMER=True)
def test_user_can_create_customer_if_he_is_not_staff_if_settings_are_tweaked(self):
self.client.force_authenticate(user=self.fixture.user)
response = self.client.post(factories.CustomerFactory.get_list_url(), self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# User became owner of created customer
self.assertEqual(response.data['owners'][0]['uuid'], self.fixture.user.uuid.hex)
def test_user_can_create_customer_if_he_is_staff(self):
self.client.force_authenticate(user=self.fixture.staff)
response = self.client.post(factories.CustomerFactory.get_list_url(), self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Mutation tests
@data('manager', 'admin', 'customer_support', 'project_support', 'global_support')
def test_user_cannot_change_customer_as_whole(self, user):
self.client.force_authenticate(user=getattr(self.fixture, user))
response = self.client.put(self._get_customer_url(self.fixture.customer),
self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_user_cannot_change_customer_he_is_owner_of(self):
self.client.force_authenticate(user=self.fixture.owner)
response = self.client.put(self._get_customer_url(self.fixture.customer),
self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_user_can_change_customer_as_whole_if_he_is_staff(self):
self.client.force_authenticate(user=self.fixture.staff)
response = self.client.put(self._get_customer_url(self.fixture.customer),
self._get_valid_payload())
self.assertEqual(response.status_code, status.HTTP_200_OK, 'Error message: %s' % response.data)
def test_user_cannot_change_single_customer_field_he_is_not_owner_of(self):
self.client.force_authenticate(user=self.fixture.user)
self._check_single_customer_field_change_permission(self.fixture.customer, status.HTTP_404_NOT_FOUND)
def test_user_cannot_change_customer_field_he_is_owner_of(self):
self.client.force_authenticate(user=self.fixture.owner)
self._check_single_customer_field_change_permission(self.fixture.customer, status.HTTP_403_FORBIDDEN)
def test_user_can_change_single_customer_field_if_he_is_staff(self):
self.client.force_authenticate(user=self.fixture.staff)
self._check_single_customer_field_change_permission(self.fixture.customer, status.HTTP_200_OK)
# Helper methods
def _get_valid_payload(self, resource=None):
resource = resource or factories.CustomerFactory()
return {
'name': resource.name,
'abbreviation': resource.abbreviation,
'contact_details': resource.contact_details,
}
def _check_single_customer_field_change_permission(self, customer, status_code):
payload = self._get_valid_payload(customer)
for field, value in payload.items():
data = {
field: value
}
response = self.client.patch(self._get_customer_url(customer), data)
self.assertEqual(response.status_code, status_code)
class CustomerQuotasTest(test.APITransactionTestCase):
def setUp(self):
self.customer = factories.CustomerFactory()
self.staff = factories.UserFactory(is_staff=True)
def test_staff_can_edit_customer_quotas(self):
self.client.force_login(self.staff)
quota = self.customer.quotas.get(name=Customer.Quotas.nc_project_count)
url = quota_factories.QuotaFactory.get_url(quota)
response = self.client.put(url, {
'limit': 100
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
quota.refresh_from_db()
self.assertEqual(quota.limit, 100)
def test_owner_can_not_edit_customer_quotas(self):
owner = factories.UserFactory()
self.customer.add_user(owner, CustomerRole.OWNER)
self.client.force_login(owner)
quota = self.customer.quotas.get(name=Customer.Quotas.nc_project_count)
url = quota_factories.QuotaFactory.get_url(quota)
response = self.client.put(url, {
'limit': 100
})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
quota.refresh_from_db()
self.assertNotEqual(quota.limit, 100)
def test_customer_projects_quota_increases_on_project_creation(self):
factories.ProjectFactory(customer=self.customer)
self.assert_quota_usage('nc_project_count', 1)
def test_customer_projects_quota_decreases_on_project_deletion(self):
project = factories.ProjectFactory(customer=self.customer)
project.delete()
self.assert_quota_usage('nc_project_count', 0)
def test_customer_services_quota_increases_on_service_creation(self):
factories.TestServiceFactory(customer=self.customer)
self.assert_quota_usage('nc_service_count', 1)
def test_customer_services_quota_decreases_on_service_deletion(self):
service = factories.TestServiceFactory(customer=self.customer)
service.delete()
self.assert_quota_usage('nc_service_count', 0)
def test_customer_and_project_service_project_link_quota_updated(self):
self.assert_quota_usage('nc_service_project_link_count', 0)
service = factories.TestServiceFactory(customer=self.customer)
project1 = factories.ProjectFactory(customer=self.customer)
factories.TestServiceProjectLinkFactory(service=service, project=project1)
project2 = factories.ProjectFactory(customer=self.customer)
factories.TestServiceProjectLinkFactory(service=service, project=project2)
self.assertEqual(project1.quotas.get(name='nc_service_project_link_count').usage, 1)
self.assertEqual(project2.quotas.get(name='nc_service_project_link_count').usage, 1)
self.assert_quota_usage('nc_service_project_link_count', 2)
self.assert_quota_usage('nc_service_count', 1)
project2.delete()
project1.delete()
self.assert_quota_usage('nc_service_count', 1)
self.assert_quota_usage('nc_service_project_link_count', 0)
def test_customer_users_quota_increases_on_adding_owner(self):
user = factories.UserFactory()
self.customer.add_user(user, CustomerRole.OWNER)
self.assert_quota_usage('nc_user_count', 1)
def test_customer_users_quota_decreases_on_removing_owner(self):
user = factories.UserFactory()
self.customer.add_user(user, CustomerRole.OWNER)
self.customer.remove_user(user)
self.assert_quota_usage('nc_user_count', 0)
def test_customer_users_quota_increases_on_adding_administrator(self):
project = factories.ProjectFactory(customer=self.customer)
user = factories.UserFactory()
project.add_user(user, ProjectRole.ADMINISTRATOR)
self.assert_quota_usage('nc_user_count', 1)
def test_customer_users_quota_decreases_on_removing_administrator(self):
project = factories.ProjectFactory(customer=self.customer)
user = factories.UserFactory()
project.add_user(user, ProjectRole.ADMINISTRATOR)
project.remove_user(user)
self.assert_quota_usage('nc_user_count', 0)
def test_customer_quota_is_not_increased_on_adding_owner_as_administrator(self):
user = factories.UserFactory()
project = factories.ProjectFactory(customer=self.customer)
self.customer.add_user(user, CustomerRole.OWNER)
project.add_user(user, ProjectRole.ADMINISTRATOR)
self.assert_quota_usage('nc_user_count', 1)
def test_customer_quota_is_not_increased_on_adding_owner_as_manager(self):
user = factories.UserFactory()
project = factories.ProjectFactory(customer=self.customer)
self.customer.add_user(user, CustomerRole.OWNER)
project.add_user(user, ProjectRole.ADMINISTRATOR)
self.assert_quota_usage('nc_user_count', 1)
def test_customer_users_quota_decreases_when_one_project_is_deleted(self):
project = factories.ProjectFactory(customer=self.customer)
user = factories.UserFactory()
project.add_user(user, ProjectRole.ADMINISTRATOR)
self.assert_quota_usage('nc_user_count', 1)
project.delete()
self.assert_quota_usage('nc_user_count', 0)
def test_customer_users_quota_decreases_when_projects_are_deleted_in_bulk(self):
count = 2
for _ in range(count):
project = factories.ProjectFactory(customer=self.customer)
user = factories.UserFactory()
project.add_user(user, ProjectRole.ADMINISTRATOR)
self.assert_quota_usage('nc_user_count', count)
self.customer.projects.all().delete()
self.assert_quota_usage('nc_user_count', 0)
def assert_quota_usage(self, name, value):
self.assertEqual(value, self.customer.quotas.get(name=name).usage)
class CustomerUnicodeTest(TransactionTestCase):
def test_customer_can_have_unicode_name(self):
factories.CustomerFactory(name="Моя организация")
@ddt
class CustomerUsersListTest(test.APITransactionTestCase):
all_users = ('staff', 'owner', 'manager', 'admin', 'customer_support', 'project_support', 'global_support')
def setUp(self):
self.fixture = fixtures.ProjectFixture()
self.url = factories.CustomerFactory.get_url(self.fixture.customer, action='users')
@data(*all_users)
def test_user_can_list_customer_users(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
# call fixture to initiate all users:
for user in self.all_users:
getattr(self.fixture, user)
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 5)
self.assertSetEqual({user['role'] for user in response.data}, {'owner', 'support', None, None})
self.assertSetEqual({user['uuid'] for user in response.data},
{self.fixture.owner.uuid.hex, self.fixture.admin.uuid.hex, self.fixture.manager.uuid.hex,
self.fixture.customer_support.uuid.hex, self.fixture.project_support.uuid.hex})
self.assertSetEqual({user['projects'] and user['projects'][0]['role'] or None
for user in response.data}, {None, 'admin', 'manager', 'support'})
def test_user_can_not_list_project_users(self):
self.client.force_authenticate(self.fixture.user)
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_users_ordering_by_concatenated_name(self):
walter = factories.UserFactory(full_name='', username='walter')
admin = factories.UserFactory(full_name='admin', username='zzz')
alice = factories.UserFactory(full_name='', username='alice')
dave = factories.UserFactory(full_name='dave', username='dave')
expected_order = [admin, alice, dave, walter]
for user in expected_order:
self.fixture.customer.add_user(user, CustomerRole.OWNER)
self.client.force_authenticate(self.fixture.staff)
response = self.client.get(self.url + '?o=concatenated_name')
for serialized_user, expected_user in zip(response.data, expected_order):
self.assertEqual(serialized_user['uuid'], expected_user.uuid.hex)
# reversed order
response = self.client.get(self.url + '?o=-concatenated_name')
for serialized_user, expected_user in zip(response.data, expected_order[::-1]):
self.assertEqual(serialized_user['uuid'], expected_user.uuid.hex)
def test_filter_by_email(self):
walter = factories.UserFactory(full_name='', username='walter', email='[email protected]')
admin = factories.UserFactory(full_name='admin', username='zzz', email='[email protected]')
alice = factories.UserFactory(full_name='', username='alice', email='[email protected]')
for user in [admin, alice, walter]:
self.fixture.customer.add_user(user, CustomerRole.OWNER)
self.client.force_authenticate(self.fixture.staff)
response = self.client.get(self.url, {'email': 'gmail.com'})
self.assertEqual(len(response.data), 2)
@ddt
class CustomerCountersListTest(test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.ServiceFixture()
self.owner = self.fixture.owner
self.customer_support = self.fixture.customer_support
self.admin = self.fixture.admin
self.manager = self.fixture.manager
self.project_support = self.fixture.project_support
self.customer = self.fixture.customer
self.service = self.fixture.service
self.url = factories.CustomerFactory.get_url(self.customer, action='counters')
@data('owner', 'customer_support')
def test_user_can_get_customer_counters(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.get(self.url, {'fields': ['users', 'projects', 'services']})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, {'users': 5, 'projects': 1, 'services': 1})
class UserCustomersFilterTest(test.APITransactionTestCase):
def setUp(self):
self.staff = factories.UserFactory(is_staff=True)
self.user1 = factories.UserFactory()
self.user2 = factories.UserFactory()
self.customer1 = factories.CustomerFactory()
self.customer2 = factories.CustomerFactory()
self.customer1.add_user(self.user1, CustomerRole.OWNER)
self.customer2.add_user(self.user1, CustomerRole.OWNER)
self.customer2.add_user(self.user2, CustomerRole.OWNER)
def test_staff_can_filter_customer_by_user(self):
self.assert_staff_can_filter_customer_by_user(self.user1, {self.customer1, self.customer2})
self.assert_staff_can_filter_customer_by_user(self.user2, {self.customer2})
def assert_staff_can_filter_customer_by_user(self, user, customers):
self.client.force_authenticate(self.staff)
response = self.client.get(factories.CustomerFactory.get_list_url(), {
'user_uuid': user.uuid.hex,
'fields': ['uuid']
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual({customer['uuid'] for customer in response.data},
{customer.uuid.hex for customer in customers})
@ddt
class AccountingIsRunningFilterTest(test.APITransactionTestCase):
def setUp(self):
self.enabled_customers = factories.CustomerFactory.create_batch(2)
future_date = timezone.now() + timezone.timedelta(days=1)
self.disabled_customers = factories.CustomerFactory.create_batch(
3, accounting_start_date=future_date)
self.all_customers = self.enabled_customers + self.disabled_customers
def count_customers(self, accounting_is_running=None):
self.client.force_authenticate(factories.UserFactory(is_staff=True))
url = factories.CustomerFactory.get_list_url()
params = {}
if accounting_is_running in (True, False):
params['accounting_is_running'] = accounting_is_running
response = self.client.get(url, params)
return len(response.data)
@data(
(True, 'enabled_customers'),
(False, 'disabled_customers'),
(None, 'all_customers')
)
@override_waldur_core_settings(ENABLE_ACCOUNTING_START_DATE=True)
def test_feature_is_enabled(self, params):
actual = self.count_customers(params[0])
expected = len(getattr(self, params[1]))
self.assertEqual(expected, actual)
@data(True, False, None)
@override_waldur_core_settings(ENABLE_ACCOUNTING_START_DATE=False)
def test_feature_is_disabled(self, param):
actual = self.count_customers({'accounting_is_running': param})
expected = len(self.all_customers)
self.assertEqual(expected, actual)
|
// Type definitions for convert-excel-to-json 1.7
// Project: https://github.com/DiegoZoracKy/convert-excel-to-json
// Definitions by: UNIDY2002 <https://github.com/UNIDY2002>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
interface SheetConfig {
header?: { rows: number } | undefined;
range?: string | undefined;
columnToKey?: { [key: string]: string } | undefined;
includeEmptyLines?: boolean | undefined;
sheetStubs?: boolean | undefined;
}
declare function excelToJson(
config: ({ sourceFile: string } | { source: string | Buffer }) // Either sourceFile or source should have a value
& { sheets?: ReadonlyArray<(string | (SheetConfig & { name: string }))> | undefined } // Nested SheetConfig should be allowed
& SheetConfig // ... or just a simple config for all
| string, // Input can also be a json-string (for cli)
sourceFile?: string, // For cli
): { [key: string]: any[] }; // Using any to provide more flexibility for downstream usages
export = excelToJson;
|
import React, { Component, CSSProperties } from 'react'
export interface IDialogProps {
open?: boolean
style?: CSSProperties
className?: string
top?: boolean
left?: boolean
right?: boolean
bottom?: boolean
}
export class Dialog extends Component<IDialogProps, any> {
constructor(props: IDialogProps) {
super(props)
}
componentDidUpdate(props: IDialogProps) {
console.log('component did update fired')
let modal: any = document.getElementById('gerami-dialog-box')
if (props.bottom) {
modal.classList.add('anime-bottom')
} else if (props.left) {
modal.classList.add('anime-left')
} else if (props.right) {
modal.classList.add('anime-right')
} else if (props.top) {
modal.classList.add('anime-top')
} else {
modal.classList.remove('anime-right', 'anime-left', 'anime-top', 'anime-bottom')
}
}
render() {
const { open, children, style, className } = this.props
return (
<div
className="gerami-dialog-container"
id={'gerami-dialog-container'}
style={{ display: open ? 'block' : 'none' }}
onClick={this.handleDialogContainer}
>
<div
style={style}
id={'gerami-dialog-box'}
className={`gerami-dialog-box ${className ? className : ''}`}
>
{children}
</div>
</div>
)
}
handleDialogContainer = () => {
let container: any = document.getElementById('gerami-dialog-container')
container.style.display = 'none'
}
}
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Apie.Diff.GParseJSON
( genericParseDiff )
where
import RIO hiding (to)
import qualified RIO.Text as T
import GHC.Generics
import Data.Aeson (Value, Object, Options, fieldLabelModifier, withObject)
import Data.Aeson.Types
import qualified Data.HashMap.Strict as H
import Apie.Diff.Types (Diff(..))
genericParseDiff :: (Generic a, GParseJSON (Rep a)) => Options -> Value -> Parser a
genericParseDiff opts v = to <$> withObject "Object diff" (parseJSONDiff opts) v
class GParseJSON f where
parseJSONDiff :: Options -> Object -> Parser (f a)
instance GParseJSON U1 where
parseJSONDiff _ _ = pure U1
instance GParseJSON f => GParseJSON (D1 x f) where
parseJSONDiff opts obj = M1 <$> parseJSONDiff @f opts obj
instance GParseJSON f => GParseJSON (C1 x f) where
parseJSONDiff opts obj = M1 <$> parseJSONDiff @f opts obj
instance (GParseJSON a, GParseJSON b) => GParseJSON (a :*: b) where
parseJSONDiff opts obj =
(:*:) <$> parseJSONDiff opts obj
<*> parseJSONDiff opts obj
instance (Selector s, FromJSON a) => GParseJSON (S1 s (K1 i a)) where
parseJSONDiff opts obj = M1 . K1 <$> obj .: label
where
label = T.pack $ fieldLabelModifier opts sname
sname = selName (undefined :: M1 _i s _f _p)
instance {-# OVERLAPPING #-} GParseJSON (S1 s (K1 i (Const () a))) where
parseJSONDiff _ _ = M1 . K1 <$> pure (Const ())
instance {-# OVERLAPPING #-} (Selector s, FromJSON a) => GParseJSON (S1 s (K1 i (Diff a))) where
parseJSONDiff opts obj =
case H.lookup label obj of
Just _ -> M1 . K1 . Changed <$> obj .: label
Nothing -> M1 . K1 <$> pure Unchanged
where
label = T.pack $ fieldLabelModifier opts sname
sname = selName (undefined :: M1 _i s _f _p)
|
# frozen_string_literal: true
class User
include Mongoid::Document
include Mongoidable::Document
devise :database_authenticatable
field :encrypted_password, type: String, default: ""
field :name, type: String
field :ids, type: Array
belongs_to :parent1, class_name: "Parent1", optional: true
belongs_to :parent2, class_name: "Parent2", optional: true
embeds_many :embedded_parents, class_name: "Parent1"
has_and_belongs_to_many :many_relations
inherits_abilities_from(:parent1)
inherits_abilities_from(:parent2)
accepts_policies(as: :policies)
define_abilities do |abilities, _model|
abilities.can :do_user_class_stuff, User
abilities.cannot :do_other_user_class_stuff, User
end
def devise_scope
:user
end
end
|
<?php
namespace apiend\modules\v1\actions\order;
use apiend\models\Response;
use apiend\modules\v1\actions\BaseAction;
use common\models\order\OrderGoodsScenePage;
use common\models\User;
use common\utils\PoseUtil;
use Yii;
use yii\db\Exception;
/**
* 保存用户上传到场景的图片
*
* @author Administrator
*/
class SaveSceneUserImage extends BaseAction
{
/* 必须参数 */
protected $requiredParams = ['ogp_id', 'user_img_url'];
public function run()
{
$ogp_id = $this->getSecretParam('ogp_id');
$page = OrderGoodsScenePage::findOne(['id' => $ogp_id, 'is_del' => 0]);
if ($page == null) {
return new Response(Response::CODE_COMMON_NOT_FOUND, null, null, ['param' => Yii::t('app', 'Scene')]);
}
$page->user_img_url = $this->getSecretParam('user_img_url');
$tran = \Yii::$app->db->beginTransaction();
try {
$res = $page->save();
$result = $this->checkPose($page, $page->user_img_url);
if ($res && $result) {
$tran->commit();
return new Response(Response::CODE_COMMON_OK, null, $result);
} else {
$tran->rollBack();
throw new \Exception("保存出错! res:{$res} result:{$result}");
}
} catch (\Exception $e) {
$tran->rollBack();
return new Response(Response::CODE_COMMON_SAVE_DB_FAIL, $e->getMessage());
}
}
/**
* 检查 pose
* @param OrderGoodsScenePage $page
* @param string $filepath
* @return array|bool
* @throws \Exception
*/
private function checkPose($page, $filepath)
{
/**
* 当得分在90~100分之间时,出现文字:动作完美,+10个演绎分。
* 当得分在80~90分之间时,出现文字:动作不错,+5个演绎分。
* 当得分在80分以下时,出现文字:动作不行喔,请重新拍摄上传。
*/
$marks = [
['avg_score' => 0,'play_score' => 0,],
['avg_score' => 80,'play_score' => 5,],
['avg_score' => 90,'play_score' => 10,]
];
$filepath .= '?x-oss-process=image/resize,m_lfit,h_720,w_720';
/* @var $user User */
$user = \Yii::$app->user->identity;
$source_page = $page->sourcePage;
if($page->orderGoods->goods->category->code != 'mofang'){
// 不是模仿
return [
'ogp_id' => $page->id,
'play_score' => -1,
'gameData' => $user->gameData
];
}
if ($source_page && $source_page->pose && $source_page->pose->pose_data) {
// 计算得分
$check_result = PoseUtil::check($filepath, json_decode($source_page->pose->required_data, true));
$avg_score = $check_result['avg_score'];
$play_score = 0;
for ($i = count($marks)-1; $i >= 0; $i--) {
if ($avg_score >= $marks[$i]['avg_score']) {
$play_score = $marks[$i]['play_score'];
break;
}
}
// 更新用户表演积分
$game_data = $user->gameData;
$game_data->play_score = $game_data->play_score + $play_score;
// 保存当前场景得分
$page->user_data = json_encode(['play_score' => $avg_score]);
$game_data->save();
$page->save();
return [
'ogp_id' => $page->id,
'play_score' => $avg_score,
'gameData' => $game_data,
];
} else {
return [
'ogp_id' => $page->id,
'play_score' => 0,
'gameData' => $user->gameData
];
}
}
}
|
#!/bin/bash
./gradlew clean build bintrayUpload -PbintrayUser=${BINTRAY_USER} -PbintrayKey=${BINTRAY_KEY} -PdryRun=false
|
using System;
#pragma warning disable 660 // 'Point' defines operator == or operator != but does not override Object.Equals(object o)
#pragma warning disable 661 // 'Point' defines operator == or operator != but does not override Object.GetHashCode()
namespace Structs {
public struct Point {
public static readonly Point Zero;
public Point (float x, float y)
{
X = x;
Y = y;
}
public float X { get; private set; }
public float Y { get; private set; }
public static bool operator == (Point left, Point right)
{
return ((left.X == right.X) && (left.Y == right.Y));
}
public static bool operator != (Point left, Point right)
{
return !(left == right);
}
public static Point operator + (Point left, Point right)
{
return new Point (left.X + right.X, left.Y + right.Y);
}
public static Point operator - (Point left, Point right)
{
return new Point (left.X - right.X, left.Y - right.Y);
}
}
public class Array
{
public static Point [] Points => new Point [] { new Point (0, 0), new Point (1, 1), new Point (2, 2) };
}
}
|
package com.netflix.spinnaker.keel.events
import com.netflix.spinnaker.keel.api.Environment
import com.netflix.spinnaker.keel.api.NotificationFrequency
import com.netflix.spinnaker.keel.api.constraints.ConstraintState
import com.netflix.spinnaker.keel.api.constraints.ConstraintStatus.OVERRIDE_PASS
import com.netflix.spinnaker.keel.api.constraints.DefaultConstraintAttributes
import com.netflix.spinnaker.keel.api.plugins.PluginNotificationConfig
import com.netflix.spinnaker.keel.api.plugins.PluginNotificationsStatus
import com.netflix.spinnaker.keel.api.constraints.StatefulConstraintEvaluator
import com.netflix.spinnaker.keel.api.constraints.SupportedConstraintType
import com.netflix.spinnaker.keel.api.events.ConstraintStateChanged
import com.netflix.spinnaker.keel.constraints.StatefulConstraintEvaluatorTests.Fixture.FakeConstraint
import com.netflix.spinnaker.keel.test.deliveryConfig
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import org.springframework.context.ApplicationEventPublisher
class ConstraintStateChangedRelayTests : JUnit5Minutests {
object Fixture {
private val constraint = FakeConstraint()
val event = ConstraintStateChanged(
environment = Environment(
name = "test",
constraints = setOf(constraint)
),
constraint = constraint,
previousState = null,
currentState = ConstraintState(
deliveryConfigName = "myconfig",
environmentName = "test",
artifactReference = "whatever",
artifactVersion = "whatever",
status = OVERRIDE_PASS,
type = constraint.type
),
deliveryConfig = deliveryConfig()
)
val pluginNotification = PluginNotificationConfig(
title = "title",
message = "message",
status = PluginNotificationsStatus.FAILED,
buttonText = null,
buttonLink = null,
notificationLevel = NotificationFrequency.normal,
provenance = "plugin",
)
internal val matchingEvaluator = mockk<StatefulConstraintEvaluator<FakeConstraint, DefaultConstraintAttributes>>() {
every { supportedType } returns SupportedConstraintType("fake", FakeConstraint::class.java)
every { onConstraintStateChanged(event) } just runs
}
internal val nonMatchingEvaluator = mockk<StatefulConstraintEvaluator<FakeConstraint, DefaultConstraintAttributes>>() {
every { supportedType } returns SupportedConstraintType("the-wrong-fake", FakeConstraint::class.java)
}
val publisher: ApplicationEventPublisher = mockk(relaxUnitFun = true)
val subject = ConstraintStateChangedRelay(listOf(matchingEvaluator, nonMatchingEvaluator), publisher)
}
fun tests() = rootContext<Fixture> {
context("a stateful constraint state changed event is emitted") {
fixture { Fixture }
before {
every { matchingEvaluator.onConstraintStateChangedWithNotification(event) } returns null
every { nonMatchingEvaluator.onConstraintStateChangedWithNotification(event) } returns null
subject.onConstraintStateChanged(event)
}
test("the event is relayed to the correct constraint evaluator") {
verify(exactly = 1) {
matchingEvaluator.onConstraintStateChanged(event)
matchingEvaluator.onConstraintStateChangedWithNotification(event)
}
verify(exactly = 0) {
nonMatchingEvaluator.onConstraintStateChanged(event)
nonMatchingEvaluator.onConstraintStateChangedWithNotification(event)
}
}
}
context("the evaluator returns a notification") {
fixture { Fixture }
before {
every { matchingEvaluator.onConstraintStateChangedWithNotification(event) } returns pluginNotification
every { nonMatchingEvaluator.onConstraintStateChangedWithNotification(event) } returns null
subject.onConstraintStateChanged(event)
}
test("the notification is propagated") {
verify(exactly = 1) {
publisher.publishEvent(PluginNotification(pluginNotification, event))
}
}
}
}
}
|
using System;
namespace DnsBits
{
/// <summary>
/// Base exceptions for BnsBits project.
/// </summary>
public class DnsBitsException : Exception
{
public DnsBitsException() : base() { }
public DnsBitsException(string message) : base(message) { }
public DnsBitsException(string message, Exception innerException) : base(message, innerException) { }
}
}
|
import 'package:flutter/material.dart';
import 'package:natbank/screens/login/new_account_form.dart';
import 'login_button.dart';
import 'login_input_field.dart';
/**
* TODO: autenticar no web service e usar o token como sessão do cliente
*/
class Login extends StatelessWidget {
final TextEditingController _userCpfFieldController = TextEditingController();
final TextEditingController _userPasswordFieldController =
TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(color: Colors.white),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
ClipPath(
clipper: LoginClipper(),
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/natbank_logo.png'),
fit: BoxFit.cover),
),
alignment: Alignment.center,
padding: EdgeInsets.only(top: 150, bottom: 100),
),
),
Padding(
padding: const EdgeInsets.only(left: 40),
child: Text(
"CPF",
style: TextStyle(color: Colors.grey, fontSize: 16),
),
),
LoginInputField(
hintText: "Digite seu CPF",
icon: Icons.person_outline,
controller: _userCpfFieldController,
keyboardType: TextInputType.number,
),
Padding(
padding: const EdgeInsets.only(left: 40),
child: Text(
"Senha",
style: TextStyle(color: Colors.grey, fontSize: 16),
),
),
LoginInputField(
icon: Icons.lock_open,
hintText: "Digite sua senha",
controller: _userPasswordFieldController,
keyboardType: TextInputType.numberWithOptions(decimal: true),
obscureText: true,
),
LoginButton(
buttonIcon: Icons.arrow_forward,
buttonText: "Entrar",
cpfController: _userCpfFieldController,
passwordController: _userPasswordFieldController,
),
CreateAccountButton()
],
),
),
),
);
}
}
class CreateAccountButton extends StatelessWidget {
const CreateAccountButton({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20),
padding: EdgeInsets.only(left: 20, right: 20),
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
color: Colors.transparent,
child: Container(
padding: EdgeInsets.only(left: 20),
alignment: Alignment.center,
child: Text(
"ABRIR UMA NOVA CONTA",
style: TextStyle(color: Theme.of(context).primaryColor),
),
),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (routeContext) => NewAccount())),
),
)
],
),
);
}
}
class LoginClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
Path p = Path()
..lineTo(size.width, 0)
..lineTo(size.width, size.height * 0.85)
..arcToPoint(
Offset(0, size.height * 0.85),
radius: const Radius.elliptical(50, 10),
rotation: 0,
)
..lineTo(0, 0)
..close();
return p;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.