text
stringlengths 27
775k
|
|---|
<?php
namespace Mdaliyan\FarsiRequest\Middleware;
use Closure;
use Illuminate\Http\Request;
class ReplaceArabicCharacters
{
private $ignoreParameters = ['q', '_method', '_token'];
/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$parameters = array_filter($request->except($this->ignoreParameters),
function ($value) {
return is_string($value);
});
$edited = [];
array_walk($parameters, function ($value, $key) use (&$edited) {
$edited[$key] = $this->replaceCharacters($value);
});
if (count($edited)) {
$request->merge($edited);
}
return $next($request);
}
/**
* @param $text
* @return mixed
* @internal param $string
*/
private function replaceCharacters($text)
{
if (is_null($text)) {
return null;
}
$replace_Pairs = [
// numbers
chr(0xD9) . chr(0xA0) => chr(0xDB) . chr(0xB0), // ٠
chr(0xD9) . chr(0xA1) => chr(0xDB) . chr(0xB1), // ١
chr(0xD9) . chr(0xA2) => chr(0xDB) . chr(0xB2), // ٢
chr(0xD9) . chr(0xA3) => chr(0xDB) . chr(0xB3), // ٣
chr(0xD9) . chr(0xA4) => chr(0xDB) . chr(0xB4), // ٤
chr(0xD9) . chr(0xA5) => chr(0xDB) . chr(0xB5), // ٥
chr(0xD9) . chr(0xA6) => chr(0xDB) . chr(0xB6), // ٦
chr(0xD9) . chr(0xA7) => chr(0xDB) . chr(0xB7), // ٧
chr(0xD9) . chr(0xA8) => chr(0xDB) . chr(0xB8), // ٨
chr(0xD9) . chr(0xA9) => chr(0xDB) . chr(0xB9), // ٩
// kaaf
chr(0xD9) . chr(0x83) => chr(0xDA) . chr(0xA9), // ك
// ye
chr(0xD9) . chr(0x89) => chr(0xDB) . chr(0x8C), // ى
chr(0xD9) . chr(0x8A) => chr(0xDB) . chr(0x8C), // ي
chr(0xD9) . chr(0x8A) => chr(0xDB) . chr(0x8C), // ي
// he
chr(0xD8) . chr(0xA9) => chr(0xD9) . chr(0x87), // ي
// he + hamze
chr(0xDB) . chr(0x80) => chr(0xD9) . chr(0x87) . chr(0xD9) . chr(0x94),
];
return strtr($text, $replace_Pairs);
}
}
|
package elem
import "bytes"
type NodeIDType byte
const (
NodeIDTypeIPv4Addr NodeIDType = 0
NodeIDTypeIPv6Addr NodeIDType = 1
NodeIDTypeFQDN NodeIDType = 2
)
type NodeID struct {
EType IEType
ELength uint16
NodeIDType
NodeID []byte
}
func NewIPv4NodeID(ipv4 []byte) *NodeID {
return &NodeID{
EType: IETypeNodeID,
ELength: uint16(4),
NodeIDType: NodeIDTypeIPv4Addr,
NodeID: ipv4,
}
}
func DecodeNodeID(buf *bytes.Buffer, len uint16) *NodeID {
return &NodeID{
EType: IETypeNodeID,
ELength: len,
NodeIDType: NodeIDType(GetValue(buf, 1)[0]),
NodeID: GetValue(buf, len-1),
}
}
func EncodeNodeID(n NodeID) []byte {
return SetValue(n.EType, n.ELength, n.NodeIDType, n.NodeID)
}
//判断是否含有NodeID
func HasNodeID(n NodeID) bool {
if n.EType == 0 {
return false
}
return true
}
|
package helpers
import (
"fmt"
"github.com/spf13/viper"
)
// DatabaseConfig is a struct to manage database configuration.
type DatabaseConfig struct {
Host string
Port string
User string
Password string
DBName string
SSLMode string
Schema string
}
// InitWithViper simply takes a configured viper pointer and returns a new DatabaseConfig
// with hydrated fields according to viper's configuration.
func InitWithViper(vpr *viper.Viper) DatabaseConfig {
return DatabaseConfig{
Host: vpr.GetString(EnvDBHost),
Port: vpr.GetString(EnvDBPort),
User: vpr.GetString(EnvDBUser),
Password: vpr.GetString(EnvDBPassword),
DBName: vpr.GetString(EnvDBName),
SSLMode: vpr.GetString(EnvDBSSlMode),
Schema: vpr.GetString(EnvDBSchema),
}
}
// ConnString returns a connexion string according to current configuration.
func (dbc DatabaseConfig) ConnString() string {
const connexionString = "host=%s port=%s user=%s password=%s dbname=%s sslmode=%s search_path=%s"
return fmt.Sprintf(connexionString, dbc.Host, dbc.Port, dbc.User, dbc.Password, dbc.DBName, dbc.SSLMode, dbc.Schema)
}
|
package typingsSlinky.tensorflowTfjsConverter
import typingsSlinky.tensorflowTfjsConverter.operationsTypesMod.OpExecutor
import typingsSlinky.tensorflowTfjsConverter.operationsTypesMod.OpMapper
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object registerMod {
@JSImport("@tensorflow/tfjs-converter/dist/operations/custom_op/register", "deregisterOp")
@js.native
def deregisterOp(name: String): Unit = js.native
@JSImport("@tensorflow/tfjs-converter/dist/operations/custom_op/register", "getRegisteredOp")
@js.native
def getRegisteredOp(name: String): OpMapper = js.native
@JSImport("@tensorflow/tfjs-converter/dist/operations/custom_op/register", "registerOp")
@js.native
def registerOp(name: String, opFunc: OpExecutor): Unit = js.native
}
|
//original license: MIT
//
//See the file license.txt for copying permission.
using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
namespace screenium.Reports
{
/// <summary>
/// horrible code to be able to serialize TimeSpan to XML via XmlSerializer
/// </summary>
/// <remarks>
/// any way to do mixins with C#?
/// OR else move away from XmlSerializer!</remarks>
public class XmlDurationHolder
{
//TODO TimeSpan serializing: replace this horrible code with other solution -> move away from XmlSerializer ?
TimeSpan _duration;
[XmlIgnore]
public TimeSpan Duration
{
get
{
return _duration;
}
set
{
DurationHumanReadableInXml = DateSupport.ToString(value);
_duration = value;
}
}
public string DurationHumanReadableInXml { get; set; }
// XmlSerializer does not support TimeSpan, so use this property for
// serialization instead.
[Browsable(false)]
[XmlElement(DataType = "duration", ElementName = "DurationXml")]
public string TimeSinceLastEventString
{
get
{
return XmlConvert.ToString(Duration);
}
set
{
Duration = string.IsNullOrWhiteSpace(value) ?
TimeSpan.Zero : XmlConvert.ToTimeSpan(value);
}
}
}
}
|
package natsclient
import (
"encoding/json"
"fmt"
"time"
nats "github.com/nats-io/nats.go"
)
//NatsClient is the state of the client
type NatsClient struct {
client *nats.Conn
subscriptions map[string]*nats.Subscription
}
//NewNatsClient creates a new NATS client and attempts to connect to the specified endpoint
func NewNatsClient(endpoint string) (*NatsClient, error) {
client, err := nats.Connect(endpoint)
if err != nil {
return nil, err
}
return &NatsClient{
client: client,
subscriptions: make(map[string]*nats.Subscription),
}, nil
}
//Publish sends a message to subject subscriptions
func (c *NatsClient) Publish(subject string, msg interface{}) error {
bytes, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("Failed to marshal message: %s", err)
}
err = c.client.Publish(subject, bytes)
if err != nil {
return fmt.Errorf("Failed to publish message: %s", err)
}
return nil
}
//Request sends a message to subject subscriptions
func (c *NatsClient) Request(subject string, msg interface{}) (*nats.Msg, error) {
bytes, err := json.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("Failed to marshal Request payload: %s", err)
}
reqMsg, err := c.client.Request(subject, bytes, 5*time.Second)
if err != nil {
return nil, fmt.Errorf("Failed to send Request: %s", err)
}
return reqMsg, nil
}
//Subscribe to a nats subject with a callback
func (c *NatsClient) Subscribe(subject string, callback func(msg *nats.Msg)) error {
if err := c.validateSubscription(subject); err != nil {
return err
}
sub, err := c.client.Subscribe(subject, callback)
if err != nil {
return err
}
c.subscriptions[subject] = sub
return nil
}
//QueueSubscribe to a nats subject and queue group with a callback
func (c *NatsClient) QueueSubscribe(subject string, queue string, callback func(msg *nats.Msg)) error {
if err := c.validateSubscription(subject); err != nil {
return err
}
sub, err := c.client.QueueSubscribe(subject, queue, callback)
if err != nil {
return err
}
c.subscriptions[subject] = sub
return nil
}
//ChanSubscribe to a nats subject with a channel
func (c *NatsClient) ChanSubscribe(subject string) (<-chan *nats.Msg, error) {
if err := c.validateSubscription(subject); err != nil {
return nil, err
}
channel := make(chan *nats.Msg, 1)
sub, err := c.client.ChanSubscribe(subject, channel)
if err != nil {
return nil, err
}
c.subscriptions[subject] = sub
return channel, nil
}
//ChanQueueSubscribe to a nats subject and queue group with a channel
func (c *NatsClient) ChanQueueSubscribe(subject string, queue string) (<-chan *nats.Msg, error) {
if err := c.validateSubscription(subject); err != nil {
return nil, err
}
channel := make(chan *nats.Msg, 1)
sub, err := c.client.QueueSubscribeSyncWithChan(subject, queue, channel)
if err != nil {
return nil, err
}
c.subscriptions[subject] = sub
return channel, nil
}
//Unsubscribe drains a subscription
func (c *NatsClient) Unsubscribe(subject string) error {
sub, exists := c.subscriptions[subject]
if !exists {
return nil
}
err := sub.Drain()
if err != nil {
return err
}
delete(c.subscriptions, subject)
return nil
}
//Shutdown gracefull cleans up subscriptions and the client
func (c *NatsClient) Shutdown() {
for _, sub := range c.subscriptions {
sub.Drain()
}
c.client.Drain()
}
func (c *NatsClient) validateSubscription(subject string) error {
if _, exists := c.subscriptions[subject]; exists {
return fmt.Errorf("Subscription for '%s' already exists", subject)
}
return nil
}
|
package ru.nikstep.alarm.util
import android.view.View
import com.google.android.material.snackbar.Snackbar
fun showSnackbar(
view: View,
message: String,
duration: Int = Snackbar.LENGTH_LONG,
actionName: String = "OK",
action: () -> Unit = {}
) {
Snackbar.make(view, message, duration)
.setAction(actionName) {
action.invoke()
}
.show()
}
|
# PHP/Goutte版 Y!mobile通信速度回復スクリプト
### これは何?
Y!mobileで通信速度を低速化された時、通信速度を通常に戻す申し込みを実行するスクリプトです。
スクレイピングライブラリとして[Goutte](https://github.com/FriendsOfPHP/Goutte)を使用しています。composerでダウンロードして使って下さい。
### 作成の目的と公開の目的
当スクリプトは私が個人的に使用することを目的として作成し、Goutteの使用例として参考になればと思って公開しています。
**スクリプトを実行する際は必ずソースコードを確認の上、自己責任でお願いします。**
### 実行方法
```sh
php Automator.php 電話番号 パスワード 契約番号
```
### 実行環境
MacOS X El Capitan (10.11.1) / PHP 5.6.16 で動作確認しています。
|
(ns oubiwann.blog.web.content.page
(:require
[dragon.selmer.core :as template]
[dragon.util :as util]
[oubiwann.blog.web.content.data :as data]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Static Pages ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn about
[system]
(template/render
"templates/pages/generic.html"
(data/about system)))
(defn contact
[system]
(template/render
"templates/pages/generic.html"
(data/contact system)))
(defn powered-by
[system]
(template/render
"templates/pages/generic.html"
(data/powered-by system)))
(defn license
[system]
(template/render
"templates/pages/generic.html"
(data/license system)))
(defn code-highlight
[system]
(template/render
"templates/pages/generic.html"
(data/code-highlight system)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dynamic Pages ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn post
[system post-key]
(template/render
"templates/pages/post.html"
(data/post system post-key)))
(defn front-page
[system]
(template/render
"templates/pages/home.html"
(data/front-page system)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Listings Pages ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn archives
[system]
(template/render
"templates/listings/archives.html"
(data/archives system)))
(defn categories
[system]
(template/render
"templates/listings/categories.html"
(data/categories system)))
(defn tags
[system]
(template/render
"templates/listings/tags.html"
(data/tags system)))
(defn authors
[system]
(template/render
"templates/listings/authors.html"
(data/authors system)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Design Pages ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn design
[system]
(template/render
"templates/design/index.html"
(data/design system)))
(defn bootstrap-theme
[system]
(template/render
"templates/design/bootswatch-theme.html"
(data/design system)))
(defn front-page-example
[system]
(template/render
"templates/design/home.html"
(data/design system)))
(defn blog-post-example
[system]
(template/render
"templates/design/post.html"
(data/design system)))
|
import * as path from 'path';
import * as sass from 'gulp-sass';
export function generate(gulp, config, gulptraum): void {
const outputFolderPath = path.resolve(config.paths.root, config.paths.output);
gulptraum.task('build-sass', {
help: 'Builds your sass files into css'
}, (callback) => {
return gulp.src(config.paths.source)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(outputFolderPath));
});
}
|
namespace FootballPredictions.Models
{
public class Prediction
{
public int Id { get; set; }
public Game Game { get; set; }
public GameResult Result { get; set; }
// TODO: prediction should have user
}
}
|
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50715
Source Host : localhost
Source Database : quartz
Target Server Type : MySQL
Target Server Version : 50715
File Encoding : utf-8
Date: 03/19/2019 17:35:03 PM
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `SCHEDULE_JOB`
-- ----------------------------
DROP TABLE IF EXISTS `SCHEDULE_JOB`;
CREATE TABLE `SCHEDULE_JOB` (
`schedule_job_id` bigint(20) NOT NULL AUTO_INCREMENT,
`job_name` varchar(255) DEFAULT NULL,
`alias_name` varchar(255) DEFAULT NULL,
`job_group` varchar(255) DEFAULT NULL,
`job_trigger` varchar(255) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`cron_expression` varchar(255) DEFAULT NULL,
`is_sync` varchar(1) NOT NULL,
`url` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`gmt_create` timestamp NULL DEFAULT NULL,
`gmt_modify` timestamp NULL DEFAULT NULL,
`job_class` varchar(255) DEFAULT NULL COMMENT '需要执行的逻辑类名',
`job_class_method` varchar(255) DEFAULT NULL COMMENT '执行作业的方法名称',
PRIMARY KEY (`schedule_job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS = 1;
|
import Vuex from "vuex";
const createStore = () => {
return new Vuex.Store({
state: {
headlines: []
},
mutations: {
setHeadlines(state, headlines) {
state.headlines = headlines;
}
},
actions: {
async loadHeadlines({ commit }, apiUrl) {
const { articles } = await this.$axios.$get(apiUrl);
commit("setHeadlines", articles);
}
},
getters: {
headlines: state => state.headlines
}
});
};
export default createStore;
|
package com.fzm.chat33.core.di
import com.fzm.chat33.core.global.EncryptInterceptor
import com.fzm.chat33.core.logic.MessageDispatcher
import com.fzm.chat33.core.logic.MessageHandler
import com.fzm.chat33.core.manager.MessageManager
import com.fzm.chat33.core.net.RequestManager
import com.fzm.chat33.core.net.socket.ChatSocket
import com.fzm.chat33.core.net.socket.SocketServiceProvider
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.provider
import org.kodein.di.generic.singleton
/**
* @author zhengjy
* @since 2019/09/12
* Description:网络请求相关类注入
*/
fun chatModule() = Kodein.Module("ChatModule") {
bind<RequestManager>() with singleton { RequestManager.INS }
bind<ChatSocket>() with provider { SocketServiceProvider.provide() }
bind<MessageManager>() with provider { MessageManager(instance(), instance(), instance()) }
bind<MessageHandler>() with singleton { MessageHandler(instance(), instance(), instance(), instance()) }
bind<MessageDispatcher>() with singleton { MessageDispatcher(instance(), instance(), instance(), instance()) }
bind<EncryptInterceptor>(tag = "encryptInterceptor") with singleton { EncryptInterceptor() }
}
|
use crate::{Canvas, Point};
pub struct StickMan{
pub points: [Point; 10]
}
impl StickMan{
pub fn new() -> StickMan{
let left_hand = Point::new(-10, 0);
let right_hand = Point::new(40, 0);
let neck = Point::new(10, 0);
let hip = Point::new(10, 10);
let left_foot = Point::new(0, 50);
let right_foot = Point::new(20, 50);
StickMan{
points: [
left_hand, neck,
right_hand, neck,
neck, hip,
left_foot, hip,
right_foot, hip
]
}
}
pub fn set_left_hand(&mut self, p: Point){
self.points[0] = p;
}
pub fn set_right_hand(&mut self, p: Point){
self.points[2] = p;
}
pub fn set_neck(&mut self, p: Point){
self.points[1] = p;
self.points[3] = p;
}
pub fn set_hip(&mut self, p: Point){
self.points[5] = p;
self.points[7] = p;
self.points[9] = p;
}
pub fn set_left_foot(&mut self, p: Point){
self.points[6] = p;
}
pub fn set_right_foot(&mut self, p: Point){
self.points[8] = p;
}
pub fn draw(&self, cvs:&mut Canvas) -> Result<(), String>{
cvs.draw_lines(self)?;
Ok(())
}
}
impl<'a> From<&'a StickMan> for &'a[Point]{
fn from(man: &'a StickMan) -> &'a [Point] {
&man.points
}
}
|
=begin
= How to play.
== with timeridconv:
% ruby -d holders.rb
druby://yourhost:1234
% ruby holderc.rb druby://yourhost:1234
== without timeridconv:
% ruby holders.rb
druby://yourhost:1234
% ruby holderc.rb druby://yourhost:1234
=end
require 'drb/drb'
class DRbEx3
include DRbUndumped
def initialize(n)
@v = n
end
def sample(list)
sum = 0
list.each do |e|
sum += e.to_i
end
@v * sum
end
end
class DRbEx4
include DRbUndumped
def initialize
@curr = 1
end
def gen
begin
@curr += 1
DRbEx3.new(@curr)
ensure
GC.start
end
end
end
if __FILE__ == $0
if $DEBUG
require 'drb/timeridconv'
DRb.install_id_conv(DRb::TimerIdConv.new(2))
end
DRb.start_service(nil, DRbEx4.new)
puts DRb.uri
DRb.thread.join
end
|
"""
Main file for running pcapmap program
"""
import argparse
import logging
import os
from pathlib import Path
from pcap2map.pcap2ip import Pcap2IP
from pcap2map.ip2map import IP2Map
class Pcap2Map():
def __init__(self):
self.file = None
self.png_path = None
def run(self, file, png_path):
"""Execute Pcap2Map functionality"""
# Instantiate logger
self.log_function()
# Get arguments from command line
if self.file is None:
self.file, self.png_path = self.get_args()
else:
self.file, self.png_path = file, png_path
# Determine correct path for final PNG
PNG_PATH = self.png_path_func(self.file,
self.png_path)
# Check that input file is .pcap
self.is_pcap(self.file)
# Get IPs, map it, output map
iplist = Pcap2IP(self.file).ips
ip2map = IP2Map(iplist)
ip2map.coord2map(PNG_PATH)
def log_function(self):
"""Instantiate logger"""
LOG = "message-log.log"
# Clear log if it already exists
if os.path.exists(LOG):
os.remove(LOG)
# Instantiate logger, include timestamp
FORMAT = '%(asctime)-15s %(levelname)-8s %(message)s'
logging.basicConfig(filename='message-log.log',
level=logging.DEBUG,
format=FORMAT)
def get_args(self):
"""Get command line arguments via argparse"""
parser = argparse.ArgumentParser(prog='pcap2map',
description="""Extract all external IP's from a network traffic
(.pcap) file, determine geo-coordinates with
database, place IP's on a world map (.png).""",
epilog="Happy pcap'ing!")
parser.add_argument('filename', metavar='file',
type=str, help='.pcap file name')
parser.add_argument('--png_path', metavar='png_path',
type=str, help='Final path for PNG map')
args = parser.parse_args()
return args.filename, args.png_path
def png_path_func(self, FILE, PNG_PATH):
"""Determine correct path for final png of map"""
# Cross-platform approach to getting filename stem
file_stem = Path(FILE).stem
full_stem = "ip_map_" + file_stem + ".png"
# If no path specified, place in images folder
if PNG_PATH is None:
# Check that image directory exists
# and create one if not
if not os.path.exists('images'):
os.mkdir('images')
png_file_name = os.path.join('images',
full_stem)
else: # Otherwise place in specified folder
# Create specified image path
PNG_IMAGE_PATH = os.path.join(
PNG_PATH,
'images')
# Check that specified directory exists
if not os.path.exists(PNG_IMAGE_PATH):
os.mkdir(PNG_IMAGE_PATH)
png_file_name = os.path.join(PNG_IMAGE_PATH,
full_stem)
return png_file_name
def is_pcap(self, filename):
"""Check that the file is a pcap. Return error if not"""
# Check that pcap is used as input
suffixes_list = Path(filename).suffixes
if ".pcap" not in suffixes_list:
raise ValueError("File must be a .pcap")
if __name__ == "__main__":
pcap2map = Pcap2Map()
# Get command line arguments
FILE, PNG_PATH = pcap2map.get_args()
# Run main function
pcap2map.run(FILE, PNG_PATH)
|
{-# LANGUAGE KindSignatures, GADTs #-}
module Assert
( Assertion(..),
checkAssertions
) where
data Assertion :: * -> * where
Assertion :: Eq a => {
actualValue :: a,
expectedValue :: a,
valuesRelationFunction :: a -> a -> Bool
} -> Assertion a
checkAssertions :: Eq a => [Assertion a] -> String
checkAssertions [] = "No assertions to check."
checkAssertions assertions = runAssertionChecker 1 assertions
runAssertionChecker :: Eq a => Int -> [Assertion a] -> String
runAssertionChecker assertionNumber (currentAssertion:remainingAssertions)
| null remainingAssertions =
if relationBetween actual expected
then "Assertion check successful (" ++ show assertionNumber ++ "/" ++ show assertionNumber ++ ")."
else "Assertion check failure at assertion #" ++ show assertionNumber ++ "."
| otherwise =
if relationBetween actual expected
then runAssertionChecker (assertionNumber + 1) remainingAssertions
else "Assertion check failure at assertion #" ++ show assertionNumber ++ "."
where
expected = expectedValue currentAssertion
relationBetween = valuesRelationFunction currentAssertion
actual = actualValue currentAssertion
|
#!/usr/bin/env python
'''
Modbus Message Generator
--------------------------------------------------------------------------
The following is an example of how to generate example encoded messages
for the supplied modbus format:
* tcp - `./generate-messages.py -f tcp -m rx -b`
* ascii - `./generate-messages.py -f ascii -m tx -a`
* rtu - `./generate-messages.py -f rtu -m rx -b`
* binary - `./generate-messages.py -f binary -m tx -b`
'''
from optparse import OptionParser
#--------------------------------------------------------------------------#
# import all the available framers
#--------------------------------------------------------------------------#
from pymodbus.transaction import ModbusSocketFramer
from pymodbus.transaction import ModbusBinaryFramer
from pymodbus.transaction import ModbusAsciiFramer
from pymodbus.transaction import ModbusRtuFramer
#--------------------------------------------------------------------------#
# import all available messages
#--------------------------------------------------------------------------#
from pymodbus.bit_read_message import *
from pymodbus.bit_write_message import *
from pymodbus.diag_message import *
from pymodbus.file_message import *
from pymodbus.other_message import *
from pymodbus.mei_message import *
from pymodbus.register_read_message import *
from pymodbus.register_write_message import *
#--------------------------------------------------------------------------#
# initialize logging
#--------------------------------------------------------------------------#
import logging
modbus_log = logging.getLogger("pymodbus")
#--------------------------------------------------------------------------#
# enumerate all request messages
#--------------------------------------------------------------------------#
_request_messages = [
ReadHoldingRegistersRequest,
ReadDiscreteInputsRequest,
ReadInputRegistersRequest,
ReadCoilsRequest,
WriteMultipleCoilsRequest,
WriteMultipleRegistersRequest,
WriteSingleRegisterRequest,
WriteSingleCoilRequest,
ReadWriteMultipleRegistersRequest,
ReadExceptionStatusRequest,
GetCommEventCounterRequest,
GetCommEventLogRequest,
ReportSlaveIdRequest,
ReadFileRecordRequest,
WriteFileRecordRequest,
MaskWriteRegisterRequest,
ReadFifoQueueRequest,
ReadDeviceInformationRequest,
ReturnQueryDataRequest,
RestartCommunicationsOptionRequest,
ReturnDiagnosticRegisterRequest,
ChangeAsciiInputDelimiterRequest,
ForceListenOnlyModeRequest,
ClearCountersRequest,
ReturnBusMessageCountRequest,
ReturnBusCommunicationErrorCountRequest,
ReturnBusExceptionErrorCountRequest,
ReturnSlaveMessageCountRequest,
ReturnSlaveNoResponseCountRequest,
ReturnSlaveNAKCountRequest,
ReturnSlaveBusyCountRequest,
ReturnSlaveBusCharacterOverrunCountRequest,
ReturnIopOverrunCountRequest,
ClearOverrunCountRequest,
GetClearModbusPlusRequest,
]
#--------------------------------------------------------------------------#
# enumerate all response messages
#--------------------------------------------------------------------------#
_response_messages = [
ReadHoldingRegistersResponse,
ReadDiscreteInputsResponse,
ReadInputRegistersResponse,
ReadCoilsResponse,
WriteMultipleCoilsResponse,
WriteMultipleRegistersResponse,
WriteSingleRegisterResponse,
WriteSingleCoilResponse,
ReadWriteMultipleRegistersResponse,
ReadExceptionStatusResponse,
GetCommEventCounterResponse,
GetCommEventLogResponse,
ReportSlaveIdResponse,
ReadFileRecordResponse,
WriteFileRecordResponse,
MaskWriteRegisterResponse,
ReadFifoQueueResponse,
ReadDeviceInformationResponse,
ReturnQueryDataResponse,
RestartCommunicationsOptionResponse,
ReturnDiagnosticRegisterResponse,
ChangeAsciiInputDelimiterResponse,
ForceListenOnlyModeResponse,
ClearCountersResponse,
ReturnBusMessageCountResponse,
ReturnBusCommunicationErrorCountResponse,
ReturnBusExceptionErrorCountResponse,
ReturnSlaveMessageCountResponse,
ReturnSlaveNoReponseCountResponse,
ReturnSlaveNAKCountResponse,
ReturnSlaveBusyCountResponse,
ReturnSlaveBusCharacterOverrunCountResponse,
ReturnIopOverrunCountResponse,
ClearOverrunCountResponse,
GetClearModbusPlusResponse,
]
#--------------------------------------------------------------------------#
# build an arguments singleton
#--------------------------------------------------------------------------#
# Feel free to override any values here to generate a specific message
# in question. It should be noted that many argument names are reused
# between different messages, and a number of messages are simply using
# their default values.
#--------------------------------------------------------------------------#
_arguments = {
'address' : 0x12,
'count' : 0x08,
'value' : 0x01,
'values' : [0x01] * 8,
'read_address' : 0x12,
'read_count' : 0x08,
'write_address ' : 0x12,
'write_registers' : [0x01] * 8,
'transaction' : 0x01,
'protocol' : 0x00,
'unit' : 0x01,
}
#---------------------------------------------------------------------------#
# generate all the requested messages
#---------------------------------------------------------------------------#
def generate_messages(framer, options):
''' A helper method to parse the command line options
:param framer: The framer to encode the messages with
:param options: The message options to use
'''
messages = _request_messages if options.messages == 'tx' else _response_messages
for message in messages:
message = message(**_arguments)
print ("%-44s = " % message.__class__.__name__)
packet = framer.buildPacket(message)
if not options.ascii:
packet = packet.encode('hex') + '\n'
print (packet) # because ascii ends with a \r\n
#---------------------------------------------------------------------------#
# initialize our program settings
#---------------------------------------------------------------------------#
def get_options():
''' A helper method to parse the command line options
:returns: The options manager
'''
parser = OptionParser()
parser.add_option("-f", "--framer",
help="The type of framer to use (tcp, rtu, binary, ascii)",
dest="framer", default="tcp")
parser.add_option("-D", "--debug",
help="Enable debug tracing",
action="store_true", dest="debug", default=False)
parser.add_option("-a", "--ascii",
help="The indicates that the message is ascii",
action="store_true", dest="ascii", default=True)
parser.add_option("-b", "--binary",
help="The indicates that the message is binary",
action="store_false", dest="ascii")
parser.add_option("-m", "--messages",
help="The messages to encode (rx, tx)",
dest="messages", default='rx')
(opt, arg) = parser.parse_args()
return opt
def main():
''' The main runner function
'''
option = get_options()
if option.debug:
try:
modbus_log.setLevel(logging.DEBUG)
logging.basicConfig()
except Exception as e:
print("Logging is not supported on this system")
framer = lookup = {
'tcp': ModbusSocketFramer,
'rtu': ModbusRtuFramer,
'binary': ModbusBinaryFramer,
'ascii': ModbusAsciiFramer,
}.get(option.framer, ModbusSocketFramer)(None)
generate_messages(framer, option)
if __name__ == "__main__":
main()
|
use crate::SpanTrace;
use std::error::Error;
use std::fmt::{self, Debug, Display};
struct Erased;
/// A wrapper type for `Error`s that bundles a `SpanTrace` with an inner `Error`
/// type.
///
/// This type is a good match for the error-kind pattern where you have an error
/// type with an inner enum of error variants and you would like to capture a
/// span trace that can be extracted during printing without formatting the span
/// trace as part of your display impl.
///
/// An example of implementing an error type for a library using `TracedError`
/// might look like this
///
/// ```rust,compile_fail
/// #[derive(Debug, thiserror::Error)]
/// enum Kind {
/// // ...
/// }
///
/// #[derive(Debug)]
/// pub struct Error {
/// source: TracedError<Kind>,
/// backtrace: Backtrace,
/// }
///
/// impl std::error::Error for Error {
/// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
/// self.source.source()
/// }
///
/// fn backtrace(&self) -> Option<&Backtrace> {
/// Some(&self.backtrace)
/// }
/// }
///
/// impl fmt::Display for Error {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt::Display::fmt(&self.source, fmt)
/// }
/// }
///
/// impl<E> From<E> for Error
/// where
/// Kind: From<E>,
/// {
/// fn from(source: E) -> Self {
/// Self {
/// source: Kind::from(source).into(),
/// backtrace: Backtrace::capture(),
/// }
/// }
/// }
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "traced-error")))]
pub struct TracedError<E> {
inner: ErrorImpl<E>,
}
impl<E> From<E> for TracedError<E>
where
E: Error + Send + Sync + 'static,
{
fn from(error: E) -> Self {
// # SAFETY
//
// This function + the repr(C) on the ErrorImpl make the type erasure throughout the rest
// of this struct's methods safe. This saves a function pointer that is parameterized on the Error type
// being stored inside the ErrorImpl. This lets the object_ref function safely cast a type
// erased `ErrorImpl` back to its original type, which is needed in order to forward our
// error/display/debug impls to the internal error type from the type erased error type.
//
// The repr(C) is necessary to ensure that the struct is layed out in the order we
// specified it so that we can safely access the vtable and spantrace fields thru a type
// erased pointer to the original object.
let vtable = &ErrorVTable {
object_ref: object_ref::<E>,
};
Self {
inner: ErrorImpl {
vtable,
span_trace: SpanTrace::capture(),
error,
},
}
}
}
#[repr(C)]
struct ErrorImpl<E> {
vtable: &'static ErrorVTable,
span_trace: SpanTrace,
// NOTE: Don't use directly. Use only through vtable. Erased type may have
// different alignment.
error: E,
}
impl ErrorImpl<Erased> {
pub(crate) fn error(&self) -> &(dyn Error + Send + Sync + 'static) {
// # SAFETY
//
// this function is used to cast a type-erased pointer to a pointer to error's
// original type. the `ErrorImpl::error` method, which calls this function, requires that
// the type this function casts to be the original erased type of the error; failure to
// uphold this is UB. since the `From` impl is parameterized over the original error type,
// the function pointer we construct here will also retain the original type. therefore,
// when this is consumed by the `error` method, it will be safe to call.
unsafe { &*(self.vtable.object_ref)(self) }
}
}
struct ErrorVTable {
object_ref: unsafe fn(&ErrorImpl<Erased>) -> &(dyn Error + Send + Sync + 'static),
}
// # SAFETY
//
// This function must be parameterized on the type E of the original error that is being stored
// inside of the `ErrorImpl`. When it is parameterized by the correct type, it safely
// casts the erased `ErrorImpl` pointer type back to the original pointer type.
unsafe fn object_ref<E>(e: &ErrorImpl<Erased>) -> &(dyn Error + Send + Sync + 'static)
where
E: Error + Send + Sync + 'static,
{
// Attach E's native Error vtable onto a pointer to e.error.
&(*(e as *const ErrorImpl<Erased> as *const ErrorImpl<E>)).error
}
impl<E> Error for TracedError<E>
where
E: std::error::Error + 'static,
{
// # SAFETY
//
// This function is safe so long as all functions on `ErrorImpl<Erased>` uphold the invariant
// that the wrapped error is only ever accessed by the `error` method. This method uses the
// function in the vtable to safely convert the pointer type back to the original type, and
// then returns the reference to the erased error.
//
// This function is necessary for the `downcast_ref` in `ExtractSpanTrace` to work, because it
// needs a concrete type to downcast to and we cannot downcast to ErrorImpls parameterized on
// errors defined in other crates. By erasing the type here we can always cast back to the
// Erased version of the ErrorImpl pointer, and still access the internal error type safely
// through the vtable.
fn source<'a>(&'a self) -> Option<&'a (dyn Error + 'static)> {
let erased = unsafe { &*(&self.inner as *const ErrorImpl<E> as *const ErrorImpl<Erased>) };
Some(erased)
}
}
impl<E> Debug for TracedError<E>
where
E: std::error::Error,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.inner.error, f)
}
}
impl<E> Display for TracedError<E>
where
E: std::error::Error,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.inner.error, f)
}
}
impl Error for ErrorImpl<Erased> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.error().source()
}
}
impl Debug for ErrorImpl<Erased> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("span backtrace:\n")?;
Debug::fmt(&self.span_trace, f)
}
}
impl Display for ErrorImpl<Erased> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("span backtrace:\n")?;
Display::fmt(&self.span_trace, f)
}
}
/// Extension trait for instrumenting errors with `SpanTrace`s
#[cfg_attr(docsrs, doc(cfg(feature = "traced-error")))]
pub trait InstrumentError {
/// The type of the wrapped error after instrumentation
type Instrumented;
/// Instrument an Error by bundling it with a SpanTrace
///
/// # Examples
///
/// ```rust
/// use tracing_error::{TracedError, InstrumentError};
///
/// fn wrap_error<E>(e: E) -> TracedError<E>
/// where
/// E: std::error::Error + Send + Sync + 'static
/// {
/// e.in_current_span()
/// }
/// ```
fn in_current_span(self) -> Self::Instrumented;
}
/// Extension trait for instrumenting errors in `Result`s with `SpanTrace`s
#[cfg_attr(docsrs, doc(cfg(feature = "traced-error")))]
pub trait InstrumentResult<T> {
/// The type of the wrapped error after instrumentation
type Instrumented;
/// Instrument an Error by bundling it with a SpanTrace
///
/// # Examples
///
/// ```rust
/// # use std::{io, fs};
/// use tracing_error::{TracedError, InstrumentResult};
///
/// # fn fallible_fn() -> io::Result<()> { fs::read_dir("......").map(drop) };
///
/// fn do_thing() -> Result<(), TracedError<io::Error>> {
/// fallible_fn().in_current_span()
/// }
/// ```
fn in_current_span(self) -> Result<T, Self::Instrumented>;
}
impl<T, E> InstrumentResult<T> for Result<T, E>
where
E: InstrumentError,
{
type Instrumented = <E as InstrumentError>::Instrumented;
fn in_current_span(self) -> Result<T, Self::Instrumented> {
self.map_err(E::in_current_span)
}
}
/// A trait for extracting SpanTraces created by `in_current_span()` from `dyn
/// Error` trait objects
#[cfg_attr(docsrs, doc(cfg(feature = "traced-error")))]
pub trait ExtractSpanTrace {
/// Attempts to downcast to a `TracedError` and return a reference to its
/// SpanTrace
///
/// # Examples
///
/// ```rust
/// use tracing_error::ExtractSpanTrace;
/// use std::error::Error;
///
/// fn print_span_trace(e: &(dyn Error + 'static)) {
/// let span_trace = e.span_trace();
/// if let Some(span_trace) = span_trace {
/// println!("{}", span_trace);
/// }
/// }
/// ```
fn span_trace(&self) -> Option<&SpanTrace>;
}
impl<E> InstrumentError for E
where
TracedError<E>: From<E>,
{
type Instrumented = TracedError<E>;
fn in_current_span(self) -> Self::Instrumented {
TracedError::from(self)
}
}
impl ExtractSpanTrace for dyn Error + 'static {
fn span_trace(&self) -> Option<&SpanTrace> {
self.downcast_ref::<ErrorImpl<Erased>>()
.map(|inner| &inner.span_trace)
}
}
|
<?php
#verifie que le titre et le contenu existent et ne sont pas trop long
if (isset($_POST['titre']) AND isset($_POST['contenu'])) {
if (is_string($_POST['titre']) AND strlen($_POST['titre']) < 40)
$titre = $_POST['titre'];
else
echo ' Votre nom est trop long, veuillez rentrer un nom moins long';
if (is_string($_POST['contenu']) AND strlen($_POST['contenu']) < 250)
$contenu = $_POST['contenu'];
else
echo 'Votre commentaire doit faire moins de 255 caractères';
if (strlen($titre) == 0 OR strlen($contenu) == 0) {
echo 'Vous n\'avez pas rempli un des champs';
header('Location:add_billet.php');
exit();
}
}
include("../Repeat/connection_BDD.php");
?>
|
---
title: "首届Dubbo开发者沙龙在北京成功举办"
linkTitle: "首届Dubbo开发者沙龙在北京成功举办"
date: 2018-05-12
description: 首届Dubbo开发者沙龙在北京成功举办
---
首届Dubbo开发者沙龙在北京成功举办, 超过400位开发者参加。这是一个很好的开始!
分享嘉宾及主体如下:
* 罗毅: Dubbo 的现状现状与未来规划 [PDF](https://github.com/dubbo/awesome-dubbo/raw/master/slides/meetup/201805%40Beijing/dubbo-present-and-future.pdf)
* 刘军: 第四届阿里中间件性能挑战赛 [PDF](https://github.com/dubbo/awesome-dubbo/raw/master/slides/meetup/201805%40Beijing/introduction-to-4th-aliware-performance-challenge.pdf)
* 陈志轩: 通过 Dubbo 和 Spring-boot 快速构建微服务 [PDF](https://github.com/dubbo/awesome-dubbo/raw/master/slides/meetup/201805%40Beijing/quickly-building-microservice-with-dubbo-and-springboot.pdf)
* 王欣: Dubbo 和微店的服务化实践历程分享 [PDF](https://github.com/dubbo/awesome-dubbo/raw/master/slides/meetup/201805%40Beijing/dubbo-and-weidian's-practice-on-microservice-architecture.pdf)
|
//
// diffuse_object.cpp
// vulkan-demos
//
// Created by Rafael Sabino on 6/5/20.
// Copyright © 2020 Rafael Sabino. All rights reserved.
//
#pragma once
#include <filesystem>
#include "assimp_obj.h"
#include "device.h"
#include "node.h"
namespace vk
{
template<uint32_t NUM_CHILDREN>
class assimp_node : public vk::node<NUM_CHILDREN>
{
public:
using node_type = vk::node<NUM_CHILDREN>;
assimp_node(vk::device* dev, const char* path):
node_type(dev),_path(path)
{
node_type::_name = path;
}
assimp_node(vk::device* dev, const char* path, vk::vertex_components& v_components):
node_type(dev), _path(path)
{
node_type::_name = path;
for(int i = 0; i < _mesh_lods.size(); ++i)
{
_mesh_lods[i].set_vertex_layout(v_components);
}
}
vk::obj_shape* get_lod(uint32_t l)
{
if( l < _num_lods)
return static_cast<vk::obj_shape*>(&_mesh_lods[l]);
return static_cast<vk::obj_shape*>(&_mesh_lods[l-1]);
}
void set_texture_relative_path(const char* p, uint32_t id)
{
for( int i = 0; i < _num_lods; ++i)
{
_mesh_lods[i].set_texture_relative_path(p, id);
}
}
virtual void init_node() override
{
EA_ASSERT_MSG(node_type::_device != nullptr, "vk::device is nullptr");
EA_ASSERT_MSG(_path != nullptr, "path directory is empty for this mesh");
for( int i = 0; i < _mesh_lods.size(); ++i)
{
eastl::fixed_string<char, 250> name = _path;
_mesh_lods[i].set_device(node_type::_device);
_mesh_lods[i].set_path(name.c_str());
if( i != 0)
{
size_t p = name.find_last_of('.', name.length());
eastl::fixed_string<char, 250> lod_name;
lod_name = name.substr(0, p);
//size_t p = name.find_last_of('.', name.length());
eastl::fixed_string<char, 250> lod_final = {};
eastl::fixed_string<char, 250> extension = name.substr(p, name.length());
lod_final.sprintf("%s_lod%i%s", lod_name.c_str(), i, extension.c_str());
if (!std::filesystem::exists(lod_name.c_str()))
break;
//name.sprintf("%s_lod%i", _path, i);
_mesh_lods[i].set_path(lod_name.c_str());
++_num_lods;
}
_mesh_lods[i].create();
}
}
void init_transforms(vk::transform& transform)
{
for( int image = 0; image < glfw_swapchain::NUM_SWAPCHAIN_IMAGES; ++image)
{
transforms[image] = transform;
transforms[image].update_transform_matrix();
}
}
virtual void update_node(vk::camera& camera, uint32_t image_id) override
{
for( int i = 0; i < _mesh_lods.size(); ++i)
{
_mesh_lods[i].transform = transforms[image_id];
}
}
virtual bool record_node_commands(command_recorder& buffer, uint32_t image_id) override { return true; }
VkPipelineStageFlagBits get_producer_stage() override { return VK_PIPELINE_STAGE_TRANSFER_BIT; };
VkPipelineStageFlagBits get_consumer_stage() override { return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; };
virtual void create_gpu_resources() override
{}
virtual void destroy() override
{
for( int i = 0; i < _mesh_lods.size(); ++i)
{
_mesh_lods[i].destroy();
}
}
eastl::array<vk::transform, glfw_swapchain::NUM_SWAPCHAIN_IMAGES> transforms {} ;
virtual char const * const * get_instance_type() override { return (&_node_type); };
static char const * const * get_class_type(){ return (&_node_type); }
private:
static constexpr char const * _node_type = nullptr;
eastl::array<vk::assimp_obj, 10> _mesh_lods;
uint32_t _num_lods = 1;
const char* _path;
};
}
|
require 'rails_helper'
require 'rspec_api_documentation'
require 'rspec_api_documentation/dsl'
RspecApiDocumentation.configure do |config|
config.format = [:json, :combined_text, :html]
config.curl_host = 'http://localhost:3000'
config.api_name = "Example App API"
config.api_explanation = "API Example Description"
end
|
#!/bin/sh
# vim: filetype=sh noexpandtab ts=8 sw=8
# $FreeBSD: head/tools/regression/pjdfstest/tests/granular/02.t 211352 2010-08-15 21:24:17Z pjd $
desc="NFSv4 granular permissions checking - ACL_READ_ACL and ACL_WRITE_ACL"
dir=`dirname $0`
. ${dir}/../misc.sh
[ "${os}:${fs}" = "FreeBSD:ZFS" ] || quick_exit
echo "1..83"
n0=`namegen`
n1=`namegen`
n2=`namegen`
expect 0 mkdir ${n2} 0755
cdir=`pwd`
cd ${n2}
# Check whether user 65534 is permitted to read ACL.
expect 0 create ${n0} 0644
expect 0 readacl ${n0}
expect 0 -u 65534 -g 65534 readacl ${n0}
expect 0 prependacl ${n0} user:65534:read_acl::deny
expect 0 readacl ${n0}
expect EACCES -u 65534 -g 65534 readacl ${n0}
expect 0 prependacl ${n0} user:65534:read_acl::allow
expect 0 -u 65534 -g 65534 readacl ${n0}
expect 0 readacl ${n0}
expect 0 unlink ${n0}
# Check whether user 65534 is permitted to write ACL.
expect 0 create ${n0} 0644
expect EPERM -u 65534 -g 65534 prependacl ${n0} user:65534:read_data::allow
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:read_data::allow
expect 0 unlink ${n0}
# Check whether user 65534 is permitted to write mode.
expect 0 create ${n0} 0755
expect EPERM -u 65534 -g 65534 chmod ${n0} 0777
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 chmod ${n0} 0777
expect 0 unlink ${n0}
# There is an interesting problem with interaction between ACL_WRITE_ACL
# and SUID/SGID bits. In case user does have ACL_WRITE_ACL, but is not
# a file owner, Solaris does the following:
# 1. Setting SUID fails with EPERM.
# 2. Setting SGID succeeds, but mode is not changed.
# 3. Modifying ACL does not clear SUID nor SGID bits.
# 4. Writing the file does clear both SUID and SGID bits.
#
# What we are doing is the following:
# 1. Setting SUID or SGID fails with EPERM.
# 2. Modifying ACL does not clear SUID nor SGID bits.
# 3. Writing the file does clear both SUID and SGID bits.
#
# Check whether user 65534 is denied to write mode with SUID bit.
expect 0 create ${n0} 0755
expect EPERM -u 65534 -g 65534 chmod ${n0} 04777
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect EPERM -u 65534 -g 65534 chmod ${n0} 04777
expect 0 unlink ${n0}
# Check whether user 65534 is denied to write mode with SGID bit.
expect 0 create ${n0} 0755
expect EPERM -u 65534 -g 65534 chmod ${n0} 02777
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect EPERM -u 65534 -g 65534 chmod ${n0} 02777
expect 0 unlink ${n0}
# Check whether user 65534 is allowed to write mode with sticky bit.
expect 0 mkdir ${n0} 0755
expect EPERM -u 65534 -g 65534 chmod ${n0} 01777
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 chmod ${n0} 01777
expect 0 rmdir ${n0}
# Check whether modifying the ACL by not-owner preserves the SUID.
expect 0 create ${n0} 04755
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:write_data::allow
expect 04755 stat ${n0} mode
expect 0 unlink ${n0}
# Check whether modifying the ACL by not-owner preserves the SGID.
expect 0 create ${n0} 02755
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:write_data::allow
expect 02755 stat ${n0} mode
expect 0 unlink ${n0}
# Check whether modifying the ACL by not-owner preserves the sticky bit.
expect 0 mkdir ${n0} 0755
expect 0 chmod ${n0} 01755
expect 0 prependacl ${n0} user:65534:write_acl::allow
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:write_data::allow
expect 01755 stat ${n0} mode
expect 0 rmdir ${n0}
# Clearing the SUID and SGID bits when being written to by non-owner
# is checked in chmod/12.t.
# Check whether the file owner is always permitted to get and set
# ACL and file mode, even if ACL_{READ,WRITE}_ACL would deny it.
expect 0 chmod . 0777
expect 0 -u 65534 -g 65534 create ${n0} 0600
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:write_acl::deny
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:read_acl::deny
expect 0 -u 65534 -g 65534 readacl ${n0}
expect 0600 -u 65534 -g 65534 stat ${n0} mode
expect 0 -u 65534 -g 65534 chmod ${n0} 0777
expect 0 unlink ${n0}
expect 0 -u 65534 -g 65534 mkdir ${n0} 0600
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:write_acl::deny
expect 0 -u 65534 -g 65534 prependacl ${n0} user:65534:read_acl::deny
expect 0 -u 65534 -g 65534 readacl ${n0}
expect 0600 -u 65534 -g 65534 stat ${n0} mode
expect 0 -u 65534 -g 65534 chmod ${n0} 0777
expect 0 rmdir ${n0}
# Check whether the root is allowed for these as well.
expect 0 -u 65534 -g 65534 create ${n0} 0600
expect 0 prependacl ${n0} everyone@:write_acl::deny
expect 0 prependacl ${n0} everyone@:read_acl::deny
expect 0 readacl ${n0}
expect 0600 stat ${n0} mode
expect 0 chmod ${n0} 0777
expect 0 unlink ${n0}
expect 0 -u 65534 -g 65534 mkdir ${n0} 0600
expect 0 prependacl ${n0} everyone@:write_acl::deny
expect 0 prependacl ${n0} everyone@:read_acl::deny
expect 0600 stat ${n0} mode
expect 0 readacl ${n0}
expect 0600 stat ${n0} mode
expect 0 chmod ${n0} 0777
expect 0 rmdir ${n0}
cd ${cdir}
expect 0 rmdir ${n2}
|
# Added Soccer Balls
After completing the steps below, you see soccer balls added to the game when you have 2 or more players!
{% include blocks/stop.md %}
{% doublecheck %}
{% checkoff %}
|
prototype Clif
{
void @add_text_lc_and_individuate_it(str lc);
void @add_text_lc_on_current_line(str lc);
int @anatomize_clif(int desired_action, str &fp);
void @edit_file_remotely();
void @edit_file_under_cursor();
void @process_batx_clif_block(str clif_block);
void @find_backwards(str args);
int @folder_exists(str path);
str @get_line();
str @get_path_using_lw();
str @get_remote_oj_using_klc(str lc, int &lc_Is_Found);
str @get_subject_or_selected_text();
int @is_paste_before_in_same_window();
void @load_my_macros_into_memory_1(); //(skw qkq) Remove from production Clif.
int @open_folder(str path);
void @open_folder_remotely();
void @repeat_command();
int @rubric_contains_1way_string();
int @run_clif_under_cursor(str &operation_outcome);
void @run_clif_internally(str lc);
void @set_clipboard(str stringToSet);
}
|
**Describe what your pull request will improve for the bot**
A clear and concise description of what the pull request will fix/add/remove ect.
**Is your pull request related to a problem? Please describe it.**
A clear and concise description of what the problem is.
**Describe the way your pull request fix that problem.**
A clear and concise description of what it should fix.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the pull request here.
|
interface SepFunc<Item> {
(item: Item): boolean
}
export function* splitIterable<Item>(iterable: Iterable<Item>, sep: SepFunc<Item>) {
let store = Array<Item>()
for (const item of iterable) {
if (sep(item)) {
yield store
store = []
} else {
store.push(item)
}
}
yield store
}
type MaybeAsyncIterable<Item> = Iterable<Item> | AsyncIterable<Item>
interface AsyncSepFunc<Item> {
(item: Item): boolean | Promise<boolean>
}
export async function* splitAsyncIterable<Item>(
iterable: MaybeAsyncIterable<Item>,
sep: AsyncSepFunc<Item>,
) {
let store = Array<Item>()
for await (const item of iterable) {
if (await sep(item)) {
yield store
store = []
} else {
store.push(item)
}
}
yield store
}
|
# frozen_string_literal: true
require 'spec_helper'
describe Clusters::Applications::ElasticStack do
include KubernetesHelpers
include_examples 'cluster application core specs', :clusters_applications_elastic_stack
include_examples 'cluster application status specs', :clusters_applications_elastic_stack
include_examples 'cluster application version specs', :clusters_applications_elastic_stack
include_examples 'cluster application helm specs', :clusters_applications_elastic_stack
describe '#install_command' do
let!(:elastic_stack) { create(:clusters_applications_elastic_stack) }
subject { elastic_stack.install_command }
it { is_expected.to be_an_instance_of(Gitlab::Kubernetes::Helm::InstallCommand) }
it 'is initialized with elastic stack arguments' do
expect(subject.name).to eq('elastic-stack')
expect(subject.chart).to eq('stable/elastic-stack')
expect(subject.version).to eq('1.8.0')
expect(subject).to be_rbac
expect(subject.files).to eq(elastic_stack.files)
end
context 'on a non rbac enabled cluster' do
before do
elastic_stack.cluster.platform_kubernetes.abac!
end
it { is_expected.not_to be_rbac }
end
context 'application failed to install previously' do
let(:elastic_stack) { create(:clusters_applications_elastic_stack, :errored, version: '0.0.1') }
it 'is initialized with the locked version' do
expect(subject.version).to eq('1.8.0')
end
end
end
describe '#uninstall_command' do
let!(:elastic_stack) { create(:clusters_applications_elastic_stack) }
subject { elastic_stack.uninstall_command }
it { is_expected.to be_an_instance_of(Gitlab::Kubernetes::Helm::DeleteCommand) }
it 'is initialized with elastic stack arguments' do
expect(subject.name).to eq('elastic-stack')
expect(subject).to be_rbac
expect(subject.files).to eq(elastic_stack.files)
end
it 'specifies a post delete command to remove custom resource definitions' do
expect(subject.postdelete).to eq([
'kubectl delete pvc --selector release\\=elastic-stack'
])
end
end
describe '#elasticsearch_client' do
context 'cluster is nil' do
it 'returns nil' do
expect(subject.cluster).to be_nil
expect(subject.elasticsearch_client).to be_nil
end
end
context "cluster doesn't have kubeclient" do
let(:cluster) { create(:cluster) }
subject { create(:clusters_applications_elastic_stack, cluster: cluster) }
it 'returns nil' do
expect(subject.elasticsearch_client).to be_nil
end
end
context 'cluster has kubeclient' do
let(:cluster) { create(:cluster, :project, :provided_by_gcp) }
let(:kubernetes_url) { subject.cluster.platform_kubernetes.api_url }
let(:kube_client) { subject.cluster.kubeclient.core_client }
subject { create(:clusters_applications_elastic_stack, cluster: cluster) }
before do
subject.cluster.platform_kubernetes.namespace = 'a-namespace'
stub_kubeclient_discover(cluster.platform_kubernetes.api_url)
create(:cluster_kubernetes_namespace,
cluster: cluster,
cluster_project: cluster.cluster_project,
project: cluster.cluster_project.project)
end
it 'creates proxy elasticsearch_client' do
expect(subject.elasticsearch_client).to be_instance_of(Elasticsearch::Transport::Client)
end
it 'copies proxy_url, options and headers from kube client to elasticsearch_client' do
expect(Elasticsearch::Client)
.to(receive(:new))
.with(url: a_valid_url)
.and_call_original
client = subject.elasticsearch_client
faraday_connection = client.transport.connections.first.connection
expect(faraday_connection.headers["Authorization"]).to eq(kube_client.headers[:Authorization])
expect(faraday_connection.ssl.cert_store).to be_instance_of(OpenSSL::X509::Store)
expect(faraday_connection.ssl.verify).to eq(1)
end
context 'when cluster is not reachable' do
before do
allow(kube_client).to receive(:proxy_url).and_raise(Kubeclient::HttpError.new(401, 'Unauthorized', nil))
end
it 'returns nil' do
expect(subject.elasticsearch_client).to be_nil
end
end
end
end
end
|
PAGE ,132
TITLE IOCTL - IOCTL system call
NAME IOCTL
;
; Microsoft Confidential
; Copyright (C) Microsoft Corporation 1991
; All Rights Reserved.
;
;** IOCTL system call.
;
; $IOCTL
;
; Revision history:
;
; Created: ARR 4 April 1983
;
; GenericIOCTL added: KGS 22 April 1985
;
; A000 version 4.00 Jan. 1988
;
; Used jump table to dispatch IOCTL functions. HKN 3/12/90
;
.xlist
.xcref
include version.inc
include dosseg.inc
INCLUDE DOSSYM.INC
INCLUDE DEVSYM.INC
include bpb.inc
include mult.inc
include dpb.inc
include sf.inc
include vector.inc
include curdir.inc
include ioctl.inc
.cref
.list
i_need THISCDS,DWORD
i_need IOCALL,BYTE
i_need IOMED,BYTE
i_need IOSCNT,WORD
i_need IOXAD,DWORD
I_need RetryCount,WORD
I_need RetryLoop,WORD
I_need EXTERR_LOCUS,BYTE
I_need OPENBUF,BYTE
I_need ExtErr,WORD
I_need DrvErr,BYTE
I_need USER_IN_AX,WORD ;AN000;
I_need Temp_Var2,WORD ;AN000;
extrn GetThisDrv:near
DOSCODE SEGMENT
ASSUME SS:DOSDATA,CS:DOSCODE
BREAK <IOCTL - munge on a handle to do device specific stuff>
;---------------------------------------------------------------------------
;
; Assembler usage:
; MOV BX, Handle
; MOV DX, Data
;
; (or LDS DX,BUF
; MOV CX,COUNT)
;
; MOV AH, Ioctl
; MOV AL, Request
; INT 21h
;
; AH = 0 Return a combination of low byte of sf_flags and device driver
; attribute word in DX, handle in BX:
; DH = high word of device driver attributes
; DL = low byte of sf_flags
; 1 Set the bits contained in DX to sf_flags. DH MUST be 0. Handle
; in BX.
; 2 Read CX bytes from the device control channel for handle in BX
; into DS:DX. Return number read in AX.
; 3 Write CX bytes to the device control channel for handle in BX from
; DS:DX. Return bytes written in AX.
; 4 Read CX bytes from the device control channel for drive in BX
; into DS:DX. Return number read in AX.
; 5 Write CX bytes to the device control channel for drive in BX from
; DS:DX. Return bytes written in AX.
; 6 Return input status of handle in BX. If a read will go to the
; device, AL = 0FFh, otherwise 0.
; 7 Return output status of handle in BX. If a write will go to the
; device, AL = 0FFh, otherwise 0.
; 8 Given a drive in BX, return 1 if the device contains non-
; removable media, 0 otherwise.
; 9 Return the contents of the device attribute word in DX for the
; drive in BX. 0200h is the bit for shared. 1000h is the bit for
; network. 8000h is the bit for local use.
; A Return 8000h if the handle in BX is for the network or not.
; B Change the retry delay and the retry count for the system. BX is
; the count and CX is the delay.
;
; Error returns:
; AX = error_invalid_handle
; = error_invalid_function
; = error_invalid_data
;
;-------------------------------------------------------------------------------
;
; This is the documentation copied from DOS 4.0 it is much better
; than the above
;
; There are several basic forms of IOCTL calls:
;
;
; ** Get/Set device information: **
;
; ENTRY (AL) = function code
; 0 - Get device information
; 1 - Set device information
; (BX) = file handle
; (DX) = info for "Set Device Information"
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (DX) = info for "Get Device Information"
; USES ALL
;
;
; ** Read/Write Control Data From/To Handle **
;
; ENTRY (AL) = function code
; 2 - Read device control info
; 3 - Write device control info
; (BX) = file handle
; (CX) = transfer count
; (DS:DX) = address for data
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (AX) = count of bytes transfered
; USES ALL
;
;
; ** Read/Write Control Data From/To Block Device **
;
; ENTRY (AL) = function code
; 4 - Read device control info
; 5 - Write device control info
; (BL) = Drive number (0=default, 1='A', 2='B', etc)
; (CX) = transfer count
; (DS:DX) = address for data
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (AX) = count of bytes transfered
; USES ALL
;
;
; ** Get Input/Output Status **
;
; ENTRY (AL) = function code
; 6 - Get Input status
; 7 - Get Output Status
; (BX) = file handle
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (AL) = 00 if not ready
; (AL) = FF if ready
; USES ALL
;
;
; ** Get Drive Information **
;
; ENTRY (AL) = function code
; 8 - Check for removable media
; 9 - Get device attributes
; (BL) = Drive number (0=default, 1='A', 2='B', etc)
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (AX) = 0/1 media is removable/fixed (func. 8)
; (DX) = device attribute word (func. 9)
; USES ALL
;
;
; ** Get Redirected bit **
;
; ENTRY (AL) = function code
; 0Ah - Network stuff
; (BX) = file handle
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (DX) = SFT flags word, 8000h set if network file
; USES ALL
;
;
; ** Change sharer retry parameters **
;
; ENTRY (AL) = function code
; 0Bh - Set retry parameters
; (CX) = retry loop count
; (DX) = number of retries
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; USES ALL
;
;
; =================================================================
;
; ** New Standard Control **
;
; ALL NEW IOCTL FACILITIES SHOULD USE THIS FORM. THE OTHER
; FORMS ARE OBSOLETE.
;
; =================================================================
;
; ENTRY (AL) = function code
; 0Ch - Control Function subcode
; (BX) = File Handle
; (CH) = Category Indicator
; (CL) = Function within category
; (DS:DX) = address for data, if any
; (SI) = Passed to device as argument, use depends upon function
; (DI) = Passed to device as argument, use depends upon function
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (SI) = Return value, meaning is function dependent
; (DI) = Return value, meaning is function dependent
; (DS:DX) = Return address, use is function dependent
; USES ALL
;
; ============== Generic IOCTL Definitions for DOS 3.2 ============
; (See inc\ioctl.inc for more info)
;
; ENTRY (AL) = function code
; 0Dh - Control Function subcode
; (BL) = Drive Number (0 = Default, 1= 'A')
; (CH) = Category Indicator
; (CL) = Function within category
; (DS:DX) = address for data, if any
; (SI) = Passed to device as argument, use depends upon function
; (DI) = Passed to device as argument, use depends upon function
;
; EXIT 'C' set if error
; (AX) = error code
; 'C' clear if OK
; (DS:DX) = Return address, use is function dependent
; USES ALL
;
;---------------------------------------------------------------------------
TABENT macro ORDINAL, handler_address
; .errnz $-IOCTLJMPTABLE-2*ORDINAL
DW handler_address
endm
IOCTLJMPTABLE label word
TABENT IOCTL_GET_DEVICE_INFO , ioctl_getset_data ; 0
TABENT IOCTL_SET_DEVICE_INFO , ioctl_getset_data ; 1
TABENT IOCTL_READ_HANDLE , ioctl_control_string ; 2
TABENT IOCTL_WRITE_HANDLE , ioctl_control_string ; 3
TABENT IOCTL_READ_DRIVE , ioctl_get_dev ; 4
TABENT IOCTL_WRITE_DRIVE , ioctl_get_dev ; 5
TABENT IOCTL_GET_INPUT_STATUS , ioctl_status ; 6
TABENT IOCTL_GET_OUTPUT_STATUS , ioctl_status ; 7
TABENT IOCTL_CHANGEABLE? , ioctl_rem_media ; 8
TABENT IOCTL_DeviceLocOrRem? , Ioctl_Drive_attr ; 9
TABENT IOCTL_HandleLocOrRem? , IOCTL_Handle_Redir ; a
TABENT IOCTL_SHARING_RETRY , Set_Retry_Parameters ; b
TABENT GENERIC_IOCTL_HANDLE , GENERICIOCTLHANDLE ; c
TABENT GENERIC_IOCTL , GENERICIOCTL ; d
TABENT IOCTL_GET_DRIVE_MAP , ioctl_drive_owner ; e
TABENT IOCTL_SET_DRIVE_MAP , ioctl_drive_owner ; f
TABENT IOCTL_QUERY_HANDLE , query_handle_support ; 10
TABENT IOCTL_QUERY_BLOCK , query_device_support ; 11
procedure $IOCTL,NEAR
ASSUME DS:NOTHING,ES:NOTHING
MOV SI,DS ; Stash DS for calls 2,3,4 and 5
context DS ;hkn; SS is DOSDATA
cmp al, 11h ; al must be between 0 & 11h
ja ioctl_bad_funj2 ; if not bad function #
push AX ; Need to save AL for generic IOCTL
mov di, ax ; di NOT a PARM
and di, 0ffh ; di = al
shl di, 1 ; di = index into jmp table
pop AX ; Restore AL for generic IOCTL
jmp word ptr cs:[IOCTLJMPTABLE+di]
ioctl_bad_funj2:
JMP ioctl_bad_fun
;--------------------------------------------------------------------------
;
; IOCTL: AL= 0,1
;
; ENTRY : DS = DOSDATA
;
;---------------------------------------------------------------------
ioctl_getset_data:
invoke SFFromHandle ; ES:DI -> SFT
JNC ioctl_check_permissions ; have valid handle
ioctl_bad_handle:
error error_invalid_handle
ioctl_check_permissions:
CMP AL,0
MOV AL,BYTE PTR ES:[DI].SF_FLAGS; Get low byte of flags
JZ ioctl_read ; read the byte
;**RMFHFE** test dh, 0feh ;AN000;MS.allow dh=1
or dh, dh
JZ ioctl_check_device ; can I set with this data?
error error_invalid_data ; no DH <> 0
ioctl_check_device:
test AL,devid_device ; can I set this handle?
;**RMFHFE** JZ do_exception ; no, it is a file.
jz ioctl_bad_funj2
OR DL,devid_device ; Make sure user doesn't turn off the
; device bit!! He can muck with the
; others at will.
MOV [EXTERR_LOCUS],errLOC_SerDev
MOV BYTE PTR ES:[DI].SF_FLAGS,DL ;AC000;MS.; Set flags
;**RMFHFE**do_exception:
;**RMFHFE** OR BYTE PTR ES:[DI.sf_flags+1],DH;AN000;MS.;set 100H bit for disk full
transfer SYS_RET_OK
ioctl_read:
MOV [EXTERR_LOCUS],errLOC_Disk
XOR AH,AH
test AL,devid_device ; Should I set high byte
JZ ioctl_no_high ; no
MOV [EXTERR_LOCUS],errLOC_SerDev
LES DI,ES:[DI.sf_devptr] ; Get device pointer
MOV AH,BYTE PTR ES:[DI.SDEVATT+1] ; Get high byte
ioctl_no_high:
MOV DX,AX
invoke get_user_stack
MOV [SI.user_DX],DX
transfer SYS_RET_OK
;--------------------------------------------------------------------------
;
; IOCTL: 2,3
;
; ENTRY : DS = DOSDATA
; Si = user's DS
;
;--------------------------------------------------------------------------
ioctl_control_string:
invoke SFFromHandle ; ES:DI -> SFT
JC ioctl_bad_handle ; invalid handle
TESTB ES:[DI].SF_FLAGS,devid_device ; can I?
jz ioctl_bad_funj2 ; No it is a file
MOV [EXTERR_LOCUS],errLOC_SerDev
LES DI,ES:[DI.sf_devptr] ; Get device pointer
XOR BL,BL ; Unit number of char dev = 0
JMP ioctl_do_string
;--------------------------------------------------------------------------
;
; IOCTL: AL = 6,7
;
; ENTRY: DS = DOSDATA
;
;--------------------------------------------------------------------------
ioctl_status:
MOV AH,1
SUB AL,6 ; 6=0,7=1
JZ ioctl_get_status
MOV AH,3
ioctl_get_status:
PUSH AX
invoke GET_IO_SFT
POP AX
JNC DO_IOFUNC
JMP ioctl_bad_handle ; invalid SFT
DO_IOFUNC:
invoke IOFUNC
MOV AH,AL
MOV AL,0FFH
JNZ ioctl_status_ret
INC AL
ioctl_status_ret:
transfer SYS_RET_OK
;------------------------------------------------------------------------
;
; IOCTL: AL = B
;
; ENTRY: DS = DOSDATA
;
;-------------------------------------------------------------------------
Set_Retry_Parameters:
MOV RetryLoop,CX ; 0 retry loop count allowed
OR DX,DX ; zero retries not allowed
JZ IoCtl_Bad_Fun
MOV RetryCount,DX ; Set new retry count
doneok:
transfer Sys_Ret_Ok ; Done
;--------------------------------------------------------------------------
;
; Generic IOCTL entry point. AL = C, D, 10h, 11h
;
; here we invoke the Generic IOCTL using the IOCTL_Req structure.
; SI:DX -> Users Device Parameter Table
; IOCALL -> IOCTL_Req structure
;
; If on entry AL >= IOCTL_QUERY_HANDLE the function is a
; QueryIOCtlSupport call ELSE it's a standard generic IOCtl
; call.
;
; BUGBUG: Don't push anything on the stack between GENERIOCTL: and
; the call to Check_If_Net because Check_If_Net gets our
; return address off the stack if the drive is invalid.
;
;----------------------------------------------------------------------------
query_handle_support: ; Entry point for handles
GENERICIOCTLHANDLE:
invoke SFFromHandle ; Get SFT for device.
jc ioctl_bad_handlej
TESTB ES:[DI].SF_FLAGS,sf_isnet ; M031;
jnz ioctl_bad_fun ; Cannot do this over net.
mov [EXTERR_LOCUS],ErrLOC_Serdev
les di,es:[di.sf_devptr] ; Get pointer to device.
jmp short Do_GenIOCTL
query_device_support: ; Entry point for devices:
GENERICIOCTL:
mov [EXTERR_LOCUS],ErrLOC_Disk
cmp ch,IOC_DC ; Only disk devices are allowed to use
jne ioctl_bad_fun ; no handles with Generic IOCTL.
CALL Check_If_Net ; ES:DI := Get_hdr_block of device in BL
JNZ ioctl_bad_fun ; There are no "net devices", and they
Do_GenIOCTL:
TESTB ES:[DI.SDEVATT],DEV320 ; Can device handle Generic IOCTL funcs
jz ioctl_bad_fun
mov byte ptr IOCALL.ReqFunc,GENIOCTL ;Assume real Request
cmp AL,IOCTL_QUERY_HANDLE ; See if this is just a query
jl SetIOCtlBlock
TESTB ES:[DI.SDEVATT],IOQUERY ; See if device supports a query
jz ioctl_bad_fun ; No support for query
mov byte ptr IOCALL.ReqFunc,IOCTL_QUERY ; Just a query (5.00)
SetIOCtlBlock:
PUSH ES ; DEVIOCALL2 expects Device header block
PUSH DI ; in DS:SI
; Setup Generic IOCTL Request Block
mov byte ptr IOCALL.ReqLen,(size IOCTL_Req)
MOV byte ptr IOCALL.ReqUnit,BL
MOV byte ptr IOCALL.MajorFunction,CH
MOV byte ptr IOCALL.MinorFunction,CL
MOV word ptr IOCALL.Reg_SI,SI
MOV word ptr IOCALL.Reg_DI,DI
MOV word ptr IOCALL.GenericIOCTL_Packet,DX
MOV word ptr IOCALL.GenericIOCTL_Packet + 2,SI
;hkn; IOCALL is in DOSDATA
MOV BX,offset DOSDATA:IOCALL
PUSH SS
POP ES
ASSUME DS:NOTHING ; DS:SI -> Device header.
POP SI
POP DS
jmp ioctl_do_IO ; Perform Call to device driver
ioctl_bad_fun:
error error_invalid_function
ioctl_bad_handlej:
jmp ioctl_bad_handle
;---------------------------------------------------------------------------
;
; IOCTL AL = 8
;
; ENTRY: DS = DOSDATA
;
; BUGBUG: Don't push anything on the stack between ioctl_rem_media: and
; the call to Check_If_Net because Check_If_Net gets our
; return address off the stack if the drive is invalid.
;
;-------------------------------------------------------------------------
ioctl_rem_media:
CALL Check_If_Net
JNZ ioctl_bad_fun ; There are no "net devices", and they
; certainly don't know how to do this
; call.
TESTB ES:[DI.SDEVATT],DEVOPCL ; See if device can
JZ ioctl_bad_fun ; NO
;hkn; SS override for IOCALL
MOV [IOCALL.REQFUNC],DEVRMD
MOV AL,REMHL
MOV AH,BL ; Unit number
MOV WORD PTR [IOCALL.REQLEN],AX
XOR AX,AX
MOV [IOCALL.REQSTAT],AX
PUSH ES
POP DS
ASSUME DS:NOTHING
MOV SI,DI ; DS:SI -> driver
PUSH SS
POP ES
;hkn; IOCALL is in DOSDATA (msconst.asm)
MOV BX,OFFSET DOSDATA:IOCALL ; ES:BX -> Call header
SAVE <DS,SI>
invoke DEVIOCALL2
RESTORE <SI,DS>
;hkn; SS override
MOV AX,[IOCALL.REQSTAT] ; Get Status word
AND AX,STBUI ; Mask to busy bit
MOV CL,9
SHR AX,CL ; Busy bit to bit 0
transfer SYS_RET_OK
;-------------------------------------------------------------------------
;
; IOCTL: AL = 9
;
; ENTRY: DS = DOSDATA
;
;-------------------------------------------------------------------------
Ioctl_Drive_attr:
mov al, bl
call GetThisDrv
jc ioctl_drv_err
call Get_Driver_BL
JC ioctl_drv_err ; drive not valid
mov dx,word ptr es:[di.SDEVATT]
; get device attribute word
MOV BL,AL ; Phys letter to BL (A=0)
;hkn; SS override
LES DI,[THISCDS]
TESTB ES:[DI.curdir_flags],curdir_isnet
JZ IOCTLShare
; Net devices don't return a device attribute word.
; Bit 12 = 1, meaning net device, all others = 0.
MOV DX,1000h
IOCTLShare:
Context DS
ASSUME DS:NOTHING
;hkn; OPENBUF is in DOSDATA
MOV SI,OFFSET DOSDATA:OPENBUF
ADD BL,"A"
MOV [SI],BL
MOV WORD PTR [SI+1],003AH ; ":",0
MOV AX,0300H
CLC
INT int_IBM
JNC ioctlLocal ; Not shared
OR DX,0200H ; Shared, bit 9
IOCTLLocal:
TESTB ES:[DI].curdir_flags,curdir_local
JZ ioctl_set_dx
OR DX,8000h
ioctl_set_DX:
invoke get_user_stack
MOV [SI.user_DX],DX
transfer SYS_RET_OK
ioctl_drv_err:
error error_invalid_drive
;--------------------------------------------------------------------------
; IOCTL: AL = A
;
; ENTRY: DS = DOSDATA
;
;--------------------------------------------------------------------------
Ioctl_Handle_redir:
invoke SFFromHandle ; ES:DI -> SFT
JNC ioctl_got_sft ; have valid handle
jmp ioctl_bad_handle
ioctl_got_sft:
MOV DX,ES:[DI].SF_FLAGS ; Get flags
JMP ioctl_set_DX ; pass dx to user and return
ioctl_bad_funj:
JMP ioctl_bad_fun
;--------------------------------------------------------------------------
;
; IOCTL: AL= 4,5
;
; ENTRY: DS = DOSDATA
; SI = user's DS
;
;
; BUGBUG: Don't push anything on the stack between ioctl_get_dev: and
; the call to Check_If_Net because Check_If_Net gets our
; return address off the stack if the drive is invalid.
;
;-------------------------------------------------------------------------
ioctl_get_dev:
DOSAssume <DS>,"IOCtl_Get_Dev"
CALL Check_If_Net
JNZ ioctl_bad_funj ; There are no "net devices", and they
; certainly don't know how to do this
; call.
ioctl_do_string:
TESTB ES:[DI.SDEVATT],DEVIOCTL; See if device accepts control
JZ ioctl_bad_funj ; NO
; assume IOCTL read
MOV [IOCALL.REQFUNC],DEVRDIOCTL
TEST AL, 1 ; is it func. 4/5 or 2/3
JZ ioctl_control_call ; it is read. goto ioctl_control_call
; it is an IOCTL write
MOV [IOCALL.REQFUNC],DEVWRIOCTL
ioctl_control_call:
MOV AL,DRDWRHL
ioctl_setup_pkt:
MOV AH,BL ; Unit number
MOV WORD PTR [IOCALL.REQLEN],AX
XOR AX,AX
MOV [IOCALL.REQSTAT],AX
MOV [IOMED],AL
MOV [IOSCNT],CX
MOV WORD PTR [IOXAD],DX
MOV WORD PTR [IOXAD+2],SI
PUSH ES
POP DS
ASSUME DS:NOTHING
MOV SI,DI ; DS:SI -> driver
PUSH SS
POP ES
;hkn; IOCALL is in DOSDATA
MOV BX,OFFSET DOSDATA:IOCALL ; ES:BX -> Call header
ioctl_do_IO:
invoke DEVIOCALL2
;hkn; SS override for IOCALL
TESTB [IOCALL.REQSTAT],STERR ;Error?
JNZ Ioctl_string_err
;hkn; SS override
MOV AX,[IOSCNT] ; Get actual bytes transferred
transfer SYS_RET_OK
Ioctl_string_err:
MOV DI,[IOCALL.REQSTAT] ;Get Error
device_err:
AND DI,STECODE ; mask out irrelevant bits
MOV AX,DI
invoke SET_I24_EXTENDED_ERROR
;hkn; use SS override
;hkn; mov ax, cs:extErr
mov ax, ss:extErr
transfer SYS_RET_ERR
;--------------------------------------------------------------------------
; Proc name : Get_Driver_BL
;
; DS is DOSDATA
; BL is drive number (0=default)
; Returns pointer to device in ES:DI, unit number in BL if carry clear
; No regs modified
;
;---------------------------------------------------------------------------
Get_Driver_BL:
DOSAssume <DS>,"Get_Driver_BL"
ASSUME ES:NOTHING
PUSH AX
MOV AL,BL ; Drive
invoke GETTHISDRV
jc ioctl_bad_drv
XOR BL,BL ; Unit zero on Net device
MOV [EXTERR_LOCUS],errLOC_Net
LES DI,[THISCDS]
TESTB ES:[DI.curdir_flags],curdir_isnet
LES DI,ES:[DI.curdir_devptr]; ES:DI -> Dpb or net dev
JNZ got_dev_ptr ; Is net
MOV [EXTERR_LOCUS],errLOC_Disk
MOV BL,ES:[DI.dpb_UNIT] ; Unit number
LES DI,ES:[DI.dpb_driver_addr] ; Driver addr
got_dev_ptr:
CLC
ioctl_bad_drv:
POP AX
return
;-------------------------------------------------------------------------
; Proc Name : Check_If_Net:
;
;
; Checks if the device is over the net or not. Returns result in ZERO flag.
; If no device is found, the return address is popped off the stack, and a
; jump is made to ioctl_drv_err.
;
; On Entry:
; Registers same as those for Get_Driver_BL
;
; On Exit:
; ZERO flag - set if not a net device
; - reset if net device
; ES:DI -> the device
;
;
; BUGBUG: This function assumes the following stack setup on entry
;
; SP+2 -> Error return address
; SP -> Normal return address
;
;-------------------------------------------------------------------------
Check_If_Net:
CALL Get_Driver_BL
JC ioctl_drv_err_pop ; invalid drive letter
PUSH ES
PUSH DI
LES DI,[THISCDS]
TESTB ES:[DI.curdir_flags],curdir_isnet
POP DI
POP ES
ret
ioctl_drv_err_pop:
pop ax ; pop off return address
jmp ioctl_drv_err
ioctl_bad_funj3:
jmp ioctl_bad_fun
ioctl_string_errj:
jmp ioctl_string_err
;--------------------------------------------------------------------------
;
; IOCTL: AL = E, F
;
; ENTRY: DS = DOSDATA
;
;
; BUGBUG: Don't push anything on the stack between ioctl_drive_owner: and
; the call to Check_If_Net because Check_If_Net gets our
; return address off the stack if the drive is invalid.
;
;--------------------------------------------------------------------------
ioctl_drive_owner:
Call Check_If_Net
JNZ ioctl_bad_funj3 ; There are no "net devices", and they
; certainly don't know how to do this
; call.
TESTB ES:[DI.SDEVATT],DEV320 ; See if device can handle this
JZ ioctl_bad_funj3 ; NO
mov [IOCALL.REQFUNC],DEVGETOWN ; default to get owner
cmp al, 0eh ; Get Owner ?
jz GetOwner
MOV [IOCALL.REQFUNC],DEVSETOWN
GetOwner:
MOV AL,OWNHL
MOV AH,BL ; Unit number
MOV WORD PTR [IOCALL.REQLEN],AX
XOR AX,AX
MOV [IOCALL.REQSTAT],AX
PUSH ES
POP DS
ASSUME DS:NOTHING
MOV SI,DI ; DS:SI -> driver
PUSH SS
POP ES
;hkn; IOCALL is in DOSDATA
MOV BX,OFFSET DOSDATA:IOCALL ; ES:BX -> Call header
SAVE <DS,SI>
invoke DEVIOCALL2
RESTORE <SI,DS>
;hkn; SS override
TESTB [IOCALL.REQSTAT],STERR
jnz ioctl_string_errj
MOV AL,BYTE PTR [IOCALL.REQUNIT] ; Get owner returned by device
; owner returned is 1-based.
transfer SYS_RET_OK
EndProc $IOCTL
DOSCODE ENDS
END
|
import React, { createContext, useContext, useReducer, Dispatch } from "react";
import { Action, initialState, reducer, Store } from "./Store";
interface Props {
children: JSX.Element | JSX.Element[];
}
export const StoreContext = createContext({} as [Store, Dispatch<Action>]);
export const StoreProvider = (props: Props) => {
const { children } = props;
return (
<StoreContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StoreContext.Provider>
);
};
export const useStore = () => useContext(StoreContext);
|
package io.provenance.scope.sdk
import io.provenance.scope.contract.annotations.Record as AnnotationRecord
import io.provenance.metadata.v1.*
import io.provenance.scope.contract.annotations.*
import io.provenance.scope.contract.proto.Commons
import io.provenance.scope.contract.proto.HelloWorldExample
import io.provenance.scope.proto.PK
import io.provenance.scope.contract.proto.Specifications
import io.provenance.scope.contract.proto.TestContractProtos
import io.provenance.scope.encryption.ecies.ECUtils
import io.provenance.scope.encryption.model.DirectKeyRef
import io.provenance.scope.encryption.util.getAddress
import io.provenance.scope.encryption.util.toJavaPrivateKey
import io.provenance.scope.encryption.util.toJavaPublicKey
import io.provenance.scope.encryption.util.toKeyPair
import io.provenance.scope.util.MetadataAddress
import io.provenance.scope.util.toByteString
import io.provenance.scope.util.toUuid
import java.net.URI
import java.security.KeyPair
import java.util.*
val localKeys = listOf(
"0A2100EF4A9391903BFE252CB240DA6695BC5F680A74A8E16BEBA003833DFE9B18C147",
"0A2100CBEDAA6241122CB6B5BD2A3E1FFDD8694C0AEC16E80A0CC72B6256C56090F6FA",
"0A21009B6CFD2525DD7EA500A3F2665047319A3D2A3F1D62177D686DF98713D8E52BDB",
).map { privateHex -> privateHex.toJavaPrivateKey().toKeyPair() }
val jarCacheSize = 20000L
val osGrpcDeadlineMs = 20000L
val specCacheSizeInBytes = 20000L
val recordCacheSizeInBytes = 20000L
val osGrpcUri = URI.create("https://localhost:5000")
fun createClientDummy(localKeyIndex: Int): Client {
val encryptionKeyRef = DirectKeyRef(localKeys[localKeyIndex])
val signingKeyRef = DirectKeyRef(localKeys[localKeyIndex + 1])
val partyType = Specifications.PartyType.OWNER
val affiliate = Affiliate(signingKeyRef, encryptionKeyRef, partyType)
val clientConfig = ClientConfig(
jarCacheSize,
specCacheSizeInBytes,
recordCacheSizeInBytes,
osGrpcUri,
osGrpcDeadlineMs,
mainNet = false
)
return Client(SharedClient(clientConfig), affiliate)
}
fun createSessionBuilderNoRecords(osClient: Client, existingScope: ScopeResponse? = null): Session.Builder {
val defSpec = Commons.DefinitionSpec.newBuilder()
.setType(Commons.DefinitionSpec.Type.PROPOSED)
.setResourceLocation(
Commons.Location.newBuilder()
.setClassname("io.provenance.scope.contract.proto.HelloWorldExample\$ExampleName")
)
.setName("record2")
val conditionSpec = Specifications.ConditionSpec.newBuilder()
.addInputSpecs(defSpec)
.setFuncName("record2")
.build()
val participants = HashMap<Specifications.PartyType, PK.PublicKey>()
participants[Specifications.PartyType.OWNER] = PK.PublicKey.newBuilder().build()
val spec = Specifications.ContractSpec.newBuilder()
.setDefinition(defSpec)
.addConditionSpecs(conditionSpec)
.addFunctionSpecs(
Specifications.FunctionSpec.newBuilder()
.setFuncName("record2")
.addInputSpecs(defSpec)
.setOutputSpec(Commons.OutputSpec.newBuilder().setSpec(defSpec))
.setInvokerParty(Specifications.PartyType.OWNER)
)
if (existingScope != ScopeResponse.getDefaultInstance()) {
spec.addInputSpecs(defSpec)
}
val provenanceReference = Commons.ProvenanceReference.newBuilder().build()
var scopeSpecUuid: UUID
if (!existingScope?.scope?.scopeSpecIdInfo?.scopeSpecUuid.isNullOrEmpty()) {
scopeSpecUuid = existingScope?.scope?.scopeSpecIdInfo?.scopeSpecUuid!!.toUuid()
} else {
scopeSpecUuid = UUID.randomUUID()
}
return Session.Builder(scopeSpecUuid)
.setContractSpec(spec.build())
.setProvenanceReference(provenanceReference)
.setClient(osClient)
.setSessionUuid(UUID.randomUUID())
.apply {
if (existingScope != null) {
setScope(existingScope)
addDataAccessKey(localKeys[2].public)
}
}
}
fun createExistingScope(): ScopeResponse.Builder {
val scopeUuid = UUID.randomUUID()
val sessionUUID = UUID.randomUUID()
val specificationUUID = UUID.randomUUID()
val scopeRecord = Record.newBuilder()
.addInputs(
RecordInput.newBuilder()
.setName("record2")
.setHash("M8PWxG2TFfO0YzL3sDW/l9kX325y+3v+5liGcjZoi4Q=")
.setStatus(RecordInputStatus.RECORD_INPUT_STATUS_PROPOSED)
)
.addOutputs(RecordOutput.newBuilder().setHash("M8PWxG2TFfO0YzL3sDW/l9kX325y+3v+5liGcjZoi4Q=").build())
.setProcess(
Process.newBuilder().setName("io.provenance.scope.contract.proto.HelloWorldExample\$ExampleName").build()
)
.setSessionId(MetadataAddress.forSession(scopeUuid, sessionUUID).bytes.toByteString())
.setName("record2")
val recordWrapper = RecordWrapper.newBuilder().setRecord(scopeRecord).build()
val scope = Scope.newBuilder()
.addDataAccess(localKeys[2].public.getAddress(false))
.addOwners(Party.newBuilder().setRole(PartyType.PARTY_TYPE_OWNER))
.setScopeId(MetadataAddress.forScope(scopeUuid).bytes.toByteString())
.setValueOwnerAddress("ownerAddress")
.setSpecificationId(MetadataAddress.forScopeSpecification(specificationUUID).bytes.toByteString())
.build()
val scopeWrapper = ScopeWrapper.newBuilder()
.setScope(scope)
.build()
val scopeResponseBuilder = ScopeResponse.newBuilder()
.setScope(scopeWrapper)
.addRecords(recordWrapper)
.apply {
scopeBuilder.scopeIdInfoBuilder.setScopeUuid(scopeUuid.toString())
scopeBuilder.scopeSpecIdInfoBuilder.setScopeSpecUuid(specificationUUID.toString())
requestBuilder
.setIncludeRecords(true)
.setIncludeSessions(true)
}
return scopeResponseBuilder
}
data class HelloWorldData(@AnnotationRecord(name = "record2") val name: HelloWorldExample.ExampleName) {}
data class HelloWorldDataNullable(
@AnnotationRecord(name = "record2") val name: HelloWorldExample.ExampleName,
@AnnotationRecord(name = "nullableRecord") val nullableRecord: TestContractProtos.TestProto?
) {}
|
<?php
namespace Modules\Notification\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Modules\Notification\Events\Handlers\NotificationHandler;
use Modules\Notification\Repositories\RuleRepository;
use Illuminate\Support\Arr;
class EventServiceProvider extends ServiceProvider
{
private $module;
private $service;
protected $listen;
public function register()
{
$this->module = app('modules');
if(isset($this->module) && $this->module && $this->module->allEnabled()){
$this->service = app('Modules\\Notification\\Repositories\\RuleRepository');
$notifiable = $this->service->moduleConfigs($this->module->allEnabled());
//dd($notifiable);
$this->listen = [];
foreach ($notifiable as $entity){
foreach ($entity["events"] as $event) {
$listen = [$event["path"] => [
NotificationHandler::class
]];
array_push(
$this->listen,
$listen
);
}
}
$this->listen = Arr::collapse($this->listen);
}
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataError = void 0;
const error_utils_1 = require("./error.utils");
class DataError extends error_utils_1.ErrorSystem {
constructor(message) {
super(message, DataError.name);
}
}
exports.DataError = DataError;
|
using HexCS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HexUN.Utilities
{
/// <summary>
/// Invokes on update whenenver the list is modified. i.e. Add, remove, set, etc.
/// Provides the List as argument
/// </summary>
/// <typeparam name="T"></typeparam>
public class OnUpdateList<T> : List<T>, IUpdateable<IReadOnlyList<T>>
{
private Event<IReadOnlyList<T>> _onUpdate = new Event<IReadOnlyList<T>>();
#region API
public IEventSubscriber<IReadOnlyList<T>> OnUpdate => _onUpdate;
public OnUpdateList() : base() { }
public OnUpdateList(IEnumerable<T> collection) : base(collection) { }
public OnUpdateList(int capacity) : base(capacity) { }
public new T this[int index] {
get => base[index];
set => base[index] = value;
}
public new void Add(T item)
{
base.Add(item);
InvokeUpdate();
}
public new void AddRange(IEnumerable<T> collection) {
base.AddRange(collection);
InvokeUpdate();
}
public new void Insert(int index, T item) {
base.Insert(index, item);
InvokeUpdate();
}
public new void InsertRange(int index, IEnumerable<T> collection) {
base.InsertRange(index, collection);
InvokeUpdate();
}
public new bool Remove(T item) {
if (base.Remove(item))
{
InvokeUpdate();
return true;
}
return false;
}
public new int RemoveAll(Predicate<T> match)
{
int c = base.RemoveAll(match);
if(c > 0) InvokeUpdate();
return c;
}
public new void RemoveAt(int index) {
base.RemoveAt(index);
InvokeUpdate();
}
public new void RemoveRange(int index, int count) {
base.RemoveRange(index, count);
InvokeUpdate();
}
public new void Reverse(int index, int count) {
base.Reverse(index, count);
InvokeUpdate();
}
public new void Reverse() {
base.Reverse();
InvokeUpdate();
}
public new void Sort(Comparison<T> comparison) {
base.Sort(comparison);
InvokeUpdate();
}
public new void Sort(int index, int count, IComparer<T> comparer) {
base.Sort(index, count, comparer);
InvokeUpdate();
}
public new void Sort() {
base.Sort();
InvokeUpdate();
}
public new void Sort(IComparer<T> comparer) {
base.Sort(comparer);
InvokeUpdate();
}
#endregion
private void InvokeUpdate()
{
_onUpdate.Invoke(AsReadOnly());
}
}
}
|
<?php
/**
* This file is part of Moltin PHP-SDK, a PHP package which
* provides convinient and rapid access to the API.
*
* Copyright (c) 2013-2014 Moltin Ltd.
* http://github.com/moltin/php-sdk
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package moltin/php-sdk
* @author Jamie Holdroyd <jamie@molt.in>
* @copyright 2014 Moltin Ltd.
* @version dev
* @link http://github.com/moltin/php-sdk
*
*/
namespace Moltin\SDK\Facade;
class Cart
{
protected static $sdk;
protected static $identifier;
public static function init(\Moltin\SDK\SDK $sdk)
{
self::$sdk = $sdk;
self::$identifier = self::$sdk->identifier();
}
public static function Identifier()
{
return self::$identifier;
}
public static function Contents()
{
return self::$sdk->get('carts/'.self::$identifier);
}
public static function Insert($id, $qty = 1, $mods = null)
{
return self::$sdk->post('carts/'.self::$identifier, array(
'id' => $id,
'quantity' => $qty,
'modifier' => $mods
));
}
public static function Update($id, $data)
{
return self::$sdk->put('carts/'.self::$identifier.'/item/'.$id, $data);
}
public static function Delete()
{
return self::$sdk->delete('carts/'.self::$identifier);
}
public static function Remove($id)
{
return self::$sdk->delete('carts/'.self::$identifier.'/item/'.$id);
}
public static function Item($id)
{
return self::$sdk->get('carts/'.self::$identifier.'/item/'.$id);
}
public static function InCart($id)
{
return self::$sdk->get('carts/'.self::$identifier.'/has/'.$id);
}
public static function Checkout()
{
return self::$sdk->get('carts/'.self::$identifier.'/checkout');
}
public static function Order($data = array())
{
return self::$sdk->post('carts/'.self::$identifier.'/checkout', $data);
}
public static function Discount($code = false)
{
if ( $code === false )
{
return self::$sdk->delete('carts/'.self::$identifier.'/discount');
}
return self::$sdk->post('carts/'.self::$identifier.'/discount', ['code' => $code]);
}
public static function Listing($terms = array())
{
return self::$sdk->get('carts', $terms);
}
}
|
using UnityEngine;
using System.Collections;
public class RNG : MonoBehaviour {
public static float Floats(float min, float max)
{
float r;
r = Random.Range(min, max);
return r;
}
public static int Ints(int min, int max)
{
int i;
i = Random.Range(min, max);
return i;
}
}
|
# frozen-string-literal: true
require "test_helper"
class EncryptedParametersTest < MiniTest::Unit::TestCase
def test_missing_encrypted_params
controller = MockController.new({})
assert_equal({}, controller.encrypted_params)
end
def test_invalid_encrypted_params
controller = MockController.new("_encrypted" => { "key" => "value" })
assert_raises ActiveSupport::MessageVerifier::InvalidSignature do
controller.encrypted_params
end
end
def test_properly_encrypted_params
value = EncryptedFormFields.encrypt_and_sign("value")
controller = MockController.new("_encrypted" => { "key" => value })
assert_equal({ "key" => "value" }, controller.encrypted_params)
controller = MockController.new("_encrypted" => { "key" => [value] })
assert_equal({ "key" => ["value"] }, controller.encrypted_params)
controller = MockController.new("_encrypted" => { "key" => { "nested" => value } })
assert_equal({ "key" => { "nested" => "value" } }, controller.encrypted_params)
end
end
|
SUBROUTINE WRITCA(LUNXX,MSGT,MSGL)
C$$$ SUBPROGRAM DOCUMENTATION BLOCK
C
C SUBPROGRAM: WRITCA
C PRGMMR: J. ATOR ORG: NP12 DATE: 2004-08-18
C
C ABSTRACT: THIS SUBROUTINE IS CONSIDERED OBSOLETE AND MAY BE REMOVED
C FROM THE BUFR ARCHIVE LIBRARY IN A FUTURE VERSION. IT NOW SIMPLY
C CALLS BUFR ARCHIVE LIBRARY SUBROUTINE CMPMSG TO TOGGLE ON MESSAGE
C COMPRESSION, FOLLOWED BY A CALL TO WRITSA (SEE WRITSA DOCBLOCK).
C THIS SUBROUTINE USES THE SAME INPUT AND OUTPUT PARAMETERS AS WRITSA.
C
C PROGRAM HISTORY LOG:
C 2004-08-18 J. ATOR -- ORIGINAL AUTHOR; BASED UPON WRITSA
C 2005-03-09 J. ATOR -- MARKED AS OBSOLETE AND ADDED PRINT
C NOTIFICATION
C DART $Id$
C
C USAGE: CALL WRITCA (LUNXX, MSGT, MSGL)
C INPUT ARGUMENT LIST:
C LUNXX - INTEGER: ABSOLUTE VALUE IS FORTRAN LOGICAL UNIT NUMBER
C FOR BUFR FILE {IF LUNXX IS LESS THAN ZERO, THEN ANY
C CURRENT MESSAGE IN MEMORY WILL BE FORCIBLY FLUSHED TO
C ABS(LUNXX) AND TO ARRAY MSGT}
C
C OUTPUT ARGUMENT LIST:
C MSGT - INTEGER: *-WORD PACKED BINARY ARRAY CONTAINING BUFR
C MESSAGE (FIRST MSGL WORDS FILLED)
C MSGL - INTEGER: NUMBER OF WORDS FILLED IN MSGT
C 0 = no message was returned
C
C REMARKS:
C THIS ROUTINE CALLS: CMPMSG WRITSA
C THIS ROUTINE IS CALLED BY: None
C Normally called only by application
C programs.
C
C ATTRIBUTES:
C LANGUAGE: FORTRAN 77
C MACHINE: PORTABLE TO ALL PLATFORMS
C
C$$$
COMMON /QUIET / IPRT
DATA IFIRST/0/
SAVE IFIRST
C-----------------------------------------------------------------------
C-----------------------------------------------------------------------
IF(IFIRST.EQ.0) THEN
IF(IPRT.GE.0) THEN
PRINT*
PRINT*,'+++++++++++++++++BUFR ARCHIVE LIBRARY++++++++++++++++++++'
PRINT 101
101 FORMAT(' BUFRLIB: WRITCA - THIS SUBROUTINE IS NOW OBSOLETE; ',
. 'USE SUBROUTINES CMPMSG AND WRITSA INSTEAD')
PRINT*,'+++++++++++++++++BUFR ARCHIVE LIBRARY++++++++++++++++++++'
PRINT*
ENDIF
IFIRST = 1
ENDIF
CALL CMPMSG('Y')
CALL WRITSA(LUNXX,MSGT,MSGL)
RETURN
END
|
# php-signaler
[中文文档](README_CN.md "中文文档")
## Introduction
This is a project build with [Workerman](https://github.com/walkor/Workerman "Workerman").
Cloud support [hlsjs-p2p-engine](https://github.com/cdnbye/hlsjs-p2p-engine "hlsjs-p2p-engine") signaler service.
Technically support all WebRTC signaler service.
Written in full pure PHP. High performance and support cluster.
## Free Public Signal Service
Websocket Address: wss://free.freesignal.net
We are maintain a public and free signal service for everybody.
Currently we use
2 servers for gateway
2 servers for worker
1 server for register
We invite you to use our service, we will do the best as we can.
Websocket Address: wss://free.freesignal.net
## Requires
1. PHP 5.3 or Higher
2. A POSIX compatible operating system (Linux, OSX, BSD)
3. POSIX and PCNTL extensions for PHP
## Install
### CentOS
yum install php-cli php-process git gcc php-devel php-pear libevent-devel -y
Basically this is already support you to run this project.
But if you are face to more than 1000 connections, please read Optimize character.
### Optimize
If you are using PHP 5.3.3, you can only install libevent extension.
pecl install channel://pecl.php.net/libevent-0.1.0
//Attention: "libevent installation [autodetect]:" message Enter
echo extension=libevent.so > /etc/php.d/libevent.ini
If your PHP version is higher than 5.3.3, install event extension will better.
pecl install event
//Attention: Include libevent OpenSSL support [yes] : type "no" then Enter,
//Attention: PHP Namespace for all Event classes :type "yes" then Enter
//Otherwise just Enter.
echo extension=event.so > /etc/php.d/event.ini
Download programe.
git clone https://github.com/RayP2P/php-signaler
## Configure
all you need to focus is [config.php](https://github.com/RayP2P/php-signaler/blob/master/config.php "config.php")
//Gateway LanIP,change it when you are using in cluster.(public IP is also could be use, but not suggested.)
'lanIP'=>'127.0.0.1',
//Register Address
'registerAddress'=>'127.0.0.1',
//Register Listen Port
'registerPort'=>1238,
//Gateway Listen Port
'gatewayPort'=>80,
//using wss:// or ws://
'wss'=>false,
//wss cert
'wss_cert'=>'/root/server.crt',
//wss key
'wss_key'=>'/root/server.key',
//Gateway Workers
'gatewayWorkers'=>4,
//Bussiness Workers
'bussinessWorkers'=>4,
## Run in single server.
php php-signaler/start_all.php
//test your signaler service.
//if the test is success, add " -d" argument to running the service in daemon mode.
php php-signaler/start_all.php -d
## Run in cluster mode.(at least need 2 servers,suggest at least 3 servers.)
// Keep all server have the same content in config.php expect "lanIP"
// lanIP is only thing you must to change when you setting up Gateway Server.
//1. run register server.[only need setup one server]
//This server is connecting gateway and worker.it will just a low loadAvg server.
php php-signaler/start_register.php
//2. run worker server.[when the loadAvg is higher than expect, you need add more.]
//This server is working to process all the logical.
php php-signaler/start_worker.php
//3. run gateway server.[when the loadAvg is higher than expect, you need add more.]
//This server is face to user, it needs public IP address.
php php-signaler/start_gateway.php
//4. Finally , test your signaler service.
//if the test is success, add " -d" argument to running the service in daemon mode.
php php-signaler/start_register.php -d
php php-signaler/start_worker.php -d
php php-signaler/start_gateway.php -d
## Configure hlsjs-p2p-engine
1.Change the signal address to your address
### Example
var hlsjsConfig = {
p2pConfig: {
wsSignalerAddr: 'wss://example.com/ws',
}
};
More info visit [hlsjs-p2p-engine API.md](https://github.com/cdnbye/hlsjs-p2p-engine/blob/master/docs/English/API.md "hlsjs-p2p-engine API.md")
|
package nl.entreco.giddyapp.viewer.ui.details
import android.view.View
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import nl.entreco.giddyapp.libhorses.*
class DetailModel(horse: Horse) {
val horseId = ObservableField(horse.id)
val name = ObservableField(horse.name)
val desc = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.desc
is Horse.Loading -> "Please wait"
is Horse.Error -> horse.msg
is Horse.NotFound -> "Perhaps this horse has been removed"
else -> ""
}
)
val ratio = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.ratio
else -> HorseRatio()
}
)
val since = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.since
else -> HorsePosted(System.currentTimeMillis())
}
)
val genderIcon = ObservableInt(
when (horse) {
is Horse.Normal -> horse.details.gender.icon()
else -> HorseGender.Unknown.icon()
}
)
val level = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.type
else -> HorseLevel.Unknown
}
)
val price = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.price
else -> HorsePrice.NotForSale
}
)
val category = ObservableField(
when (horse) {
is Horse.Normal -> horse.details.category
else -> HorseCategory.Unknown
}
)
val visibility = ObservableInt(
when (horse) {
is Horse.Normal -> View.VISIBLE
else -> View.INVISIBLE
}
)
}
|
[](https://ci.consulo.io/job/consulo-aspnet)
|
/*
* @(#)RotatedIcon.java
*
* $Date: 2014-03-13 09:15:48 +0100 (Do, 13 Mär 2014) $
*
* Copyright (c) 2014 by Jeremy Wood.
* All rights reserved.
*
* The copyright of this software is owned by Jeremy Wood.
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* Jeremy Wood. For details see accompanying license terms.
*
* This software is probably, but not necessarily, discussed here:
* https://javagraphics.java.net/
*
* That site should also contain the most recent official version
* of this software. (See the SVN repository for more details.)
*/
package com.bric.swing;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.Icon;
import com.bric.math.MathG;
/** A rotated rendering of a given icon.
* <P>This is (currently) intended for animation, so for
* the sake of uniformity: this icon uses the same width and height
* (calculated as the maximum that may be required for the transformed icon).
* The source icon is always rendered in the center of this space.
* <p>For example: if you have a 100x100 icon, then the RotatedIcon
* wrapper will be 142x142 pixels (because it has to allow room for
* the icon to rotate 45 degrees).
*/
public class RotatedIcon implements Icon {
float rotation;
Icon icon;
int size;
public RotatedIcon(Icon icon,float radians) {
this.rotation = radians;
this.icon = icon;
int h = icon.getIconHeight();
int w = icon.getIconWidth();
double k = Math.sqrt(h*h+w*w);
size = MathG.ceilInt(k);
}
public void paintIcon(Component c, Graphics g0, int x, int y) {
Graphics2D g = (Graphics2D)g0.create();
g.rotate(rotation, x + size/2, y + size/2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(c, g,
x + getIconWidth()/2 - icon.getIconWidth()/2,
y + getIconHeight()/2 - icon.getIconHeight()/2 );
g.dispose();
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
|
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
fn validate_scale_factor(scale_factor: f64) -> bool {
scale_factor.is_sign_positive() && scale_factor.is_normal()
}
/// A pixel definition. Must be created from a `f64` value.
pub trait Pixel: Copy + Into<f64> {
/// Creates the pixel from the `f64` value.
fn from_f64(f: f64) -> Self;
/// Casts a pixel.
fn cast<P: Pixel>(self) -> P {
P::from_f64(self.into())
}
}
impl Pixel for u8 {
fn from_f64(f: f64) -> Self {
f.round() as u8
}
}
impl Pixel for u16 {
fn from_f64(f: f64) -> Self {
f.round() as u16
}
}
impl Pixel for u32 {
fn from_f64(f: f64) -> Self {
f.round() as u32
}
}
impl Pixel for i8 {
fn from_f64(f: f64) -> Self {
f.round() as i8
}
}
impl Pixel for i16 {
fn from_f64(f: f64) -> Self {
f.round() as i16
}
}
impl Pixel for i32 {
fn from_f64(f: f64) -> Self {
f.round() as i32
}
}
impl Pixel for f32 {
fn from_f64(f: f64) -> Self {
f as f32
}
}
impl Pixel for f64 {
#[allow(clippy::wrong_self_convention)]
fn from_f64(f: f64) -> Self {
f
}
}
/// A position represented in physical pixels.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash, Serialize, Deserialize)]
pub struct PhysicalPosition<P> {
/// Vertical axis value.
pub x: P,
/// Horizontal axis value.
pub y: P,
}
impl<P: Pixel> PhysicalPosition<P> {
/// Converts the physical position to a logical one, using the scale factor.
#[inline]
pub fn to_logical<X: Pixel>(self, scale_factor: f64) -> LogicalPosition<X> {
assert!(validate_scale_factor(scale_factor));
let x = self.x.into() / scale_factor;
let y = self.y.into() / scale_factor;
LogicalPosition { x, y }.cast()
}
}
/// A position represented in logical pixels.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash, Serialize, Deserialize)]
pub struct LogicalPosition<P> {
/// Vertical axis value.
pub x: P,
/// Horizontal axis value.
pub y: P,
}
impl<T: Pixel> LogicalPosition<T> {
/// Casts the logical size to another pixel type.
#[inline]
pub fn cast<X: Pixel>(&self) -> LogicalPosition<X> {
LogicalPosition {
x: self.x.cast(),
y: self.y.cast(),
}
}
}
/// A position that's either physical or logical.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum Position {
/// Physical position.
Physical(PhysicalPosition<i32>),
/// Logical position.
Logical(LogicalPosition<f64>),
}
/// A size represented in physical pixels.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash, Serialize, Deserialize)]
pub struct PhysicalSize<T> {
/// Width.
pub width: T,
/// Height.
pub height: T,
}
impl<T: Pixel> PhysicalSize<T> {
/// Converts the physical size to a logical one, applying the scale factor.
#[inline]
pub fn to_logical<X: Pixel>(self, scale_factor: f64) -> LogicalSize<X> {
assert!(validate_scale_factor(scale_factor));
let width = self.width.into() / scale_factor;
let height = self.height.into() / scale_factor;
LogicalSize { width, height }.cast()
}
}
/// A size represented in logical pixels.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash, Serialize, Deserialize)]
pub struct LogicalSize<T> {
/// Width.
pub width: T,
/// Height.
pub height: T,
}
impl<T: Pixel> LogicalSize<T> {
/// Casts the logical size to another pixel type.
#[inline]
pub fn cast<X: Pixel>(&self) -> LogicalSize<X> {
LogicalSize {
width: self.width.cast(),
height: self.height.cast(),
}
}
}
/// A size that's either physical or logical.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum Size {
/// Physical size.
Physical(PhysicalSize<u32>),
/// Logical size.
Logical(LogicalSize<f64>),
}
|
/*=========================================================================
Image-based Vascular Analysis Toolkit (IVAN)
Copyright (c) 2012, Iván Macía Oliver
Vicomtech Foundation, San Sebastián - Donostia (Spain)
University of the Basque Country, San Sebastián - Donostia (Spain)
All rights reserved
See LICENSE file for license details
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
==========================================================================*/
// File: ivanVesselnessBasedSearchVesselTrackerFilter.h
// Author: Iv�n Mac�a (imacia@vicomtech.org)
// Date: 2011/01/21
#ifndef __ivanVesselnessBasedSearchVesselTrackerFilter_h
#define __ivanVesselnessBasedSearchVesselTrackerFilter_h
#include "ivanVesselTrackerFilter.h"
#include "ivanImageFunctionInitializerBase.h"
#include "itkImage.h"
#include "itkSingleValuedNonLinearOptimizer.h"
namespace ivan
{
/** \class VesselnessBasedSearchVesselTrackerFilter
* \brief VesselTracker that takes a vesselness measure to guide the a search stage.
*
* VesselnessBasedSearchVesselTrackerFilter takes a vesselness measure to guide the search stage. This is
* a correction stage used to reestimate parameters such as the section center, normal or scale.
* This vesselness measure can be calculated on the fly from the source image or can be retrieved
* from an external image.
*
* The vesselness measure is specified as a template parameter which corresponds to an image function.
*
*
*/
template <class TInputImage, class TOutputVessel, class TVesselnessFunction>
class ITK_EXPORT VesselnessBasedSearchVesselTrackerFilter : public VesselTrackerFilter<TInputImage,TOutputVessel>
{
public:
/** Standard class typedefs. */
typedef VesselnessBasedSearchVesselTrackerFilter
<TInputImage, TOutputVessel, TVesselnessFunction> Self;
typedef VesselTrackerFilter
<TInputImage,TOutputVessel> Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Some convenient typedefs. */
typedef TInputImage InputImageType;
typedef typename Superclass::InputImagePointer InputImagePointer;
typedef typename Superclass::InputImageConstPointer InputImageConstPointer;
typedef typename Superclass::InputImageRegionType InputImageRegionType;
typedef typename Superclass::InputImagePixelType InputImagePixelType;
typedef typename Superclass::InputImagePointType InputImagePointType;
typedef typename Superclass::InputImageIndexType InputImageIndexType;
/** Some convenient typedefs. */
typedef TOutputVessel OutputVesselType;
typedef typename OutputVesselType::Pointer OutputVesselPointer;
typedef typename Superclass::CenterlineType CenterlineType;
typedef typename Superclass::SectionType SectionType;
typedef itk::Image<typename TVesselnessFunction::OutputType,
InputImageType::ImageDimension> VesselnessImageType;
typedef TVesselnessFunction VesselnessFunctionType;
typedef typename VesselnessFunctionType::Pointer VesselnessFunctionPointer;
typedef typename VesselnessFunctionType::OutputType VesselnessValueType;
typedef ImageFunctionInitializerBase
<VesselnessFunctionType,InputImageType> VesselnessFunctionInitializerType;
typedef typename VesselnessFunctionInitializerType::Pointer VesselnessFunctionInitializerPointer;
public:
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro( VesselnessBasedSearchVesselTrackerFilter, VesselTrackerFilter );
virtual void SetInput( const InputImageType *image );
virtual void SetInput( unsigned int, const InputImageType * image );
/** Set/Get the VesselnessImageFunction to use. This can be a vesselness calculated from a source
* image as an image function, or, if the full vesselness image has been previously calculated,
* can be an interpolator of that image, such as nearest neighbour or linear interpolator. */
virtual void SetVesselnessImageFunction( VesselnessFunctionType *func )
{
m_VesselnessFunction = func;
this->Modified();
}
itkGetObjectMacro( VesselnessFunction, VesselnessFunctionType );
itkGetConstObjectMacro( VesselnessFunction, VesselnessFunctionType );
itkSetObjectMacro( VesselnessFunctionInitializer, VesselnessFunctionInitializerType );
itkGetObjectMacro( VesselnessFunctionInitializer, VesselnessFunctionInitializerType );
itkGetConstObjectMacro( VesselnessFunctionInitializer, VesselnessFunctionInitializerType );
VesselnessValueType GetVesselnessValueAtCurrentPoint();
VesselnessValueType GetVesselnessValueAtPreviousPoint();
protected:
VesselnessBasedSearchVesselTrackerFilter();
~VesselnessBasedSearchVesselTrackerFilter() {}
virtual void PrintSelf( std::ostream& os, itk::Indent indent ) const;
private:
VesselnessBasedSearchVesselTrackerFilter(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
protected:
VesselnessFunctionPointer m_VesselnessFunction;
/** Provide a means to initialize the vesselness function for each scale. This is called at
* initialization for the metrics of all scales and during the search stage whenever the
* scale changes. */
VesselnessFunctionInitializerPointer m_VesselnessFunctionInitializer;
};
} // end namespace ivan
#ifndef ITK_MANUAL_INSTANTIATION
#include "ivanVesselnessBasedSearchVesselTrackerFilter.hxx"
#endif
#endif
|
package main
import (
"fmt"
"qqlt"
)
func main() {
bot := qqlt.NewBotApiClient()
//发送消息
bot.SendMsg(qqlt.MT_Friend, "", "qq号", "")
// 私聊消息
bot.SendMsg(qqlt.MT_Friend, "", "somebody qq", "发送的内容")
bot.SendPrivateMsg("somebody qq", "发送的内容")
qqlt.NewMessage().
QQ("qq").
Text("aasdasd").
Send(bot)
qqlt.NewMessage().
Text("aasdasd").
Dice(bot, qqlt.MT_Friend, "qq号")
// 发群消息
bot.SendMsg(qqlt.MT_Group, "群号", "", "发送的内容")
bot.SendGroupMsg("群号", "消息")
qqlt.NewMessage().
Group("群号").
At("@的人的qq").
Text("消息").
Send(bot)
qqlt.NewMessage().
At("@的人的qq").
Text("aasdasd").
Dice(bot, qqlt.MT_Group, "群号")
//
s := qqlt.NewDefaultServer()
go s.DefaultRun()
for update := range s.Updates {
fmt.Println(update)
}
}
|
package lt.markmerkk.widgets.main
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class SidePaneHandlerHandleAnyPaneOpenTest {
@Mock lateinit var listener: SidePaneHandler.Listener
@Mock lateinit var paneStateProviderLogs: SidePaneHandler.SidePaneStateProvider
@Mock lateinit var paneStateProviderTickets: SidePaneHandler.SidePaneStateProvider
lateinit var sidePaneHandler: SidePaneHandler
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
sidePaneHandler = SidePaneHandler(
listener = listener,
paneLogs = paneStateProviderLogs,
paneTickets = paneStateProviderTickets
)
}
@Test
fun noPaneOpen() {
// Assemble
doReturn(false).whenever(paneStateProviderLogs).isOpen()
doReturn(false).whenever(paneStateProviderTickets).isOpen()
// Act
val result = sidePaneHandler.sidePanelState()
// Assert
assertThat(result).isEqualTo(SidePaneHandler.PaneState.CLOSED)
}
@Test
fun logsOpen() {
// Assemble
doReturn(true).whenever(paneStateProviderLogs).isOpen()
doReturn(false).whenever(paneStateProviderTickets).isOpen()
// Act
val result = sidePaneHandler.sidePanelState()
// Assert
assertThat(result).isEqualTo(SidePaneHandler.PaneState.OPEN_ONLY_LOGS)
}
@Test
fun ticketsOpen() {
// Assemble
doReturn(false).whenever(paneStateProviderLogs).isOpen()
doReturn(true).whenever(paneStateProviderTickets).isOpen()
// Act
val result = sidePaneHandler.sidePanelState()
// Assert
assertThat(result).isEqualTo(SidePaneHandler.PaneState.OPEN_ALL)
}
@Test
fun bothOpen() {
// Assemble
doReturn(true).whenever(paneStateProviderLogs).isOpen()
doReturn(true).whenever(paneStateProviderTickets).isOpen()
// Act
val result = sidePaneHandler.sidePanelState()
// Assert
assertThat(result).isEqualTo(SidePaneHandler.PaneState.OPEN_ALL)
}
}
|
to_euro= lambda {|dollars| dollars*0.95}
to_pesos= lambda {|dollars| dollars*20.67}
to_rupees= lambda {|dollars| dollars*68.13}
def convert(dollars,currency_lambda)
currency_lambda.call(dollars) if dollars.is_a?(Numeric)
end
# def convert_to_euro(dollars)
# dollars *0.95 if dollars.is_a?(Numeric)
# end
#
# def convert_to_pesos(dollars)
# dollars *20.67 if dollars.is_a?(Numeric)
# end
#
# def convert_to_rupees(dollars)
# dollars *68.13 if dollars.is_a?(Numeric)
# end
p convert(1000,to_euro)
p convert(1000,to_pesos)
p convert(1000,to_rupees)
|
const Maybe = require('folktale/maybe');
const { stateToResult, prepareForCaching } = require('../create/mgetUtils');
const pair = require('./mocks/pair');
// request state in different cases
const request = [pair('ETH', 'BTC'), pair('AMUR', 'BTC'), pair('BTC', 'USD')];
const getPairResp = index => Maybe.of({ pair: request[index] });
const fullResp = [getPairResp(0), getPairResp(1), getPairResp(2)];
const fullCache = {
request,
cacheResp: fullResp,
dbResp: [],
};
const zeroCacheFullDb = {
request,
cacheResp: [Maybe.Nothing(), Maybe.Nothing(), Maybe.Nothing()],
dbResp: fullResp,
};
const partCachePartDb = {
request,
cacheResp: [Maybe.Nothing(), getPairResp(1), Maybe.Nothing()],
dbResp: [Maybe.Nothing(), getPairResp(2)],
};
describe('stateToResult', () => {
it('returns everything in case of full cache response', () => {
expect(stateToResult(fullCache)).toEqual(fullResp);
});
it('returns everything in case of zero cache/full db response', () => {
expect(stateToResult(zeroCacheFullDb)).toEqual(fullResp);
});
it('returns partial output merged from partial cache/partial db response', () => {
expect(stateToResult(partCachePartDb)).toEqual([
Maybe.Nothing(),
getPairResp(1),
getPairResp(2),
]);
});
});
describe('prepareForCaching', () => {
it('caches nothing in case of full cache response', () => {
expect(prepareForCaching(fullCache)).toEqual([]);
});
it('caches everything in case of zero cache/full db response', () => {
expect(prepareForCaching(zeroCacheFullDb)).toEqual(
request.map((r, i) => [r, getPairResp(i).getOrElse()])
);
});
it('caches right values in case of partial cache/partial db response', () => {
expect(prepareForCaching(partCachePartDb)).toEqual([
[request[2], getPairResp(2).getOrElse()],
]);
});
});
|
@{
ViewData["Title"] = "Index";
}
<div class="jumbotron">
<h5>Welcome : <b>@User.Identity.Name</b></h5><hr />
<br />
<div class="text-center">
<a asp-action="Index" asp-controller="Categories" class="btn btn-success btn-lg text-white">View Categories</a>
<a asp-action="Index" asp-controller="Products" class="btn btn-primary btn-lg text-white">View Products</a>
<a asp-action="Index" asp-controller="User" class="btn btn-danger btn-lg text-white">Manage Users</a>
</div>
</div>
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MetricsContext } from '../../src/logger/MetricsContext';
import { ISink } from '../../src/sinks/Sink';
/**
* A sink that flushes log data to stdout.
* This is the preferred sink for Lambda functions.
*/
export class TestSink implements ISink {
public readonly name: string = 'TestSink';
public events: MetricsContext[] = [];
public forceAcceptRejects: boolean;
constructor(forceAcceptRejects: boolean) {
this.forceAcceptRejects = forceAcceptRejects;
}
public accept(context: MetricsContext): Promise<void> {
this.events.push(context);
return this.forceAcceptRejects ? Promise.reject(): Promise.resolve();
}
}
|
-- =============================================
-- Author: Ken Taylor
-- Create date: February 3, 2021
-- Description: Update the data for the cross-listed courses.
-- Prerequsites: The Courses table must have already been loaded with
-- the base course data.
-- Notes:
/*
Logic for populating the data for cross listed courses:
Note that the courses table must have already been loaded, as we
use the AverageEnrollment present in that table.
Input:
1. A list of all of the crosslisted courses, and their average enrollment from the courses table.
2. A list of the crosslisted courses and their crosslistings.
Output:
1. Crosslisted courses with their sum of the Average Enrollment for the course itself and
each of its crosslistings. This sum will be the new Average Enrollment for the crosslisted
course and its corresponding crosslistings.
*/
-- Usage:
/*
USE [Tacos]
GO
EXEC usp_UpdateDataForCrossListedCourses
*/
-- Modifications:
--
-- =============================================
CREATE PROCEDURE usp_UpdateDataForCrossListedCourses
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @CommonRows TABLE (
Course varchar(10),
AverageEnrollment float,
CombinedAverageEnrollment float,
CrossListing varchar(10),
CrossListingsString varchar(50),
IsCrossListed bit,
IsBaseCourse bit -- This allows us to easily determine the base row.
)
-- We're using the course description table for this as it
-- will contain all the active courses, regardless of their
-- enrollment values.
-- We will not worry about whether or not a course was taught within
-- the past 2 years at this time, because one of it's other sectons might have
-- been, and we'll figure that out using the courses table.
-- @CommonRows contains each course (n times, one entry for each cross listing),
-- and the cross-listed course's individual cross listing(s),
-- plus the original non-parsed cross listing field from the CourseDescription table.
-- Note that this does not add a row for the base course as a cross-listed entry, so we'll
-- need to account for this later.
-- Add record for each of the cross-listed courses:
INSERT INTO @CommonRows (Course, CrossListing, CrossListingsString,
IsCrossListed, IsBaseCourse)
SELECT REPLACE(t1.Course, ' ', '') Course,
REPLACE(t2.CrossListing, ' ', ''), t1.CrossListing,
1 AS IsCrossListed,
0 AS IsBaseCourse
FROM CourseDescription t1
CROSS APPLY [dbo].[udf_ParseOutCrossListedCourses] (
t1.[Course], t1.CrossListing
) t2
WHERE t1.[CrossListing] IS NOT NULL AND
Status = 'Active' --AND t1.Course = 'EBS 148'
ORDER BY t1.Course
-- Add a record for each of the base courses:
INSERT INTO @CommonRows (
Course,
CrossListing,
CrossListingsString,
IsCrossListed,
IsBaseCourse
)
SELECT DISTINCT Course, Course AS CrossListing, CrossListingsString,
1 AS IsCrossListed, 1 AS IsBaseCourse
FROM @CommonRows t1
ORDER BY Course, CrossListing, CrossListingsString
-- Set the AverageEnrollment for the base courses:
UPDATE @CommonRows
SET AverageEnrollment = t2.NonCrossListedAverageEnrollment
FROM @CommonRows t1
INNER JOIN Courses t2 ON t1.Course = t2.Number
-- This logic sets the average enrollment for the courses' cross-listed
-- segments, which are currently set to the base course' AverageEnrollment:
-- (See previous example.)
UPDATE @CommonRows
SET AverageEnrollment = t2.AverageEnrollment
FROM @CommonRows t1
INNER JOIN (
SELECT t2.Course, t2.AverageEnrollment, t1.CrossListing
FROM @CommonRows t1
INNER JOIN @CommonRows t2 ON
t1.CrossListing = t2.Course
) t2 ON t1.CrossListing = t2.Course
-- Now we perform the actual update of the combined average enrollment:
UPDATE @CommonRows
SET CombinedAverageEnrollment = CombinedEnrollment
FROM @CommonRows t1
INNER JOIN (
SELECT Course, SUM(AverageEnrollment) CombinedEnrollment
FROM @CommonRows
GROUP BY Course
) t2 ON t1.Course = t2.Course
---- Check to make sure things happened as we had intended:
-- SELECT Course, AverageEnrollment AS NonCrossListedAverageEnrollment,
--CombinedAverageEnrollment AS AverageEnrollment,
--CrossListingsString, IsCrossListed
-- FROM @CommonRows
-- WHERE IsBaseCourse = 1
-- ORDER BY Course
-- Second to last is to update the actual Courses table with all of the cross-listed course data:
UPDATE Courses
SET NonCrossListedAverageEnrollment = t2.NonCrossListedAverageEnrollment,
AverageEnrollment = t2.CombinedAverageEnrollment,
IsCrossListed = t2.IsCrossListed,
CrossListingsString = t2.CrossListingsString
FROM Courses t1
INNER JOIN (
SELECT Course, t1.AverageEnrollment AS NonCrossListedAverageEnrollment,
t1.IsCrossListed, t1.CrossListingsString,t1.CombinedAverageEnrollment
FROM @CommonRows t1
INNER JOIN Courses t2 ON t1.Course = t2.Number
WHERE IsBaseCourse = 1
) t2 ON t1.Number = t2.Course
-- Last is to take care of some final housekeeping:
-- Since we've identified all of the cross listed courses that are active, but
-- not offered within the past 2 years, and other active, but not offered within
-- the past 2 years courses must not be cross listed courses.
-- Therefore, we can update any remaing null IsCrossListed fields with 0,
-- as these courses can assumed not to be cross listed.
--
UPDATE Courses
SET IsCrossListed = 0
WHERE IsCrossListed IS NULL
-- Populate the department name as this may have yet to be done:
-- (I think there was/is an issue with updating the department name
-- using data present in the registration data as the department name can
-- (and does) differ between one year and the next, and this caused duplicate
-- entries.
-- Making the update here using the CourseDescription table eliminates that
-- possibility, as the CourseDescription table only contains a single entry
-- for each active course, and hence, only a single Department.)
UPDATE Courses
SET DeptName = t2.Department
FROM Courses t1
INNER JOIN (
SELECT t2.*, t1.*
FROM Courses t1
LEFT OUTER JOIN (
SELECT DISTINCT Course, Department
FROM CourseDescription
WHERE Status = 'Active'
) t2 ON t1.Number = REPLACE(Course, ' ' ,'')
) t2 ON t1.Number = t2.Number
WHERE t1.DeptName IS NULL AND t2.Department IS NOT NULL
END
|
<?php
namespace MadWizard\WebAuthn\Tests\Dom;
use MadWizard\WebAuthn\Dom\AuthenticatorAttachment;
use MadWizard\WebAuthn\Dom\AuthenticatorSelectionCriteria;
use MadWizard\WebAuthn\Dom\UserVerificationRequirement;
use PHPUnit\Framework\TestCase;
class AuthenticatorSelectionCriteriaTest extends TestCase
{
public function testDefault()
{
$criteria = new AuthenticatorSelectionCriteria();
self::assertNull($criteria->getAuthenticatorAttachment());
self::assertNull($criteria->getRequireResidentKey());
self::assertNull($criteria->getUserVerification());
}
public function testWrongAttachment()
{
$criteria = new AuthenticatorSelectionCriteria();
$this->expectException(\InvalidArgumentException::class);
$criteria->setAuthenticatorAttachment('invalid');
}
public function testWrongVerification()
{
$criteria = new AuthenticatorSelectionCriteria();
$this->expectException(\InvalidArgumentException::class);
$criteria->setUserVerification('invalid');
}
public function testFull()
{
$criteria = new AuthenticatorSelectionCriteria();
$criteria->setUserVerification(UserVerificationRequirement::DISCOURAGED);
$criteria->setAuthenticatorAttachment(AuthenticatorAttachment::CROSS_PLATFORM);
$criteria->setRequireResidentKey(true);
self::assertSame(UserVerificationRequirement::DISCOURAGED, $criteria->getUserVerification());
self::assertSame(AuthenticatorAttachment::CROSS_PLATFORM, $criteria->getAuthenticatorAttachment());
self::assertTrue($criteria->getRequireResidentKey());
}
}
|
/**
* @jest-environment node
*/
// test that import does not crash
import * as ReactTransitionGroup from '../src'; // eslint-disable-line no-unused-vars
describe('SSR', () => {
it('should import react-transition-group in node env', () => {});
});
|
require 'httpclient'
require 'json'
module Openbd
# Raised for request error.
class RequestError < StandardError; end
# Raised for response error.
class ResponseError < StandardError; end
END_POINT = 'https://api.openbd.jp/v1'
# The Client class provides a wrapper to the openBD service
#
# @see https://openbd.jp/
# @example
# require 'openbd'
#
# client = Openbd::Client.new
#
# # get
# client.get('978-4-7808-0204-7')
class Client
# call /get
#
# @param [String|Array] isbn ISBN
# @raise [RequestError] if the request is wrong
# @raise [ResponseError] if the response is wrong
# @return [Hash] Biblio infomation
def get(isbn)
url = "#{end_point}/get"
isbns = isbn_param(isbn)
method = get_method(isbns)
q = { isbn: isbns.join(',') }
resp = httpclient.send(method, url, q)
body(resp)
end
# call /coverage
#
# @raise [ResponseError] if the response is wrong
# @return [Array<String>] List of ISBN
def coverage
url = "#{end_point}/coverage"
resp = httpclient.get(url)
body(resp)
end
# call /schema
#
# @raise [ResponseError] if the response is wrong
# @return [Hash] schema
def schema
url = "#{end_point}/schema"
resp = httpclient.get(url)
body(resp)
end
# get HTTPClient
#
# @return [HTTPClient] HTTPClient
def httpclient
@httpclient ||= HTTPClient.new
end
private
def end_point
END_POINT
end
def body(resp)
return JSON.parse(resp.body) if resp.ok?
raise Openbd::ResponseError, "#{resp.status}\n#{resp.content}"
end
def get_method(isbn_num)
if isbn_num.size > 10_000
raise Openbd::RequestError, 'Param limit exceeded.'
end
isbn_num.size > 1_000 ? :post : :get
end
def isbn_param(value)
if value.instance_of?(String)
value.split(',')
elsif value.instance_of?(Array)
value
else
raise Openbd::RequestError,
"Invalid type of param: #{value.class}(#{value})"
end
end
end
end
|
module ForumTopicsHelper
def forum_topic_category_select(object, field, options = {})
select(object, field, ForumCategory.visible.reverse_mapping, options)
end
def available_min_user_levels
ForumTopic::MIN_LEVELS.select { |name, level| level <= CurrentUser.level }.to_a
end
def tag_request_message(obj)
if obj.is_a?(TagRelationship)
if obj.is_approved?
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been approved."
elsif obj.is_retired?
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been retired."
elsif obj.is_deleted?
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been rejected."
elsif obj.is_pending?
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] is pending approval."
elsif obj.is_errored?
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] (#{obj.relationship} failed during processing."
else # should never happen
return "The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has an unknown status."
end
end
if obj.is_a?(BulkUpdateRequest)
if obj.script.size < 700
embedded_script = obj.script_with_links
else
embedded_script = "[section]#{obj.script_with_links}[/section]"
end
if obj.is_approved?
return "The bulk update request ##{obj.id} is active.\n\n#{embedded_script}"
elsif obj.is_pending?
return "The \"bulk update request ##{obj.id}\":/bulk_update_requests/#{obj.id} is pending approval.\n\n#{embedded_script}"
elsif obj.is_rejected?
return "The bulk update request ##{obj.id} has been rejected.\n\n#{embedded_script}"
end
end
end
def parse_embedded_tag_request_text(text)
[TagAlias, TagImplication, BulkUpdateRequest].each do |tag_request|
text = text.gsub(tag_request.embedded_pattern) do |match|
begin
obj = tag_request.find($~[:id])
tag_request_message(obj) || match
rescue ActiveRecord::RecordNotFound
match
end
end
end
text
end
end
|
#!/bin/bash
set -e
npm pack
TARBALL=$(ls *.tgz)
trap "rm ${TARBALL}" EXIT
tar tfz ${TARBALL} | grep '^package/lib/.*\.js$' || (echo "tarball contained no .js files"; exit 1)
tar tfz ${TARBALL} | grep '^package/lib/.*\.d\.ts$' || (echo "tarball contained no .d.ts files"; exit 1)
echo "tarball contained .js and .d.ts files in package/lib/ - OK"
|
module Spree
module Admin
class CategoriesController < ResourceController
private
def location_after_save
if @category.created_at == @category.updated_at
edit_admin_category_url(@category)
else
admin_categories_url
end
end
end
end
end
|
# Gop
## What is gop?
Gop is a package manager for godot.
## Installating Gop
```bash
pip3 install git+https://github.com/felix-hellman/gop.git --user
```
## Installing Public Packages
Installing packages with gop is pretty simple and requires no log in.
```bash
gop init
gop add --dependency=felix-hellman/awesome --version=0.0.1
gop install
```
## Installing Private Packages
Please see the wiki entry on [Packages](https://github.com/felix-hellman/gop/wiki/Packages)
## Features
* Public Repositories
* Transitive Dependency Resolution
* Package verification using PKI (RSA)
* Version control
* Private Non-Versioned Github Backed Dependencies
* Transitive Dependency Resolution
### Example projects
Usage of Genetic Algorithm - https://github.com/felix-hellman/gop-example-genetics
|
Sequel.migration do
up do
run 'ALTER TABLE storage_apps CONVERT TO CHARACTER SET utf8mb4;'
end
down do
run 'ALTER TABLE storage_apps CONVERT TO CHARACTER SET utf8;'
end
end
|
container_prefix=${CONTAINER_PREFIX:-docker.io/alukiano}
container_tag=${CONTAINER_TAG:-latest}
namespace=openshift-machine-api
image_pull_policy=${IMAGE_PULL_POLICY:-IfNotPresent}
verbosity=${VERBOSITY:-2}
kubevirtci_git_hash="45cdf80da619866cdab36295de25a8aeea7eccbc"
|
class ProfileDecorator < ApplicationDecorator
delegate_all
def birthday
I18n.l(profile.birthday) if profile.birthday
end
end
|
-module(es_store_ets).
-behaviour(es_store).
-export([
init/0,
store/1,
stream/0
]).
init() ->
ets:new(event_store, [set, named_table, private]).
store(#{aggregate_id := AggregateId} = Event) ->
case ets:lookup(event_store, AggregateId) of
[] ->
ets:insert(event_store, {AggregateId, [Event]});
[{AggregateId, Events}] ->
ets:insert(event_store, {AggregateId, [Event | Events]})
end.
stream() ->
[].
|
/*
* Copyright (C) 2019 The Winc Authors. All Rights Reserved.
* Copyright (C) 2010-2013 Allen Dang. All Rights Reserved.
*/
package winc
import (
"fmt"
"syscall"
"unsafe"
"github.com/tadvi/winc/w32"
)
func internalTrackMouseEvent(hwnd w32.HWND) {
var tme w32.TRACKMOUSEEVENT
tme.CbSize = uint32(unsafe.Sizeof(tme))
tme.DwFlags = w32.TME_LEAVE
tme.HwndTrack = hwnd
tme.DwHoverTime = w32.HOVER_DEFAULT
w32.TrackMouseEvent(&tme)
}
func ToggleStyle(hwnd w32.HWND, b bool, style int) {
originalStyle := int(w32.GetWindowLongPtr(hwnd, w32.GWL_STYLE))
if originalStyle != 0 {
if b {
originalStyle |= style
} else {
originalStyle ^= style
}
w32.SetWindowLongPtr(hwnd, w32.GWL_STYLE, uintptr(originalStyle))
}
}
func ToggleExStyle(hwnd w32.HWND, b bool, style int) {
originalStyle := int(w32.GetWindowLongPtr(hwnd, w32.GWL_EXSTYLE))
if originalStyle != 0 {
if b {
originalStyle |= style
} else {
originalStyle ^= style
}
w32.SetWindowLongPtr(hwnd, w32.GWL_EXSTYLE, uintptr(originalStyle))
}
}
func CreateWindow(className string, parent Controller, exStyle, style uint) w32.HWND {
instance := GetAppInstance()
var parentHwnd w32.HWND
if parent != nil {
parentHwnd = parent.Handle()
}
var hwnd w32.HWND
hwnd = w32.CreateWindowEx(
exStyle,
syscall.StringToUTF16Ptr(className),
nil,
style,
w32.CW_USEDEFAULT,
w32.CW_USEDEFAULT,
w32.CW_USEDEFAULT,
w32.CW_USEDEFAULT,
parentHwnd,
0,
instance,
nil)
if hwnd == 0 {
errStr := fmt.Sprintf("Error occurred in CreateWindow(%s, %v, %d, %d)", className, parent, exStyle, style)
panic(errStr)
}
return hwnd
}
func RegisterClass(className string, wndproc uintptr) {
instance := GetAppInstance()
icon := w32.LoadIcon(instance, w32.MakeIntResource(w32.IDI_APPLICATION))
var wc w32.WNDCLASSEX
wc.Size = uint32(unsafe.Sizeof(wc))
wc.Style = w32.CS_HREDRAW | w32.CS_VREDRAW
wc.WndProc = wndproc
wc.Instance = instance
wc.Background = w32.COLOR_BTNFACE + 1
wc.Icon = icon
wc.Cursor = w32.LoadCursor(0, w32.MakeIntResource(w32.IDC_ARROW))
wc.ClassName = syscall.StringToUTF16Ptr(className)
wc.MenuName = nil
wc.IconSm = icon
if ret := w32.RegisterClassEx(&wc); ret == 0 {
panic(syscall.GetLastError())
}
}
func getMonitorInfo(hwnd w32.HWND) *w32.MONITORINFO {
currentMonitor := w32.MonitorFromWindow(hwnd, w32.MONITOR_DEFAULTTONEAREST)
var info w32.MONITORINFO
info.CbSize = uint32(unsafe.Sizeof(info))
w32.GetMonitorInfo(currentMonitor, &info)
return &info
}
func getWindowInfo(hwnd w32.HWND) *w32.WINDOWINFO {
var info w32.WINDOWINFO
info.CbSize = uint32(unsafe.Sizeof(info))
w32.GetWindowInfo(hwnd, &info)
return &info
}
func RegClassOnlyOnce(className string) {
isExists := false
for _, class := range gRegisteredClasses {
if class == className {
isExists = true
break
}
}
if !isExists {
RegisterClass(className, GeneralWndprocCallBack)
gRegisteredClasses = append(gRegisteredClasses, className)
}
}
func ScreenToClientRect(hwnd w32.HWND, rect *w32.RECT) *Rect {
l, t, r, b := rect.Left, rect.Top, rect.Right, rect.Bottom
l1, t1, _ := w32.ScreenToClient(hwnd, int(l), int(t))
r1, b1, _ := w32.ScreenToClient(hwnd, int(r), int(b))
return NewRect(l1, t1, r1, b1)
}
|
import * as React from 'react';
import IconDone from '../../../../public/images/mission/mission-done.svg';
import IconTodo from '../../../../public/images/mission/mission-todo.svg';
import IconUnknown from '../../../../public/images/mission/mission-todo.svg';
import styles from './timeline.module.scss';
interface TimelineItemProps {
name: string;
date: string;
isDone?: boolean;
unknown?: boolean;
}
export const TimelineItem: React.FC<TimelineItemProps> = ({
name,
date,
children,
isDone = false,
unknown = false,
}) => {
return (
<>
<span className={styles.timelineItemSymbol}>
<span className={styles.icon}>
{isDone ? <IconDone /> : unknown ? <IconUnknown /> : <IconTodo />}
</span>
</span>
{!unknown && (
<div className={styles.item}>
<span className={styles.itemDate}>{date}</span>
<h3 className={styles.itemName}>{name}</h3>
<div className={styles.itemContent}>
<p>{children}</p>
</div>
</div>
)}
</>
);
};
export const TimelineSeparator: React.FC = ({ children }) => (
<span className={styles.timelineSeparator}>{children}</span>
);
TimelineSeparator.displayName = 'TimelineSeparator';
|
using System;
using System.Reflection;
using ObjectSql.Core.SchemaManager.EntitySchema;
namespace ObjectSql.Core.SchemaManager
{
public interface IEntitySchemaManager
{
EntitySchema.EntitySchema GetSchema(Type entityType);
FuncSchema GetFuncSchema(MethodInfo method);
IStorageFieldType ParseDbType(string value);
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Node;
use \App\LayoutSlot;
use Log;
class SlotController extends Controller {
// This receives (via post) an array of node ids to sort into itself
// The array may be dirtied with non-existent ids
public function sort(Request $request, LayoutSlot $slot) {
$potentialIds = $request->get('order');
$nodes = Node::whereIn('id', $potentialIds)->get();
for ($i=0; $i < count($potentialIds); $i++) {
$node = $nodes->firstWhere('id', $potentialIds[$i]);
if($node) {
$node->layoutSlot()->associate($slot);
$node->sort_order = $i;
$node->save();
}
Log::info('node ' .$node->id);
}
return $nodes->toJson();
}
}
|
//! Parsing utilities for TripAdvisor XML feed.
use futures::stream::Stream;
use tokio::io::{AsyncBufRead, AsyncBufReadExt};
use tracing::debug;
/// Expected string at start of a <Property /> item.
const START_TOKEN: &[u8] = b"<Property ";
/// Expected string at the end of a <Property /> item.
const END_TOKEN: &[u8] = b"</Property>\n";
/// Split each <Property /> item into a buffer that can be deserialized independently.
///
/// There are a few assumptions that are made over the input data, mostly for
/// performance reasons:
/// - each item starts with a line containing "<Property ", the beginning of
/// the line will be ignored.
/// - each item ends with a line "</Property>"
pub fn split_raw_properties(input: impl AsyncBufRead + Unpin) -> impl Stream<Item = Vec<u8>> {
futures::stream::unfold(input, |mut input| async {
let mut buffer = Vec::new();
while input
.read_until(b'\n', &mut buffer)
.await
.expect("failed to read line from XML")
> 0
{
if buffer.ends_with(END_TOKEN) {
// The first buffer may contain some extra information
let token_start = find_naive(&buffer, START_TOKEN)
.expect("found a property which didn't start with expected pattern");
if token_start > 0 {
debug!(
"Ignored beginning of buffer: {}",
String::from_utf8_lossy(&buffer[..token_start])
);
buffer = buffer[token_start..].to_vec();
}
return Some((buffer, input));
}
}
if !buffer.is_empty() {
debug!("Ignored end of file: {}", String::from_utf8_lossy(&buffer));
}
None
})
}
/// Search for first occurrence of `needle` in `haystack`.
///
/// This is a naïve approach that runs in `O(haystack.len() * needle.len())`
/// but which is still very efficient with small instances of `needle` which
/// is the case here.
///
/// # Example
///
/// ```
/// # use fafnir::sources::tripadvisor::parse::find_naive;
/// assert_eq!(find_naive(b"barbarbare", b"barbare"), Some(3));
/// assert_eq!(find_naive(b"yes", b"no"), None);
/// ```
pub fn find_naive(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|win| win == needle)
}
|
import * as core from '@actions/core'
import { getNpmrcContent } from './npmrc'
import { INpmRcConfig } from './inteface'
import { createFile } from './file'
// import { getYarnrcContent } from './yarnrc'
import { setGlobalConfig } from './global'
const run = async () => {
try {
const registry = core.getInput('registry')
const alwaysAuth = core.getInput('always-auth')
const username = core.getInput('username')
const token = core.getInput('token')
if (!registry) {
throw new Error('Registry url required: set `registry` variable')
}
const config: INpmRcConfig = {
registry,
alwaysAuth,
username,
token,
}
await setGlobalConfig(config)
const npmrcContent = getNpmrcContent(config)
// const yarnrcContent = getYarnrcContent(config)
await createFile('.npmrc', npmrcContent)
// await createFile('.yarnrc', yarnrcContent)
} catch (error) {
core.setFailed(error.message)
}
}
run()
|
// 🎯 Dart imports:
import 'dart:io';
// 📦 Package imports:
import 'package:console/console.dart';
/// Output for an error
void error(String message, {int indentation = 0}) {
final pen = TextPen();
pen.red();
pen('${_generateIndentation(indentation)}${Platform.isWindows ? '' : '❌'} $message');
pen();
exit(64); // Exit code for incorrect usage
}
/// Output for a step in the program
void step(String message, String emoji, {int indentation = 0}) {
print(
'${_generateIndentation(indentation)}${Platform.isWindows ? '' : emoji} $message');
}
/// Output for a successful step
void success(String message, {int indentation = 0}) {
final pen = TextPen();
pen.green();
pen('${_generateIndentation(indentation)}${Platform.isWindows ? '' : '✅'} $message');
pen();
}
/// Generate indentation based of the number of indents
String _generateIndentation(int indentation) {
final indents = <String>[];
for (var i = 0; i < indentation; i++) {
indents.add(' ');
}
return indents.join();
}
|
namespace KerioConnect.Entities
{
/// <summary>
/// Extension of Apple Address Book
/// </summary>
public class ABExtension
{
public string groupId { get; set; }
public string label { get; set; }
}
}
|
#include "common.h"
#include "math.h"
#include "string.h"
int strcmp(const char *s1, const char *s2)
{
while(*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
void * memcpy (void *dest, const void *src, size_t len)
{
char *d = dest;
const char *s = src;
while (len--)
*d++ = *s++;
return dest;
}
char *my_strcat(char *dest, const char *src)
{
size_t i, j;
for (i = 0; dest[i] != '\0'; i++)
;
for (j = 0; src[j] != '\0'; j++)
dest[i + j] = src[j];
dest[i + j] = '\0';
return dest;
}
void *memset(void *str, int c, size_t n)
{
size_t i = 0;
while (i < n)
{
*(char *)str = c;
str += 1;
++i;
}
return str;
}
void reverse(char str[], int length)
{
int start = 0;
int end = length - 1;
while (start < end)
{
int tmp;
tmp = *(str + start);
*(str + start) = *(str + end);
*(str + end) = tmp;
start++;
end--;
}
}
// Implementation of itoa()
char *itoa(int num, char *str, int base)
{
int i = 0;
int isNegative = 0;
/* Handle 0 explicitely, otherwise empty string is printed for 0 */
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
return str;
}
// In standard itoa(), negative numbers are handled only with
// base 10. Otherwise numbers are considered unsigned.
if (num < 0 && base == 10)
{
isNegative = 1;
num = -num;
}
// Process individual digits
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
num = num / base;
}
// If number is negative, append '-'
if (isNegative)
str[i++] = '-';
str[i] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
return str;
}
int atoi(const char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and
// update result
for (int i = 0; str[i] != '\0' && str[i] != '\n'; ++i)
res = res * 10 + str[i] - '0';
// return result.
return res;
}
int intToStr(int x, char str[], int d)
{
int i = 0;
while (x)
{
str[i++] = (x % 10) + '0';
x = x / 10;
}
// If number of digits required is more, then
// add 0s at the beginning
while (i < d)
str[i++] = '0';
reverse(str, i);
str[i] = '\0';
return i;
}
// Converts a floating-point/double number to a string.
void ftoa(float n, char *res, int afterpoint)
{
// Extract integer part
int ipart = (int)n;
// Extract floating part
float fpart = n - (float)ipart;
// convert integer part to string
int i = intToStr(ipart, res, 0);
// check for display option after point
if (afterpoint != 0)
{
res[i] = '.'; // add dot
// Get the value of fraction part upto given no.
// of points after dot. The third parameter
// is needed to handle cases like 233.007
fpart = fpart * my_pow(10, afterpoint);
intToStr((int)fpart, res + i + 1, afterpoint);
}
}
|
namespace AzureFunctionWithDependencyInjectionAndConfigInKeyvault
{
public interface IMyService
{
string GetValuesFromConfiguration();
}
}
|
require 'qb/docker'
describe_spec_file(
spec_path: __FILE__,
class: QB::Docker::Image::Name,
) do
describe_section "loading" do
# ========================================================================
describe_method :from_s do
describe_group "accepts" do
shared_examples described_class do |**attrs|
attrs = {
registry_server: nil,
port: nil,
repository: nil,
name: nil,
}.merge attrs
it { is_expected.to be_a described_class }
it { is_expected.to have_attributes attrs }
end # example name
describe_called_with "neilio" do
include_examples described_class,
name: 'neilio'
end
describe_called_with "nrser/neilio" do
include_examples described_class,
repository: 'nrser',
name: 'neilio'
end
describe_called_with "nrser/neilio/yo/ho/ho" do
include_examples described_class,
repository: 'nrser',
name: 'neilio/yo/ho/ho'
end
describe_called_with "docker.nrser.com:8888/nrser/neilio" do
include_examples described_class,
registry_server: 'docker.nrser.com',
port: 8888,
repository: 'nrser',
name: 'neilio'
end # called with "docker.nrser.com:8888/nrser/neilio"
describe_called_with "nrser/neilio:latest" do
include_examples described_class,
repository: 'nrser',
name: 'neilio'
describe_attribute :tag do
it { is_expected.to be_a QB::Docker::Image::Tag }
it do
is_expected.to have_attributes \
version: nil,
source: 'latest',
to_s: 'latest'
end
end # Attribute tag Description
end # called with "nrser/neilio:latest"
describe_called_with "nrser/neilio:0.1.2" do
include_examples described_class,
repository: 'nrser',
name: 'neilio'
describe_attribute :tag do
it { is_expected.to be_a QB::Docker::Image::Tag }
it do
is_expected.to have_attributes \
version: be_a( QB::Package::Version ).and(
have_attributes(
major: 0,
minor: 1,
patch: 2,
)
),
source: '0.1.2',
to_s: '0.1.2'
end
end # Attribute tag Description
end # called with "nrser/neilio:latest"
end
end # Method from_s Description
end # section loading
# ************************************************************************
end # spec file
|
<?php
namespace Reusables;
class Template {
public static function make( $file, $identifier )
{
Page::addAssetFile( "template", $file );
$View = View::factory( 'reusables/views/template/' . $file );
$data = Data::get( $identifier );
$View->set( 'templatedict', $data );
$View->set( 'identifier', $identifier );
return $View->render();
}
}
|
part of smalltalk;
/**
* Smalltalk grammar definition.
*/
class SmalltalkGrammar extends CompositeParser {
@override
void initialize() {
_whitespace();
_number();
_smalltalk();
}
void _whitespace() {
// the original implementation uses a handwritten parser to
// efficiently consume whitespace and comments
def('whitespace', whitespace()
.or(ref('comment')));
def('comment', char('"')
.seq(char('"').neg().star())
.seq(char('"')));
}
void _number() {
// the original implementation uses the hand written number
// parser of the system, this is the spec of the ANSI standard
def('number', char('-').optional()
.seq(ref('positiveNumber')));
def('positiveNumber', ref('scaledDecimal')
.or(ref('float'))
.or(ref('integer')));
def('integer', ref('radixInteger')
.or(ref('decimalInteger')));
def('decimalInteger', ref('digits'));
def('digits', digit().plus());
def('radixInteger', ref('radixSpecifier')
.seq(char('r'))
.seq(ref('radixDigits')));
def('radixSpecifier', ref('digits'));
def('radixDigits', pattern('0-9A-Z').plus());
def('float', ref('mantissa')
.seq(ref('exponentLetter')
.seq(ref('exponent'))
.optional()));
def('mantissa', ref('digits')
.seq(char('.'))
.seq(ref('digits')));
def('exponent', char('-')
.seq(ref('decimalInteger')));
def('exponentLetter', pattern('edq'));
def('scaledDecimal', ref('scaledMantissa')
.seq(char('s'))
.seq(ref('fractionalDigits').optional()));
def('scaledMantissa', ref('decimalInteger')
.or(ref('mantissa')));
def('fractionalDigits', ref('decimalInteger'));
}
Parser _token(input) {
var parser = input;
if (parser is String) {
parser = parser.length == 1 ? char(parser) : string(parser);
}
return parser.token().trim(ref('whitespace'));
}
void _smalltalk() {
def('array', _token('{')
.seq(ref('expression').separatedBy(ref('periodToken'))
.seq(ref('periodToken').optional()).optional())
.seq(_token('}')));
def('arrayItem', ref('literal')
.or(ref('symbolLiteralArray'))
.or(ref('arrayLiteralArray'))
.or(ref('byteLiteralArray')));
def('arrayLiteral', _token('#(')
.seq(ref('arrayItem').star())
.seq(_token(')')));
def('arrayLiteralArray', _token('(')
.seq(ref('arrayItem').star())
.seq(_token(')')));
def('assignment', ref('variable')
.seq(ref('assignmentToken')));
def('assignmentToken', _token(':='));
def('binary', pattern('!%&*+,-/<=>?@\\|~').plus());
def('binaryExpression', ref('unaryExpression')
.seq(ref('binaryMessage').star()));
def('binaryMessage', ref('binaryToken')
.seq(ref('unaryExpression')));
def('binaryMethod', ref('binaryToken')
.seq(ref('variable')));
def('binaryPragma', ref('binaryToken')
.seq(ref('arrayItem')));
def('binaryToken', _token(ref('binary')));
def('block', _token('[')
.seq(ref('blockBody'))
.seq(_token(']')));
def('blockArgument', _token(':')
.seq(ref('variable')));
def('blockArguments', ref('blockArgumentsWith')
.or(ref('blockArgumentsWithout')));
def('blockArgumentsWith', ref('blockArgument').plus()
.seq(_token('|').or(_token(']').and())));
def('blockArgumentsWithout', epsilon());
def('blockBody', ref('blockArguments')
.seq(ref('sequence')));
def('byteLiteral', _token('#[')
.seq(ref('numberLiteral').star())
.seq(_token(']')));
def('byteLiteralArray', _token('[')
.seq(ref('numberLiteral').star())
.seq(_token(']')));
def('cascadeExpression', ref('keywordExpression')
.seq(ref('cascadeMessage').star()));
def('cascadeMessage', _token(';')
.seq(ref('message')));
def('char', char('\$').seq(any()));
def('charLiteral', ref('charToken'));
def('charToken', _token(ref('char')));
def('expression', ref('assignment').star()
.seq(ref('cascadeExpression')));
def('falseLiteral', ref('falseToken'));
def('falseToken', _token('false')
.seq(word().not()));
def('identifier', pattern('a-zA-Z_')
.seq(word().star()));
def('identifierToken', _token(ref('identifier')));
def('keyword', ref('identifier')
.seq(char(':')));
def('keywordExpression', ref('binaryExpression')
.seq(ref('keywordMessage').optional()));
def('keywordMessage', ref('keywordToken')
.seq(ref('binaryExpression')).plus());
def('keywordMethod', ref('keywordToken')
.seq(ref('variable')).plus());
def('keywordPragma', ref('keywordToken')
.seq(ref('arrayItem')).plus());
def('keywordToken', _token(ref('keyword')));
def('literal', ref('numberLiteral')
.or(ref('stringLiteral'))
.or(ref('charLiteral'))
.or(ref('arrayLiteral'))
.or(ref('byteLiteral'))
.or(ref('symbolLiteral'))
.or(ref('nilLiteral'))
.or(ref('trueLiteral'))
.or(ref('falseLiteral')));
def('message', ref('keywordMessage')
.or(ref('binaryMessage'))
.or(ref('unaryMessage')));
def('method', ref('methodDeclaration')
.seq(ref('methodSequence')));
def('methodDeclaration', ref('keywordMethod')
.or(ref('unaryMethod'))
.or(ref('binaryMethod')));
def('methodSequence', ref('periodToken').star()
.seq(ref('pragmas'))
.seq(ref('periodToken').star())
.seq(ref('temporaries'))
.seq(ref('periodToken').star())
.seq(ref('pragmas'))
.seq(ref('periodToken').star())
.seq(ref('statements')));
def('multiword', ref('keyword').plus());
def('nilLiteral', ref('nilToken'));
def('nilToken', _token('nil')
.seq(word().not()));
def('numberLiteral', ref('numberToken'));
def('numberToken', _token(ref('number')));
def('parens', _token('(')
.seq(ref('expression'))
.seq(_token(')')));
def('period', char('.'));
def('periodToken', _token(ref('period')));
def('pragma', _token('<')
.seq(ref('pragmaMessage'))
.seq(_token('>')));
def('pragmaMessage', ref('keywordPragma')
.or(ref('unaryPragma'))
.or(ref('binaryPragma')));
def('pragmas', ref('pragma').star());
def('primary', ref('literal')
.or(ref('variable'))
.or(ref('block'))
.or(ref('parens'))
.or(ref('array')));
def('return', _token('^')
.seq(ref('expression')));
def('sequence', ref('temporaries')
.seq(ref('periodToken').star())
.seq(ref('statements')));
def('start', ref('startMethod'));
def('startMethod', ref('method').end());
def('statements', ref('expression')
.seq(ref('periodToken').plus().seq(ref('statements'))
.or(ref('periodToken').star()))
.or(ref('return').seq(ref('periodToken').star()))
.or(ref('periodToken').star()));
def('string', char('\'')
.seq(string('\'\'').or(pattern('^\'')).star())
.seq(char('\'')));
def('stringLiteral', ref('stringToken'));
def('stringToken', _token(ref('string')));
def('symbol', ref('unary')
.or(ref('binary'))
.or(ref('multiword'))
.or(ref('string')));
def('symbolLiteral', _token('#').plus()
.seq(_token(ref('symbol'))));
def('symbolLiteralArray', _token(ref('symbol')));
def('temporaries', _token('|')
.seq(ref('variable').star())
.seq(_token('|'))
.optional());
def('trueLiteral', ref('trueToken'));
def('trueToken', _token('true')
.seq(word().not()));
def('unary', ref('identifier')
.seq(char(':').not()));
def('unaryExpression', ref('primary')
.seq(ref('unaryMessage').star()));
def('unaryMessage', ref('unaryToken'));
def('unaryMethod', ref('identifierToken'));
def('unaryPragma', ref('identifierToken'));
def('unaryToken', _token(ref('unary')));
def('variable', ref('identifierToken'));
}
}
|
import 'package:flutter/material.dart';
import 'package:splttr/widgets/empty_list_message.dart';
import 'package:splttr/widgets/two_button_row.dart';
class AppScreenTitleWithImageWidget extends StatelessWidget {
final String imagePath;
final String title;
final TwoButtonRow buttonRow;
final bool showEmptyListMessage;
final EmptyListEmoticonMessage message;
AppScreenTitleWithImageWidget({
this.imagePath,
this.title,
this.buttonRow,
this.showEmptyListMessage,
this.message,
});
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
margin: EdgeInsets.all(32),
width: MediaQuery.of(context).size.width / 3,
height: MediaQuery.of(context).size.width / 3,
child: Image.asset(
imagePath,
fit: BoxFit.cover,
),
),
Text(
title,
style: Theme.of(context).textTheme.headline5.copyWith(
fontFamily: 'Montserrat',
),
),
SizedBox(height: 16),
buttonRow,
(showEmptyListMessage)
? message
: null,
].where((widget) => widget != null).toList(),
),
);
}
}
|
package main.basicprogramming.implementation.kotlin
fun main(args: Array<String>) {
val input = readLine()!!
val goodLuck = fortuneCounter(input)
if(goodLuck) println("Good luck!") else println("Sorry, sorry!")
}
private fun fortuneCounter(input: String) : Boolean{
/**
* To count the consecutive numbers side by side. If >6, then return false, else return true.
* */
var consecutiveCount = 1
for (i in 1 until input.length) {
if (input[i] == input[i - 1]) {
consecutiveCount += 1
if (consecutiveCount >= 6) {
return false
}
} else if (consecutiveCount < 6) {
consecutiveCount = 1
}
}
return true
}
|
namespace iayos.flashcardapi.Domain.Infrastructure
{
public interface ITransactionalGateway
{
void BeginTransaction();
void CommitTransaction();
void RollbackTransaction();
}
}
|
#!/bin/bash
source envs_local.sh
function setup_db() {
echo "Setting up DB for user ${1}"
cd src/btwa_api \
&& alembic upgrade head \
&& python scripts.py add-user $1
}
if [ $# -ne 1 ]; then
echo "Usage: ./setup_local.sh username"
exit 1
fi
pip install -e .\
&& setup_db $1
|
<?php
namespace NFePHP\NFSe\Models\ETransparencia\Factories;
class CancelaNotaEletronicaV3 extends Factory
{
}
|
<div class="panel panel-default" id="system-menu">
<div class="panel-heading text-center">Sistem</div>
<div class="panel list-group">
<a class="list-group-item" data-toggle="collapse" href="#system" data-parent="#system-menu">
<span class="hidden-xs hidden-sm"><i class="fa fa-cog"></i> Sistem </span>
<i class="fa fa-cog fa-2x visible-xs visible-sm text-center"></i>
</a>
<ul class="nav nav-pills nav-stacked collapse" role="ablist" id="system">
<li role="presentation">
<a href="/admin/activations">
<span class="hidden-xs hidden-sm"><i class="glyphicon glyphicon-chevron-right"></i> Aktivasyon</span>
<i class="fa fa-unlock fa-1x visible-xs visible-sm" title="Aktivasyon"></i>
</a>
</li>
<li role="presentation">
<a href="/admin/settings/show">
<span class="hidden-xs hidden-sm"><i class="glyphicon glyphicon-chevron-right"></i> Ayarlar</span>
<i class="fa fa-wrench fa-1x visible-xs visible-sm" title="Ayarlar"></i>
</a>
</li>
<li role="presentation">
<a href="/admin/logs">
<span class="hidden-xs hidden-sm"><i class="glyphicon glyphicon-chevron-right"></i> Loglar</span>
<i class="fa fa-archive fa-1x visible-xs visible-sm" title="Loglar"></i>
</a>
</li>
</ul>
</div>
</div>
|
from collections import deque
stack = deque()
stack.append(1)
stack.append(3)
stack.append(5)
stack.append(7)
stack.append(9)
print("Initial stack : ", stack)
print("Removing the element from the stack : ")
print(stack.pop())
print(stack.pop())
print(stack.popleft())
print("Stack : ", stack )
|
/*
* Copyright (c) 2018. paascloud.net All Rights Reserved.
* 项目名称:paascloud快速搭建企业级分布式微服务平台
* 类名称:MqConsumerStore.java
* 创建人:刘兆明
* 联系方式:paascloud.net@gmail.com
* 开源地址: https://github.com/paascloud
* 博客地址: http://blog.paascloud.net
* 项目官网: http://paascloud.net
*/
package com.paascloud.provider.annotation;
import java.lang.annotation.*;
/**
* 保存消费者消息.
*
* @author tiger
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MqConsumerStore {
boolean storePreStatus() default true;
}
|
<?php
namespace Modules\Trade\Sidebar;
use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
//use Modules\Auth\Contracts\Authentication;
class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
/**
* @var Authentication
*/
protected $auth;
/**
* @param Authentication $auth
*
* @internal param Guard $guard
*/
public function __construct(Authentication $auth)
{
$this->auth = $auth;
}
/**
* @param Menu $menu
*
* @return Menu
*/
public function extendWith(Menu $menu)
{
$menu->group(trans('core::sidebar.content'), function (Group $group) {
$group->item(trans('trade::salesorders.title.salesorders'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(10);
$item->authorize(
/* append */
);
$item->item(trans('trade::salesorders.title.salesorders'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(0);
$item->append('admin.trade.salesorder.create');
$item->route('admin.trade.salesorder.index');
$item->authorize(
$this->auth->hasAccess('trade.salesorders.index')
);
});
$item->item(trans('trade::purchaseorders.title.purchaseorders'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(0);
$item->append('admin.trade.purchaseorder.create');
$item->route('admin.trade.purchaseorder.index');
$item->authorize(
$this->auth->hasAccess('trade.purchaseorders.index')
);
});
$item->item(trans('trade::products.title.products'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(0);
$item->append('admin.trade.product.create');
$item->route('admin.trade.product.index');
$item->authorize(
$this->auth->hasAccess('trade.products.index')
);
});
$item->item(trans('trade::productcategories.title.productcategories'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(0);
$item->append('admin.trade.productcategory.create');
$item->route('admin.trade.productcategory.index');
$item->authorize(
$this->auth->hasAccess('trade.productcategories.index')
);
});
$item->item(trans('trade::producttypes.title.producttypes'), function (Item $item) {
$item->icon('fa fa-copy');
$item->weight(0);
$item->append('admin.trade.producttype.create');
$item->route('admin.trade.producttype.index');
$item->authorize(
$this->auth->hasAccess('trade.producttypes.index')
);
});
// append
});
});
return $menu;
}
}
|
use Test;
use DateTime::Julian :ALL;
plan 60;
my %jpl =
# using test data from the JPL website:
# https://ssd.jpl.nasa.gov/tc.cgi
'-4000-01-01T11:59:59.99Z' => [260423.9999999, 'Thursday'],
'-4000-01-01T12:00:00.00Z' => [260424, 'Thursday'],
'-4000-01-01T13:00:00.01Z' => [260424.0416668, 'Thursday'],
'-4000-01-01T23:59:59.99Z' => [260424.4999999, 'Thursday'],
'-4000-01-02T00:00:00.00Z' => [260424.5, 'Friday'],
'-4000-01-01T00:00:00.01Z' => [260423.5000001, 'Thursday'],
'-3000-01-01T11:59:59.99Z' => [625673.9999999, 'Monday'],
'-3000-01-01T12:00:00.00Z' => [625674, 'Monday'],
'-3000-01-01T13:00:00.01Z' => [625674.0416668, 'Monday'],
'-3000-01-01T23:59:59.99Z' => [625674.4999999, 'Monday'],
'-3000-01-02T00:00:00.00Z' => [625674.5, 'Tuesday'],
'-3000-01-01T00:00:00.01Z' => [625673.5000001, 'Monday'],
'-2000-01-01T11:59:59.99Z' => [990923.9999999, 'Friday'],
'-2000-01-01T12:00:00.00Z' => [990924, 'Friday'],
'-2000-01-01T13:00:00.01Z' => [990924.0416668, 'Friday'],
'-2000-01-01T23:59:59.99Z' => [990924.4999999, 'Friday'],
'-2000-01-02T00:00:00.00Z' => [990924.5, 'Saturday'],
'-2000-01-01T00:00:00.01Z' => [990923.5000001, 'Friday'],
'-1000-01-01T11:59:59.99Z' => [1356173.9999999, 'Tuesday'],
'-1000-01-01T12:00:00.00Z' => [1356174, 'Tuesday'],
'-1000-01-01T13:00:00.01Z' => [1356174.0416668, 'Tuesday'],
'-1000-01-01T23:59:59.99Z' => [1356174.4999999, 'Tuesday'],
'-1000-01-02T00:00:00.00Z' => [1356174.5, 'Wednesday'],
'-1000-01-01T00:00:00.01Z' => [1356173.5000001, 'Tuesday'],
'+0001-01-01T11:59:59.99Z' => [1721423.9999999, 'Saturday'],
'+0001-01-01T12:00:00.00Z' => [1721424, 'Saturday'],
'+0001-01-01T13:00:00.01Z' => [1721424.0416668, 'Saturday'],
'+0001-01-01T23:59:59.99Z' => [1721424.4999999, 'Saturday'],
'+0001-01-02T00:00:00.00Z' => [1721424.5, 'Sunday'],
'+0001-01-01T00:00:00.01Z' => [1721423.5000001, 'Saturday'],
'-0001-01-01T11:59:59.99Z' => [1721057.9999999, 'Thursday'],
'-0001-01-01T12:00:00.00Z' => [1721058, 'Thursday'],
'-0001-01-01T13:00:00.01Z' => [1721058.0416668, 'Thursday'],
'-0001-01-01T23:59:59.99Z' => [1721058.4999999, 'Thursday'],
'-0001-01-02T00:00:00.00Z' => [1721058.5, 'Friday'],
'-0001-01-01T00:00:00.01Z' => [1721057.5000001, 'Thursday'],
'+1000-01-01T11:59:59.99Z' => [2086307.9999999, 'Monday'],
'+1000-01-01T12:00:00.00Z' => [2086308, 'Monday'],
'+1000-01-01T13:00:00.01Z' => [2086308.0416668, 'Monday'],
'+1000-01-01T23:59:59.99Z' => [2086308.4999999, 'Monday'],
'+1000-01-02T00:00:00.00Z' => [2086308.5, 'Tuesday'],
'+1000-01-01T00:00:00.01Z' => [2086307.5000001, 'Monday'],
'+2000-01-01T11:59:59.99Z' => [2451544.9999999, 'Saturday'],
'+2000-01-01T12:00:00.00Z' => [2451545, 'Saturday'],
'+2000-01-01T13:00:00.01Z' => [2451545.0416668, 'Saturday'],
'+2000-01-01T23:59:59.99Z' => [2451545.4999999, 'Saturday'],
'+2000-01-02T00:00:00.00Z' => [2451545.5, 'Sunday'],
'+2000-01-01T00:00:00.01Z' => [2451544.5000001, 'Saturday'],
'+3000-01-01T11:59:59.99Z' => [2816787.9999999, 'Wednesday'],
'+3000-01-01T12:00:00.00Z' => [2816788, 'Wednesday'],
'+3000-01-01T13:00:00.01Z' => [2816788.0416668, 'Wednesday'],
'+3000-01-01T23:59:59.99Z' => [2816788.4999999, 'Wednesday'],
'+3000-01-02T00:00:00.00Z' => [2816788.5, 'Thursday'],
'+3000-01-01T00:00:00.01Z' => [2816787.5000001, 'Wednesday'],
'+4000-01-01T11:59:59.99Z' => [3182029.9999999, 'Saturday'],
'+4000-01-01T12:00:00.00Z' => [3182030, 'Saturday'],
'+4000-01-01T13:00:00.01Z' => [3182030.0416668, 'Saturday'],
'+4000-01-01T23:59:59.99Z' => [3182030.4999999, 'Saturday'],
'+4000-01-02T00:00:00.00Z' => [3182030.5, 'Sunday'],
'+4000-01-01T00:00:00.01Z' => [3182029.5000001, 'Saturday'],
;
for %jpl.keys.sort -> $ut {
# with key and value JPL test data:
my $jd = %jpl{$ut}[0];
my $dow = %jpl{$ut}[1];
my $ut-dt = DateTime::Julian.new: $ut;
my $jd-dt = DateTime::Julian.new: :juliandate($jd);
is $ut-dt, $jd-ut;
}
|
;
(function ($) {
function Table(elem) {
var table = this;
var $elem = $(elem);
elem = $elem.get(0);
var o = {
cellTag: 'span',
cellClass: 'Table-cell',
thAttr: 'data-th',
formatHeader: function(text) {
return text+':';
}
};
table.init = function (options) {
setProperties(options);
if (elem.dataTable) {
return elem.dataTable;
}
$elem.find('td').wrapInner('<' + o.cellTag + ' class="' + o.cellClass + '">');
$elem.find('th').each(function(i) {
$elem.find('td:nth-child('+(i+1)+')').attr(o.thAttr, o.formatHeader($(this).text()));
});
elem.dataTable = table;
return elem.dataTable
};
function setProperties(options) {
$.extend(o, options);
}
}
$.fn.dataTable = function (options) {
return this.each(function () {
var opts = $(this).data('table');
if (typeof opts === 'string') {
opts = new Function('return {' + opts + '};')();
}
opts = $.extend({}, options, opts);
return new Table(this).init(opts);
});
};
})(jQuery || Zepto);
|
import 'package:brasil_fields/brasil_fields.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:xlomobx/stores/cep_store.dart';
import 'package:xlomobx/stores/create_store.dart';
class CepField extends StatelessWidget {
CepField({Key key, this.createStore})
: cepStore = createStore.cepStore,
super(key: key);
final CreateStore createStore;
final CepStore cepStore;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Observer(builder: (_) {
return TextFormField(
initialValue: cepStore.cep,
onChanged: cepStore.setCep,
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
CepInputFormatter()
],
decoration: InputDecoration(
labelText: 'CEP',
labelStyle: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: Colors.grey,
),
errorText: createStore.addressError,
contentPadding: const EdgeInsets.fromLTRB(16, 10, 12, 10)),
);
}),
Observer(
builder: (_) {
if (cepStore.error == null &&
cepStore.address == null &&
!cepStore.loading) {
return Container();
} else if (cepStore.address == null && cepStore.error == null) {
return LinearProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.purple),
backgroundColor: Colors.transparent,
);
} else if (cepStore.error != null) {
return Container(
color: Colors.red.withAlpha(100),
height: 50,
padding: const EdgeInsets.all(8),
alignment: Alignment.center,
child: Text(
cepStore.error,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.red,
),
),
);
} else {
final a = cepStore.address;
return Container(
color: Colors.purple.withAlpha(150),
height: 50,
padding: const EdgeInsets.all(8),
alignment: Alignment.center,
child: Text(
'Localizacao: ${a.district}, ${a.city.name} - ${a.uuf}',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
);
}
},
)
],
);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Week1 : MonoBehaviour
{
// Start is called before the first frame update
public string Win;
public GameObject input;
public GameObject output;
public void tao()
{
Win = input.GetComponent<Text>().text;
if (Win == "Unity")
{
output.GetComponent<Text>().text="[ Unity ] Is Found";
}
if (Win == "Unreal")
{
output.GetComponent<Text>().text = "[ Unreal ] Is Found";
}
if (Win == "Google")
{
output.GetComponent<Text>().text = "[ Google ] Is Found";
}
if (Win == "Line")
{
output.GetComponent<Text>().text = "[ Line ] Is Found";
}
if (Win == "Facebook")
{
output.GetComponent<Text>().text = "[ Facebook ] Is Found";
}
if (Win!= "Unity")
{
output.GetComponent<Text>().text = "[ ]Is not Found";
}
}
}
|
module TestScikitLearn
using MLJBase
using Test
import MLJModels
import ScikitLearn
using MLJModels.ScikitLearn_
using CategoricalArrays
task = load_iris();
X, y = X_and_y(task)
train, test = partition(eachindex(y), 0.6) # levels of y are split across split
plain_classifier = SVMClassifier()
nu_classifier = SVMNuClassifier()
linear_classifier = SVMLClassifier(max_iter=10000)
plain_regressor = SVMRegressor()
nu_regressor = SVMNuRegressor()
linear_regressor = SVMLRegressor(max_iter=10000)
# Xr = [[0, 0], [1, 1]]
# yr = [0, 1]
# targetr = [[1, 1]]
task = load_boston()
Xr, yr = X_and_y(task)
fitresultC, cacheC, reportC = MLJBase.fit(plain_classifier, 1,
selectrows(X, train), y[train]);
fitresultCnu, cacheCnu, reportCnu = MLJBase.fit(nu_classifier, 1,
selectrows(X, train), y[train]);
fitresultCL, cacheCL, reportCL = MLJBase.fit(linear_classifier, 1,
selectrows(X, train), y[train]);
fitresultR, cacheR, reportR = MLJBase.fit(plain_regressor, 1, Xr, yr);
fitresultRnu, cacheRnu, reportRnu = MLJBase.fit(nu_regressor, 1, Xr, yr);
fitresultRL, cacheRL, reportRL = MLJBase.fit(linear_regressor, 1, Xr, yr);
pcpred = predict(plain_classifier, fitresultC, selectrows(X, test));
nucpred = predict(nu_classifier, fitresultCnu, selectrows(X, test));
lcpred = predict(linear_classifier, fitresultCL, selectrows(X, test));
@test levels(pcpred) == levels(y[train])
@test levels(nucpred) == levels(y[train])
@test levels(lcpred) == levels(y[train])
rpred = predict(plain_regressor, fitresultR, targetr);
nurpred = predict(nu_regressor, fitresultRnu, targetr);
Lrpred = predict(linear_regressor, fitresultRL, targetr);
end
true
|
// Copyright Epic Games, Inc. All Rights Reserved.
// This file is automatically generated. Changes to this file may be overwritten.
namespace Epic.OnlineServices.Logging
{
/// <summary>
/// A structure representing a log message
/// </summary>
public class LogMessage : ISettable
{
/// <summary>
/// A string representation of the log message category, encoded in UTF-8. Only valid during the life of the callback, so copy the string if you need it later.
/// </summary>
public string Category { get; private set; }
/// <summary>
/// The log message, encoded in UTF-8. Only valid during the life of the callback, so copy the string if you need it later.
/// </summary>
public string Message { get; private set; }
/// <summary>
/// The log level associated with the message
/// </summary>
public LogLevel Level { get; private set; }
internal void Set(LogMessageInternal? other)
{
if (other != null)
{
Category = other.Value.Category;
Message = other.Value.Message;
Level = other.Value.Level;
}
}
public void Set(object other)
{
Set(other as LogMessageInternal?);
}
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 8)]
internal struct LogMessageInternal
{
private System.IntPtr m_Category;
private System.IntPtr m_Message;
private LogLevel m_Level;
public string Category
{
get
{
string value;
Helper.TryMarshalGet(m_Category, out value);
return value;
}
}
public string Message
{
get
{
string value;
Helper.TryMarshalGet(m_Message, out value);
return value;
}
}
public LogLevel Level
{
get
{
return m_Level;
}
}
}
}
|
#!/bin/ash
set -e
sed -i "s|{{REST_ENDPOINT}}|$REST_ENDPOINT|g" /usr/share/nginx/html/main.js
sed -i "s|{{TITANIUM_REPORT_GENERATION_URL}}|$TITANIUM_REPORT_GENERATION_URL|g" /usr/share/nginx/html/main.js
exec "$@"
|
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Sre
{
class HostedService : IHostedService
{
#region constructor
private readonly ILogger<HostedService> logger;
private readonly ILogic logic;
public HostedService(ILogger<HostedService> logger, ILogic logic)
{
this.logger = logger;
this.logic = logic;
}
#endregion
/// <summary>
/// Przeniesione tutaj z Program.cs zeby testy mogly latwiej siegac do konfigurowania serwisow
/// </summary>
/// <param name="context"></param>
/// <param name="services"></param>
public static void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
services.Configure<AppSettings>(context.Configuration);
services.AddHostedService<HostedService>();
services.TryAddTransient<ILogic, Logic>();
}
/// <summary>
/// Logger w tej metodzie jest domyslnie skonfigurowany tak, ze Information sie nie wyswietla, Error+ tak
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task StartAsync(CancellationToken cancellationToken)
{
logger.LogTrace("Hosted service starting");
await logic.RunAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Hosted service stopping");
return Task.CompletedTask;
}
}
}
|
package ro.pub.cs.aipi.lab02.entities;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(User.class)
public class User_ {
public static volatile SingularAttribute<User, Long> id;
public static volatile SingularAttribute<User, Long> personalIdentifier;
public static volatile SingularAttribute<User, String> firstName;
public static volatile SingularAttribute<User, String> lastName;
public static volatile SingularAttribute<User, String> address;
public static volatile SingularAttribute<User, Long> phoneNumber;
public static volatile SingularAttribute<User, String> email;
public static volatile SingularAttribute<User, String> type;
public static volatile SingularAttribute<User, String> username;
public static volatile SingularAttribute<User, String> password;
}
|
module ConfigHelpers
# SOCCER
def self.set_api_football_com
Sports::Butler::Configuration.configure do |config|
config.api_token = { soccer: {}, basketball: {} }
config.api_token[:soccer][:api_football_com] = 'my_dummy_token'
config.api_base_url = { soccer: {}, basketball: {} }
config.api_base_url[:soccer][:api_football_com] = 'https://v3.football.api-sports.io'
end
end
def self.set_apifootball_com
Sports::Butler::Configuration.configure do |config|
config.api_token = { soccer: {}, basketball: {} }
config.api_token[:soccer][:apifootball_com] = 'my_dummy_token'
config.api_base_url = { soccer: {}, basketball: {} }
config.api_base_url[:soccer][:apifootball_com] = 'https://apiv2.apifootball.com'
end
end
def self.set_football_data_org
Sports::Butler::Configuration.configure do |config|
config.api_token = { soccer: {}, basketball: {} }
config.api_token[:soccer][:football_data_org] = 'my_dummy_token'
config.api_base_url = { soccer: {}, basketball: {} }
config.api_base_url[:soccer][:football_data_org] = 'https://api.football-data.org'
end
end
# BASKETBALL
def self.set_api_basketball_com
Sports::Butler::Configuration.configure do |config|
config.api_token = { soccer: {}, basketball: {} }
config.api_token[:basketball][:api_basketball_com] = 'my_dummy_token'
config.api_base_url = { soccer: {}, basketball: {} }
config.api_base_url[:basketball][:api_basketball_com] = 'https://v3.basketball.api-sports.io'
end
end
end
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using ReactiveMachine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Counter.Service
{
[DataContract]
public class Counter2 :
IPartitionedState<ICounterAffinity,uint>
{
[DataMember]
public int Count;
}
[DataContract]
public class IncrementUpdate :
IUpdate<Counter2, int>,
ICounterAffinity
{
[DataMember]
public uint CounterId { get; set; }
[CreateIfNotExists]
public int Execute(IUpdateContext<Counter2> context)
{
return ++(context.State.Count);
}
}
}
|
'use strict';
import { window } from 'vscode';
import { isMarkdownFileCheck, noActiveEditorMessage } from '../helper/common';
import { addNewColumn, addNewColumnWithSpan, createRow } from '../helper/rows-columns';
import { sendTelemetryData } from '../helper/telemetry';
const rowWithColumns = 'Two-column structure';
const newColumn = 'New column';
const newColumnWithSpan = 'New column with span';
const telemetryCommand: string = 'insertColumn';
let commandOption: string;
export function insertRowsAndColumnsCommand() {
const commands = [{ command: insertRowsAndColumns.name, callback: insertRowsAndColumns }];
return commands;
}
export function insertRowsAndColumns() {
const editor = window.activeTextEditor;
if (!editor) {
noActiveEditorMessage();
return;
} else {
if (!isMarkdownFileCheck(editor, false)) {
return;
}
const commandOptions = [rowWithColumns, newColumn, newColumnWithSpan];
window.showQuickPick(commandOptions).then(qpSelection => {
if (!qpSelection) {
return;
}
switch (qpSelection) {
case rowWithColumns:
insertRowsWithColumns();
break;
case newColumn:
insertNewColumn();
break;
case newColumnWithSpan:
insertNewColumnWithSpan();
break;
}
});
}
}
export function insertRowsWithColumns() {
createRow(2);
commandOption = 'row';
sendTelemetryData(telemetryCommand, commandOption);
}
export function insertNewColumn() {
addNewColumn();
commandOption = 'column';
sendTelemetryData(telemetryCommand, commandOption);
}
export function insertNewColumnWithSpan() {
addNewColumnWithSpan();
commandOption = 'column-with-span';
sendTelemetryData(telemetryCommand, commandOption);
}
|
alter table ACT_RU_TASK add column SUB_TASK_COUNT_ integer;
update ACT_RU_TASK t set t.SUB_TASK_COUNT_ = (select count(*) from (select * from ACT_RU_TASK where IS_COUNT_ENABLED_ = true) as count_table where PARENT_TASK_ID_ = t.ID_) where t.IS_COUNT_ENABLED_ = true;
update ACT_GE_PROPERTY set VALUE_ = '6.3.0.0' where NAME_ = 'task.schema.version';
|
package com.wix.hoopoe.koboshi.scheduler
import java.util.concurrent.{Executors, ScheduledExecutorService}
class JavaUtilExecutorsSchedulers extends Schedulers {
override def aScheduler(namespace: String): ScheduledExecutorService = Executors.newScheduledThreadPool(1)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.