text
stringlengths 27
775k
|
---|
export default [{
question: 'How many stuff',
options: [1, 2, 3, 4, 0]
}, {
question: 'Something something',
options: [ 'Yes', 'No' ]
}, {
question: 'Super duper',
options: [590, 45]
}];
|
package io.wax911.challenge.feature.detail.component.viewmodel
import androidx.lifecycle.*
import io.wax911.challenge.core.component.viewmodel.AbstractViewModel
import io.wax911.challenge.domain.common.DataState
import io.wax911.challenge.domain.credit.enity.Credit
import io.wax911.challenge.domain.detail.interactor.IDetailUseCase
class DetailViewModel(
private val useCase: IDetailUseCase
) : AbstractViewModel<Credit.Detail>() {
private val useCaseResult = MutableLiveData<DataState<Credit.Detail>>()
override val model = Transformations.switchMap(useCaseResult) {
it.data.asLiveData(viewModelScope.coroutineContext)
}
override val isLoading = Transformations.switchMap(useCaseResult) {
it.isLoading.asLiveData(viewModelScope.coroutineContext)
}
override val error = Transformations.switchMap(useCaseResult) {
it.error.asLiveData(viewModelScope.coroutineContext)
}
operator fun invoke() {
val data = useCase(viewModelScope)
useCaseResult.value = data
}
} |
package com.badoo.reaktive.utils.atomic
actual class AtomicBoolean actual constructor(initialValue: Boolean) {
private val delegate = kotlin.native.concurrent.AtomicInt(initialValue.intValue)
actual var value: Boolean
get() = delegate.value != 0
set(value) {
delegate.value = value.intValue
}
actual fun compareAndSet(expectedValue: Boolean, newValue: Boolean): Boolean =
delegate.compareAndSet(expectedValue.intValue, newValue.intValue)
private companion object {
private val Boolean.intValue: Int get() = if (this) 1 else 0
}
}
|
echo -e '\e[31;1m* Generating random data file\e[m'
dd if=/dev/urandom of=test64M bs=64M count=1 iflag=fullblock
echo -e '\n\e[31;1m* Sending data file through mypipe\e[m'
dd if=test64M of=/dev/mypipe_in bs=64M count=1 iflag=fullblock &
dd if=/dev/mypipe_out of=recv64M bs=64M count=1 iflag=fullblock
wait
echo -e '\n\e[31;1m* Showing SHA256 of generated and received file\e[m'
sha256sum test64M recv64M
rm test64M recv64M
|
#!/bin/bash
# we cannot use the --verbose anymore since this would block
#asadmin start-domain --verbose
asadmin --user admin --passwordfile=/opt/payara41/pwdfile --interactive=false start-domain --debug --verbose &
PID=$!
# sleep a few seconds to give the broker time to bootup
sleep 20
asadmin --user admin --passwordfile=/opt/payara41/pwdfile deploy /discovery-directory-jee-shared-db.war
# should we have a tail -f here?
# where are the logs in this payara installation?
wait $PID
echo "end of start-me-up of joynr-infra"
|
<?php declare(strict_types=1);
namespace Sunkan\Dictus;
final class FrozenClock implements ClockInterface
{
public static function fromString(string $date): self
{
return new self(DateParser::fromString($date));
}
public function __construct(
private \DateTimeImmutable $now,
) {}
public function now(): \DateTimeImmutable
{
return $this->now;
}
}
|
/*
Title: De spanning begint te komen...
Description: Voorbereiding op mijn stage bij Mangrove
Date: 2015/08/27
*/
De spanning voor mijn stage begint te komen.
Hoe zal het zijn? Hoe zal het gaan?
Wat wordt van mij verwacht?
Heb ik wel genoeg kennis?
Allemaal vragen die in mijn hoofd rondspoken en waar ik over 4 dagen antwoord op hoop te krijgen.
Intussen ben ik bezig met een aantal kleine dingetjes voorbereiden.
Deze blog is één van die dingen, maar voordat ik begin wil ik ook alvast een kijkje nemen naar het stageovereenkomst.
Verder ben ik er vooral klaar voor en hoop ik gewoon op een leervolle stage periode.
|
#pragma once
#include "../Module.hpp"
namespace tge::gui {
class GUIModule : public tge::main::Module {
public:
void *pool;
void *buffer;
void *renderpass;
void *framebuffer;
main::Error init() override;
void tick(double deltatime) override;
void destroy() override;
virtual void renderGUI() = 0;
};
} // namespace tge::gui
|
-- +migrate Up
CREATE TABLE IF NOT EXISTS users (
id CHAR(36) NOT NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
username VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
-- +migrate Down
DROP TABLE users; |
export const pending = actionType => `${actionType}_PENDING`
export const fulfilled = actionType => `${actionType}_FULFILLED`
export const rejected = actionType => `${actionType}_REJECTED`
|
[](https://pub.dev/packages/mime)
[](https://travis-ci.org/dart-lang/mime)
Package for working with MIME type definitions and for processing
streams of MIME multipart media types.
## Determining the MIME type for a file
The `MimeTypeResolver` class can be used to determine the MIME type of
a file. It supports both using the extension of the file name and
looking at magic bytes from the beginning of the file.
There is a builtin instance of `MimeTypeResolver` accessible through
the top level function `lookupMimeType`. This builtin instance has
the most common file name extensions and magic bytes registered.
```dart
import 'package:mime/mime.dart';
void main() {
print(lookupMimeType('test.html'));
// text/html
print(lookupMimeType('test', headerBytes: [0xFF, 0xD8]));
// image/jpeg
print(lookupMimeType('test.html', headerBytes: [0xFF, 0xD8]));
// image/jpeg
}
```
You can build you own resolver by creating an instance of
`MimeTypeResolver` and adding file name extensions and magic bytes
using `addExtension` and `addMagicNumber`.
## Processing MIME multipart media types
The class `MimeMultipartTransformer` is used to process a `Stream` of
bytes encoded using a MIME multipart media types encoding. The
transformer provides a new `Stream` of `MimeMultipart` objects each of
which have the headers and the content of each part. The content of a
part is provided as a stream of bytes.
Below is an example showing how to process an HTTP request and print
the length of the content of each part.
```dart
// HTTP request with content type multipart/form-data.
HttpRequest request = ...;
// Determine the boundary form the content type header
String boundary = request.headers.contentType.parameters['boundary'];
// Process the body just calculating the length of each part.
request
.transform(new MimeMultipartTransformer(boundary))
.map((part) => part.fold(0, (p, d) => p + d))
.listen((length) => print('Part with length $length'));
```
Take a look at the `HttpBodyHandler` in the [http_server][http_server]
package for handling different content types in an HTTP request.
## Features and bugs
Please file feature requests and bugs at the [issue tracker][tracker].
[tracker]: https://github.com/dart-lang/mime/issues
[http_server]: https://pub.dev/packages/http_server
|
// Esse método retorna o primeiro índice em que o elemento pode ser encontrado no array
let nums = [1, 2, 3, 4, 5]
console.log(nums.indexOf(2))
console.log(nums.indexOf(3, 1)) // o "1" indica qual o indice que deve ser o primeiro a ser buscado
console.log(nums.indexOf(6))
let nomes = ['Ana', 'Bia', 'Caio', 'Duda']
console.log(nomes.indexOf('Ana')) |
import knex, { Config, RawBinding, Sql } from 'knex'
import QueryBuilder from 'knex/lib/query/builder'
import Raw from 'knex/lib/raw'
import Runner from 'knex/lib/runner'
import SchemaBuilder from 'knex/lib/schema/builder'
import createDebug from './debug'
import { after, before, override } from './override'
const debug = createDebug('client-multi-tenant')
/**
* Build knex tenant configuration changing details related to multi-tenant
*/
export const buildConfig = (config: Config, tenantId: number) => {
const multiTenantConfig = {
...config,
tenantId,
}
multiTenantConfig.migrations = { ...(multiTenantConfig.migrations || {}) }
// custom migration with the table name prefix
const tableName = multiTenantConfig.migrations.tableName || 'knex_migrations'
multiTenantConfig.migrations.tableName = `${tenantId}_${tableName}`
return multiTenantConfig
}
/**
* Installs the tenant monkey patch on knex.
*
* It overrides some base knex functions changing the original behavior to
* include multi-tenant configurations such as the tenant prefix in every table.
*/
export function install() {
const hasDefinedTenantId = Object.getOwnPropertyDescriptor(knex.Client.prototype, 'tenantId')
if (hasDefinedTenantId) {
return
}
Object.defineProperty(knex.Client.prototype, 'tenantId', {
get() {
return this.config.tenantId
},
})
override(
QueryBuilder.prototype,
'toSQL',
after(function (toSQLFunction: Sql) {
debug('knex.Client.prototype.QueryBuilder.prototype.toSQL', arguments)
toSQLFunction.sql = applyTenant(toSQLFunction.sql, this.client.tenantId)
return toSQLFunction
}),
)
override(
SchemaBuilder.prototype,
'toSQL',
after(function (toSQLSchemaQueries: Sql[]) {
debug('knex.Client.prototype.SchemaBuilder.prototype.toSQL', arguments)
return toSQLSchemaQueries.map((toSQLFunction: Sql) => {
toSQLFunction.sql = applyTenant(toSQLFunction.sql, this.client.tenantId)
return toSQLFunction
})
}),
)
override(
Raw.prototype,
'set',
before(function (rawSQLQuery: string, bindings: readonly RawBinding[]) {
debug('knex.Client.prototype.Raw.prototype.set', arguments)
const tenantSQL = applyTenant(rawSQLQuery, this.client.tenantId)
return [tenantSQL, bindings]
}),
)
override(
Runner.prototype,
'query',
after(async function (promise, originalArgs) {
debug('knex.Client.prototype.Runner.prototype.query', arguments)
const options = originalArgs[0].options
const result = await promise
if (!options || !options.nestTables) {
return result
}
return result.map((row) =>
Object.keys(row).reduce((processedRow, tableJoinName) => {
processedRow[misapplyTenant(tableJoinName, this.client.tenantId)] = row[tableJoinName]
return processedRow
}, {}),
)
}),
)
}
const misapplyTenant = (sql: string, tenant: number) => sql.replace(new RegExp(`^(${tenant}_)`), '$_')
const applyTenant = (sql: string, tenant: number) => sql.replace(/\$_/g, `${tenant}_`)
|
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
config.routes = false
end |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
module AD where
import qualified Data.Map as Map
--import Data.Function
--import Data.List
import Data.String
--import Data.Monoid
import Data.Traversable
--import Data.Reflection (Reifies)
--import Control.Applicative
import qualified Data.Traversable as T
import qualified Data.Foldable as F
--import Numeric.AD.Internal.Reverse (Tape)
import Numeric.AD ()
import Data.Reify
--import Data.Reify.Graph
newtype Mu a = In (a (Mu a))
instance (T.Traversable a) => MuRef (Mu a) where
type DeRef (Mu a) = a
mapDeRef f (In a) = T.traverse f a
data Exp_ a
= C_ Float
| Var_ String
| Add_ a a
| Mul_ a a
| Neg_ a
| Recip_ a
| Abs_ a
| Signum_ a
| Sin_ a
| Cos_ a
| ASin_ a
| ACos_ a
| ATan_ a
| Sinh_ a
| Cosh_ a
| ASinh_ a
| ACosh_ a
| ATanh_ a
| Exp_ a
| Log_ a
deriving (Show, Functor, F.Foldable, Traversable)
type Exp = Mu Exp_
pattern C x = In (C_ x)
pattern Var x = In (Var_ x)
pattern Add x y = In (Add_ x y)
pattern Mul x y = In (Mul_ x y)
pattern Neg x = In (Neg_ x)
pattern Recip x = In (Recip_ x)
pattern Abs x = In (Abs_ x)
pattern Signum x = In (Signum_ x)
pattern Sin x = In (Sin_ x)
pattern Cos x = In (Cos_ x)
pattern ASin x = In (ASin_ x)
pattern ACos x = In (ACos_ x)
pattern ATan x = In (ATan_ x)
pattern Sinh x = In (Sinh_ x)
pattern Cosh x = In (Cosh_ x)
pattern ASinh x = In (ASinh_ x)
pattern ACosh x = In (ACosh_ x)
pattern ATanh x = In (ATanh_ x)
pattern Exp x = In (Exp_ x)
pattern Log x = In (Log_ x)
reify :: Exp -> IO (Graph Exp_)
reify = reifyGraph
pattern Zero <- C 0
pattern One <- C 1
instance IsString Exp where
fromString = Var
withC f _ (C x) = C $ f x
withC _ g x = g x
flipC _ g x y@(C _) = g y x
flipC f _ x y = f x y
add = flipC f f where
f (C a) (C b) = C $ a + b
f Zero x = x
f (C a) (Add (C b) c) = Add (C $ a + b) c
f (Add (C a) a') (Add (C b) c) = Add (C $ a + b) $ a' + c
f (Neg x) (Neg y) = negate $ x + y
f x y = Add x y
negate_ (Neg a) = a
negate_ a = Neg a
recip_ (Recip a) = a
recip_ (Neg a) = negate $ recip a
recip_ a = Recip a
mul = flipC f f where
f (C a) (C b) = C $ a * b
f Zero _ = 0
f One x = x
f (C a) (Mul (C b) c) = Mul (C $ a * b) c
f (Mul (C a) a') (Mul (C b) c) = Mul (C $ a * b) $ a' * c
f (Neg x) y = negate (x * y)
f x (Neg y) = negate (x * y)
f (Recip x) (Recip y) = recip (x * y)
f x y = Mul x y
type Env a = Map.Map String a
instance Show Exp where
showsPrec p e = case e of
Add x y -> showParen (p > 2) $ showsPrec 2 x . (" + " ++) . showsPrec 2 y
Neg x -> showParen (p >= 2) $ (" -" ++) . showsPrec 2 x
Mul x y -> showParen (p > 3) $ showsPrec 3 x . (" * " ++) . showsPrec 3 y
Recip x -> showParen (p >= 3) $ (" 1/" ++) . showsPrec 3 x
Abs x -> showParen (p > 9) $ ("abs " ++) . showsPrec 10 x
Signum x -> showParen (p > 9) $ ("signum " ++) . showsPrec 10 x
Sin x -> showParen (p > 9) $ ("sin " ++) . showsPrec 10 x
Cos x -> showParen (p > 9) $ ("cos " ++) . showsPrec 10 x
ASin x -> showParen (p > 9) $ ("asin " ++) . showsPrec 10 x
ACos x -> showParen (p > 9) $ ("acos " ++) . showsPrec 10 x
Exp x -> showParen (p > 9) $ ("exp " ++) . showsPrec 10 x
Log x -> showParen (p > 9) $ ("log " ++) . showsPrec 10 x
Var s -> (s ++)
C 0 -> ("0" ++)
C 1 -> ("1" ++)
C i -> shows i
instance Num Exp where
(*) = mul
(+) = add
negate = withC negate negate_
abs = withC abs Abs
signum = withC signum Signum
fromInteger = C . fromInteger
instance Fractional Exp where
fromRational = C . fromRational
recip = withC recip recip_
instance Floating Exp where
exp = withC exp Exp
log = withC log Log
pi = 3.141592653589793
sin = withC sin Sin
cos = withC cos Cos
asin = withC asin ASin
acos = withC acos ACos
atan = withC atan ATan
sinh = withC sinh Sinh
cosh = withC cosh Cosh
asinh = withC asinh ASinh
acosh = withC acosh ACosh
atanh = withC atanh ATanh
(x:y:z:_) = map (Var . (:[])) ['x'..]
(a:b:c:d:_) = map (Var . (:[])) ['a'..]
vec = [x, y, z]
{-
adds (Add a b) = adds a ++ adds b
adds x = [x]
muls (Mul a b) = muls a ++ muls b
muls x = [x]
norm e
| l@(_:_:_) <- adds e = foldl1 add $ sortBy (compare `on` ty) $ concatMap adds $ map norm l
| l@(_:_:_) <- muls e = foldl1 mul $ sortBy (compare `on` ty) $ concatMap muls $ map norm l
| otherwise = e
-}
{-
ty (C _) = 0
ty (Var _) = 1
ty _ = 2
instance Ord Exp where
compare a b = compare (eval mempty a) (eval mempty b)
-}
{-
subs :: Env Exp -> Exp -> Exp
subs e x = case x of
Add a b -> subs e a + subs e b
Mul a b -> subs e a * subs e b
Sub a b -> subs e a - subs e b
Div a b -> subs e a / subs e b
Abs a -> abs (subs e a)
Signum a -> signum (subs e a)
Sin a -> sin (subs e a)
Cos a -> cos (subs e a)
Exp a -> exp (subs e a)
Log a -> log (subs e a)
C a -> realToFrac a
Var s -> case Map.lookup s e of
Nothing -> Var s
Just e -> e
eval :: Floating a => Env a -> Exp -> a
eval e x = case x of
Add a b -> eval e a + eval e b
Mul a b -> eval e a * eval e b
Sub a b -> eval e a - eval e b
Div a b -> eval e a / eval e b
Abs a -> abs (eval e a)
Signum a -> signum (eval e a)
Sin a -> sin (eval e a)
Cos a -> cos (eval e a)
ASin a -> asin (eval e a)
ACos a -> acos (eval e a)
Exp a -> exp (eval e a)
Log a -> log (eval e a)
C a -> realToFrac a
Var s -> case Map.lookup s e of
Nothing -> error $ "unknown value of: " ++ s
Just e -> e
-- Var s -> e Map.! s
-}
--deriving instance Functor (AD s)
--deriving instance Functor Forward
--der v@(Var name) e = diff (\x -> eval (Map.singleton name x) e) v
{-
grad_ :: (forall s. Reifies s Tape => [Reverse s Exp] -> Reverse s Exp) -> Vec
grad_ f = map norm $ grad f vec
grad__ :: Exp -> Vec
grad__ x = grad_ (flip evalMap x)
--grad' f = grad f vec
type Vec = [Exp]
testDiff :: Exp
testDiff = diff (\x -> 3 * x^2 + 2 * x - 4) 4
testGrad :: [Exp]
testGrad = grad (\[x, y, z] -> 3 * x^20 + 2 * x * y - 4) [x,3 * y,0]
testJacobian :: [[Exp]]
testJacobian = jacobian (\[x,y] -> [y,x,sin (x*y)]) [2 * x * y,1]
mkMap = Map.fromList . zip ["x","y","z"]
evalMap = eval . mkMap
hessian_ = map grad__ . grad__
testHessian :: [[Exp]]
testHessian = hessian_ $ x*y
-}
|
package r2.util
import zio.interop.reactivestreams._
import zio.stream._
import zio.test.Assertion._
import zio.test._
object ReactiveStreamsUtilsSpec extends DefaultRunnableSpec {
import ReactiveStreamsUtils._
val spec = suite("ReactiveStreamsUtils")(
suite("mono")(
testM("returns a single element") {
for {
publisher <- Stream.succeed(42).toPublisher
head <- mono(publisher)
} yield {
assert(head)(equalTo(42))
}
},
testM("fails if the stream completes without emitting an element") {
for {
publisher <- Stream[Int]().toPublisher
error <- mono(publisher).flip
} yield {
assert(error)(isSubtype[NoSuchElementException](hasMessage(containsString("Stream completed"))))
}
}
),
suite("awaitCompletion")(
testM("returns after the stream completes") {
for {
publisher <- Stream[Void]().toPublisher
_ <- awaitCompletion(publisher)
} yield {
assertCompletes
}
}
)
)
}
|
# Copyright (C) 2011-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2010 Lorenzo Gil Sanchez <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import saml2
def create_conf(sp_host='sp.example.com', idp_hosts=['idp.example.com'],
metadata_file='remote_metadata.xml', authn_requests_signed=None):
try:
from saml2.sigver import get_xmlsec_binary
except ImportError:
get_xmlsec_binary = None
if get_xmlsec_binary:
xmlsec_path = get_xmlsec_binary(["/opt/local/bin"])
else:
xmlsec_path = '/usr/bin/xmlsec1'
BASEDIR = os.path.dirname(os.path.abspath(__file__))
config = {
'xmlsec_binary': xmlsec_path,
'entityid': 'http://%s/saml2/metadata/' % sp_host,
'attribute_map_dir': os.path.join(BASEDIR, 'attribute-maps'),
'service': {
'sp': {
'name': 'Test SP',
'name_id_format': saml2.saml.NAMEID_FORMAT_PERSISTENT,
'endpoints': {
'assertion_consumer_service': [
('http://%s/saml2/acs/' % sp_host,
saml2.BINDING_HTTP_POST),
],
'single_logout_service': [
('http://%s/saml2/ls/' % sp_host,
saml2.BINDING_HTTP_REDIRECT),
],
},
'required_attributes': ['uid'],
'optional_attributes': ['eduPersonAffiliation'],
'idp': {}, # this is filled later
'want_response_signed': False,
},
},
'metadata': {
'local': [os.path.join(BASEDIR, metadata_file)],
},
'debug': 1,
# certificates
'key_file': os.path.join(BASEDIR, 'mycert.key'),
'cert_file': os.path.join(BASEDIR, 'mycert.pem'),
# These fields are only used when generating the metadata
'contact_person': [
{'given_name': 'Technical givenname',
'sur_name': 'Technical surname',
'company': 'Example Inc.',
'email_address': '[email protected]',
'contact_type': 'technical'},
{'given_name': 'Administrative givenname',
'sur_name': 'Administrative surname',
'company': 'Example Inc.',
'email_address': '[email protected]',
'contact_type': 'administrative'},
],
'organization': {
'name': [('Ejemplo S.A.', 'es'), ('Example Inc.', 'en')],
'display_name': [('Ejemplo', 'es'), ('Example', 'en')],
'url': [('http://www.example.es', 'es'),
('http://www.example.com', 'en')],
},
'valid_for': 24,
}
if authn_requests_signed is not None:
config['service']['sp']['authn_requests_signed'] = authn_requests_signed
for idp in idp_hosts:
entity_id = 'https://%s/simplesaml/saml2/idp/metadata.php' % idp
config['service']['sp']['idp'][entity_id] = {
'single_sign_on_service': {
saml2.BINDING_HTTP_REDIRECT: 'https://%s/simplesaml/saml2/idp/SSOService.php' % idp,
},
'single_logout_service': {
saml2.BINDING_HTTP_REDIRECT: 'https://%s/simplesaml/saml2/idp/SingleLogoutService.php' % idp,
},
}
return config
|
2019年10月1日
vesion: 0.3.26
新添加一个群助手功能:空气质量PM2.5查询
也可以添加到每日提醒中。
2019年9月5日
vesion: 0.3.20
新添加一个群助手功能:快递物流信息查询
2019年8月27日
vesion: 0.3.10
新添加一个群助手功能:实时票房查询
2019年8月27日
vesion: 0.3.07
1.添加了一个新的机器人渠道:思知机器人
2019年8月14日
1. 更新天气更新不及时的 Bug。
2019年7月13日
1. 天气预报、星座运势、日历的提醒可以用明日。
2. 自动回复可以回复所有人,添加不受影响的『白名单』。
3. 新功能:群助手,可自动回复成员,查询天气,日历。
4. 添加了 mongodb 数据库做缓存处理。
2019年7月2日
新添三个机器人渠道:「智能闲聊」、「天行机器人」 「海知智能机器人」
2019年6月30日
新添每日一言渠道:彩虹屁
2019年6月29日
1.新添内容:万年历。
2.『在一起』文案可自定义。
3.可添加多个定时提醒。
4.更新非 windows 平台登录出现的 Bug.
5.星座运势可直接填具体星座
2019年6月24日
重构代码结构。
2019年6月20日
新添内容:星座运势
2019年6月19日
新添每日一言渠道:民国情书
2019年6月16日
新添机器人渠道:一个 AI
2019年6月15日
1.好友可选『文件传输助手』
2.定时发送消息可支持群聊组。
2019年6月15日
代码重构
2019年6月12日
添加图灵机器人
更早,不知道了。 |
{-# LANGUAGE FlexibleContexts #-}
module Content.Service.TimeSeriesService
( TimeSeriesService
, mkTimeSeriesService
, GroupedTimeSeriesService
, mkGroupedTimeSeriesService
)
where
import qualified Content.Model.TimeSeries as TimeSeries
import Control.Monad.Reader (MonadReader)
import qualified Core.Database.Model.Status as CStatus
import Data.Maybe (fromMaybe)
import qualified Data.Time as T
import OpenEnv (Embedded, embedded)
type TimeSeriesService m
= Maybe T.UTCTime -- start time, default value: `end` - `defaultPeriod`
-> Maybe T.UTCTime -- end time, default value: now
-> m TimeSeries.TimeSeries
type GroupedTimeSeriesService m
= Maybe T.UTCTime -- start time, see `TimeSeriesService m`
-> Maybe T.UTCTime -- end time, see `TimeSeriesService m`
-> Maybe T.NominalDiffTime
-> m TimeSeries.TimeSeries
defaultDt, defaultPeriod :: T.NominalDiffTime
defaultDt = 60
defaultPeriod = 24 * 3600
{- |returns a time series of the temperature and humiditiy within a defined
timeframe (start, end). If end is undefined, then end=now. If start is
undefined, then start=end -1hour. -}
mkTimeSeriesService
:: (MonadReader e m, Embedded T.UTCTime e m)
=> CStatus.FetchStatusPeriodRepository m
-> TimeSeriesService m
mkTimeSeriesService fetchStatusPeriodRepository startOpt endOpt = do
(start, end) <- case (startOpt, endOpt) of
(Nothing , Nothing ) -> periodEnd <$> embedded
(Just start, Nothing ) -> (,) start <$> embedded
(Nothing , Just end) -> return $ periodEnd end
(Just start, Just end) -> return (start, end)
TimeSeries.from <$> fetchStatusPeriodRepository (start, end)
where periodEnd time = (T.addUTCTime (-defaultPeriod) time, time)
-- |using a `TimeSeriesService m` this service returns the resukt convoluted
mkGroupedTimeSeriesService
:: (Functor m) => TimeSeriesService m -> GroupedTimeSeriesService m
mkGroupedTimeSeriesService timeSeriesService startOpt endOpt dt = do
let dt' = fromMaybe defaultDt dt
grouped = TimeSeries.group dt'
TimeSeries.groupTimeSeries dt' <$> timeSeriesService startOpt endOpt
|
module ActiveCucumber
# A decorator for ActiveRecord objects that adds methods to
# format record attributes as they are displayed in Cucumber tables.
#
# This class is used by default. You can subclass it to create
# custom Cucumberators for your ActiveRecord classes.
class Cucumberator
# object - the instance to decorate
def initialize object, context
@object = object
context.each do |key, value|
instance_variable_set "@#{key}", value
end
end
# Returns the Cucumber value for the given attribute key.
#
# If a value_for_* method is not defined for the given key,
# returns the attribute value of the decorated object,
# converted to a String.
def value_for key
method_name = value_method_name key
if respond_to? method_name
send(method_name).to_s
else
@object.send(normalized_key key).to_s
end
end
private
def method_missing method_name
# This is necessary so that a Cucumberator subclass can access
# attributes of @object as if they were its own.
@object.send method_name
end
# Converts the key given in Cucumber format into the format used to
# access attributes on an ActiveRecord instance.
def normalized_key key
key.to_s.downcase.parameterize.underscore
end
# Returns the name of the value_of_* method for the given key
def value_method_name key
"value_for_#{normalized_key key}"
end
end
end
|
using System.Threading.Tasks;
using System.Windows;
using NgDesk;
namespace Wpf
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var server = NgDesk.Factory.GetServerUsingFilePath();
Task.Factory.StartNew(
async() => await server.ServeAsync("http://localhost:4444/"));
}
}
} |
package io.holyguacamole.bot.controller
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.nhaarman.mockito_kotlin.mock
import io.holyguacamole.bot.MockAppMentions
import io.holyguacamole.bot.MockJoinedChannelEvents
import io.holyguacamole.bot.MockMessages
import io.holyguacamole.bot.MockUrlVerification
import io.holyguacamole.bot.MockUserChangeEvent
import org.junit.Test
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.test.web.servlet.setup.MockMvcBuilders
class EventControllerTest {
private val mvc: MockMvc = MockMvcBuilders
.standaloneSetup(EventController("thisisagoodtoken", mock()))
.build()
@Test
fun `it receives messages and returns 400 error when no body is present`() {
mvc.perform(post("/events"))
.andExpect(status().isBadRequest)
}
@Test
fun `it receives a challenge and responds success with the challenge value`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockUrlVerification.withCorrectToken))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
.andExpect(content().string("{\"challenge\":\"somechallenge\"}"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
}
@Test
fun `it verifies the token received in requests`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockUrlVerification.withCorrectToken))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockUrlVerification.withIncorrectToken))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isUnauthorized)
}
@Test
fun `it receives message events and returns 200`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockMessages.withSingleMentionAndSingleAvocado))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
}
@Test
fun `it returns a 400 when request is not a challenge or message event`() {
mvc.perform(post("/events")
.content("{\"token\": \"thisisagoodtoken\", \"type\": \"BAD\"}")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest)
}
@Test
fun `it receives app_mention events and returns a 200`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockAppMentions.leaderboard))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
}
@Test
fun `it receives user_change events and returns a 200`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockUserChangeEvent.markNameUpdate))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
}
@Test
fun `it receives member_joined_channel events and returns a 200`() {
mvc.perform(post("/events")
.content(jacksonObjectMapper().writeValueAsString(MockJoinedChannelEvents.botJoined))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk)
}
}
|
module Math.LinearAlgebra.Sparse.Algorithms.SolveLinear
(
solveLinear, solveLinSystems
)
where
import Data.Maybe
import Data.Monoid
import Data.IntMap as M hiding ((!))
import Math.LinearAlgebra.Sparse.Matrix
import Math.LinearAlgebra.Sparse.Vector
import Math.LinearAlgebra.Sparse.Algorithms.Staircase
import Math.LinearAlgebra.Sparse.Algorithms.Diagonal
-- | Solves system for matrix in diagonal form
solveDiagonal :: Integral α
=> (SparseMatrix α, SparseMatrix α, SparseMatrix α) -- ^ return triple-value of `toDiag`
-> SparseVector α -- ^ right-hand-side vector
-> Either String (SparseVector α) -- ^ either error message or solution
solveDiagonal (d,t,u) b
| height d /= dim b = Left "width m /= dim b"
| isZeroVec b = Right $ zeroVec (width d)
| isZeroMx d = Left "left side is zero-matrix, while right side is not zero-vector"
| otherwise =
let (dd,a) = (mainDiag d, t ×· b)
(bad,sol) = solveDiag dd a
in if size (vec dd) < size (vec a) then Left "zeroes in lhs, while non-zeroes in rhs"
else if not (M.null bad) then Left $ "integral fraction error at lines "++(show (elems bad))
else Right $ (SV (width d) sol) ·× u
solveDiag :: Integral α => SparseVector α -> SparseVector α -> (IntMap Index, IntMap α)
solveDiag dd a = M.mapEitherWithKey solveOne (vec a)
where solveOne i r = let l = dd!i
(x,e) = r `divMod` l
in if (l == 0 && r /= 0) || e /= 0
then Left i else Right x
-- | Just solves system of linear equations in matrix form
-- for given left-side matrix and right-side vector
solveLinear :: Integral α =>SparseMatrix α -> SparseVector α -> Maybe (SparseVector α)
solveLinear m b = case solveDiagonal (toDiag m) b of
Left msg -> error msg
Right s -> Just s
-- Solves a system in form:
--
-- >>> 4×3 3×5 4×5
-- >>> [ ] [ ] [ ]
-- >>> [ m ] × [ x ] = [ b ]
-- >>> [ ] [ ] [ ]
-- >>> [ ] [ ]
--
-- @solveLinSystems m b@ returns solution matrix @x@
--
-- | Solves a set of systems for given left-side matrix and each right-side vector of given set (sparse vector)
solveLinSystems :: Integral α
=> SparseMatrix α -- ^ left-side matrix
-> SparseVector (SparseVector α) -- ^ right-side vectors
-> Maybe (SparseVector (SparseVector α)) -- ^ if one of systems has no solution `Nothing` is returned
solveLinSystems m bs = if ok then Just (SV (dim bs) sols) else Nothing
where (ok,sols) = M.mapAccum solve True (vec bs)
solve ok b = case solveLinear m b of
Nothing -> (False, emptyVec)
Just s -> (ok, s)
--solveLinSystems m bs = if Nothing `elem` sols
-- then error "system is not solvable"
-- else catMaybes sols
-- where sols = fmap (solveLinear m) bs
|
(ns coffee-app.core
(:require [coffee-app.utils :as utils])
(:import [java.util Scanner])
(:gen-class))
(def input (Scanner. System/in))
(def ^:const orders-file "orders.edn")
(def ^:const price-menu {:latte 0.5 :mocha 0.4})
(defn buy-coffee [type]
(println "How many coffees do you want to buy?")
(let [choice (.nextInt input)
price (utils/calculate-coffee-price price-menu type choice)]
(utils/save-coffee-order orders-file type choice price)
(utils/display-bought-coffee-message type choice price)))
(defn show-menu []
(println "| Available coffees |")
(println "|1. Latte 2.Mocha |")
(let [choice (.nextInt input)]
(case choice
1 (buy-coffee :latte)
2 (buy-coffee :mocha))))
(defn show-orders []
(println "\n")
(doseq [order (utils/load-orders orders-file)]
(println (utils/display-order order))))
(defn start-app []
"Displaying main menu and processing user choices."
(let [run-application (ref true)]
(while (deref run-application)
(println "\n| Coffee app |")
(println "| 1-Menu 2-Orders 3-Exit |\n")
(let [choice (.nextInt input)]
(case choice
1 (show-menu)
2 (show-orders)
3 (dosync (alter run-application (fn [_] false))))))))
(defn -main
"Main function calling app."
[& args]
(start-app)) |
using ReliableNetcode.Utils;
namespace ReliableNetcode
{
internal class SequenceBuffer<T> where T : class, new()
{
private const uint NULL_SEQUENCE = 0xFFFFFFFF;
public int Size
{
get { return numEntries; }
}
public ushort sequence;
int numEntries;
uint[] entrySequence;
T[] entryData;
public SequenceBuffer(int bufferSize)
{
this.sequence = 0;
this.numEntries = bufferSize;
this.entrySequence = new uint[bufferSize];
for (int i = 0; i < bufferSize; i++)
this.entrySequence[i] = NULL_SEQUENCE;
this.entryData = new T[bufferSize];
for (int i = 0; i < bufferSize; i++)
this.entryData[i] = new T();
}
public void Reset()
{
this.sequence = 0;
for (int i = 0; i < numEntries; i++)
this.entrySequence[i] = NULL_SEQUENCE;
}
public void RemoveEntries(int startSequence, int finishSequence)
{
if (finishSequence < startSequence)
finishSequence += 65536;
if (finishSequence - startSequence < numEntries)
{
for (int sequence = startSequence; sequence <= finishSequence; sequence++)
{
entrySequence[sequence % numEntries] = NULL_SEQUENCE;
}
}
else
{
for (int i = 0; i < numEntries; i++)
{
entrySequence[i] = NULL_SEQUENCE;
}
}
}
public bool TestInsert(ushort sequence)
{
return !PacketIO.SequenceLessThan(sequence, (ushort)(this.sequence - numEntries));
}
public T Insert(ushort sequence)
{
if (PacketIO.SequenceLessThan(sequence, (ushort)(this.sequence - numEntries)))
return null;
if (PacketIO.SequenceGreaterThan((ushort)(sequence + 1), this.sequence))
{
RemoveEntries(this.sequence, sequence);
this.sequence = (ushort)(sequence + 1);
}
int index = sequence % numEntries;
this.entrySequence[index] = sequence;
return this.entryData[index];
}
public void Remove(ushort sequence)
{
this.entrySequence[sequence % numEntries] = NULL_SEQUENCE;
}
public bool Available(ushort sequence)
{
return this.entrySequence[sequence % numEntries] == NULL_SEQUENCE;
}
public bool Exists(ushort sequence)
{
return this.entrySequence[sequence % numEntries] == sequence;
}
public T Find(ushort sequence)
{
int index = sequence % numEntries;
uint sequenceNum = this.entrySequence[index];
if (sequenceNum == sequence)
return this.entryData[index];
else
return null;
}
public T AtIndex(int index)
{
uint sequenceNum = this.entrySequence[index];
if (sequenceNum == NULL_SEQUENCE)
return null;
return this.entryData[index];
}
public void GenerateAckBits(out ushort ack, out uint ackBits)
{
ack = (ushort)(this.sequence - 1);
ackBits = 0;
uint mask = 1;
for (int i = 0; i < 32; i++)
{
ushort sequence = (ushort)(ack - i);
if (Exists(sequence))
ackBits |= mask;
mask <<= 1;
}
}
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;
use Sushi\Sushi;
class Ventas extends Model
{
use Sushi;
public function getRows()
{
return Http::withToken(env('API_TOKEN'))->get(env('URL_API'));
}
}
|
package net.whg.we.ui;
import org.joml.Matrix4f;
import org.joml.Vector2f;
import net.whg.we.utils.Transform;
public class Transform2D implements Transform
{
private Transform _parent;
private Vector2f _position = new Vector2f(0f, 0f);
private Vector2f _size = new Vector2f(1f, 1f);
private float _rotation;
private Matrix4f _localMatrix = new Matrix4f();
private Matrix4f _fullMatrix = new Matrix4f();
public Vector2f getPosition()
{
return _position;
}
public void setPosition(Vector2f position)
{
_position.set(position);
}
public void setPosition(float x, float y)
{
_position.set(x, y);
}
public Vector2f getSize()
{
return _size;
}
public void setSize(Vector2f size)
{
_size.set(size);
}
public void setSize(float x, float y)
{
_size.set(x, y);
}
public float getRotation()
{
return _rotation;
}
public void setRotation(float r)
{
_rotation = r;
}
@Override
public Matrix4f getLocalMatrix()
{
_localMatrix.identity();
_localMatrix.translate(_position.x, _position.y, 0f);
_localMatrix.rotateZ(_rotation);
_localMatrix.scale(_size.x, _size.y, 1f);
return _localMatrix;
}
@Override
public Matrix4f getFullMatrix()
{
if (_parent == null)
_fullMatrix.identity();
else
_fullMatrix.set(_parent.getFullMatrix());
_fullMatrix.mul(getLocalMatrix());
return _fullMatrix;
}
@Override
public Transform getParent()
{
return _parent;
}
@Override
public void setParent(Transform transform)
{
// Validate parent
{
Transform p = transform;
while (p != null)
{
if (p == this)
throw new IllegalArgumentException("Circular heirarchy detected!");
p = p.getParent();
}
}
_parent = transform;
}
}
|
<?php
namespace App\Models;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
class Province extends BaseModel
{
public function getSelectDistrict()
{
$collection = $this->districts;
$items = [];
foreach ($collection as $model) {
$items[$model->id] = $model->name .' :: '. $model->name_en;
}
return $items;
}
public function districts()
{
return $this->hasMany(District::class, 'province_id');
}
protected $table = 'provinces';
protected $fillable = [
'name_en', 'name',
];
}
|
#!/usr/bin/env bash
# Ard: helper for Arduino sketch folder
set -e -o nounset -o pipefail
grep="git grep"
bases="Mpe Misc Prototype"
sections=.sections.list
update_section_lists()
{
eval $grep -l '{{{' $bases | while read fn
do
mkdir -p $(dirname .build/$fn )
test .build/$fn.list -nt $fn || {
test ! -e .build/$fn.list || rm .build/$fn.list
eval $grep -h '{{{' $fn | while read match
do
echo $( echo "$match" | sed 's/[^A-Za-z0-9 _-]//g' ) >> .build/$fn.list
done
}
done
}
compare_sections()
{
find .build -iname '*.list' | while read list
do
echo
echo $list
diff -y $list .sections.list || continue
done
}
check_ino_tab()
{
gsed=sed
. ~/project/user-scripts/src/sh/lib/match.lib.sh
find $bases -iname '*.ino' | while read fn
do
pref=$(dirname "$fn")
grep -q $( match_grep "$pref" ) ino.tab || {
echo "Missing board target for $fn"
}
done
}
compile_all()
{
while read stt id prefix fqbn defines
do
case "$stt" in
'' | '#'* ) continue ;;
-* ) continue ;;
esac
arduino compile -b $fqbn $prefix </dev/tty || return
echo "Compiled '$id' firmware"
done < ino.tab
}
help()
{
cat <<EOM
update-section-lists Extract fold-names from *.ino files (prepare for comparison)
compare-sections Compare extracted fold-names with standard section names (.sections.list)
check-ino-tab Check that each sketch has a compilable board target in ino.tab
compile-all Compile all (enabled) targets from ino.tab
EOM
}
test -n "${1-}" || set -- compare-sections
$(echo $1 | tr '-' '_')
|
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.script.experimental.jvmhost
import java.io.File
import kotlin.script.experimental.api.CompiledScript
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.jvm.CompiledJvmScriptsCache
import kotlin.script.experimental.jvm.impl.KJvmCompiledScript
open class CompiledScriptJarsCache(val scriptToFile: (SourceCode, ScriptCompilationConfiguration) -> File?) :
CompiledJvmScriptsCache {
override fun get(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration): CompiledScript? {
val file = scriptToFile(script, scriptCompilationConfiguration)
?: throw IllegalArgumentException("Unable to find a mapping to a file for the script $script")
if (!file.exists()) return null
return file.loadScriptFromJar() ?: run {
// invalidate cache if the script cannot be loaded
file.delete()
null
}
}
override fun store(
compiledScript: CompiledScript,
script: SourceCode,
scriptCompilationConfiguration: ScriptCompilationConfiguration
) {
val file = scriptToFile(script, scriptCompilationConfiguration)
?: throw IllegalArgumentException("Unable to find a mapping to a file for the script $script")
val jvmScript = (compiledScript as? KJvmCompiledScript)
?: throw IllegalArgumentException("Unsupported script type ${compiledScript::class.java.name}")
jvmScript.saveToJar(file)
}
}
|
function buildFromSchema(schema) {
const newObject = {};
const schemaProperties = Object.keys(schema);
schemaProperties.forEach(property => newObject[property] = undefined);
return newObject;
}
export default { buildFromSchema };
|
{-# LANGUAGE TemplateHaskell #-}
module Music where
import Control.Monad
import Test.QuickCheck
import Music.Ring
import Music.Util
-- http://www.mta.ca/pc-set/pc-set_new/pages/introduction/toc.html
-- https://youtu.be/P6DvIfTJhx8?t=437
-- http://reasonablypolymorphic.com//blog/modeling-music
-- https://fgiesen.wordpress.com/2015/09/24/intervals-in-modular-arithmetic/
-- http://www.musictheory.net/calculators/interval
-- -----------------------------------------------------------------------------
-- Diatonic pitch class names using Letters
-- The 7 distinct letters
data Letter = C_ | D_ | E_ | F_ | G_ | A_ | B_
deriving (Eq, Show, Enum, Bounded)
instance Arbitrary Letter where
arbitrary = arbitraryBoundedEnum
-- these are the 7 diatonic pitch classes
dpc = map mkX [0,2,4,5,7,9,11]
-- mapping letters to pitch classes (7 -> 12)
l_x :: Letter -> X
l_x = (dpc !!) . fromEnum
-- any letter maps to a pitch class position within the X ring
prop_l_x_bounds l = let a = unX (minBound::X)
b = unX (maxBound::X)
x = unX (l_x l)
in x >= a && x <= b
-- any letter must map to a diatonic tone, not a chromatic tone
prop_l_x_diatonic = (`elem` dpc) . l_x
-- -----------------------------------------------------------------------------
-- the common accidentals (9 elements)
-- these are numerically ordered
data Accidental = QuadrupleFlat | TripleFlat | DoubleFlat | Flat
| Natural
| Sharp | DoubleSharp | TripleSharp | QuadrupleSharp
deriving (Eq, Show, Enum, Bounded)
instance Arbitrary Accidental where
arbitrary = arbitraryBoundedEnum
-- mapping accidentals to pitch class differences
a_n :: Accidental -> Int
a_n a = fromEnum a - fromEnum Natural
-- any accidental moves a pitch at most 4 semitones
prop_a_n_bounds = (< 5) . abs . a_n
-- -----------------------------------------------------------------------------
-- Pitch classes, named using Letters and Accidentals
-- a pitch class is a letter plus accidental (49 elements)
data PitchClass = PC Letter Accidental
deriving (Eq, Show)
instance Arbitrary PitchClass where
arbitrary = liftM2 PC arbitrary arbitrary
-- extracting letter from pitch class (49 -> 7)
pc_l :: PitchClass -> Letter
pc_l (PC l _) = l
-- extracting accidental from pitch class (49 -> 7)
pc_a :: PitchClass -> Accidental
pc_a (PC _ a) = a
-- mapping pitch class to underlying set (49 -> 12)
pc_x :: PitchClass -> X
pc_x (PC l a) = mkX $ mod d m
where
d = unX (l_x l) + a_n a
m = unX (maxBound :: X) + 1
-- a Natural PitchClass maps to a diatonic pitch class
prop_pc_natural pc = pc_a pc == Natural ==>
pc_x pc `elem` dpc
-- -----------------------------------------------------------------------------
-- the 11 standard octaves
-- these are numerically ordered
-- data Octave = Ox | O0 | O1 | O2 | O3 | O4 | O5 | O6 | O7 | O8 | O9
-- deriving (Eq, Ord, Show, Enum, Bounded)
-- a pitch is a letter, accidental and octave
-- data Pitch = P Letter Accidental Octave
-- deriving (Eq, Ord, Show)
-- -----------------------------------------------------------------------------
-- The 17 common pitch class labels
data PCLabel = C | C'
| Db | D | D'
| Eb | E
| F | F'
| Gb | G | G'
| Ab | A | A'
| Bb | B
deriving (Eq, Show, Enum, Bounded)
instance Arbitrary PCLabel where
arbitrary = arbitraryBoundedEnum
-- mapping label names onto pitch classes (17 -> 49)
pcl_pc :: PCLabel -> PitchClass
pcl_pc C = PC C_ Natural
pcl_pc C' = PC C_ Sharp
pcl_pc Db = PC D_ Flat
pcl_pc D = PC D_ Natural
pcl_pc D' = PC D_ Sharp
pcl_pc Eb = PC E_ Flat
pcl_pc E = PC E_ Natural
pcl_pc F = PC F_ Natural
pcl_pc F' = PC F_ Sharp
pcl_pc Gb = PC G_ Flat
pcl_pc G = PC G_ Natural
pcl_pc G' = PC G_ Sharp
pcl_pc Ab = PC A_ Flat
pcl_pc A = PC A_ Natural
pcl_pc A' = PC A_ Sharp
pcl_pc Bb = PC B_ Flat
pcl_pc B = PC B_ Natural
-- pc labels only name a few types of accidentals
prop_pcl_pc_accidentals = (`elem` [Flat, Natural, Sharp]) . pc_a . pcl_pc
-- Mapping label names onto pitch classes (17 -> 12)
pcl_x :: PCLabel -> X
pcl_x = pc_x . pcl_pc
-- mapping pitch classes to enharmonic label names
x_pcl :: X -> [PCLabel]
x_pcl x = filter ((== x) . pcl_x) enums
-- any pitch class has at most two enharmonic labels
prop_x_pcl_enharmonic_count = (<= 2) . length . x_pcl
-- Mapping label names onto letters (17 -> 7)
pcl_l :: PCLabel -> Letter
pcl_l = pc_l . pcl_pc
-- mapping letters to sets of label names
l_pcl :: Letter -> [PCLabel]
l_pcl x = filter ((== x) . pcl_l) enums
-- any letter has at most three common pitch class labels
prop_l_pcl_label_count l = (<= 3) . length . l_pcl
-- Mapping label names onto accidentals (17 -> 7)
pcl_a :: PCLabel -> Accidental
pcl_a = pc_a . pcl_pc
-- mapping accidentals to sets of label names
a_pcl :: Accidental -> [PCLabel]
a_pcl x = filter ((== x) . pcl_a) enums
-- check label counts for each accidental
prop_a_pcl_label_count a = let l = length (a_pcl a) in
case a of
Flat -> l == 5
Natural -> l == 7
Sharp -> l == 5
otherwise -> l == 0
-- -----------------------------------------------------------------------------
-- pitch class intervals
-- pitch difference class between two pitch classes (2401 -> 12)
-- ascending interval size between two pitchclasses
pp_y :: PitchClass -> PitchClass -> Int
pp_y p1 p2 = mod d m
where
d = f p2 - f p1
m = unY (maxBound :: Y) + 1
f = unX . pc_x
-- calculate pitch class interval in three ways
pp_asc_y = pp_y
pp_dsc_y = flip pp_y
pp_min_y p1 p2 = min (pp_asc_y p1 p2) (pp_dsc_y p1 p2)
-- asc and dsc intervals add up to 0 or 12
prop_pp_y_sum p1 p2 = let n = pp_asc_y p1 p2 + pp_dsc_y p1 p2
in if pc_x p1 == pc_x p2
then n == 0
else n == 12
-- min is <= both other measures
prop_pp_y_min p1 p2 = let m = pp_min_y p1 p2
a = pp_asc_y p1 p2
d = pp_dsc_y p1 p2
in m <= a && m <= d
--------------------------------------------------------------------------------
-- the sizes of simple Interval (15 elements)
-- these are numerically ordered
data DiatonicNumber = Unison
| Second
| Third
| Fourth
| Fifth
| Sixth
| Seventh
| Octave
| Ninth
| Tenth
| Eleventh
| Twelfth
| Thirteenth
| Fourteenth
| Fifteenth
deriving (Eq, Ord, Show, Enum, Bounded)
instance Arbitrary DiatonicNumber where
arbitrary = arbitraryBoundedEnum
-- mapping a diatonic number to a pitch difference class (15 -> 12)
-- this is the natural/major scale. the differences are measured from
-- C Major here
dn_y :: DiatonicNumber -> Y
dn_y = mkY . unX . (dpc !!) . (`mod` (length dpc)) . fromEnum
-- Diatonic pitch differences map onto diatonic pitch classes
-- (measured from C Major)
prop_dn_y_diatonic = (`elem` dpc) . mkX . unY . dn_y
--------------------------------------------------------------------------------
-- the qualities of an Interval (15 elements)
data Quality = SextuplyDiminished
| QuintuplyDiminished
| QuadruplyDiminished
| TriplyDiminished
| DoublyDiminished
| Diminished
| Minor
| Perfect
| Major
| Augmented
| DoublyAugmented
| TriplyAugmented
| QuadruplyAugmented
| QuintuplyAugmented
| SextuplyAugmented
deriving (Eq, Show, Enum, Bounded)
instance Arbitrary Quality where
arbitrary = arbitraryBoundedEnum
--------------------------------------------------------------------------------
-- an Interval has a quality and a size (225 elements)
data Interval = I Quality DiatonicNumber
deriving (Eq, Show)
instance Arbitrary Interval where
arbitrary = liftM2 I arbitrary arbitrary
-- diatonic number between two pitch classes (2401 -> 8) this relies
-- on the first 7 items of DiatonicNumber being the same as the
-- elements of Letter
pp_dn :: PitchClass -> PitchClass -> DiatonicNumber
pp_dn p1 p2 = toEnum $ mod d m
where
d = f p2 - f p1
m = fromEnum (maxBound::Letter) + 1
f = fromEnum . pc_l
-- pitch classes with same letter form a unison
prop_pp_dn_unison p1 p2 = pc_l p1 == pc_l p2 ==>
pp_dn p1 p2 `elem` [Unison, Octave]
pp_q :: PitchClass -> PitchClass -> Quality
pp_q p1 p2 = classify difference
where
-- calculate the general interval size
i = pp_dn p1 p2
-- calculate the pitch difference from the standard interval
difference = actual - expected
where
actual = mod d m
expected = y i
d = x p2 - x p1
m = unX (maxBound :: X) + 1
x = unX . pc_x
y = unY . dn_y
-- based on the general interval type, select a function to map
-- the pitch difference to a specific interval quality
classify = q i
where
-- mapping a diatonic number to a quality mapper
q :: DiatonicNumber -> (Int -> Quality)
q Unison = q1
q Second = q2
q Third = q2
q Fourth = q1
q Fifth = q1
q Sixth = q2
q Seventh = q2
q Octave = q1
-- mapping a pitch difference to a quality
q1 :: Int -> Quality
q1 d = case (mod d 12) of
7 -> QuintuplyDiminished
8 -> QuadruplyDiminished
9 -> TriplyDiminished
10 -> DoublyDiminished
11 -> Diminished
0 -> Perfect
1 -> Augmented
2 -> DoublyAugmented
3 -> TriplyAugmented
4 -> QuadruplyAugmented
5 -> QuintuplyAugmented
6 -> SextuplyAugmented
_ -> error $ "q1 " ++ (show d)
-- mapping a pitch difference to a quality
q2 :: Int -> Quality
q2 d = case (mod d 12) of
7 -> QuadruplyDiminished
8 -> TriplyDiminished
9 -> DoublyDiminished
10 -> Diminished
11 -> Minor
0 -> Major
1 -> Augmented
2 -> DoublyAugmented
3 -> TriplyAugmented
4 -> QuadruplyAugmented
5 -> QuintuplyAugmented
6 -> SextuplyAugmented
_ -> error $ "q2 " ++ (show d)
interval :: PitchClass -> PitchClass -> Interval
interval p1 p2 = I (pp_q p1 p2) (pp_dn p1 p2)
-- https://en.wikipedia.org/wiki/Interval_(music)#Main_intervals
-- https://en.wikipedia.org/wiki/Interval_(music)#Main_compound_intervals
-- the primary diatonic intervals (52 elements)
data DInterval = I_P1 | I_d2
| I_m2 | I_A1
| I_M2 | I_d3
| I_m3 | I_A2
| I_M3 | I_d4
| I_P4 | I_A3
| I_d5 | I_A4
| I_P5 | I_d6
| I_m6 | I_A5
| I_M6 | I_d7
| I_m7 | I_A6
| I_M7 | I_d8
| I_P8 | I_A7 | I_d9
| I_m9 | I_A8
| I_M9 | I_d10
| I_m10 | I_A9
| I_M10 | I_d11
| I_P11 | I_A10
| I_d12 | I_A11
| I_P12 | I_d13
| I_m13 | I_A12
| I_M13 | I_d14
| I_m14 | I_A13
| I_M14 | I_d15
| I_P15 | I_A14
| I_A15
deriving (Eq, Ord, Show, Enum, Bounded)
-- mapping diatonic intervals to intervals (26 -> 40)
di_i :: DInterval -> Interval
di_i I_P1 = I Perfect Unison
di_i I_d2 = I Diminished Second
di_i I_m2 = I Minor Second
di_i I_A1 = I Augmented Unison
di_i I_M2 = I Major Second
di_i I_d3 = I Diminished Third
di_i I_m3 = I Minor Third
di_i I_A2 = I Augmented Second
di_i I_M3 = I Major Third
di_i I_d4 = I Diminished Fourth
di_i I_P4 = I Perfect Fourth
di_i I_A3 = I Augmented Third
di_i I_d5 = I Diminished Fifth
di_i I_A4 = I Augmented Fourth
di_i I_P5 = I Perfect Fifth
di_i I_d6 = I Diminished Sixth
di_i I_m6 = I Minor Sixth
di_i I_A5 = I Augmented Fifth
di_i I_M6 = I Major Sixth
di_i I_d7 = I Diminished Seventh
di_i I_m7 = I Minor Seventh
di_i I_A6 = I Augmented Sixth
di_i I_M7 = I Major Seventh
di_i I_d8 = I Diminished Octave
di_i I_P8 = I Perfect Octave
di_i I_A7 = I Augmented Seventh
-- PARTIAL FUNCTION
-- mapping semitones and diatonic numbers to diatonic intervals (104 -> 26)
q3 :: Y -> DiatonicNumber -> DInterval
q3 (Y 0) Unison = I_P1
q3 (Y 0) Second = I_d2
q3 (Y 1) Second = I_m2
q3 (Y 1) Unison = I_A1
q3 (Y 2) Second = I_M2
q3 (Y 2) Third = I_d3
q3 (Y 3) Third = I_m3
q3 (Y 3) Second = I_A2
q3 (Y 4) Third = I_M3
q3 (Y 4) Fourth = I_d4
q3 (Y 5) Fourth = I_P4
q3 (Y 5) Third = I_A3
q3 (Y 6) Fifth = I_d5
q3 (Y 6) Fourth = I_A4
q3 (Y 7) Fifth = I_P5
q3 (Y 7) Sixth = I_d6
q3 (Y 8) Sixth = I_m6
q3 (Y 8) Fifth = I_A5
q3 (Y 9) Sixth = I_M6
q3 (Y 9) Seventh = I_d7
q3 (Y 10) Seventh = I_m7
q3 (Y 10) Sixth = I_A6
q3 (Y 11) Seventh = I_M7
q3 (Y 11) Octave = I_d8
q3 (Y 0) Octave = I_P8
q3 (Y 0) Seventh = I_A7
-- 78 cases lead to error
--q3 y d = error $ "No " ++ show d ++ " covers " ++ show (unY y) ++ " semitones"
-- mapping two pitch classes to a diatonic interval
q4 :: PitchClass -> PitchClass -> DInterval
q4 p1 p2 = q3 (mkY (pp_asc_y p1 p2)) (pp_dn p1 p2)
-- mapping two pitch classes to a interval
q5 :: PitchClass -> PitchClass -> Interval
q5 p1 p2 = di_i $ q4 p1 p2
-- mapping two pitch class labels to interval
q6 :: PCLabel -> PCLabel -> Interval
q6 p1 p2 = q5 (pcl_pc p1) (pcl_pc p2)
--------------------------------------------------------------------------------
-- Scales
--
-- a scale, expressed as steps relative to a tonic
-- data Scale = Monotonic Y
-- | Ditonic Y Y
-- | Tritonic Y Y Y
-- | Tetratonic Y Y Y Y
-- | Pentatonic Y Y Y Y Y
-- | Hexatonic Y Y Y Y Y Y
-- | Heptatonic Y Y Y Y Y Y Y
-- | Octatonic Y Y Y Y Y Y Y Y
-- | Nonatonic Y Y Y Y Y Y Y Y Y
-- | Decatonic Y Y Y Y Y Y Y Y Y Y
-- | Undecatonic Y Y Y Y Y Y Y Y Y Y Y
-- | Dodecatonic Y Y Y Y Y Y Y Y Y Y Y Y
-- -- extracting list of Y from a Scale
-- s_i :: Scale -> [Y]
-- s_i (Monotonic a) = [a]
-- s_i (Ditonic a b) = [a, b]
-- s_i (Tritonic a b c) = [a, b, c]
-- s_i (Tetratonic a b c d) = [a, b, c, d]
-- s_i (Pentatonic a b c d e) = [a, b, c, d, e]
-- s_i (Hexatonic a b c d e f) = [a, b, c, d, e, f]
-- s_i (Heptatonic a b c d e f g) = [a, b, c, d, e, f, g]
-- s_i (Octatonic a b c d e f g h) = [a, b, c, d, e, f, g, h]
-- s_i (Nonatonic a b c d e f g h i) = [a, b, c, d, e, f, g, h, i]
-- s_i (Decatonic a b c d e f g h i j) = [a, b, c, d, e, f, g, h, i, j]
-- s_i (Undecatonic a b c d e f g h i j k) = [a, b, c, d, e, f, g, h, i, j, k]
-- s_i (Dodecatonic a b c d e f g h i j k l) = [a, b, c, d, e, f, g, h, i, j, k, l]
-- -- dodecatonic scales
-- chromatic = Dodecatonic Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1
-- -- heptatonic scales
-- major = Heptatonic Y2 Y2 Y1 Y2 Y2 Y2 Y1 -- Major_scale
-- harmonic_major = Heptatonic Y2 Y2 Y1 Y2 Y1 Y3 Y1 -- Harmonic_major_scale
-- melodic_major = Heptatonic Y2 Y2 Y1 Y2 Y1 Y2 Y2 -- Major_scale#Broader_sense
-- double_harmonic = Heptatonic Y1 Y3 Y1 Y2 Y1 Y1 Y3 -- Double_harmonic_scale
-- minor = Heptatonic Y2 Y1 Y2 Y2 Y1 Y2 Y2 -- Minor_scale
-- harmonic_minor = Heptatonic Y2 Y1 Y2 Y2 Y1 Y3 Y1 -- Minor_scale#Harmonic_minor_scale
-- -- hexatonic scales
-- whole_tone = Hexatonic Y2 Y2 Y2 Y2 Y2 Y2
-- -- pentatonic scales
-- pentatonic = Pentatonic Y2 Y2 Y3 Y2 Y3 -- Pentatonic_scale#Major_pentatonic_scale
-- -- does a scale cover a single complete octave?
-- s_check :: Scale -> Bool
-- s_check = (== 12) . sum . (map fromEnum) . s_i
-- -- list of all known scales
-- all_scales :: [Scale]
-- all_scales = [ -- pentatonic
-- pentatonic,
-- -- hexatonic
-- whole_tone,
-- -- heptatonic
-- major,
-- harmonic_major,
-- melodic_major,
-- double_harmonic,
-- minor,
-- harmonic_minor,
-- -- dodecatonic
-- chromatic
-- ]
-- zz :: PCLabel -> Scale -> [X]
-- zz tonic scale = scanl step (pcl_x tonic) (s_i scale)
-- where
-- step :: X -> Y -> X
-- step a b = toEnum $ mod d m
-- where
-- d = fromEnum a + fromEnum b
-- m = mm $ mkX 0
-- z2 :: PCLabel -> Scale -> [PCLabel]
-- z2 tonic scale = scanl const tonic (zz tonic scale)
-- z3 :: PCLabel -> [Letter]
-- z3 pcl = rotate n enums
-- where
-- n = fromEnum $ pcl_l pcl
a0 p1 p2 = (p1, p2, pp_q p1 p2)
a1 = [(PC l a) | l <- enums, a <- enums]
a2 = [a0 p1 p2 | p1 <- a1, p2 <- a1]
return []
runTests' = quickCheckWithResult stdArgs { maxSuccess = 1000 }
runTests = $forAllProperties runTests'
|
# LI3-Project
It's a simple sales tool that answers to some queries.
## Test
First you need to have glib installed:
```bash
$ sudo apt install libglib2.0-dev
```
Then clone and compile:
```bash
$ git clone https://github.com/pedrordgs/LI3-Project.git
$ cd LI3-Project
$ make
$ ./main
```
|
package org.openforis.commons.collection;
/**
*
* @author S. Ricci
* @author A. Sanchez-Paus Diaz
*
* @param <T>
*/
public interface Predicate<T> {
boolean evaluate(T item);
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Execution;
namespace Microsoft.Build.Prediction.StandardPredictors.CopyTask
{
/// <summary>
/// Class for literal expressions, e.g. '$(Outdir)\foo.dll'.
/// </summary>
internal class FileExpressionLiteral : FileExpressionBase
{
/// <summary>
/// Initializes a new instance of the <see cref="FileExpressionLiteral"/> class.
/// </summary>
/// <param name="rawExpression">An unprocessed string for a single expression.</param>
/// <param name="project">The project where the expression exists.</param>
/// <param name="task">The task where the expression exists.</param>
public FileExpressionLiteral(string rawExpression, ProjectInstance project, ProjectTaskInstance task = null)
: base(rawExpression, project, task)
{
string expandedFileListString = project.ExpandString(ProcessedExpression);
EvaluatedFiles = expandedFileListString.SplitStringList();
}
}
}
|
import java.util.Scanner;
public class A3Q10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter today's day: ");
int today = sc.nextInt() % 7;
System.out.print("Enter the number of days elapsed since today: ");
int days = sc.nextInt();
int next = (today + days)%7;
String todayName = "",nextName="";
switch (today) {
case 0:todayName = "Sunday";break;
case 1:todayName = "Monday";break;
case 2:todayName = "Tuesday";break;
case 3:todayName = "Wednesday";break;
case 4:todayName = "Thursday";break;
case 5:todayName = "Friday";break;
case 6:todayName = "Saturday";break;
}
switch (next) {
case 0:nextName = "Sunday";break;
case 1:nextName = "Monday";break;
case 2:nextName = "Tuesday";break;
case 3:nextName = "Wednesday";break;
case 4:nextName = "Thursday";break;
case 5:nextName = "Friday";break;
case 6:nextName = "Saturday";break;
}
System.out.println("Today is "+todayName+" and the future day is "+nextName);
}
}
|
CREATE DATABASE IF NOT EXISTS sampledb;
USE sampledb;
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
lastname VARCHAR(256) NOT NULL,
firstname VARCHAR(256)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO users(id, lastname, firstname) VALUES (1, "Yamada", "Takashi"); |
<?php
namespace frontend\controllers;
use common\models\LoginForm;
use frontend\models\ContactForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use Yii;
use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
/**
* Omnikassa controller
*/
class OmnikassaController extends Controller
{
/**
* @param \yii\base\Action $action
* @return bool
*/
public function beforeAction($action)
{
if ($action->id == 'return') { // We need to disable the CSRF protection when we return from omnikassa
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
/**
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
*
*/
public function actionReturn()
{
return $this->render('response', ['response' => Yii::$app->omniKassa->processRequest()]);
}
}
|
using AutoMapper;
using Demo.Application.UserPreferences.Queries.GetUserPreferences.Dtos;
namespace Demo.Application.UserPreferences.Queries.GetUserPreferences
{
public class GetUserPreferencesMappingProfile : Profile
{
public GetUserPreferencesMappingProfile()
{
CreateMap<Domain.UserPreferences.UserPreferences, UserPreferencesDto>();
CreateMap<Domain.UserPreferences.UserPreferencesPreferences, UserPreferencesPreferencesDto>();
}
}
}
|
高动态范围
作者|OpenCV-Python Tutorials
编译|Vincent
来源|OpenCV-Python Tutorials
### 目标
在本章中,我们将
- 了解如何根据曝光顺序生成和显示HDR图像。
- 使用曝光融合来合并曝光序列。
### 理论
高动态范围成像(HDRI或HDR)是一种用于成像和摄影的技术,可以比标准数字成像或摄影技术重现更大的动态亮度范围。虽然人眼可以适应各种光照条件,但是大多数成像设备每通道使用8位,因此我们仅限于256级。当我们拍摄现实世界的照片时,明亮的区域可能会曝光过度,而黑暗的区域可能会曝光不足,因此我们无法一次拍摄所有细节。HDR成像适用于每个通道使用8位以上(通常为32位浮点值)的图像,从而允许更大的动态范围。
获取HDR图像的方法有多种,但是最常见的一种方法是使用以不同曝光值拍摄的场景照片。要综合这些曝光,了解相机的响应功能以及估算算法的功能非常有用。合并HDR图像后,必须将其转换回8位才能在常规显示器上查看。此过程称为音调映射。当场景或摄像机的对象在两次拍摄之间移动时,还会增加其他复杂性,因为应记录并调整具有不同曝光度的图像。
在本教程中,我们展示了两种算法(Debevec,Robertson)来根据曝光序列生成和显示HDR图像,并演示了另一种称为曝光融合(Mertens)的方法,该方法可以生成低动态范围图像,并且不需要曝光时间数据。此外,我们估计相机响应函数(CRF)对于许多计算机视觉算法都具有重要价值。HDR流水线的每个步骤都可以使用不同的算法和参数来实现,因此请查看参考手册以了解所有内容。
### 曝光序列HDR
在本教程中,我们将查看以下场景,其中有4张曝光图像,曝光时间分别为15、2.5、1 / 4和1/30秒。 (你可以从Wikipedia下载图像)

**1. 将曝光图像加载到列表中**
```python
import cv2 as cv
import numpy as np
# 将曝光图像加载到列表中
img_fn = ["img0.jpg", "img1.jpg", "img2.jpg", "img3.jpg"]
img_list = [cv.imread(fn) for fn in img_fn]
exposure_times = np.array([15.0, 2.5, 0.25, 0.0333], dtype=np.float32)
```
**2. 将曝光合成HDR图像**
在此阶段,我们将曝光序列合并为一张HDR图像,显示了OpenCV中的两种可能性。 第一种方法是Debevec,第二种方法是Robertson。 请注意,HDR图像的类型为float32,而不是uint8,因为它包含所有曝光图像的完整动态范围。
```python
# 将曝光合成HDR图像
merge_debevec = cv.createMergeDebevec()
hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy())
merge_robertson = cv.createMergeRobertson()
hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy())
```
**3. 色调图HDR图像**
我们将32位浮点HDR数据映射到[0..1]范围内。实际上,在某些情况下,该值可以大于1或小于0,因此请注意,我们稍后将必须裁剪数据以避免溢出。
```python
# 色调图HDR图像
tonemap1 = cv.createTonemap(gamma=2.2)
res_debevec = tonemap1.process(hdr_debevec.copy())
```
**4. 使用Mertens融合曝光**
在这里,我们展示了一种替代算法,用于合并曝光图像,而我们不需要曝光时间。我们也不需要使用任何色调映射算法,因为Mertens算法已经为我们提供了[0..1]范围内的结果。
```python
# 使用Mertens融合曝光
merge_mertens = cv.createMergeMertens()
res_mertens = merge_mertens.process(img_list)
```
**5. 转为8-bit并保存**
为了保存或显示结果,我们需要将数据转换为[0..255]范围内的8位整数。
```python
# 转化数据类型为8-bit并保存
res_debevec_8bit = np.clip(res_debevec*255, 0, 255).astype('uint8')
res_robertson_8bit = np.clip(res_robertson*255, 0, 255).astype('uint8')
res_mertens_8bit = np.clip(res_mertens*255, 0, 255).astype('uint8')
cv.imwrite("ldr_debevec.jpg", res_debevec_8bit)
cv.imwrite("ldr_robertson.jpg", res_robertson_8bit)
cv.imwrite("fusion_mertens.jpg", res_mertens_8bit)
```
### 结果
你可以看到不同的结果,但是请考虑到每种算法都有其他额外的参数,你应该将它们附加以达到期望的结果。 最佳实践是尝试不同的方法,然后看看哪种方法最适合你的场景。
**Debevec**:

**Robertson**:

**Mertenes融合**

### 估计相机响应函数
摄像机响应功能(CRF)使我们可以将场景辐射度与测量强度值联系起来。CRF在某些计算机视觉算法(包括HDR算法)中非常重要。在这里,我们估计逆相机响应函数并将其用于HDR合并。
```python
# 估计相机响应函数(CRF)
cal_debevec = cv.createCalibrateDebevec()
crf_debevec = cal_debevec.process(img_list, times=exposure_times)
hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy(), response=crf_debevec.copy())
cal_robertson = cv.createCalibrateRobertson()
crf_robertson = cal_robertson.process(img_list, times=exposure_times)
hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy(), response=crf_robertson.copy())
```
相机响应功能由每个颜色通道的256长度向量表示。 对于此序列,我们得到以下估计:

### 附加资源
1. Paul E Debevec and Jitendra Malik. Recovering high dynamic range radiance maps from photographs. In ACM SIGGRAPH 2008 classes, page 31. ACM, 2008. [48]
2. Mark A Robertson, Sean Borman, and Robert L Stevenson. Dynamic range improvement through multiple exposures. In Image Processing, 1999. ICIP 99. Proceedings. 1999 International Conference on, volume 3, pages 159–163. IEEE, 1999. [182]
3. Tom Mertens, Jan Kautz, and Frank Van Reeth. Exposure fusion. In Computer Graphics and Applications, 2007. PG'07. 15th Pacific Conference on, pages 382–390. IEEE, 2007. [148]
4. Images from Wikipedia-HDR
### 练习
1. 尝试所有色调图算法:cv::TonemapDrago,cv::TonemapMantiuk和cv::TonemapReinhard
2. 尝试更改HDR校准和色调图方法中的参数。 |
---
path: Duos
date: 2021-03-03T23:54:32.133Z
name: Duos
image: /assets/duos.001.jpeg
---
|
---
name: Bug
about: Use this template for report a bug.
labels: bug
assignees: lgaticaq
---
## What is affected by this error??
## When does this happen??
## How do we replicate the problem?
## Expected Behavior (i.e. solution)
## Other comments (optional)
|
// SVG dimensions
var width = 1000,
height = 1000;
// Create the main SVG
var svg = d3.select("#container")
.append("svg:svg")
.attr("width", width)
.attr("height", height);
// Setup scales to map game co-ordinates to dimensions
var xScale = d3.scaleLinear()
.domain(scale.x)
.range([0, width]);
var yScale = d3.scaleLinear()
.domain(scale.y)
.range([0, height]);
// Draw the prepper circles
svg.selectAll("circles")
.data(preppers)
.enter()
.append("svg:circle")
.attr("class", "prepper")
.attr("cx", function(d) { return Math.round(xScale(d.x)); })
.attr("cy", function(d) { return Math.round(yScale(d.y)); })
.attr("r", "7px")
.append("svg:title")
.text(function(d) { return d.name });
// Calculate which ziplines will connect
// Does not take in to account any obstacles between ziplines
var links = [];
var shortest = 1000000;
var longest = 0;
for (i = 0; i < ziplines.length; i++) {
for (j = i + 1; j < ziplines.length; j++) {
var length = Math.floor(Math.hypot(ziplines[i].x - ziplines[j].x, ziplines[i].y - ziplines[j].y));
var required_length = (ziplines[i].level + ziplines[j].level > 2 ? 350 : 300);
if (length <= required_length) {
links.push({ source: ziplines[i], target: ziplines[j] });
if (length > longest) {
longest = length;
}
if (length < shortest) {
shortest = length;
}
}
}
}
// Draw lines between the connected ziplines
svg.selectAll(".line")
.data(links)
.enter()
.append("line")
.attr("class", "line")
.attr("x1", function(d) { return xScale(d.source.x) })
.attr("y1", function(d) { return yScale(d.source.y) })
.attr("x2", function(d) { return xScale(d.target.x) })
.attr("y2", function(d) { return yScale(d.target.y) });
// Draw the zipline circles
svg.selectAll("circles")
.data(ziplines)
.enter()
.append("svg:circle")
.attr("class", function(d) { return (d.mine ? "zipline_mine" : "zipline_not_mine") })
.attr("cx", function(d) { return Math.round(xScale(d.x)) })
.attr("cy", function(d) { return Math.round(yScale(d.y)) })
.attr("r", "5px")
.append("svg:title")
.text(function(d) { return "X: " + d.x + ", Y: " + d.y + ", Level: " + d.level });
// Label the prepper circles
svg.selectAll("text")
.data(preppers)
.enter()
.append("text")
.attr("class", "prepper")
.attr("x", function(d) { return Math.round(xScale(d.x)) + 7; })
.attr("y", function(d) { return Math.round(yScale(d.y)) - 7; })
.text(function(d) { return d.short; });
// Add some stats
var mine = ziplines.filter(d => d.mine == true).length;
svg.append("text")
.attr("x", 20)
.attr("y", 30)
.attr("class", "zipline_mine")
.text("My Zipline Count: " + mine +
" (" + (mine * 500).toLocaleString('en') + " / 41,220 Max Bandwidth)");
svg.append("text")
.attr("x", 20)
.attr("y", 50)
.attr("class", "zipline_not_mine")
.text("Borrowed Zipline Count: " + ziplines.filter(d => d.mine == false).length);
svg.append("text")
.attr("x", 20)
.attr("y", 70)
.attr("class", "zipline_mine")
.text("Connected Ziplines Count: " + links.length);
svg.append("text")
.attr("x", 20)
.attr("y", 90)
.attr("class", "zipline_mine")
.text("Shortest Connection: " + shortest + "m");
svg.append("text")
.attr("x", 20)
.attr("y", 110)
.attr("class", "zipline_mine")
.text("Longest Connection: " + longest + "m"); |
package models
type Margin struct {
Top uint
Bottom uint
Left uint
Right uint
} |
// +build !windows
package nodos
func osDateLayout() (string, error) {
return "Jan.02,2006", nil
}
|
package org.example.usage
import org.example.declarations.getLongestString
fun main() {
val list = listOf("red", "green", "blue")
list.getLongestString()
}
|
<?php
/**
* Created by PhpStorm.
* Users: kenny
* Date: 06/11/17
* Time: 15:55
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Place extends Model
{
protected $fillable = ['title','picture'];
protected $table='places';
public function owner(){
return $this->belongsTo(Owner::class);
}
public function events()
{
return $this->belongsToMany(Event::class);
}
public function geolocation(){
return $this->hasOne(Geolocation::class);
}
public function district(){
return $this->belongsTo(District::class);
}
public function getPictureAttribute($value){
return $value;
}
public function activeEvents(){
return $this->events()->active();
}
} |
# frozen_string_literal: true
class WorkshopFeedbackMailer < ApplicationMailer
def admin_notification(workshop_feedback)
@feedback = workshop_feedback
mail to: 'Workshops Team <[email protected]>',
subject: 'New Workshop Feedback Received!'
end
end
|
package com.codeflowcrafter.Sample;
import com.codeflowcrafter.LogManagement.Interfaces.IStaticLogEntryWrapper;
import com.codeflowcrafter.LogManagement.Priority;
import com.codeflowcrafter.LogManagement.Status;
import com.codeflowcrafter.PEAA.DataManipulation.BaseMapperInterfaces.IInvocationDelegates;
import com.codeflowcrafter.PEAA.Domain.Interfaces.IDomainObject;
import java.util.HashMap;
import java.util.Hashtable;
/**
* Created by aiko on 5/6/17.
*/
public class MapperInvocationDelegate implements IInvocationDelegates {
private Hashtable _results;
private IStaticLogEntryWrapper _slc;
public MapperInvocationDelegate(IStaticLogEntryWrapper slc)
{
_slc = slc;
}
@Override
public Hashtable GetResults() {
return _results;
}
@Override
public void SetResults(Hashtable results) {
_results = results;
}
@Override
public void SuccessfulInvocation(IDomainObject domainObject) {
_slc
.SetEvent("Successful Mapper Invocation")
.EmitLog(Priority.Info, Status.Success, Convert(_results));
}
@Override
public void FailedInvocationDelegate(IDomainObject domainObject) {
}
HashMap<String, String> Convert(Hashtable results)
{
HashMap<String, String> params = new HashMap<String, String>(results);
return params;
}
}
|
import { Entity } from "./Entity";
import Collisions from './collisions/src/Collisions';
import { PhysicEntity } from "./PhysicEntity";
import { GraphicEntity } from "./GraphicEntity";
export class Room {
public entities: Array<Entity>;
private collisionSystem: Collisions;
constructor(initialEntities: Array<Entity>){
this.collisionSystem = new Collisions();
this.entities = [];
initialEntities.forEach(entity => {
this.pushEntity(entity);
})
}
/**
* Pushes an entity to the room.
* @param entity Entity to push
*/
public pushEntity(entity: Entity){
this.entities.push(entity);
if(entity instanceof PhysicEntity){
this.collisionSystem.insert(entity.getCollisionMask().instance);
}
}
public getDrawableEntities(): Array<PhysicEntity>{
return this.entities.filter(entity =>
(entity instanceof GraphicEntity || entity instanceof PhysicEntity)
) as Array<PhysicEntity>;
}
/**
* Process all room collisions.
*/
public _handleCollisions(){
this.collisionSystem.update();
const result = this.collisionSystem.createResult();
this.entities.forEach(entity => {
if(entity instanceof PhysicEntity && !entity.isStatic()){
const collider = entity.getCollisionMask().instance;
const potentials = collider.potentials();
for(const body of potentials){
if(collider.collides(body, result)){
entity._x -= result.overlap * result.overlap_x;
entity._y -= result.overlap * result.overlap_y;
}
}
}
})
}
} |
{-# LANGUAGE OverloadedStrings #-}
module Emit where
import LLVM.General.Module
import LLVM.General.Context
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Float as F
import qualified LLVM.General.AST.FloatingPointPredicate as FP
import Data.Word
import Data.Int
import Control.Monad.Except
import Control.Applicative
import qualified Data.Map as Map
import Codegen
import qualified Syntax as S
-- Emit toplevel constructions in modules ( functions and external definitions )
codegenTop :: S.Expr -> LLVM ()
codegenTop (S.Function name args body) = do
define double name fnargs bls
where
fnargs = toSig args
bls = createBlocks $ execCodegen $ do
entry <- addBlock entryBlockName
setBlock entry
forM args $ \a -> do
var <- alloca double
store var (local (AST.Name a))
assign a var
cgen body >>= ret
codegenTop (S.Extern name args) = do
external double name fnargs
where fnargs = toSig args
codegenTop exp = do
define double "main" [] blks
where blks = createBlocks $ execCodegen $ do
entry <- addBlock entryBlockName
setBlock entry
cgen exp >>= ret
-------------------------------------------------------------------------------
-- Operations
-------------------------------------------------------------------------------
lt :: AST.Operand -> AST.Operand -> Codegen AST.Operand
lt a b = do
test <- fcmp FP.ULT a b
uitofp double test
binops = Map.fromList [
("+", fadd)
, ("-", fsub)
, ("*", fmul)
, ("/", fdiv)
, ("<", lt)
]
-- Expression level code generation which will recursively walk the AST pushing
-- instructions on the stack and changing the current block as needed
cgen :: S.Expr -> Codegen AST.Operand
cgen (S.BinaryOp "=" (S.Var var) val) = do
a <- getvar var
cval <- cgen val
store a cval
return cval
cgen (S.BinaryOp op a b) = do
case Map.lookup op binops of
Just f -> do ca <- cgen a
cb <- cgen b
f ca cb
Nothing -> error "No such operator"
cgen (S.Float n) = return $ cons $ C.Float (F.Double n)
cgen (S.Var x) = getvar x >>= load
cgen (S.Call fn args) = do
largs <- mapM cgen args -- first evaluate each argument
call (externf (AST.Name fn)) largs -- all functions are defined global
toSig :: [String] -> [(AST.Type, AST.Name)]
toSig = map (\x -> (double, AST.Name x))
-------------------------------------------------------------------------------
-- Compilation
-------------------------------------------------------------------------------
liftError :: ExceptT String IO a -> IO a
liftError = runExceptT >=> either fail return
codegen :: AST.Module -> [S.Expr] -> IO AST.Module
codegen mod fns = withContext $ \context ->
liftError $ withModuleFromAST context newast $ \m -> do
llstr <- moduleLLVMAssembly m
putStrLn llstr
return newast
where
modn = mapM codegenTop fns
newast = runLLVM mod modn
|
#!/usr/bin/env ruby
# encoding: utf-8
require_relative '../../environment.rb'
include Sinatra::Mimsy::Helpers
catalog_counts = CatalogTaxon.group(:mkey).count
catalog_counts.each do |pr|
next if pr[1] < 2
ct = CatalogTaxon.where(mkey: pr[0]).pluck(:affiliation, :speckey)
collection = Taxon.find(ct.first[1]).collection
next if collection != "Botany"
if pr[1] != ct.map{|a| a[0]}.compact.count + 1
gm = GroupMember.new
gm.table_key = pr[0]
gm.group_id = 4751
gm.save
end
end |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/bigquery/storage/v1beta2/stream.proto
package com.google.cloud.bigquery.storage.v1beta2;
public final class StreamProto {
private StreamProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableModifiers_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableModifiers_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableReadOptions_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableReadOptions_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_bigquery_storage_v1beta2_ReadStream_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_bigquery_storage_v1beta2_ReadStream_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n2google/cloud/bigquery/storage/v1beta2/"
+ "stream.proto\022%google.cloud.bigquery.stor"
+ "age.v1beta2\032\037google/api/field_behavior.p"
+ "roto\032\031google/api/resource.proto\0321google/"
+ "cloud/bigquery/storage/v1beta2/arrow.pro"
+ "to\0320google/cloud/bigquery/storage/v1beta"
+ "2/avro.proto\032\037google/protobuf/timestamp."
+ "proto\"\336\006\n\013ReadSession\022\021\n\004name\030\001 \001(\tB\003\340A\003"
+ "\0224\n\013expire_time\030\002 \001(\0132\032.google.protobuf."
+ "TimestampB\003\340A\003\022K\n\013data_format\030\003 \001(\01621.go"
+ "ogle.cloud.bigquery.storage.v1beta2.Data"
+ "FormatB\003\340A\005\022M\n\013avro_schema\030\004 \001(\01321.googl"
+ "e.cloud.bigquery.storage.v1beta2.AvroSch"
+ "emaB\003\340A\003H\000\022O\n\014arrow_schema\030\005 \001(\01322.googl"
+ "e.cloud.bigquery.storage.v1beta2.ArrowSc"
+ "hemaB\003\340A\003H\000\022\r\n\005table\030\006 \001(\t\022_\n\017table_modi"
+ "fiers\030\007 \001(\0132A.google.cloud.bigquery.stor"
+ "age.v1beta2.ReadSession.TableModifiersB\003"
+ "\340A\001\022^\n\014read_options\030\010 \001(\0132C.google.cloud"
+ ".bigquery.storage.v1beta2.ReadSession.Ta"
+ "bleReadOptionsB\003\340A\001\022G\n\007streams\030\n \003(\01321.g"
+ "oogle.cloud.bigquery.storage.v1beta2.Rea"
+ "dStreamB\003\340A\003\032C\n\016TableModifiers\0221\n\rsnapsh"
+ "ot_time\030\001 \001(\0132\032.google.protobuf.Timestam"
+ "p\032D\n\020TableReadOptions\022\027\n\017selected_fields"
+ "\030\001 \003(\t\022\027\n\017row_restriction\030\002 \001(\t:k\352Ah\n*bi"
+ "gquerystorage.googleapis.com/ReadSession"
+ "\022:projects/{project}/locations/{location"
+ "}/sessions/{session}B\010\n\006schema\"\234\001\n\nReadS"
+ "tream\022\021\n\004name\030\001 \001(\tB\003\340A\003:{\352Ax\n)bigquerys"
+ "torage.googleapis.com/ReadStream\022Kprojec"
+ "ts/{project}/locations/{location}/sessio"
+ "ns/{session}/streams/{stream}*>\n\nDataFor"
+ "mat\022\033\n\027DATA_FORMAT_UNSPECIFIED\020\000\022\010\n\004AVRO"
+ "\020\001\022\t\n\005ARROW\020\002B\210\001\n)com.google.cloud.bigqu"
+ "ery.storage.v1beta2B\013StreamProtoP\001ZLgoog"
+ "le.golang.org/genproto/googleapis/cloud/"
+ "bigquery/storage/v1beta2;storageb\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.bigquery.storage.v1beta2.ArrowProto.getDescriptor(),
com.google.cloud.bigquery.storage.v1beta2.AvroProto.getDescriptor(),
com.google.protobuf.TimestampProto.getDescriptor(),
});
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_descriptor,
new java.lang.String[] {
"Name",
"ExpireTime",
"DataFormat",
"AvroSchema",
"ArrowSchema",
"Table",
"TableModifiers",
"ReadOptions",
"Streams",
"Schema",
});
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableModifiers_descriptor =
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableModifiers_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableModifiers_descriptor,
new java.lang.String[] {
"SnapshotTime",
});
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableReadOptions_descriptor =
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableReadOptions_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_bigquery_storage_v1beta2_ReadSession_TableReadOptions_descriptor,
new java.lang.String[] {
"SelectedFields", "RowRestriction",
});
internal_static_google_cloud_bigquery_storage_v1beta2_ReadStream_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_bigquery_storage_v1beta2_ReadStream_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_bigquery_storage_v1beta2_ReadStream_descriptor,
new java.lang.String[] {
"Name",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.ResourceProto.resource);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.bigquery.storage.v1beta2.ArrowProto.getDescriptor();
com.google.cloud.bigquery.storage.v1beta2.AvroProto.getDescriptor();
com.google.protobuf.TimestampProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
RSpec.describe Ruboty::Handlers::Echo do
let(:robot) do
Ruboty::Robot.new
end
describe '#echo' do
shared_examples 'echoes given message' do
it 'echoes given message' do
expect(robot).to receive(:say).with(
hash_including(
body: given_message,
),
)
robot.receive(body: "#{robot.name} echo #{given_message}")
end
end
context 'without line break' do
let(:given_message) do
'test'
end
include_examples 'echoes given message'
end
context 'with line break' do
let(:given_message) do
"test\ntest"
end
include_examples 'echoes given message'
end
end
end
|
<?php
namespace Test\Entity\Beneficiary;
use PHPUnit\Framework\TestCase;
use Railsbank\Entity\Beneficiary\BeneficiaryId;
class BeneficiaryIdTest extends TestCase
{
public function testBeneficiaryId()
{
$response = [
'beneficiary_id' => '1234',
];
$entity = new BeneficiaryId($response);
self::assertEquals('1234', $entity->getBeneficiaryId());
}
}
|
class TrendingEntryType {
TrendingEntryType._();
static const int News = 0;
static const int DestinyItem = 1;
static const int DestinyActivity = 2;
static const int DestinyRitual = 3;
static const int SupportArticle = 4;
static const int Creation = 5;
static const int Stream = 6;
static const int Update = 7;
static const int Link = 8;
static const int ForumTag = 9;
static const int Container = 10;
static const int Release = 11;
}
|
# mod p の原子根を全部求める O(p log p)
def primitive_roots(p)
return [1] if p == 2
visited = [false] * p
(2 ... p).each do |r|
roots = []
x = r
count = 1
while x != 1
roots << x if count.gcd(p - 1) == 1
visited[x] = true
x = x * r % p
count += 1
end
return roots if count == p - 1
end
end
|
# frozen_string_literal: true
require "test_helper"
class PrimerButtonComponentTest < Minitest::Test
include Primer::ComponentTestHelpers
def test_renders_content
render_inline(Primer::ButtonComponent.new) { "content" }
assert_text("content")
end
def test_defaults_button_tag_with_scheme
render_inline(Primer::ButtonComponent.new) { "content" }
assert_selector("button.btn[type='button']")
end
def test_renders_a_as_a_button
render_inline(Primer::ButtonComponent.new(tag: :a)) { "content" }
assert_selector("a.btn[role='button']")
end
def test_renders_href
render_inline(Primer::ButtonComponent.new(href: "www.example.com")) { "content" }
assert_selector("button[href='www.example.com']")
end
def test_renders_buttons_as_a_group_item
render_inline(Primer::ButtonComponent.new(group_item: true)) { "content" }
assert_selector("button.btn.BtnGroup-item")
end
def test_falls_back_when_type_isn_t_valid
without_fetch_or_fallback_raises do
render_inline(Primer::ButtonComponent.new(scheme: :invalid)) { "content" }
assert_selector(".btn")
end
end
def test_renders_with_the_css_class_mapping_to_the_provided_type
render_inline(Primer::ButtonComponent.new(scheme: :primary)) { "content" }
assert_selector(".btn.btn-primary")
end
def test_falls_back_when_variant_isn_t_valid
without_fetch_or_fallback_raises do
render_inline(Primer::ButtonComponent.new(variant: :invalid)) { "content" }
assert_selector(".btn")
end
end
def test_renders_with_the_css_class_variant_mapping_to_the_provided_variant
render_inline(Primer::ButtonComponent.new(variant: :small)) { "content" }
assert_selector(".btn.btn-sm")
end
end
|
import { RouteMiddleware } from '../../types/route-middleware';
import { userWithScope } from '../../utility/user-with-scope';
export const deleteSlot: RouteMiddleware<{ slotId: string }> = async context => {
const { siteId } = userWithScope(context, ['site.admin']);
const slotId = Number(context.params.slotId);
await context.pageBlocks.deleteSlot(slotId, siteId);
context.response.status = 200;
};
|
<?php
$link =mysqli_connect('localhost','root','');
if($link==false)
{
echo "Error:Could not connect" . mysqli_connect_error();
}
$sqli= "CREATE DATABASE homework1";
if(mysqli_query($link,$sqli))
{
echo "DB CREATED";
}
else
{
echo "DB Not CREATED " . mysqli_error($link);
}
?> |
#!/bin/sh
# Teste da função GOLDEN
phi=3 # chute inicial
prec=15 # casas decimais
. ./golden.sh $phi $prec
printf "$iter iterações: ϕ = %1.${prec}f\n" $phi
|
import "../output/output_ast.dart" as o;
import "../template_ast.dart" show TemplateAst;
import "compile_view.dart" show CompileView;
class _DebugState {
num nodeIndex;
TemplateAst sourceAst;
_DebugState(this.nodeIndex, this.sourceAst);
}
var NULL_DEBUG_STATE = new _DebugState(null, null);
class CompileMethod {
CompileView _view;
_DebugState _newState = NULL_DEBUG_STATE;
_DebugState _currState = NULL_DEBUG_STATE;
bool _debugEnabled;
List<o.Statement> _bodyStatements = [];
CompileMethod(this._view) {
this._debugEnabled = this._view.genConfig.genDebugInfo;
}
void _updateDebugContextIfNeeded() {
if (!identical(this._newState.nodeIndex, this._currState.nodeIndex) ||
!identical(this._newState.sourceAst, this._currState.sourceAst)) {
var expr = this._updateDebugContext(this._newState);
if (expr != null) {
this._bodyStatements.add(expr.toStmt());
}
}
}
o.Expression _updateDebugContext(_DebugState newState) {
this._currState = this._newState = newState;
if (this._debugEnabled) {
var sourceLocation = newState.sourceAst != null
? newState.sourceAst.sourceSpan.start
: null;
return new o.InvokeMemberMethodExpr('dbg', [
o.literal(newState.nodeIndex),
sourceLocation != null ? o.literal(sourceLocation.line) : o.NULL_EXPR,
sourceLocation != null ? o.literal(sourceLocation.col) : o.NULL_EXPR
]);
} else {
return null;
}
}
o.Expression resetDebugInfoExpr(num nodeIndex, TemplateAst templateAst) {
var res = this._updateDebugContext(new _DebugState(nodeIndex, templateAst));
return res ?? o.NULL_EXPR;
}
void resetDebugInfo(num nodeIndex, TemplateAst templateAst) {
this._newState = new _DebugState(nodeIndex, templateAst);
}
void addStmt(o.Statement stmt) {
this._updateDebugContextIfNeeded();
this._bodyStatements.add(stmt);
}
void addStmts(List<o.Statement> stmts) {
this._updateDebugContextIfNeeded();
this._bodyStatements.addAll(stmts);
}
List<o.Statement> finish() {
return this._bodyStatements;
}
bool isEmpty() {
return identical(this._bodyStatements.length, 0);
}
}
|
package types
import (
"testing"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
key = secp256k1.GenPrivKey()
pub = key.PubKey()
addr = sdk.AccAddress(pub.Address())
)
func TestWalletAction(t *testing.T) {
for _, tt := range []struct {
name string
msg *MsgWalletAction
shouldErr bool
}{
{
name: "empty",
msg: &MsgWalletAction{},
shouldErr: true,
},
{
name: "normal",
msg: NewMsgWalletAction(addr, "null"),
},
{
name: "empty action",
msg: NewMsgWalletAction(addr, ""),
shouldErr: true,
},
{
name: "bad json",
msg: NewMsgWalletAction(addr, "foo"),
shouldErr: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
err := tt.msg.ValidateBasic()
if err != nil && !tt.shouldErr {
t.Fatalf("unexpected validation error %s", err)
}
if err == nil && tt.shouldErr {
t.Fatalf("wanted validation error")
}
})
}
}
func TestWalletSpendAction(t *testing.T) {
for _, tt := range []struct {
name string
msg *MsgWalletSpendAction
shouldErr bool
}{
{
name: "empty",
msg: &MsgWalletSpendAction{},
shouldErr: true,
},
{
name: "normal",
msg: NewMsgWalletSpendAction(addr, "null"),
},
{
name: "empty action",
msg: NewMsgWalletSpendAction(addr, ""),
shouldErr: true,
},
{
name: "bad json",
msg: NewMsgWalletSpendAction(addr, "foo"),
shouldErr: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
err := tt.msg.ValidateBasic()
if err != nil && !tt.shouldErr {
t.Fatalf("unexpected validation error %s", err)
}
if err == nil && tt.shouldErr {
t.Fatalf("wanted validation error")
}
})
}
}
|
public class Solution {
public IList<string> GenerateParenthesis(int n) {
List<string> res=new List<string>();
if(n<=0)
return res;
else
Parenthesis(n,n,"",res);
return res;
}
private void Parenthesis(int left,int right,string str,List<string> res)
{
if(right<left)
return;
if(right==0&&left==0)
res.Add(str);
if(left>0)
Parenthesis(left-1,right,str+"(",res);
if(right>0)
Parenthesis(left,right-1,str+")",res);
}
} |
# dumper
Windows service for uploading files added to a watched directory to a FTP server.
#### Install and start service
```
$ py dumpersvc.py install
$ NET START DumperSvc
```
#### Stop and uninstall service
```
$ NET STOP DumperSvc
$ py dumpersvc.py remove
```
#### Run as script
```
$ py dumper/run.py
```
#### Dependencies
* python3.5
* pywin32
#### Settings
Modify settings and FTP server credentials in [config.ini](config.ini)
|
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.5.4
-- Dumped by pg_dump version 9.5.4
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
--
-- Name: step_state; Type: TYPE; Schema: public; Owner: postgres
--
CREATE TYPE step_state AS ENUM (
'to_do',
'completed',
'work_in_progress',
'archived'
);
ALTER TYPE step_state OWNER TO postgres;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: contributors; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE contributors (
id bigint NOT NULL,
role character varying(255),
user_id bigint NOT NULL,
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE contributors OWNER TO postgres;
--
-- Name: contributors_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE contributors_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE contributors_id_seq OWNER TO postgres;
--
-- Name: contributors_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE contributors_id_seq OWNED BY contributors.id;
--
-- Name: dependencies; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE dependencies (
depender_id bigint NOT NULL,
depended_id bigint NOT NULL
);
ALTER TABLE dependencies OWNER TO postgres;
--
-- Name: emails; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE emails (
id bigint NOT NULL,
email character varying(255),
user_id bigint NOT NULL,
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE emails OWNER TO postgres;
--
-- Name: emails_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE emails_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE emails_id_seq OWNER TO postgres;
--
-- Name: emails_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE emails_id_seq OWNED BY emails.id;
--
-- Name: passwords; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE passwords (
id bigint NOT NULL,
password character varying(255),
user_id bigint NOT NULL,
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE passwords OWNER TO postgres;
--
-- Name: passwords_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE passwords_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE passwords_id_seq OWNER TO postgres;
--
-- Name: passwords_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE passwords_id_seq OWNED BY passwords.id;
--
-- Name: projects; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE projects (
id bigint NOT NULL,
name character varying(255),
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
owner_id bigint NOT NULL,
public_visible boolean DEFAULT false NOT NULL
);
ALTER TABLE projects OWNER TO postgres;
--
-- Name: projects_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE projects_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE projects_id_seq OWNER TO postgres;
--
-- Name: projects_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE projects_id_seq OWNED BY projects.id;
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE schema_migrations (
version bigint NOT NULL,
inserted_at timestamp without time zone
);
ALTER TABLE schema_migrations OWNER TO postgres;
--
-- Name: steps; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE steps (
id bigint NOT NULL,
title character varying(255),
description text,
project_id bigint NOT NULL,
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
completed boolean DEFAULT false NOT NULL,
state step_state DEFAULT 'to_do'::step_state NOT NULL
);
ALTER TABLE steps OWNER TO postgres;
--
-- Name: steps_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE steps_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE steps_id_seq OWNER TO postgres;
--
-- Name: steps_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE steps_id_seq OWNED BY steps.id;
--
-- Name: users; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE users (
id bigint NOT NULL,
name character varying(255),
username character varying(255),
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE users OWNER TO postgres;
--
-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE users_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE users_id_seq OWNER TO postgres;
--
-- Name: users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE users_id_seq OWNED BY users.id;
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY contributors ALTER COLUMN id SET DEFAULT nextval('contributors_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY emails ALTER COLUMN id SET DEFAULT nextval('emails_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY passwords ALTER COLUMN id SET DEFAULT nextval('passwords_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY projects ALTER COLUMN id SET DEFAULT nextval('projects_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY steps ALTER COLUMN id SET DEFAULT nextval('steps_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY users ALTER COLUMN id SET DEFAULT nextval('users_id_seq'::regclass);
--
-- Data for Name: contributors; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY contributors (id, role, user_id, inserted_at, updated_at) FROM stdin;
\.
--
-- Name: contributors_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('contributors_id_seq', 828, true);
--
-- Data for Name: dependencies; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY dependencies (depender_id, depended_id) FROM stdin;
\.
--
-- Data for Name: emails; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY emails (id, email, user_id, inserted_at, updated_at) FROM stdin;
\.
--
-- Name: emails_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('emails_id_seq', 167, true);
--
-- Data for Name: passwords; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY passwords (id, password, user_id, inserted_at, updated_at) FROM stdin;
\.
--
-- Name: passwords_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('passwords_id_seq', 167, true);
--
-- Data for Name: projects; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY projects (id, name, inserted_at, updated_at, owner_id, public_visible) FROM stdin;
\.
--
-- Name: projects_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('projects_id_seq', 92, true);
--
-- Data for Name: schema_migrations; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY schema_migrations (version, inserted_at) FROM stdin;
20180723212733 2018-07-23 22:27:27.425162
20180723212737 2018-07-23 22:27:28.037604
20180723212759 2018-07-23 22:27:28.805295
20180724152511 2018-08-07 14:10:37.624448
20180724152719 2018-08-07 14:10:37.966132
20180724152924 2018-08-07 14:10:38.088772
20180724180328 2018-08-07 14:10:38.32324
20180725215149 2018-08-07 14:10:38.445965
20180806221907 2018-08-07 14:10:38.675891
20181022213506 2018-11-04 19:07:53.692909
20181028192737 2018-11-04 19:07:53.941765
20181104185937 2018-11-04 19:07:54.008973
\.
--
-- Data for Name: steps; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY steps (id, title, description, project_id, inserted_at, updated_at, completed, state) FROM stdin;
\.
--
-- Name: steps_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('steps_id_seq', 1, false);
--
-- Data for Name: users; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY users (id, name, username, inserted_at, updated_at) FROM stdin;
\.
--
-- Name: users_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('users_id_seq', 1120, true);
--
-- Name: contributors_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY contributors
ADD CONSTRAINT contributors_pkey PRIMARY KEY (id);
--
-- Name: emails_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY emails
ADD CONSTRAINT emails_pkey PRIMARY KEY (id);
--
-- Name: passwords_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY passwords
ADD CONSTRAINT passwords_pkey PRIMARY KEY (id);
--
-- Name: projects_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY projects
ADD CONSTRAINT projects_pkey PRIMARY KEY (id);
--
-- Name: schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
--
-- Name: steps_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY steps
ADD CONSTRAINT steps_pkey PRIMARY KEY (id);
--
-- Name: users_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY users
ADD CONSTRAINT users_pkey PRIMARY KEY (id);
--
-- Name: contributors_user_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX contributors_user_id_index ON contributors USING btree (user_id);
--
-- Name: dependencies_depender_id_depended_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX dependencies_depender_id_depended_id_index ON dependencies USING btree (depender_id, depended_id);
--
-- Name: emails_email_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX emails_email_index ON emails USING btree (email);
--
-- Name: emails_user_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE INDEX emails_user_id_index ON emails USING btree (user_id);
--
-- Name: passwords_password_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX passwords_password_index ON passwords USING btree (password);
--
-- Name: passwords_user_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE INDEX passwords_user_id_index ON passwords USING btree (user_id);
--
-- Name: projects_contributor_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE INDEX projects_contributor_id_index ON projects USING btree (owner_id);
--
-- Name: steps_project_id_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE INDEX steps_project_id_index ON steps USING btree (project_id);
--
-- Name: users_username_index; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX users_username_index ON users USING btree (username);
--
-- Name: contributors_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY contributors
ADD CONSTRAINT contributors_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
--
-- Name: dependencies_depended_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY dependencies
ADD CONSTRAINT dependencies_depended_id_fkey FOREIGN KEY (depended_id) REFERENCES steps(id) ON DELETE CASCADE;
--
-- Name: dependencies_depender_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY dependencies
ADD CONSTRAINT dependencies_depender_id_fkey FOREIGN KEY (depender_id) REFERENCES steps(id) ON DELETE CASCADE;
--
-- Name: emails_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY emails
ADD CONSTRAINT emails_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
--
-- Name: passwords_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY passwords
ADD CONSTRAINT passwords_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
--
-- Name: projects_contributor_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY projects
ADD CONSTRAINT projects_contributor_id_fkey FOREIGN KEY (owner_id) REFERENCES contributors(id) ON DELETE CASCADE;
--
-- Name: steps_project_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY steps
ADD CONSTRAINT steps_project_id_fkey FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE;
--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
|
package interfaces
type WithAddress interface {
GetAddress() (address Address)
SetAddress(address Address)
}
|
package jsoniter
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFrozenConfig_MarshalIndentErrors(t *testing.T) {
var panicOccured interface{} = nil
defer func() {
panicOccured = recover()
}()
_, err := MarshalIndent(`{"foo":"bar"}`, "", "\n\n")
assert.NoError(t, err)
assert.NotNil(t, panicOccured, "MarshalIndent should panic due to invalid indent chars")
panicOccured = nil
_, err = MarshalIndent(`{"foo":"bar"}`, "", " \t ")
panicOccured = recover()
assert.NoError(t, err)
assert.NotNil(t, panicOccured, "MarshalIndent should panic due to mixed spaces and tabs")
}
|
package eu.kanade.tachiyomi.data.database.queries
import com.pushtorefresh.storio.Queries
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import eu.kanade.tachiyomi.data.database.AnimeDbProvider
import eu.kanade.tachiyomi.data.database.inTransaction
import eu.kanade.tachiyomi.data.database.models.Anime
import eu.kanade.tachiyomi.data.database.models.AnimeCategory
import eu.kanade.tachiyomi.data.database.tables.AnimeCategoryTable
interface AnimeCategoryQueries : AnimeDbProvider {
fun insertAnimesCategories(animesCategories: List<AnimeCategory>) = db.put().objects(animesCategories).prepare()
fun deleteOldAnimesCategories(animes: List<Anime>) = db.delete()
.byQuery(
DeleteQuery.builder()
.table(AnimeCategoryTable.TABLE)
.where("${AnimeCategoryTable.COL_ANIME_ID} IN (${Queries.placeholders(animes.size)})")
.whereArgs(*animes.map { it.id }.toTypedArray())
.build(),
)
.prepare()
fun setAnimeCategories(animesCategories: List<AnimeCategory>, animes: List<Anime>) {
db.inTransaction {
deleteOldAnimesCategories(animes).executeAsBlocking()
insertAnimesCategories(animesCategories).executeAsBlocking()
}
}
}
|
2020年12月20日01时数据
Status: 200
1.张檬最后悔的事情是整容
微博热度:1073628
2.香港一确诊男子擅自离开医院
微博热度:735472
3.杨幂郑爽同框吐槽好敢说
微博热度:674094
4.盛一伦 我现在已经凉透了
微博热度:552750
5.追光吧哥哥
微博热度:381074
6.我就是演员
微博热度:348865
7.青春有你3初C
微博热度:330506
8.中国已为全球提供超2000亿只口罩
微博热度:328760
9.奇葩说
微博热度:324242
10.于正我从来不用流量
微博热度:318406
11.路人镜头下的丁真
微博热度:312097
12.章子怡说马嘉祺谢可寅争气
微博热度:307193
13.108岁糖果奶奶去世
微博热度:286543
14.美国五分之一囚犯感染新冠
微博热度:277275
15.于朦胧李泽锋嗑到了
微博热度:270542
16.肖战南京
微博热度:266371
17.新兵投弹失手指导员3秒救人
微博热度:237968
18.螺蛳粉产销量5年翻了21倍
微博热度:234948
19.成都最壕窗台挂千斤香肠
微博热度:233796
20.谢娜张颜齐把野子唱成二人转
微博热度:221943
21.公司回应员工健身房外猝死
微博热度:219443
22.SBS演艺大赏
微博热度:214056
23.国网湖南电力全面进入战时状态
微博热度:195593
24.章若楠吃瓜倒立吻戏吃到自己
微博热度:192024
25.紧急救援
微博热度:182357
26.中国远征军女兵张炳芝逝世
微博热度:168476
27.南非发现新冠病毒变异
微博热度:168313
28.崔世安钟南山获授大莲花荣誉勋章
微博热度:168275
29.小鹿 女人的幽默会消解性感
微博热度:168274
30.郑爽贝雷帽造型
微博热度:164386
31.劳荣枝
微博热度:159930
32.5名快递员考入同所大学同专业
微博热度:132362
33.美舰穿航台湾海峡东部战区回应
微博热度:130187
34.一诺状态
微博热度:129728
35.有翡配音收到王一博粉丝鼓励
微博热度:128830
36.周震南星光大赏彩排图
微博热度:127317
37.首次发现战国时期秦国后宫遗址
微博热度:125589
38.胖虎斥易烊千玺私生饭
微博热度:119452
39.快乐大本营
微博热度:115335
40.这英文翻译很上头
微博热度:114527
41.宋紫薇
微博热度:113108
42.SK 不会跌倒第三次
微博热度:110957
43.李汶翰李泽锋平板支撑七分钟
微博热度:107303
44.SBS演艺大赏艺人定制口罩
微博热度:103805
45.鹿晗兑现医护粉丝承诺
微博热度:98737
46.丰田汽车掌门人炮轰电动汽车
微博热度:91406
47.如何应对被社会性死亡
微博热度:76685
48.一茶一坐全国大面积关店
微博热度:66037
49.DYG夺冠
微博热度:65669
50.刘雨昕星耀闪钻西装
微博热度:65127
|
import axios, {AxiosResponse} from "axios";
import * as React from "react";
import {Theme, withStyles, WithStyles} from "@material-ui/core";
import HitsChart from "./HitsChart";
import {HitsData} from "./Types";
import {PlotDatum} from "plotly.js";
import HitsImages from "./HitsImages";
import Export from "../export/Export";
interface HitsViewState {
hits: HitsData | null;
points: PlotDatum[];
}
const styles = (theme:Theme) => ({
});
class HitsView extends React.Component<{}, HitsViewState> {
public state = {hits: null, points: []};
public loadData() {
axios
.get<HitsData>('credocut.json')
.then((response) => {
this.setState({hits: response.data});
})
}
public render() {
const { hits, points } = this.state;
if (hits !== null) {
return (
<>
<HitsChart data={hits} onHover={this.onHover}/>
<HitsImages points={points}/>
<Export data={hits}/>
</>
);
} else {
return (
<p>Loading...</p>
)
}
}
public componentDidMount(): void {
this.loadData();
}
private onHover = (points: PlotDatum[]) => {
this.setState({points});
}
}
export default withStyles(styles)(HitsView);
|
{-|
Module : Elab
Description : Elabora un término fully named a uno locally closed.
Copyright : (c) Mauro Jaskelioff, Guido Martínez, 2020.
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Este módulo permite elaborar términos y declaraciones para convertirlas desde
fully named (@NTerm) a locally closed (@Term@)
-}
module Elab ( elab, desugarSdecl, elabAndDesugar ) where
import Lang
import Subst
import MonadFD4 (failPosFD4, MonadFD4, lookupSTy)
import Common (Pos(NoPos))
import Control.Monad (when)
import Data.Maybe (isNothing, fromJust)
-- | 'elab' transforma variables ligadas en índices de de Bruijn
-- en un término dado.
elab :: NTerm -> Term
elab = elab' []
elabAndDesugar :: MonadFD4 m => STerm -> m Term
elabAndDesugar s = do
t <- desugarSterm s
return $ elab t
elab' :: [Name] -> NTerm -> Term
elab' env (V p v) = V p (Free v)
-- Tenemos que hver si la variable es Global o es un nombre local
-- En env llevamos la lista de nombres locales.
-- if v `elem` env
-- then V p (Free v)
-- else V p (Global v)
elab' _ (Const p c) = Const p c
elab' env (Lam p v ty t) = Lam p v ty (close v (elab' (v:env) t))
elab' env (Fix p f fty x xty t) = Fix p f fty x xty (closeN [f, x] (elab' (x:f:env) t))
elab' env (IfZ p c t e) = IfZ p (elab' env c) (elab' env t) (elab' env e)
-- Operador Print
elab' env (Print i str t) = Print i str (elab' env t)
-- Operadores binarios
elab' env (BinaryOp i o t u) = BinaryOp i o (elab' env t) (elab' env u)
-- Aplicaciones generales
elab' env (App p h a) = App p (elab' env h) (elab' env a)
elab' env (Let p v vty def body) = Let p v vty (elab' env def) (close v (elab' (v:env) body))
desugarSdecl :: MonadFD4 m => SDecl STerm -> m (Decl NTerm)
desugarSdecl (SDecl p True n sty binders body) = do
let l = (n, sty):binders
b <- desugarSterm $ SFix p ((n, typeFromBinders l):binders) body
return (Decl p n b)
desugarSdecl (SDecl p False n sty binders body) = do
b <- desugarSterm $ SLam p binders body
return (Decl p n b)
desugarSdecl (SDeclType p n sty) = failPosFD4 p "desugarSdecl: Esto no debería haber pasado"
desugarSterm :: MonadFD4 m => STerm -> m NTerm
desugarSterm (SV info var) = return (V info var)
desugarSterm (SConst info c) = return (Const info c)
desugarSterm (SLam info ((n, ty):xs) exp) = do
ty <- slookupTy ty
typeExist info ty
Lam info n (fromJust ty) <$> desugarSterm (SLam info xs exp)
desugarSterm (SLam info [] exp) = desugarSterm exp
desugarSterm (SApp info exp1 exp2) = do
e1 <- desugarSterm exp1
e2 <- desugarSterm exp2
return (App info e1 e2)
-- η-expansion del termino Print
desugarSterm (SPrint info str) = return (Lam info "x" NatTy (Print info str (V info "x")))
desugarSterm (SBinaryOp info op sexp1 sexp2) = do
exp1 <- desugarSterm sexp1
exp2 <- desugarSterm sexp2
return (BinaryOp info op exp1 exp2)
desugarSterm (SFix info ((y, ysty):((x, xsty):xs)) exp) = do
yty <- slookupTy ysty
typeExist info yty
xty <- slookupTy xsty
Fix info y (fromJust yty) x (fromJust xty) <$> desugarSterm (SLam info xs exp)
desugarSterm (SIfZ info sexp1 sexp2 sexp3) = do
exp1 <- desugarSterm sexp1
exp2 <- desugarSterm sexp2
exp3 <- desugarSterm sexp3
return (IfZ info exp1 exp2 exp3)
desugarSterm (SLet False info f sty [] st1 st2) = do
ty <- slookupTy sty
typeExist info ty
t1 <- desugarSterm st1
t2 <- desugarSterm st2
return $ Let info f (fromJust ty) t1 t2
desugarSterm (SLet False info f sty ((x, xty):xs) st1 st2) =
desugarSterm (SLet False info f (SFunTy xty sty) xs (SLam info [(x, xty)] st1) st2)
desugarSterm (SLet True info n sty binders sexp1 sexp2) = do
ty <- slookupTy sty
typeExist info ty
let binders' = (n, sty):binders
let t1 = typeFromBinders binders'
t2 <- slookupTy t1
exp2 <- desugarSterm sexp2
exp1 <- desugarSterm (SFix info ((n, typeFromBinders binders'):binders) sexp1)
return (Let info n (fromJust t2) exp1 exp2)
desugarSterm _ = failPosFD4 NoPos "desugarSterm: esto no deberia haber pasado"
slookupTy :: MonadFD4 m => STy -> m (Maybe Ty)
slookupTy SNatTy = return (Just NatTy)
slookupTy (SFunTy sty1 sty2) =
do ty1 <- slookupTy sty1
ty2 <- slookupTy sty2
if isNothing ty1 || isNothing ty2 then return Nothing
else return (Just (FunTy (fromJust ty1) (fromJust ty2)))
slookupTy (SSynType n) = do
st <- lookupSTy n
case st of
Nothing -> return Nothing
Just SNatTy -> return $ Just NatTy
Just x -> slookupTy x
typeExist :: MonadFD4 m => Pos -> Maybe Ty -> m ()
typeExist p ty = when (isNothing ty) $ do
failPosFD4 p "El tipo no existe"
typeFromBinders :: [(Name, STy)] -> STy
typeFromBinders [(n, t)] = t
typeFromBinders ((x, t):xs) = SFunTy t $ typeFromBinders xs
typeFromBinders [] = errorWithoutStackTrace "typeFromBinders"
|
---
title: SizedDtblCheckBox
manager: soliver
ms.date: 03/09/2015
ms.audience: Developer
ms.topic: reference
ms.prod: office-online-server
ms.localizationpriority: medium
api_name:
- MAPI.SizedDtblCheckBox
api_type:
- COM
ms.assetid: 9d04a124-54d4-43ac-967f-ea8e7a09b1d0
description: 上次修改时间:2015 年 3 月 9 日
ms.openlocfilehash: 9282562032279ab11a36d0ed1687ccd1d1ae8365
ms.sourcegitcommit: a1d9041c20256616c9c183f7d1049142a7ac6991
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 09/24/2021
ms.locfileid: "59586724"
---
# <a name="sizeddtblcheckbox"></a>SizedDtblCheckBox
**适用于**:Outlook 2013 | Outlook 2016
创建一个命名结构,其中包含用于描述复选框控件和指定长度的标签的 [DTBLCHECKBOX](dtblcheckbox.md) 结构。
|||
|:-----|:-----|
|标头文件: <br/> |Mapidefs.h <br/> |
|相关结构: <br/> |**DTBLCHECKBOX** <br/> |
```cpp
SizedDtblCheckBox (n, u)
```
## <a name="parameters"></a>参数
_n_
> 要包含在新结构中的标签的长度。
_u_
> 新结构的名称。
## <a name="remarks"></a>注解
**SizedDtblCheckBox** 宏允许您在标签字符数已知时定义一个复选框。 新结构由以下成员创建:
```cpp
DTBLCHECKBOX dtblcheckbox;
TCHAR lpszLabel[n];
```
若要将指向 **SizedDtblCheckBox** 宏生成的结构的指针用作 **DTBLCHECKBOX** 结构指针,请执行以下转换:
```cpp
lpDtblCheckBox = (LPDTBLCHECKBOX) &SizedDtblCheckBox;
```
## <a name="see-also"></a>另请参阅
- [DTBLCHECKBOX](dtblcheckbox.md)
- [与结构相关的宏](macros-related-to-structures.md)
|
package whatsub.convert
import cats.Applicative
import cats.syntax.all.*
import effectie.cats.Effectful.*
import extras.cats.syntax.all.*
import effectie.cats.Fx
import whatsub.{Smi, Srt, SupportedSub}
/** @author Kevin Lee
* @since 2021-06-18
*/
trait Convert[F[*], A, B] {
def convert(a: A): F[Either[ConversionError, B]]
}
object Convert {
def apply[F[*], A, B](using Convert[F, A, B]): Convert[F, A, B] = summon[Convert[F, A, B]]
given smiToSrtConvert[F[*]: Fx: Applicative]: Convert[F, Smi, Srt] =
smi =>
(if (smi.lines.isEmpty)
ConversionError
.noContent(
SupportedSub.Smi,
s"""The smi titled "${smi.title}"""",
)
.leftTF[F, Srt]
else
effectOf(
for {
(smiLine, index) <- smi.lines.zipWithIndex
start = smiLine.start.value
end = smiLine.end.value
line = smiLine.line.value
} yield Srt.SrtLine(
Srt.Index(index + 1),
Srt.Start(start),
Srt.End(end),
Srt.Line(line),
),
).rightT[ConversionError].map(Srt(_))).value
given srtToSmiConvert[F[*]: Fx: Applicative]: Convert[F, Srt, Smi] =
srt =>
if (srt.lines.isEmpty) {
pureOf(
ConversionError
.noContent(
SupportedSub.Srt,
s"""The srt"""",
)
.asLeft[Smi],
)
} else {
val lines = srt.lines.map {
case Srt.SrtLine(_, start, end, line) =>
Smi.SmiLine(
Smi.Start.fromSrt(start),
Smi.End.fromSrt(end),
Smi.Line.fromSrt(line),
)
}
pureOf(
Smi(
Smi.Title(""),
lines,
).asRight[ConversionError],
)
}
}
|
---
title: '<扩展>'
ms.date: 03/30/2017
ms.assetid: bcfe5c44-04ef-4a20-96a5-90bfadf39623
ms.openlocfilehash: 9f25c5f99eafe0f87123d8c8c3f5c182220e8c58
ms.sourcegitcommit: 11f11ca6cefe555972b3a5c99729d1a7523d8f50
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 05/03/2018
ms.locfileid: "32746873"
---
# <a name="ltextensionsgt"></a><扩展>
此配置元素包含一个 XML 元素集合,该集合包含随可检测到的标准元数据(EPR、ContractTypeName、BindingName、Scope 和 ListenURI)一起发布的自定义元数据。 下面是使用此配置元素的示例。
```xml
<services>
<service name="CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<endpoint binding="basicHttpBinding"
address="calculator"
contract="ICalculatorService"
behaviorConfiguration="calculatorEndpointBehavior" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceDiscovery />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="calculatorEndpointBehavior">
<endpointDiscovery enable="true">
<extensions>
<e:Publisher xmlns:e="http://example.org">
<e:Name>The Example Organization</e:Name>
<e:Address>One Example Way, ExampleTown, EX 12345</e:Address>
<e:Contact>[email protected]</e:Contact>
</e:Publisher>
<AnotherCustomMetadata>Custom Metadata</AnotherCustomMetadata>
</extensions>
</endpointDiscovery>
</behavior>
</endpointBehaviors>
</behaviors>
```
## <a name="see-also"></a>请参阅
<xref:System.ServiceModel.Discovery.EndpointDiscoveryBehavior>
|
source /opt/intel/openvino_2021/bin/setupvars.sh
cd Modules/object_detection_yolov5openvino
python3 yolo_openvino.py -m weights/yolov5s.xml -i cam -at yolov5 --rtmp_stream
|
exclude :test_define_method, "needs investigation"
exclude :test_double_include, "needs investigation"
exclude :test_double_include2, "needs investigation"
exclude :test_super_in_BEGIN, "needs investigation"
exclude :test_super_in_END, "needs investigation"
exclude :test_super_in_at_exit, "needs investigation"
exclude :test_super_in_instance_eval, "needs investigation"
exclude :test_super_in_instance_eval_with_define_method, "needs investigation"
exclude :test_super_in_orphan_block_with_instance_eval, "needs investigation"
|
namespace ApprovalTests.Reporters.Mac
{
public class P4MergeReporter : GenericDiffReporter
{
public static readonly P4MergeReporter INSTANCE = new P4MergeReporter();
public P4MergeReporter() : base(DiffPrograms.Mac.P4MERGE)
{
}
}
} |
const fs = require('fs');
const path = require('path');
const target = path.resolve(__dirname, '..', 'test', 'setup', 'McashWeb.js');
try {
fs.unlinkSync(target);
} catch(ex) {}
fs.copyFileSync(
path.resolve(__dirname, '..', 'test', 'setup', 'node.js'),
target
);
|
#[macro_use]
mod macros;
test!(
named_args,
"a {\n color: selector-parse($selector: \"c\");\n}\n",
"a {\n color: c;\n}\n"
);
test!(
simple_class,
"a {\n color: selector-parse(\".c\");\n}\n",
"a {\n color: .c;\n}\n"
);
test!(
simple_id,
"a {\n color: selector-parse(\"#c\");\n}\n",
"a {\n color: #c;\n}\n"
);
test!(
simple_placeholder,
"a {\n color: selector-parse(\"%c\");\n}\n",
"a {\n color: %c;\n}\n"
);
test!(
simple_attribute,
"a {\n color: selector-parse(\"[c^=d]\");\n}\n",
"a {\n color: [c^=d];\n}\n"
);
test!(
simple_universal,
"a {\n color: selector-parse(\"*\");\n}\n",
"a {\n color: *;\n}\n"
);
test!(
simple_pseudo,
"a {\n color: selector-parse(\":c\");\n}\n",
"a {\n color: :c;\n}\n"
);
test!(
pseudo_weird_args,
"a {\n color: selector-parse(\":c(@#$)\");\n}\n",
"a {\n color: :c(@#$);\n}\n"
);
test!(
pseudo_matches_with_list_args,
"a {\n color: selector-parse(\":matches(b, c)\");\n}\n",
"a {\n color: :matches(b, c);\n}\n"
);
test!(
pseudo_element,
"a {\n color: selector-parse(\"::c\");\n}\n",
"a {\n color: ::c;\n}\n"
);
test!(
pseudo_element_args,
"a {\n color: selector-parse(\"::c(@#$)\");\n}\n",
"a {\n color: ::c(@#$);\n}\n"
);
test!(
pseudo_element_slotted_list_args_output,
"a {\n color: selector-parse(\"::slotted(b, c)\");\n}\n",
"a {\n color: ::slotted(b, c);\n}\n"
);
test!(
pseudo_element_slotted_list_args_structure,
"a {\n color: selector-parse(\"::slotted(b, c)\") == (append((), \"::slotted(b, c)\"),);\n}\n",
"a {\n color: true;\n}\n"
);
test!(
multiple_compound,
"a {\n color: selector-parse(\"b.c:d\");\n}\n",
"a {\n color: b.c:d;\n}\n"
);
test!(
multiple_complex,
"a {\n color: selector-parse(\"b c d\");\n}\n",
"a {\n color: b c d;\n}\n"
);
test!(
sibling_combinator,
"a {\n color: selector-parse(\"b ~ c ~ d\");\n}\n",
"a {\n color: b ~ c ~ d;\n}\n"
);
test!(
adjacent_combinator,
"a {\n color: selector-parse(\"b + c + d\");\n}\n",
"a {\n color: b + c + d;\n}\n"
);
test!(
child_combinator,
"a {\n color: selector-parse(\"b > c > d\");\n}\n",
"a {\n color: b > c > d;\n}\n"
);
test!(
comma_and_space_list,
"a {\n color: selector-parse(\"b c, d e, f g\");\n}\n",
"a {\n color: b c, d e, f g;\n}\n"
);
error!(
invalid_selector,
"a {\n color: selector-parse(\"!!!!!!!!\");\n}\n", "Error: $selector: expected selector."
);
error!(
selector_contains_curly_brace,
"a {\n color: selector-parse(\"a {\");\n}\n", "Error: $selector: expected selector."
);
|
import gulp from 'gulp';
import {CLIOptions} from 'aurelia-cli';
import project from '../aurelia.json';
export default function copy() {
const output = CLIOptions.getFlagValue('out', 'o');
if (!output) {
throw new Error('--out argument is required');
}
return gulp.src(project.deploy.sources, { base: './' }).pipe(gulp.dest(output));
}
|
use super::{Fold, FoldWith, Visit, VisitWith};
use crate::{
pass::{CompilerPass, Repeated, RepeatedPass},
util::move_map::MoveMap,
};
use std::borrow::Cow;
#[macro_export]
macro_rules! chain {
($a:expr, $b:expr) => {{
use $crate::fold::and_then::AndThen;
AndThen {
first: $a,
second: $b,
}
}};
($a:expr, $b:expr,) => {
chain!($a, $b)
};
($a:expr, $b:expr, $($rest:tt)+) => {{
use $crate::fold::and_then::AndThen;
AndThen{
first: $a,
second: chain!($b, $($rest)*),
}
}};
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AndThen<A, B> {
pub first: A,
pub second: B,
}
impl<T, A, B> Fold<T> for AndThen<A, B>
where
T: FoldWith<Self>,
{
default fn fold(&mut self, node: T) -> T {
// println!(
// "Default<{}, {}>({})",
// type_name::<A>(),
// type_name::<B>(),
// type_name::<T>()
// );
node.fold_children(self)
}
}
impl<T, A, B> Fold<T> for AndThen<A, B>
where
T: FoldWith<Self>,
A: Fold<T>,
B: Fold<T>,
{
default fn fold(&mut self, node: T) -> T {
// println!(
// "Folding<{}, {}>({})",
// type_name::<A>(),
// type_name::<B>(),
// type_name::<T>()
// );
self.second.fold(self.first.fold(node))
}
}
impl<T, A, B> Fold<Vec<T>> for AndThen<A, B>
where
Vec<T>: FoldWith<Self>,
A: Fold<T>,
B: Fold<T>,
{
fn fold(&mut self, nodes: Vec<T>) -> Vec<T> {
nodes.move_map(|node| self.second.fold(self.first.fold(node)))
}
}
impl<T, A, B> Visit<T> for AndThen<A, B>
where
T: VisitWith<Self>,
A: Visit<T>,
B: Visit<T>,
{
fn visit(&mut self, node: &T) {
self.first.visit(node);
self.second.visit(node);
}
}
impl<A, B> CompilerPass for AndThen<A, B>
where
A: CompilerPass,
B: CompilerPass,
{
fn name() -> Cow<'static, str> {
format!("{} -> {}", A::name(), B::name()).into()
}
}
impl<A, B, At> RepeatedPass<At> for AndThen<A, B>
where
A: RepeatedPass<At>,
B: RepeatedPass<At>,
{
}
impl<A, B> Repeated for AndThen<A, B>
where
A: Repeated,
B: Repeated,
{
fn changed(&self) -> bool {
self.first.changed() || self.second.changed()
}
fn reset(&mut self) {
self.first.reset();
self.second.reset();
}
}
|
using System;
using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
public class Form1: Form
{
protected TextBox textBox1;
// <Snippet1>
public void CreateMyTextBoxControl()
{
// Create a new TextBox control using this constructor.
TextBox textBox1 = new TextBox();
// Assign a string of text to the new TextBox control.
textBox1.Text = "Hello World!";
// Code goes here to add the control to the form's control collection.
}
// </Snippet1>
}
|
package FunCLBMSpark
import Tools._
import breeze.linalg.{DenseMatrix, DenseVector}
import breeze.numerics.sin
import scala.math._
import breeze.stats.distributions.MultivariateGaussian
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import com.github.unsupervise.spark.tss
import com.github.unsupervise.spark.tss.core.TSS
import org.apache.spark.sql.SparkSession
import breeze.stats.distributions.Gaussian
import scala.util.Random
object DataGeneration {
// Sin prototype
def f1(x: List[Double], sigma: Double): List[Double] = {
x.map(t => 1+0.5*sin(4*scala.math.Pi*t) + Gaussian(0,sigma).draw())
}
// Sigmoid prototype
def f2(x: List[Double], sigma: Double): List[Double] = {
val center = Gaussian(0.6,0.02).draw()
val slope = 20D
val maxVal = Gaussian(1,0.02).draw()
x.map(t => maxVal/(1+exp(-slope*(t-center))) + Gaussian(0,sigma).draw())
}
// Rectangular prototype
def f3(x: List[Double], sigma: Double): List[Double] = {
val start = Gaussian(0.3,0.02).draw()
val duration = Gaussian(0.3,0.001).draw()
x.map({
case t if t <`start` || t>=(`start`+`duration`) => 0D + Gaussian(0,sigma).draw()
case _ => 1D + Gaussian(0,sigma).draw()
})
}
// Morlet prototype
def f4(x: List[Double], sigma: Double): List[Double] = {
val center = Gaussian(0.5,0.02).draw()
x.map(t => {
val u = (t-center)*10
exp(-0.5*pow(u,2))*cos(5*u) + Gaussian(0,sigma).draw()
})
}
// Gaussian prototype
def f5(x: List[Double], sigma: Double): List[Double] = {
val center = Gaussian(0.5,0.02).draw()
val sd = 0.1
val G = Gaussian(center, sd)
x.map(t => 1.5*G.pdf(t)/G.pdf(center)+ Gaussian(0,sigma).draw())
}
// Double Gaussian prototype
def f6(x: List[Double], sigma: Double): List[Double] = {
val center1 = Gaussian(0.2,0.02).draw()
val center2 = Gaussian(0.7,0.02).draw()
val sd = 0.1
val G1 = Gaussian(center1, sd)
val G2 = Gaussian(center2, sd)
x.map(t => G1.pdf(t)/G1.pdf(center1)+ G2.pdf(t)/G2.pdf(center2)+ Gaussian(0,sigma).draw() )
}
// y-shifted Gaussian prototype
def f7(x: List[Double], sigma: Double): List[Double] = {
x.map(t => 0.3+ 0.3*sin(2*scala.math.Pi*t) + Gaussian(0,sigma).draw())
}
// sin by rectangular prototype
def f8(x: List[Double], sigma: Double): List[Double] = {
val start = Gaussian(0.3,0.02).draw()
val duration = Gaussian(0.3,0.001).draw()
x.map({
case t if t <`start` || t>=(`start`+`duration`) => -1 + 0.5* sin(2*Pi*t) + Gaussian(0,sigma).draw()
case t => 2+ 0.5*sin(2*Pi*t) + Gaussian(0,sigma).draw()
})
}
def randomDataGeneration(prototypes: List[List[(List[Double],Double)=> List[Double]]],
sigma: Double,
sizeClusterRow: List[List[Int]],
sizeClusterCol: List[Int],
shuffled: Boolean=true,
numPartition: Int=200)(implicit ss: SparkSession): TSS = {
require(Tools.allEqual(prototypes.map(_.length), sizeClusterRow.map(_.length)))
require(sizeClusterCol.length == prototypes.length)
require(sizeClusterRow.map(_.sum == sizeClusterRow.head.sum).forall(identity))
val kVec = prototypes.map(_.length)
val l = prototypes.length
val length = 100
val indices:List[Double] = (1 to length).map(_/length.toDouble).toList
val dataPerBlock: List[List[DenseMatrix[List[Double]]]] =
prototypes.indices.map(l => {
prototypes(l).indices.map(k_l => {
val ArrayTS: Array[List[Double]] = (0 until sizeClusterRow(l)(k_l) * sizeClusterCol(l)).map(e =>
prototypes(l)(k_l)(indices, sigma)).toArray
DenseMatrix(ArrayTS).reshape(sizeClusterRow(l)(k_l), sizeClusterCol(l))
}).toList
}).toList
var data: DenseMatrix[List[Double]] = (0 until l).map(l => {
(0 until kVec(l)).map(k_l => {
dataPerBlock(l)(k_l)
}).reduce(DenseMatrix.vertcat(_, _))
}).reduce(DenseMatrix.horzcat(_, _))
data = if(shuffled){
val shuffledColdata: DenseMatrix[List[Double]] = DenseMatrix(
Random.shuffle((0 until data.cols).map(j => data(::, j))).toList:_*).t
val shuffledRowdata: DenseMatrix[List[Double]] = DenseMatrix(
Random.shuffle((0 until data.rows).map(i => shuffledColdata(i, ::).t)).toList:_*).t
shuffledRowdata
} else data
var dataList: List[(Int, Int, List[Double], List[Double])] = (0 until data.rows).map(i => {
(0 until data.cols).map(j => {
(i, j, indices, data(i,j))
}).toList
}).reduce(_++_)
val dataRDD = ss.sparkContext.parallelize(dataList, numPartition)
TSSInterface.toTSS(dataRDD)
}
}
|
namespace SFA.DAS.Payments.Automation.Application.GherkinSpecs
{
public class ValidationViolation
{
public string RuleId { get; set; }
public string SpecificationName { get; set; }
public string Description { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DiceRoll : MonoBehaviour
{
// Message if you win
private string winMessage = "GEWONNEN! Deine Nummer lautet: ";
// Prints the Description in the console
void Start()
{
Debug.Log("Lucky Number Zahlen: 6, 13 und 17. Drücke Space um zu würfeln. Viel Glück!");
}
// After hitting the space key the dice will roll
// if: When the result is 6, 13 or 17 you win and get the win message printed
// else: Any other number let you lose and the lose-message will be printed
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int diceRoll = Random.Range(1,21);
if (diceRoll == 6 || diceRoll == 13 || diceRoll == 17)
{
Debug.Log(winMessage + diceRoll);
}
else
{
Debug.Log("VERLOREN! Deine Nummer lautet: " + diceRoll);
}
}
}
}
|
# newmoney-cointracker-api
API for NewMoney Cryptocurrency Cointracker
## Getting Started
- ```git clone ...```
- ```npm i```
### Set up the database
- ```npm run db:init```
### Run the server
- ```npm start```
## Contributing
- Fork the repository
- ```git clone ...```
- ```npm i```
### Set up the database
- ```npm run db:init```
### Run the server
- ```npm start```
|
import 'package:dig_core/dig_core.dart';
import 'package:dig_mobile_app/app/viewmodel/import_account_viewmodel.dart';
import 'package:equatable/equatable.dart';
abstract class ImportAccountState extends Equatable {
final ImportAccountViewmodel viewmodel;
const ImportAccountState({this.viewmodel = const ImportAccountViewmodel()});
@override
List<Object?> get props => [viewmodel];
}
class ImportAccountPrimaryState extends ImportAccountState {
const ImportAccountPrimaryState(
{ImportAccountViewmodel viewmodel = const ImportAccountViewmodel()})
: super(viewmodel: viewmodel);
}
class ImportAccountLoadingState extends ImportAccountState {
const ImportAccountLoadingState(
{ImportAccountViewmodel viewmodel = const ImportAccountViewmodel()})
: super(viewmodel: viewmodel);
}
class ImportAccountSuccessState extends ImportAccountState {
const ImportAccountSuccessState(
{ImportAccountViewmodel viewmodel = const ImportAccountViewmodel()})
: super(viewmodel: viewmodel);
}
class ImportAccountErrorState extends ImportAccountState {
final BaseDigException exception;
const ImportAccountErrorState(
{ImportAccountViewmodel viewmodel = const ImportAccountViewmodel(),
this.exception = const DigException()})
: super(viewmodel: viewmodel);
@override
List<Object?> get props => [viewmodel, exception];
}
class ImportAccountChangedFormState extends ImportAccountState {
const ImportAccountChangedFormState(
{ImportAccountViewmodel viewmodel = const ImportAccountViewmodel()})
: super(viewmodel: viewmodel);
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Inventory.Application.Items.Commands.CreateItem
{
public class CreateItemDto
{
public string Name { get; set; }
public string Description { get; set; }
public Guid ItemTypeId { get; set; }
public DateTime? PurchaseDate { get; set; }
public double? PurchasePrice { get; set; }
public DateTime? ExpirationDate { get; set; }
public DateTime? LastUsed { get; set; }
}
}
|
use crate::config::{Named, Project, Test};
use crate::docker::Verification;
use crate::io::Logger;
use curl::easy::{Handler, WriteError};
use serde::Deserialize;
#[derive(Clone, Debug)]
pub struct Verifier {
pub verification: Verification,
logger: Logger,
}
impl Verifier {
pub fn new(
project: &Project,
test: &Test,
test_type: &(&String, &String),
logger: &Logger,
) -> Self {
let mut logger = logger.clone();
logger.set_log_file("verifications.txt");
Self {
logger,
verification: Verification {
framework_name: project.framework.get_name(),
test_name: test.get_name(),
type_name: test_type.0.clone(),
warnings: vec![],
errors: vec![],
},
}
}
}
impl Handler for Verifier {
fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
if let Ok(logs) = std::str::from_utf8(&data) {
for line in logs.lines() {
if !line.trim().is_empty() {
if let Ok(warning) = serde_json::from_str::<WarningMessage>(line) {
self.verification.warnings.push(warning.warning);
} else if let Ok(error) = serde_json::from_str::<ErrorMessage>(line) {
self.verification.errors.push(error.error);
} else {
self.logger.log(line.trim_end()).unwrap();
}
}
}
}
Ok(data.len())
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct Warning {
pub message: String,
pub short_message: String,
}
#[derive(Deserialize, Clone, Debug)]
pub struct Error {
pub message: String,
pub short_message: String,
}
#[derive(Deserialize)]
struct WarningMessage {
warning: Warning,
}
#[derive(Deserialize)]
struct ErrorMessage {
error: Error,
}
|
package com.example.muumuu.animationshowcase
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.transition.ArcMotion
import androidx.transition.ChangeBounds
import androidx.transition.TransitionManager
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_arc_transition.*
class ArcTransitionFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_arc_transition, null)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpButton()
viewCodeButton.setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(CodeSampleUrl.ARC_TRANSITION.url)))
}
}
private fun setUpButton() {
button.setOnClickListener {
TransitionManager.beginDelayedTransition(
heartContainer,
ChangeBounds().apply {
setPathMotion(ArcMotion())
duration = 1000L
}
)
val params = (heartContainer.layoutParams as ConstraintLayout.LayoutParams).apply {
horizontalBias = if (horizontalBias == 0f) 1f else 0f
verticalBias = if (verticalBias == 0.2f) 0.8f else 0.2f
}
heartContainer.layoutParams = params
}
}
} |
---
layout: post
category: project
title: "Grandy"
brief: "freelance design marketplace"
date: 2014-11-17
thumbnail: grandy_logo.png
color: "#76C185"
---
{% contentfor intro %}
Grandy removes the pain from freelancing for designers and clients with a marketplace for $1,000 projects.
{% endcontentfor %}
{% include pic.html file="grandy_logo.png" %}
{% include pic.html file="grandy_macbook.png" %}
{% include pic.html file="grandy_landing-display.png" %}
|
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.load.java.components
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.FilePreprocessorExtension
import org.jetbrains.kotlin.resolve.addElementToSlice
import org.jetbrains.kotlin.util.slicedMap.BasicWritableSlice
import org.jetbrains.kotlin.util.slicedMap.Slices
import org.jetbrains.kotlin.util.slicedMap.WritableSlice
// TODO: this component is actually only needed by CLI, see CliLightClassGenerationSupport
class FilesByFacadeFqNameIndexer(private val trace: BindingTrace) : FilePreprocessorExtension {
override fun preprocessFile(file: KtFile) {
if (!file.hasTopLevelCallables()) return
trace.addElementToSlice(FACADE_FILES_BY_FQ_NAME, file.javaFileFacadeFqName, file)
trace.addElementToSlice(FACADE_FILES_BY_PACKAGE_NAME, file.javaFileFacadeFqName.parent(), file)
}
companion object {
@JvmField
val FACADE_FILES_BY_FQ_NAME: WritableSlice<FqName, MutableCollection<KtFile>> = Slices.createSimpleSlice()
@JvmField
val FACADE_FILES_BY_PACKAGE_NAME: WritableSlice<FqName, MutableCollection<KtFile>> = Slices.createSimpleSlice()
init {
BasicWritableSlice.initSliceDebugNames(FilesByFacadeFqNameIndexer::class.java)
}
}
}
|
use super::gtk_widget_event_type::*;
use flo_ui::*;
use flo_canvas::*;
use gtk::*;
/// ID used to identify a Gtk window
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum WindowId {
Unassigned,
Assigned(i64)
}
/// ID used to identify a Gtk widget
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum WidgetId {
Unassigned,
Assigned(i64)
}
///
/// Actions that can be performed on a window
///
#[derive(Clone, PartialEq, Debug)]
pub enum GtkWindowAction {
New(WindowType),
SetPosition(WindowPosition),
SetDefaultSize(i32, i32),
SetTitle(String),
ShowAll,
Hide,
Close
}
///
/// Types of widget that can be created
///
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum GtkWidgetType {
Generic,
Layout,
Fixed,
Button,
ToggleButton,
CheckBox,
TextBox,
Label,
Scale,
ScrollArea,
Popover,
Rotor,
CanvasDrawingArea,
CanvasLayout,
CanvasNanovg
}
///
/// Actions that can be performed on a widget
///
#[derive(Clone, PartialEq, Debug)]
pub enum GtkWidgetAction {
/// Creates a new widget of the specifed type
New(GtkWidgetType),
/// Requests a particular event type for this widget, generating the specified action name
RequestEvent(GtkWidgetEventType, String),
/// Removes all the widgets from the specified window and makes this one the new root
SetRoot(WindowId),
/// Marks this widget as displayed
Show,
/// Put this widget inside an event box
Box,
/// Updates the layout of this widget
Layout(WidgetLayout),
/// Updates the content of this widget
Content(WidgetContent),
/// Updates the appearance of this widget
Appearance(Appearance),
/// Updates the state of this widget
State(WidgetState),
/// Updates the font properties for this widget
Font(Font),
/// Updates how the content of this widget scrolls
Scroll(Scroll),
/// Controls the popup attributes of this widget
Popup(WidgetPopup),
/// Deletes this widget (and any child widgets it may contain)
Delete
}
///
/// Specifies a change to the content of a widget
///
#[derive(Clone, PartialEq, Debug)]
pub enum WidgetContent {
/// Sets the children of this widget to be a particular set of widgets
SetChildren(Vec<WidgetId>),
/// Sets the text of this widget to the specified string
SetText(String),
/// Adds a class to this widget
AddClass(String),
/// Removes a class from this widget
RemoveClass(String),
/// Specifies a drawing to perform on this widget
Draw(Vec<Draw>)
}
impl From<WidgetContent> for GtkWidgetAction {
fn from(item: WidgetContent) -> GtkWidgetAction {
GtkWidgetAction::Content(item)
}
}
///
/// Specifies a change to how a widget is laid out
///
#[derive(Clone, PartialEq, Debug)]
pub enum WidgetLayout {
/// Specifies how this widget should be laid out
BoundingBox(Bounds),
/// Specifies the floating offset for this widget
Floating(f64, f64),
/// Specifies the Z-index of this widget
ZIndex(u32),
/// Specifies the padding for this widget
Padding((u32, u32), (u32, u32))
}
impl From<WidgetLayout> for GtkWidgetAction {
fn from(item: WidgetLayout) -> GtkWidgetAction {
GtkWidgetAction::Layout(item)
}
}
///
/// Specifies a change to the state of a widget
///
#[derive(Clone, PartialEq, Debug)]
pub enum WidgetState {
/// Sets whether or not this widget is highlighted as being selected
SetSelected(bool),
/// Sets whether or not this widget shows a badge next to it
SetBadged(bool),
/// Sets whether or not this widget is enabled
SetEnabled(bool),
/// Sets the value of this widget as a bool
SetValueBool(bool),
/// Sets the value of this widget
SetValueFloat(f64),
/// Sets the value of this widget as an integer
SetValueInt(i64),
/// Sets the value of this widget as a text string
SetValueText(String),
/// Sets the minimum value for this widget
SetRangeMin(f64),
/// Sets the maximum value for this widget
SetRangeMax(f64)
}
impl From<WidgetState> for GtkWidgetAction {
fn from(item: WidgetState) -> GtkWidgetAction {
GtkWidgetAction::State(item)
}
}
///
/// Actions for widgets supporting pop-up behaviour
///
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum WidgetPopup {
/// Sets the direction this popup will open
SetDirection(PopupDirection),
/// Sets the size of this popup
SetSize(u32, u32),
/// Sets the offset of this popup from the center of its parent widget
SetOffset(u32),
/// Sets whether or not this popup is open
SetOpen(bool)
}
impl From<WidgetPopup> for GtkWidgetAction {
fn from (item: WidgetPopup) -> GtkWidgetAction {
GtkWidgetAction::Popup(item)
}
}
impl From<Font> for GtkWidgetAction {
fn from(item: Font) -> GtkWidgetAction {
GtkWidgetAction::Font(item)
}
}
impl From<Appearance> for GtkWidgetAction {
fn from(item: Appearance) -> GtkWidgetAction {
GtkWidgetAction::Appearance(item)
}
}
impl From<Scroll> for GtkWidgetAction {
fn from(item: Scroll) -> GtkWidgetAction {
GtkWidgetAction::Scroll(item)
}
}
///
/// GTK actions that can be requested
///
#[derive(Clone, PartialEq, Debug)]
pub enum GtkAction {
/// Shuts down Gtk
Stop,
/// Performs some actions on a window
Window(WindowId, Vec<GtkWindowAction>),
/// Performs some actions on a widget
Widget(WidgetId, Vec<GtkWidgetAction>)
}
impl GtkAction {
///
/// True if this action is a no-op (can be removed from the actions list)
///
pub fn is_no_op(&self) -> bool {
match self {
&GtkAction::Window(_, ref window_actions) => window_actions.len() == 0,
&GtkAction::Widget(_, ref widget_actions) => widget_actions.len() == 0,
_ => false
}
}
}
|
package com.syleiman.gingermoney.ui.common.navigation
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
interface NavigationHelperBase {
/**
* Move back in back stack
*/
fun moveBack(currentFragment: Fragment, finishCurrentActivity: Boolean = false)
/**
* Move back in back stack
*/
fun moveBack(currentActivity: FragmentActivity)
fun getTitle(activity: FragmentActivity): String
fun processBackAnimation(activity: FragmentActivity)
} |
use super::ecs::*;
use ron;
use specs::error::NoError;
use specs::prelude::*;
use specs::saveload::{DeserializeComponents, SerializeComponents, U64Marker, U64MarkerAllocator};
use std::fs::File;
pub fn save(world: &mut World) {
//SaveWorld(format!("{}/save", env!("CARGO_MANIFEST_DIR"))).run_now(&world.res);
SaveWorld("./save".to_owned()).run_now(&world.res);
}
pub fn load(world: &mut World) {
//LoadWorld(format!("{}/save", env!("CARGO_MANIFEST_DIR"))).run_now(&world.res);
SaveWorld("./save".to_owned()).run_now(&world.res);
}
struct SaveWorld(String);
impl<'a> System<'a> for SaveWorld {
type SystemData = (
Entities<'a>,
ReadStorage<'a, U64Marker>,
ReadStorage<'a, Position>,
ReadStorage<'a, Tile>,
);
fn run(&mut self, (entities, markers, positions, sprites): Self::SystemData) {
let mut serializer = ron::ser::Serializer::new(Some(Default::default()), true);
SerializeComponents::<NoError, U64Marker>::serialize(
&(positions, sprites),
&entities,
&markers,
&mut serializer,
).unwrap();
let save = serializer.into_output_string();
info!("{}", &save);
use std::io::Write;
File::create(&self.0)
.expect("Could not create save file.")
.write_all(save.as_bytes())
.expect("Could not write save file.");
}
}
struct LoadWorld(String);
impl<'a> System<'a> for LoadWorld {
type SystemData = (
Entities<'a>,
Write<'a, U64MarkerAllocator>,
WriteStorage<'a, U64Marker>,
WriteStorage<'a, Position>,
WriteStorage<'a, Tile>,
);
fn run(
&mut self,
(entities, mut allocator, mut markers, positions, sprites): Self::SystemData,
) {
let save = {
let mut file = match File::open(&self.0) {
Ok(file) => file,
Err(e) => {
panic!("Could not open save file: {} ({})", self.0, e);
}
};
let mut save = Vec::new();
use std::io::Read;
file.read_to_end(&mut save).expect("Could not read file.");
save
};
let mut deserializer = ron::de::Deserializer::from_bytes(&save).unwrap();
DeserializeComponents::<NoError, U64Marker>::deserialize(
&mut (positions, sprites),
&entities,
&mut markers,
&mut allocator,
&mut deserializer,
).unwrap();
}
}
|
@file:Suppress("unused")
package com.library.common.extension
import android.view.View
/**
* 批量设置控件点击事件。
*
* @param v 点击的控件
* @param block 处理点击事件回调代码块
*/
fun setOnClickListener(vararg v: View?, block: View.() -> Unit) {
val listener = View.OnClickListener { it.block() }
v.forEach { it?.setOnClickListener(listener) }
}
/**
* 批量设置控件点击事件。
*
* @param v 点击的控件
* @param listener 处理点击事件监听器
*/
fun setOnClickListener(vararg v: View?, listener: View.OnClickListener) {
v.forEach { it?.setOnClickListener(listener) }
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace Jeuxjeux20.Mvvm
{
public abstract class MultiThreadedPropertyChangedObject : PropertyChangedObject
{
private static List<WindowSyncData> Contexts { get; } = new List<WindowSyncData>();
private static readonly object IsChanging = new object();
protected override void OnPropertyChanged(string propertyName = null)
{
lock (IsChanging)
{
if (!Contexts.Any())
{
// No contexts configured.
base.OnPropertyChanged(propertyName);
return;
}
try
{
foreach (var context in Contexts)
{
if (context.Dispatcher == Dispatcher.CurrentDispatcher)
{
// Called on the same thread as the sync. No need to use the context.
base.OnPropertyChanged(propertyName);
}
else
{
context.Context.Post(
_ => base.OnPropertyChanged(propertyName),
null);
}
}
}
catch (InvalidOperationException e)
{
Trace.WriteLine("[Jeuxjeux20.Mvvm] Something bad happened: " + e);
}
}
}
public static void RegisterWindow(Window window)
{
lock (IsChanging)
{
Contexts.Add(new WindowSyncData(window));
}
window.Closed += RegisteredWindowClosed;
}
private static void RegisteredWindowClosed(object sender, System.EventArgs e)
{
lock (IsChanging)
{
Contexts.Remove(Contexts.First(w => w.Window == sender));
}
((Window)sender).Closed -= RegisteredWindowClosed;
}
private class WindowSyncData
{
public SynchronizationContext Context { get; }
public Window Window { get; }
public Dispatcher Dispatcher { get; }
public WindowSyncData(Window window, SynchronizationContext context = null)
{
Window = window;
Context = context ?? SynchronizationContext.Current;
Dispatcher = Window.Dispatcher;
}
}
}
} |
package io.github.forezp.cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import java.util.concurrent.TimeUnit;
public class RouteRuleCache<AuthRule> extends AbstractCaffineCache {
@Override
LoadingCache createLoadingCache() {
LoadingCache loadingCache = Caffeine.newBuilder()
.expireAfterWrite(100000, TimeUnit.DAYS)
.initialCapacity(10)
.maximumSize(99999999)
.recordStats()
.build(new CacheLoader<String, AuthRule>() {
@Override
public AuthRule load(String key) throws Exception {
return null;
}
});
return loadingCache;
}
} |
package com.frogobox.appadmob.mvvm.main
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.frogobox.appadmob.R
import com.frogobox.appadmob.base.BaseActivity
import com.frogobox.appadmob.databinding.ActivityMainBinding
import com.frogobox.appadmob.mvvm.compose.ComposeActivity
import com.frogobox.appadmob.mvvm.compose.HybridActivity
import com.frogobox.appadmob.mvvm.interstitial.InterstitialActivity
import com.frogobox.appadmob.mvvm.movie.MovieActivity
import com.frogobox.appadmob.mvvm.news.NewsActivity
import com.frogobox.appadmob.mvvm.rewarded.RewardedActivity
import com.google.android.gms.ads.AdSize
class MainActivity : BaseActivity<ActivityMainBinding>() {
override fun setupViewBinding(): ActivityMainBinding {
return ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestAdmobApi()
setupButtonClick()
setupBannerAds()
}
private fun setupBannerAds() {
showAdBanner(binding.adsXml.adsPhoneTabSpecialSmartBanner)
showAdBannerContainer(
getString(R.string.admob_banner),
AdSize.SMART_BANNER,
binding.includeAdsView.frogoAdsBanner
)
}
private fun setupButtonClick() {
binding.apply {
btnInterstitial.setOnClickListener {
frogoStartActivity<InterstitialActivity>()
}
btnRewarded.setOnClickListener {
frogoStartActivity<RewardedActivity>()
}
btnRecyclerView.setOnClickListener {
frogoStartActivity<NewsActivity>()
}
btnRecyclerView2.setOnClickListener {
frogoStartActivity<MovieActivity>()
}
btnComposeActivity.setOnClickListener {
frogoStartActivity<ComposeActivity>()
}
btnHybridActivity.setOnClickListener {
frogoStartActivity<HybridActivity>()
}
btnJavaSampleActivity.setOnClickListener {
frogoStartActivity<MainJavaActivity>()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_toolbar_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.toolbar_menu_about -> {
frogoStartActivity<AboutUsActivity>()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.